{"dataset": "python_comparative_degradation", "name": "Python transformations", "kind": "controlled", "samples": [{"task_id": "pyint-512cc0777c37-SRC", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass NullSession(SecureCookieSession):\n    \"\"\"Class used to generate nicer error messages if sessions are not\n    available.  Will still allow read-only access to the empty session\n    but fail on setting.\n    \"\"\"\n\n    def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"\n        )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-060f9823bc721c4c", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 27, "local_path": "source-original/SRC__flask__NullSession__c0777c37.py", "order": 0, "original_content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L83-L97", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "NullSession", "variant_id": "pyint-512cc0777c37-SRC", "group_id": "py-060f9823bc721c4c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 491, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0f5ae077d667-I01", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass NullSession(SecureCookieSession):\n    \n\n    def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"\n        )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-060f9823bc721c4c", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "0de9fc1810087dde7a85eccdbafe76273980ab72ab01e76504066bec8e9ce85e", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 24, "local_path": "comments/remove-comments/I01__flask__NullSession__e077d667.py", "order": 1, "original_content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "parent_variant_id": "pyint-512cc0777c37-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L83-L97", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 170, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "NullSession", "variant_id": "pyint-0f5ae077d667-I01", "group_id": "py-060f9823bc721c4c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 492, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1482e4eecc88-I02", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass NullSession(SecureCookieSession):\n    \"\"\"Class used to generate nicer error messages if sessions are not\n    available.  Will still allow read-only access to the empty session\n    but fail on setting.\n    \"\"\"\n\n    def fai(self, *arg: t.Any, **kwa: t.Any) -> t.NoReturn:\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"\n        )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-060f9823bc721c4c", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "51e3c3b16a7abeac4d4ea26a103562f8f151cdfb8b26883c6da4c3888ed5fee5", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 27, "local_path": "identifiers/shorten-identifiers/I02__flask__NullSession__e4eecc88.py", "order": 2, "original_content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "parent_variant_id": "pyint-512cc0777c37-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L83-L97", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 3, "identifiers_declared": 3}, "unit_kind": "class", "unit_name": "NullSession", "variant_id": "pyint-1482e4eecc88-I02", "group_id": "py-060f9823bc721c4c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 493, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5887de341b85-I03", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass NullSession(SecureCookieSession):\n    \"\"\"Class used to generate nicer error messages if sessions are not\n    available.  Will still allow read-only access to the empty session\n    but fail on setting.\n    \"\"\"\n\n    def route(self, *step: t.Any, **amount: t.Any) -> t.NoReturn:\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"\n        )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-060f9823bc721c4c", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "9bb4b49b3c2192f528d83063a0db0ea385e0e275970be7a849229549fb8cc278", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 27, "local_path": "identifiers/mislead-identifiers/I03__flask__NullSession__de341b85.py", "order": 3, "original_content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "parent_variant_id": "pyint-512cc0777c37-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L83-L97", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 3, "identifiers_declared": 3, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 2, "local_random_pool_selections": 2, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "NullSession", "variant_id": "pyint-5887de341b85-I03", "group_id": "py-060f9823bc721c4c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 494, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-95440670c805-I04", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass NullSession(SecureCookieSession):\n    \"\"\"Class used to generate nicer error messages if sessions are not\n    available.  Will still allow read-only access to the empty session\n    but fail on setting.\n    \"\"\"\n\n    def a(self, *b: t.Any, **c: t.Any) -> t.NoReturn:\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"\n        )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-060f9823bc721c4c", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "136ac97d49ba6a4d1028e46c1c36317a155380c91a8e9d010845ca57b4b3bd3b", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 27, "local_path": "identifiers/garble-identifiers/I04__flask__NullSession__0670c805.py", "order": 4, "original_content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "parent_variant_id": "pyint-512cc0777c37-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L83-L97", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 3, "identifiers_declared": 3}, "unit_kind": "class", "unit_name": "NullSession", "variant_id": "pyint-95440670c805-I04", "group_id": "py-060f9823bc721c4c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 495, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ee4212f5ea91-I05", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass NullSession(SecureCookieSession):\n    \"\"\"Class used to generate nicer error messages if sessions are not\n    available.  Will still allow read-only access to the empty session\n    but fail on setting.\n    \"\"\"\n\n    def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"\n        )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-060f9823bc721c4c", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 27, "local_path": "expressions/encode-integer-literals/I05__flask__NullSession__12f5ea91.py", "order": 5, "original_content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "parent_variant_id": "pyint-512cc0777c37-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L83-L97", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "NullSession", "variant_id": "pyint-ee4212f5ea91-I05", "group_id": "py-060f9823bc721c4c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 496, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2ce6ab591f60-I06", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass NullSession(SecureCookieSession):\n    \"\"\"Class used to generate nicer error messages if sessions are not\n    available.  Will still allow read-only access to the empty session\n    but fail on setting.\n    \"\"\"\n\n    def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"\n        )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-060f9823bc721c4c", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 27, "local_path": "expressions/invert-conditions/I06__flask__NullSession__ab591f60.py", "order": 6, "original_content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "parent_variant_id": "pyint-512cc0777c37-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L83-L97", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "NullSession", "variant_id": "pyint-2ce6ab591f60-I06", "group_id": "py-060f9823bc721c4c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 497, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-25a1bf88b3ab-I07", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass NullSession(SecureCookieSession):\n    \"\"\"Class used to generate nicer error messages if sessions are not\n    available.  Will still allow read-only access to the empty session\n    but fail on setting.\n    \"\"\"\n\n    def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n        if ((0x2bf2 ^ 0x2bf2) != 0):\n            raise AssertionError()\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"\n        )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-060f9823bc721c4c", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "c1290fb49a8b9094fd318f9b00794b1bf5a0392a2f6fbf525f47a3422eddec38", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 29, "local_path": "code-injection/insert-dead-branches/I07__flask__NullSession__bf88b3ab.py", "order": 7, "original_content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "parent_variant_id": "pyint-512cc0777c37-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L83-L97", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "NullSession", "variant_id": "pyint-25a1bf88b3ab-I07", "group_id": "py-060f9823bc721c4c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 498, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b8dff5654966-I08", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass NullSession(SecureCookieSession):\n    \"\"\"Class used to generate nicer error messages if sessions are not\n    available.  Will still allow read-only access to the empty session\n    but fail on setting.\n    \"\"\"\n\n    def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n        even_number_count = 0\n        for candidate_number in range(6):\n            if candidate_number % 2 == 0:\n                even_number_count += 1\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"\n        )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-060f9823bc721c4c", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "b5bebdae17ed286a13c936511e8271c99f6b55cdd070e1540800f111110cd410", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 31, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__NullSession__f5654966.py", "order": 8, "original_content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "parent_variant_id": "pyint-512cc0777c37-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L83-L97", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 4, "readable_template_index": 2}, "unit_kind": "class", "unit_name": "NullSession", "variant_id": "pyint-b8dff5654966-I08", "group_id": "py-060f9823bc721c4c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 499, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9317c35ce0c2-I09", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass NullSession(SecureCookieSession):\n    \"\"\"Class used to generate nicer error messages if sessions are not\n    available.  Will still allow read-only access to the empty session\n    but fail on setting.\n    \"\"\"\n\n    def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n        lI0O_294b89d9 = 0xca62\n        lI0O_294b89d9 = (0 if (lI0O_294b89d9 ^ lI0O_294b89d9) == 0 else 1) if (lI0O_294b89d9 & 0) == 0 else 2\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"\n        )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-060f9823bc721c4c", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "8dbb5fbec8b77fdd51e9b9a15d7007116fcb56ff0c1814617092fec762602e73", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 29, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__NullSession__c35ce0c2.py", "order": 9, "original_content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "parent_variant_id": "pyint-512cc0777c37-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L83-L97", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 8}, "unit_kind": "class", "unit_name": "NullSession", "variant_id": "pyint-9317c35ce0c2-I09", "group_id": "py-060f9823bc721c4c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 500, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2ae0c9810baf-I10", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\nclass NullSession(SecureCookieSession):\n    \"\"\"Class used to generate nicer error messages if sessions are not\n    available.  Will still allow read-only access to the empty session\n    but fail on setting.\n    \"\"\"\n\n    def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"         )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-060f9823bc721c4c", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "a6534e037782f6cb4ef971bc2b177960dd0595d4582e8a9e064ddcf077877bd4", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 25, "local_path": "layout/partially-compact-layout/I10__flask__NullSession__c9810baf.py", "order": 10, "original_content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "parent_variant_id": "pyint-512cc0777c37-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L83-L97", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 7, "line_break_groups_removed": 2, "line_breaks_removed": 2, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "NullSession", "variant_id": "pyint-2ae0c9810baf-I10", "group_id": "py-060f9823bc721c4c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 501, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-06e76eda52e2-I11", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass NullSession(SecureCookieSession):\n    \"\"\"Class used to generate nicer error messages if sessions are not\n    available.  Will still allow read-only access to the empty session\n    but fail on setting.\n    \"\"\"\n\n    def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"\n        )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-060f9823bc721c4c", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 27, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__NullSession__6eda52e2.py", "order": 11, "original_content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "parent_variant_id": "pyint-512cc0777c37-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L83-L97", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "NullSession", "variant_id": "pyint-06e76eda52e2-I11", "group_id": "py-060f9823bc721c4c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 502, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-58985f40358a-I12", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass NullSession(SecureCookieSession):\n    \"\"\"Class used to generate nicer error messages if sessions are not\n    available.  Will still allow read-only access to the empty session\n    but fail on setting.\n    \"\"\"\n\n    def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"\n        )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-060f9823bc721c4c", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 27, "local_path": "data-flow/inline-intermediate-variables/I12__flask__NullSession__5f40358a.py", "order": 12, "original_content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "parent_variant_id": "pyint-512cc0777c37-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L83-L97", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "NullSession", "variant_id": "pyint-58985f40358a-I12", "group_id": "py-060f9823bc721c4c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 503, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-00599e188990-I13", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass NullSession(SecureCookieSession):\n    \"\"\"Class used to generate nicer error messages if sessions are not\n    available.  Will still allow read-only access to the empty session\n    but fail on setting.\n    \"\"\"\n\n    def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n        raise RuntimeError(\n            \"The session is unavailable because no secret \"\n            \"key was set.  Set the secret_key on the \"\n            \"application to something unique and secret.\"\n        )\n\n    __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n    del _fail\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-060f9823bc721c4c", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 27, "local_path": "control-flow/lower-for-to-while/I13__flask__NullSession__9e188990.py", "order": 13, "original_content_sha256": "cbc8df4af59405ac3b4ac77e8032f8c1aaa42b78da1e17b70034f83e05fec75a", "parent_variant_id": "pyint-512cc0777c37-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L83-L97", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "NullSession", "variant_id": "pyint-00599e188990-I13", "group_id": "py-060f9823bc721c4c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 504, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-778e6459b9ee-SRC", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OptionalValidator:\n    validator = attrib()\n\n    def __call__(self, inst, attr, value):\n        if value is None:\n            return\n\n        self.validator(inst, attr, value)\n\n    def __repr__(self):\n        return f\"<optional validator for {self.validator!r} or None>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-0687b2a72be52dd5", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 21, "local_path": "source-original/SRC__attrs___OptionalValidator__6459b9ee.py", "order": 0, "original_content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L202-L212", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_OptionalValidator", "variant_id": "pyint-778e6459b9ee-SRC", "group_id": "py-0687b2a72be52dd5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1079, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9414a97e403d-I01", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OptionalValidator:\n    validator = attrib()\n\n    def __call__(self, inst, attr, value):\n        if value is None:\n            return\n\n        self.validator(inst, attr, value)\n\n    def __repr__(self):\n        return f\"<optional validator for {self.validator!r} or None>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-0687b2a72be52dd5", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 21, "local_path": "comments/remove-comments/I01__attrs___OptionalValidator__a97e403d.py", "order": 1, "original_content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "parent_variant_id": "pyint-778e6459b9ee-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L202-L212", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "_OptionalValidator", "variant_id": "pyint-9414a97e403d-I01", "group_id": "py-0687b2a72be52dd5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1080, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7687d21c0e3f-I02", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OptionalValidator:\n    validator = attrib()\n\n    def __call__(self, ins, att, val):\n        if val is None:\n            return\n\n        self.validator(ins, att, val)\n\n    def __repr__(self):\n        return f\"<optional validator for {self.validator!r} or None>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-0687b2a72be52dd5", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "f161cfdedfcd8320c8fc2f6111e687cb5309628416068a86859bb99937224bdf", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 21, "local_path": "identifiers/shorten-identifiers/I02__attrs___OptionalValidator__d21c0e3f.py", "order": 2, "original_content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "parent_variant_id": "pyint-778e6459b9ee-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L202-L212", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 7, "identifiers_declared": 3}, "unit_kind": "class", "unit_name": "_OptionalValidator", "variant_id": "pyint-7687d21c0e3f-I02", "group_id": "py-0687b2a72be52dd5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1081, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-901c1a4292ff-I03", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OptionalValidator:\n    validator = attrib()\n\n    def __call__(self, date, step, total):\n        if total is None:\n            return\n\n        self.validator(date, step, total)\n\n    def __repr__(self):\n        return f\"<optional validator for {self.validator!r} or None>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-0687b2a72be52dd5", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "02e0e367e49845b3b4d5bad0016a7eab9f4c13fb788a9bf14a68233b9352bb6a", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 21, "local_path": "identifiers/mislead-identifiers/I03__attrs___OptionalValidator__1a4292ff.py", "order": 3, "original_content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "parent_variant_id": "pyint-778e6459b9ee-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L202-L212", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 7, "identifiers_declared": 3, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 3, "local_random_pool_selections": 3, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_OptionalValidator", "variant_id": "pyint-901c1a4292ff-I03", "group_id": "py-0687b2a72be52dd5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1082, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-970abc183d98-I04", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OptionalValidator:\n    validator = attrib()\n\n    def __call__(self, a, b, c):\n        if c is None:\n            return\n\n        self.validator(a, b, c)\n\n    def __repr__(self):\n        return f\"<optional validator for {self.validator!r} or None>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-0687b2a72be52dd5", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "bd1483c08b5c8495a5bd493c240a49c2e7e44a3ab379496b390ef9cc8480fa1c", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 21, "local_path": "identifiers/garble-identifiers/I04__attrs___OptionalValidator__bc183d98.py", "order": 4, "original_content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "parent_variant_id": "pyint-778e6459b9ee-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L202-L212", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 7, "identifiers_declared": 3}, "unit_kind": "class", "unit_name": "_OptionalValidator", "variant_id": "pyint-970abc183d98-I04", "group_id": "py-0687b2a72be52dd5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1083, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4aa4a313ba34-I05", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OptionalValidator:\n    validator = attrib()\n\n    def __call__(self, inst, attr, value):\n        if value is None:\n            return\n\n        self.validator(inst, attr, value)\n\n    def __repr__(self):\n        return f\"<optional validator for {self.validator!r} or None>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-0687b2a72be52dd5", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 21, "local_path": "expressions/encode-integer-literals/I05__attrs___OptionalValidator__a313ba34.py", "order": 5, "original_content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "parent_variant_id": "pyint-778e6459b9ee-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L202-L212", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "_OptionalValidator", "variant_id": "pyint-4aa4a313ba34-I05", "group_id": "py-0687b2a72be52dd5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1084, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6c182fb0b78e-I06", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OptionalValidator:\n    validator = attrib()\n\n    def __call__(self, inst, attr, value):\n        if not (value is None):\n            pass\n        else:\n            return\n\n        self.validator(inst, attr, value)\n\n    def __repr__(self):\n        return f\"<optional validator for {self.validator!r} or None>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-0687b2a72be52dd5", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "50377772961ecabcd8524310faf2ddb86bf6016726f3840a8569d7c751f749b3", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 23, "local_path": "expressions/invert-conditions/I06__attrs___OptionalValidator__2fb0b78e.py", "order": 6, "original_content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "parent_variant_id": "pyint-778e6459b9ee-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L202-L212", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "_OptionalValidator", "variant_id": "pyint-6c182fb0b78e-I06", "group_id": "py-0687b2a72be52dd5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1085, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-72965d918b11-I07", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OptionalValidator:\n    validator = attrib()\n\n    def __call__(self, inst, attr, value):\n        if ((0x75d7 ^ 0x75d7) != 0):\n            raise AssertionError()\n        if value is None:\n            return\n\n        self.validator(inst, attr, value)\n\n    def __repr__(self):\n        if ((0x5f93 ^ 0x5f93) != 0):\n            raise AssertionError()\n        return f\"<optional validator for {self.validator!r} or None>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-0687b2a72be52dd5", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "9f52c983fd5f4a73383ccab1017236877425bdf7de17840b34a90635bd22adea", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 25, "local_path": "code-injection/insert-dead-branches/I07__attrs___OptionalValidator__5d918b11.py", "order": 7, "original_content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "parent_variant_id": "pyint-778e6459b9ee-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L202-L212", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "_OptionalValidator", "variant_id": "pyint-72965d918b11-I07", "group_id": "py-0687b2a72be52dd5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1086, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9a611e086c38-I08", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OptionalValidator:\n    validator = attrib()\n\n    def __call__(self, inst, attr, value):\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        if value is None:\n            return\n\n        self.validator(inst, attr, value)\n\n    def __repr__(self):\n        return f\"<optional validator for {self.validator!r} or None>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-0687b2a72be52dd5", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "4748f4518d63a1d1e63f99e835635540aa85fce34cf3d3add688548f035951d3", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 26, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___OptionalValidator__1e086c38.py", "order": 8, "original_content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "parent_variant_id": "pyint-778e6459b9ee-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L202-L212", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "_OptionalValidator", "variant_id": "pyint-9a611e086c38-I08", "group_id": "py-0687b2a72be52dd5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1087, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-50634413a27b-I09", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OptionalValidator:\n    validator = attrib()\n\n    def __call__(self, inst, attr, value):\n        if value is None:\n            return\n\n        self.validator(inst, attr, value)\n\n    def __repr__(self):\n        lI0O_c3701a78 = 0xbece ^ 0xbece\n        if lI0O_c3701a78 == 0:\n            lI0O_c3701a78 |= 0\n        else:\n            lI0O_c3701a78 &= 0\n        return f\"<optional validator for {self.validator!r} or None>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-0687b2a72be52dd5", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "fad2f94335391e36c76022caee7c777c66aef968d2a6f52fb06e8600f133eed6", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 26, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___OptionalValidator__4413a27b.py", "order": 9, "original_content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "parent_variant_id": "pyint-778e6459b9ee-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L202-L212", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 6}, "unit_kind": "class", "unit_name": "_OptionalValidator", "variant_id": "pyint-50634413a27b-I09", "group_id": "py-0687b2a72be52dd5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1088, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-263435bf94e5-I10", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OptionalValidator:\n    validator = attrib()\n\n    def __call__(self, inst, attr, value):\n        if value is None:\n            return\n        self.validator(inst, attr, value)\n\n    def __repr__(self):\n        return f\"<optional validator for {self.validator!r} or None>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-0687b2a72be52dd5", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "512cbb3bb54db4c4906bca1c9c5b4621ea6f2dcc4636b2a821c9906012b65d52", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 20, "local_path": "layout/partially-compact-layout/I10__attrs___OptionalValidator__35bf94e5.py", "order": 10, "original_content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "parent_variant_id": "pyint-778e6459b9ee-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L202-L212", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 4, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "_OptionalValidator", "variant_id": "pyint-263435bf94e5-I10", "group_id": "py-0687b2a72be52dd5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1089, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-16f356fa18d8-I11", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OptionalValidator:\n    validator = attrib()\n\n    def __call__(self, inst, attr, value):\n        if value is None:\n            return\n\n        self.validator(inst, attr, value)\n\n    def __repr__(self):\n        return f\"<optional validator for {self.validator!r} or None>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-0687b2a72be52dd5", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 21, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___OptionalValidator__56fa18d8.py", "order": 11, "original_content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "parent_variant_id": "pyint-778e6459b9ee-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L202-L212", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "_OptionalValidator", "variant_id": "pyint-16f356fa18d8-I11", "group_id": "py-0687b2a72be52dd5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1090, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4fdef0dcce6b-I12", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OptionalValidator:\n    validator = attrib()\n\n    def __call__(self, inst, attr, value):\n        if value is None:\n            return\n\n        self.validator(inst, attr, value)\n\n    def __repr__(self):\n        return f\"<optional validator for {self.validator!r} or None>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-0687b2a72be52dd5", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 21, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___OptionalValidator__f0dcce6b.py", "order": 12, "original_content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "parent_variant_id": "pyint-778e6459b9ee-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L202-L212", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_OptionalValidator", "variant_id": "pyint-4fdef0dcce6b-I12", "group_id": "py-0687b2a72be52dd5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1091, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1b2423feccc6-I13", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OptionalValidator:\n    validator = attrib()\n\n    def __call__(self, inst, attr, value):\n        if value is None:\n            return\n\n        self.validator(inst, attr, value)\n\n    def __repr__(self):\n        return f\"<optional validator for {self.validator!r} or None>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-0687b2a72be52dd5", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 21, "local_path": "control-flow/lower-for-to-while/I13__attrs___OptionalValidator__23feccc6.py", "order": 13, "original_content_sha256": "a0a098187e92d826a946b4cebf40539a80e413ff9323620ad52be66bf518e5cd", "parent_variant_id": "pyint-778e6459b9ee-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L202-L212", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "_OptionalValidator", "variant_id": "pyint-1b2423feccc6-I13", "group_id": "py-0687b2a72be52dd5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1092, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d596f0405d89-SRC", "source": "from datetime import datetime\nfrom django.conf import settings\nfrom django.utils.crypto import constant_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\n\nclass PasswordResetTokenGenerator:\n    \"\"\"\n    Strategy object used to generate and check tokens for the password\n    reset mechanism.\n    \"\"\"\n\n    key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n    algorithm = None\n    _secret = None\n    _secret_fallbacks = None\n\n    def __init__(self):\n        self.algorithm = self.algorithm or \"sha256\"\n\n    def _get_secret(self):\n        return self._secret or settings.SECRET_KEY\n\n    def _set_secret(self, secret):\n        self._secret = secret\n\n    secret = property(_get_secret, _set_secret)\n\n    def _get_fallbacks(self):\n        if self._secret_fallbacks is None:\n            return settings.SECRET_KEY_FALLBACKS\n        return self._secret_fallbacks\n\n    def _set_fallbacks(self, fallbacks):\n        self._secret_fallbacks = fallbacks\n\n    secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n    def make_token(self, user):\n        \"\"\"\n        Return a token that can be used once to do a password reset\n        for the given user.\n        \"\"\"\n        return self._make_token_with_timestamp(\n            user,\n            self._num_seconds(self._now()),\n            self.secret,\n        )\n\n    def check_token(self, user, token):\n        \"\"\"\n        Check that a password reset token is correct for a given user.\n        \"\"\"\n        if not (user and token):\n            return False\n        # Parse the token\n        try:\n            ts_b36, _ = token.split(\"-\")\n        except ValueError:\n            return False\n\n        try:\n            ts = base36_to_int(ts_b36)\n        except ValueError:\n            return False\n\n        # Check that the timestamp/uid has not been tampered with\n        for secret in [self.secret, *self.secret_fallbacks]:\n            if constant_time_compare(\n                self._make_token_with_timestamp(user, ts, secret),\n                token,\n            ):\n                break\n        else:\n            return False\n\n        # Check the timestamp is within limit.\n        if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT:\n            return False\n\n        return True\n\n    def _make_token_with_timestamp(self, user, timestamp, secret):\n        # timestamp is number of seconds since 2001-1-1. Converted to base 36,\n        # this gives us a 6 digit string until about 2069.\n        ts_b36 = int_to_base36(timestamp)\n        hash_string = salted_hmac(\n            self.key_salt,\n            self._make_hash_value(user, timestamp),\n            secret=secret,\n            algorithm=self.algorithm,\n        ).hexdigest()[\n            ::2\n        ]  # Limit to shorten the URL.\n        return \"%s-%s\" % (ts_b36, hash_string)\n\n    def _make_hash_value(self, user, timestamp):\n        \"\"\"\n        Hash the user's primary key, email (if available), and some user state\n        that's sure to change after a password reset to produce a token that is\n        invalidated when it's used:\n        1. The password field will change upon a password reset (even if the\n           same password is chosen, due to password salting).\n        2. The last_login field will usually be updated very shortly after\n           a password reset.\n        Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually\n        invalidates the token.\n\n        Running this data through salted_hmac() prevents password cracking\n        attempts using the reset token, provided the secret isn't compromised.\n        \"\"\"\n        # Truncate microseconds so that tokens are consistent even if the\n        # database doesn't support microseconds.\n        login_timestamp = (\n            \"\"\n            if user.last_login is None\n            else user.last_login.replace(microsecond=0, tzinfo=None)\n        )\n        email_field = user.get_email_field_name()\n        email = getattr(user, email_field, \"\") or \"\"\n        return f\"{user.pk}{user.password}{login_timestamp}{timestamp}{email}\"\n\n    def _num_seconds(self, dt):\n        return int((dt - datetime(2001, 1, 1)).total_seconds())\n\n    def _now(self):\n        # Used for mocking in tests\n        return datetime.now()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-09d4d7861d58cec1", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 127, "local_path": "source-original/SRC__django__PasswordResetTokenGenerator__f0405d89.py", "order": 0, "original_content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/tokens.py#L8-L129", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "PasswordResetTokenGenerator", "variant_id": "pyint-d596f0405d89-SRC", "group_id": "py-09d4d7861d58cec1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 239, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-360af88aded6-I01", "source": "from datetime import datetime\nfrom django.conf import settings\nfrom django.utils.crypto import constant_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\n\nclass PasswordResetTokenGenerator:\n    \n\n    key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n    algorithm = None\n    _secret = None\n    _secret_fallbacks = None\n\n    def __init__(self):\n        self.algorithm = self.algorithm or \"sha256\"\n\n    def _get_secret(self):\n        return self._secret or settings.SECRET_KEY\n\n    def _set_secret(self, secret):\n        self._secret = secret\n\n    secret = property(_get_secret, _set_secret)\n\n    def _get_fallbacks(self):\n        if self._secret_fallbacks is None:\n            return settings.SECRET_KEY_FALLBACKS\n        return self._secret_fallbacks\n\n    def _set_fallbacks(self, fallbacks):\n        self._secret_fallbacks = fallbacks\n\n    secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n    def make_token(self, user):\n        \n        return self._make_token_with_timestamp(\n            user,\n            self._num_seconds(self._now()),\n            self.secret,\n        )\n\n    def check_token(self, user, token):\n        \n        if not (user and token):\n            return False\n         \n        try:\n            ts_b36, _ = token.split(\"-\")\n        except ValueError:\n            return False\n\n        try:\n            ts = base36_to_int(ts_b36)\n        except ValueError:\n            return False\n\n         \n        for secret in [self.secret, *self.secret_fallbacks]:\n            if constant_time_compare(\n                self._make_token_with_timestamp(user, ts, secret),\n                token,\n            ):\n                break\n        else:\n            return False\n\n         \n        if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT:\n            return False\n\n        return True\n\n    def _make_token_with_timestamp(self, user, timestamp, secret):\n         \n         \n        ts_b36 = int_to_base36(timestamp)\n        hash_string = salted_hmac(\n            self.key_salt,\n            self._make_hash_value(user, timestamp),\n            secret=secret,\n            algorithm=self.algorithm,\n        ).hexdigest()[\n            ::2\n        ]   \n        return \"%s-%s\" % (ts_b36, hash_string)\n\n    def _make_hash_value(self, user, timestamp):\n        \n         \n         \n        login_timestamp = (\n            \"\"\n            if user.last_login is None\n            else user.last_login.replace(microsecond=0, tzinfo=None)\n        )\n        email_field = user.get_email_field_name()\n        email = getattr(user, email_field, \"\") or \"\"\n        return f\"{user.pk}{user.password}{login_timestamp}{timestamp}{email}\"\n\n    def _num_seconds(self, dt):\n        return int((dt - datetime(2001, 1, 1)).total_seconds())\n\n    def _now(self):\n         \n        return datetime.now()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-09d4d7861d58cec1", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "0c2c0622d9c4bab674387bc7e59ab86bde5366aa07c1ea964eb41d9537758186", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 106, "local_path": "comments/remove-comments/I01__django__PasswordResetTokenGenerator__f88aded6.py", "order": 1, "original_content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "parent_variant_id": "pyint-d596f0405d89-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/tokens.py#L8-L129", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 1394, "comments_removed": 13, "docstrings_removed": 4, "line_comments_removed": 9}, "unit_kind": "class", "unit_name": "PasswordResetTokenGenerator", "variant_id": "pyint-360af88aded6-I01", "group_id": "py-09d4d7861d58cec1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 240, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3319b9ee86c0-I02", "source": "from datetime import datetime\nfrom django.conf import settings\nfrom django.utils.crypto import constant_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\n\nclass PasswordResetTokenGenerator:\n    \"\"\"\n    Strategy object used to generate and check tokens for the password\n    reset mechanism.\n    \"\"\"\n\n    key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n    algorithm = None\n    _secret = None\n    _secret_fallbacks = None\n\n    def __init__(self):\n        self.algorithm = self.algorithm or \"sha256\"\n\n    def get(self):\n        return self._secret or settings.SECRET_KEY\n\n    def set(self, sec):\n        self._secret = sec\n\n    secret = property(_get_secret, _set_secret)\n\n    def get2(self):\n        if self._secret_fallbacks is None:\n            return settings.SECRET_KEY_FALLBACKS\n        return self._secret_fallbacks\n\n    def set2(self, fal):\n        self._secret_fallbacks = fal\n\n    secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n    def make(self, use):\n        \"\"\"\n        Return a token that can be used once to do a password reset\n        for the given user.\n        \"\"\"\n        return self.make2(\n            use,\n            self.num(self.now2()),\n            self.secret,\n        )\n\n    def check(self, use2, tok):\n        \"\"\"\n        Check that a password reset token is correct for a given user.\n        \"\"\"\n        if not (use2 and tok):\n            return False\n        # Parse the token\n        try:\n            ts2, _2 = tok.split(\"-\")\n        except ValueError:\n            return False\n\n        try:\n            ts3 = base36_to_int(ts2)\n        except ValueError:\n            return False\n\n        # Check that the timestamp/uid has not been tampered with\n        for sec2 in [self.secret, *self.secret_fallbacks]:\n            if constant_time_compare(\n                self.make2(use2, ts3, sec2),\n                tok,\n            ):\n                break\n        else:\n            return False\n\n        # Check the timestamp is within limit.\n        if (self.num(self.now2()) - ts3) > settings.PASSWORD_RESET_TIMEOUT:\n            return False\n\n        return True\n\n    def make2(self, use3, tim, sec3):\n        # timestamp is number of seconds since 2001-1-1. Converted to base 36,\n        # this gives us a 6 digit string until about 2069.\n        ts4 = int_to_base36(tim)\n        hash = salted_hmac(\n            self.key_salt,\n            self.make3(use3, tim),\n            secret=sec3,\n            algorithm=self.algorithm,\n        ).hexdigest()[\n            ::2\n        ]  # Limit to shorten the URL.\n        return \"%s-%s\" % (ts4, hash)\n\n    def make3(self, use4, tim2):\n        \"\"\"\n        Hash the user's primary key, email (if available), and some user state\n        that's sure to change after a password reset to produce a token that is\n        invalidated when it's used:\n        1. The password field will change upon a password reset (even if the\n           same password is chosen, due to password salting).\n        2. The last_login field will usually be updated very shortly after\n           a password reset.\n        Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually\n        invalidates the token.\n\n        Running this data through salted_hmac() prevents password cracking\n        attempts using the reset token, provided the secret isn't compromised.\n        \"\"\"\n        # Truncate microseconds so that tokens are consistent even if the\n        # database doesn't support microseconds.\n        login = (\n            \"\"\n            if use4.last_login is None\n            else use4.last_login.replace(microsecond=0, tzinfo=None)\n        )\n        email2 = use4.get_email_field_name()\n        ema = getattr(use4, email2, \"\") or \"\"\n        return f\"{use4.pk}{use4.password}{login}{tim2}{ema}\"\n\n    def num(self, dt2):\n        return int((dt2 - datetime(2001, 1, 1)).total_seconds())\n\n    def now2(self):\n        # Used for mocking in tests\n        return datetime.now()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-09d4d7861d58cec1", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "589b33a29d44d4eb0eeedf3d3b21e19b0c83cfb4bfc0b44a6c020a7ce65f44f9", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 127, "local_path": "identifiers/shorten-identifiers/I02__django__PasswordResetTokenGenerator__b9ee86c0.py", "order": 2, "original_content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "parent_variant_id": "pyint-d596f0405d89-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/tokens.py#L8-L129", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 66, "identifiers_declared": 30}, "unit_kind": "class", "unit_name": "PasswordResetTokenGenerator", "variant_id": "pyint-3319b9ee86c0-I02", "group_id": "py-09d4d7861d58cec1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 241, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ecda7ba47f14-I03", "source": "from datetime import datetime\nfrom django.conf import settings\nfrom django.utils.crypto import constant_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\n\nclass PasswordResetTokenGenerator:\n    \"\"\"\n    Strategy object used to generate and check tokens for the password\n    reset mechanism.\n    \"\"\"\n\n    key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n    algorithm = None\n    _secret = None\n    _secret_fallbacks = None\n\n    def __init__(self):\n        self.algorithm = self.algorithm or \"sha256\"\n\n    def buildWindow(self):\n        return self._secret or settings.SECRET_KEY\n\n    def createOrder(self, buffer):\n        self._secret = buffer\n\n    secret = property(_get_secret, _set_secret)\n\n    def refreshRequest(self):\n        if self._secret_fallbacks is None:\n            return settings.SECRET_KEY_FALLBACKS\n        return self._secret_fallbacks\n\n    def refreshSession(self, nextValue):\n        self._secret_fallbacks = nextValue\n\n    secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n    def findConfig(self, data):\n        \"\"\"\n        Return a token that can be used once to do a password reset\n        for the given user.\n        \"\"\"\n        return self.validateMessage(\n            data,\n            self.validateItem(self.open()),\n            self.secret,\n        )\n\n    def sendAccount(self, mode, cache):\n        \"\"\"\n        Check that a password reset token is correct for a given user.\n        \"\"\"\n        if not (mode and cache):\n            return False\n        # Parse the token\n        try:\n            record, key = cache.split(\"-\")\n        except ValueError:\n            return False\n\n        try:\n            age = base36_to_int(record)\n        except ValueError:\n            return False\n\n        # Check that the timestamp/uid has not been tampered with\n        for client in [self.secret, *self.secret_fallbacks]:\n            if constant_time_compare(\n                self.validateMessage(mode, age, client),\n                cache,\n            ):\n                break\n        else:\n            return False\n\n        # Check the timestamp is within limit.\n        if (self.validateItem(self.open()) - age) > settings.PASSWORD_RESET_TIMEOUT:\n            return False\n\n        return True\n\n    def validateMessage(self, mode, remoteKey, config):\n        # timestamp is number of seconds since 2001-1-1. Converted to base 36,\n        # this gives us a 6 digit string until about 2069.\n        option = int_to_base36(remoteKey)\n        remoteEvent = salted_hmac(\n            self.key_salt,\n            self.validateSession(mode, remoteKey),\n            secret=config,\n            algorithm=self.algorithm,\n        ).hexdigest()[\n            ::2\n        ]  # Limit to shorten the URL.\n        return \"%s-%s\" % (option, remoteEvent)\n\n    def validateSession(self, node, remoteKey):\n        \"\"\"\n        Hash the user's primary key, email (if available), and some user state\n        that's sure to change after a password reset to produce a token that is\n        invalidated when it's used:\n        1. The password field will change upon a password reset (even if the\n           same password is chosen, due to password salting).\n        2. The last_login field will usually be updated very shortly after\n           a password reset.\n        Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually\n        invalidates the token.\n\n        Running this data through salted_hmac() prevents password cracking\n        attempts using the reset token, provided the secret isn't compromised.\n        \"\"\"\n        # Truncate microseconds so that tokens are consistent even if the\n        # database doesn't support microseconds.\n        pendingMessage = (\n            \"\"\n            if node.last_login is None\n            else node.last_login.replace(microsecond=0, tzinfo=None)\n        )\n        cachedScore = node.get_email_field_name()\n        state = getattr(node, cachedScore, \"\") or \"\"\n        return f\"{node.pk}{node.password}{pendingMessage}{remoteKey}{state}\"\n\n    def validateItem(self, age):\n        return int((age - datetime(2001, 1, 1)).total_seconds())\n\n    def open(self):\n        # Used for mocking in tests\n        return datetime.now()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-09d4d7861d58cec1", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "ef3dfe0f5409f0c8a44d318f33bb3242deb190c87bb01d25493af9f85b1b719e", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 127, "local_path": "identifiers/mislead-identifiers/I03__django__PasswordResetTokenGenerator__7ba47f14.py", "order": 3, "original_content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "parent_variant_id": "pyint-d596f0405d89-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/tokens.py#L8-L129", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 66, "identifiers_declared": 30, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 16, "local_random_pool_selections": 20, "local_total_length_difference": 5, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 8, "method_random_pool_selections": 10, "method_total_length_difference": 12}, "unit_kind": "class", "unit_name": "PasswordResetTokenGenerator", "variant_id": "pyint-ecda7ba47f14-I03", "group_id": "py-09d4d7861d58cec1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 242, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b434f1b28fa3-I04", "source": "from datetime import datetime\nfrom django.conf import settings\nfrom django.utils.crypto import constant_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\n\nclass PasswordResetTokenGenerator:\n    \"\"\"\n    Strategy object used to generate and check tokens for the password\n    reset mechanism.\n    \"\"\"\n\n    key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n    algorithm = None\n    _secret = None\n    _secret_fallbacks = None\n\n    def __init__(self):\n        self.algorithm = self.algorithm or \"sha256\"\n\n    def a(self):\n        return self._secret or settings.SECRET_KEY\n\n    def b(self, k):\n        self._secret = k\n\n    secret = property(_get_secret, _set_secret)\n\n    def c(self):\n        if self._secret_fallbacks is None:\n            return settings.SECRET_KEY_FALLBACKS\n        return self._secret_fallbacks\n\n    def d(self, l):\n        self._secret_fallbacks = l\n\n    secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n    def e(self, m):\n        \"\"\"\n        Return a token that can be used once to do a password reset\n        for the given user.\n        \"\"\"\n        return self.g(\n            m,\n            self.i(self.j()),\n            self.secret,\n        )\n\n    def f(self, n, o):\n        \"\"\"\n        Check that a password reset token is correct for a given user.\n        \"\"\"\n        if not (n and o):\n            return False\n        # Parse the token\n        try:\n            p, q = o.split(\"-\")\n        except ValueError:\n            return False\n\n        try:\n            r = base36_to_int(p)\n        except ValueError:\n            return False\n\n        # Check that the timestamp/uid has not been tampered with\n        for s in [self.secret, *self.secret_fallbacks]:\n            if constant_time_compare(\n                self.g(n, r, s),\n                o,\n            ):\n                break\n        else:\n            return False\n\n        # Check the timestamp is within limit.\n        if (self.i(self.j()) - r) > settings.PASSWORD_RESET_TIMEOUT:\n            return False\n\n        return True\n\n    def g(self, t, u, v):\n        # timestamp is number of seconds since 2001-1-1. Converted to base 36,\n        # this gives us a 6 digit string until about 2069.\n        w = int_to_base36(u)\n        x = salted_hmac(\n            self.key_salt,\n            self.h(t, u),\n            secret=v,\n            algorithm=self.algorithm,\n        ).hexdigest()[\n            ::2\n        ]  # Limit to shorten the URL.\n        return \"%s-%s\" % (w, x)\n\n    def h(self, y, z):\n        \"\"\"\n        Hash the user's primary key, email (if available), and some user state\n        that's sure to change after a password reset to produce a token that is\n        invalidated when it's used:\n        1. The password field will change upon a password reset (even if the\n           same password is chosen, due to password salting).\n        2. The last_login field will usually be updated very shortly after\n           a password reset.\n        Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually\n        invalidates the token.\n\n        Running this data through salted_hmac() prevents password cracking\n        attempts using the reset token, provided the secret isn't compromised.\n        \"\"\"\n        # Truncate microseconds so that tokens are consistent even if the\n        # database doesn't support microseconds.\n        A = (\n            \"\"\n            if y.last_login is None\n            else y.last_login.replace(microsecond=0, tzinfo=None)\n        )\n        B = y.get_email_field_name()\n        C = getattr(y, B, \"\") or \"\"\n        return f\"{y.pk}{y.password}{A}{z}{C}\"\n\n    def i(self, D):\n        return int((D - datetime(2001, 1, 1)).total_seconds())\n\n    def j(self):\n        # Used for mocking in tests\n        return datetime.now()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-09d4d7861d58cec1", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "f6c709ae5db02ac81eb7cdcb3c73d7e980b0279af4cd2e1dc1fa1a4e8a91d367", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 127, "local_path": "identifiers/garble-identifiers/I04__django__PasswordResetTokenGenerator__f1b28fa3.py", "order": 4, "original_content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "parent_variant_id": "pyint-d596f0405d89-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/tokens.py#L8-L129", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 66, "identifiers_declared": 30}, "unit_kind": "class", "unit_name": "PasswordResetTokenGenerator", "variant_id": "pyint-b434f1b28fa3-I04", "group_id": "py-09d4d7861d58cec1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 243, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d916faee63f1-I05", "source": "from datetime import datetime\nfrom django.conf import settings\nfrom django.utils.crypto import constant_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\n\nclass PasswordResetTokenGenerator:\n    \"\"\"\n    Strategy object used to generate and check tokens for the password\n    reset mechanism.\n    \"\"\"\n\n    key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n    algorithm = None\n    _secret = None\n    _secret_fallbacks = None\n\n    def __init__(self):\n        self.algorithm = self.algorithm or \"sha256\"\n\n    def _get_secret(self):\n        return self._secret or settings.SECRET_KEY\n\n    def _set_secret(self, secret):\n        self._secret = secret\n\n    secret = property(_get_secret, _set_secret)\n\n    def _get_fallbacks(self):\n        if self._secret_fallbacks is None:\n            return settings.SECRET_KEY_FALLBACKS\n        return self._secret_fallbacks\n\n    def _set_fallbacks(self, fallbacks):\n        self._secret_fallbacks = fallbacks\n\n    secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n    def make_token(self, user):\n        \"\"\"\n        Return a token that can be used once to do a password reset\n        for the given user.\n        \"\"\"\n        return self._make_token_with_timestamp(\n            user,\n            self._num_seconds(self._now()),\n            self.secret,\n        )\n\n    def check_token(self, user, token):\n        \"\"\"\n        Check that a password reset token is correct for a given user.\n        \"\"\"\n        if not (user and token):\n            return False\n        # Parse the token\n        try:\n            ts_b36, _ = token.split(\"-\")\n        except ValueError:\n            return False\n\n        try:\n            ts = base36_to_int(ts_b36)\n        except ValueError:\n            return False\n\n        # Check that the timestamp/uid has not been tampered with\n        for secret in [self.secret, *self.secret_fallbacks]:\n            if constant_time_compare(\n                self._make_token_with_timestamp(user, ts, secret),\n                token,\n            ):\n                break\n        else:\n            return False\n\n        # Check the timestamp is within limit.\n        if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT:\n            return False\n\n        return True\n\n    def _make_token_with_timestamp(self, user, timestamp, secret):\n        # timestamp is number of seconds since 2001-1-1. Converted to base 36,\n        # this gives us a 6 digit string until about 2069.\n        ts_b36 = int_to_base36(timestamp)\n        hash_string = salted_hmac(\n            self.key_salt,\n            self._make_hash_value(user, timestamp),\n            secret=secret,\n            algorithm=self.algorithm,\n        ).hexdigest()[\n            ::0x2\n        ]  # Limit to shorten the URL.\n        return \"%s-%s\" % (ts_b36, hash_string)\n\n    def _make_hash_value(self, user, timestamp):\n        \"\"\"\n        Hash the user's primary key, email (if available), and some user state\n        that's sure to change after a password reset to produce a token that is\n        invalidated when it's used:\n        1. The password field will change upon a password reset (even if the\n           same password is chosen, due to password salting).\n        2. The last_login field will usually be updated very shortly after\n           a password reset.\n        Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually\n        invalidates the token.\n\n        Running this data through salted_hmac() prevents password cracking\n        attempts using the reset token, provided the secret isn't compromised.\n        \"\"\"\n        # Truncate microseconds so that tokens are consistent even if the\n        # database doesn't support microseconds.\n        login_timestamp = (\n            \"\"\n            if user.last_login is None\n            else user.last_login.replace(microsecond=0x0, tzinfo=None)\n        )\n        email_field = user.get_email_field_name()\n        email = getattr(user, email_field, \"\") or \"\"\n        return f\"{user.pk}{user.password}{login_timestamp}{timestamp}{email}\"\n\n    def _num_seconds(self, dt):\n        return int((dt - datetime(0x7d1, 0x1, 0x1)).total_seconds())\n\n    def _now(self):\n        # Used for mocking in tests\n        return datetime.now()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-09d4d7861d58cec1", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "7ed2956b43a71c35e2ba7296f4543cbc1cfbb7c1d74337a559c3b7965380e6ae", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 127, "local_path": "expressions/encode-integer-literals/I05__django__PasswordResetTokenGenerator__faee63f1.py", "order": 5, "original_content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "parent_variant_id": "pyint-d596f0405d89-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/tokens.py#L8-L129", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 5}, "unit_kind": "class", "unit_name": "PasswordResetTokenGenerator", "variant_id": "pyint-d916faee63f1-I05", "group_id": "py-09d4d7861d58cec1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 244, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8c144b9b1dd8-I06", "source": "from datetime import datetime\nfrom django.conf import settings\nfrom django.utils.crypto import constant_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\n\nclass PasswordResetTokenGenerator:\n    \"\"\"\n    Strategy object used to generate and check tokens for the password\n    reset mechanism.\n    \"\"\"\n\n    key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n    algorithm = None\n    _secret = None\n    _secret_fallbacks = None\n\n    def __init__(self):\n        self.algorithm = self.algorithm or \"sha256\"\n\n    def _get_secret(self):\n        return self._secret or settings.SECRET_KEY\n\n    def _set_secret(self, secret):\n        self._secret = secret\n\n    secret = property(_get_secret, _set_secret)\n\n    def _get_fallbacks(self):\n        if not (self._secret_fallbacks is None):\n            pass\n        else:\n            return settings.SECRET_KEY_FALLBACKS\n        return self._secret_fallbacks\n\n    def _set_fallbacks(self, fallbacks):\n        self._secret_fallbacks = fallbacks\n\n    secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n    def make_token(self, user):\n        \"\"\"\n        Return a token that can be used once to do a password reset\n        for the given user.\n        \"\"\"\n        return self._make_token_with_timestamp(\n            user,\n            self._num_seconds(self._now()),\n            self.secret,\n        )\n\n    def check_token(self, user, token):\n        \"\"\"\n        Check that a password reset token is correct for a given user.\n        \"\"\"\n        if not (not (user and token)):\n            pass\n        else:\n            return False\n        # Parse the token\n        try:\n            ts_b36, _ = token.split(\"-\")\n        except ValueError:\n            return False\n\n        try:\n            ts = base36_to_int(ts_b36)\n        except ValueError:\n            return False\n\n        # Check that the timestamp/uid has not been tampered with\n        for secret in [self.secret, *self.secret_fallbacks]:\n            if constant_time_compare(\n                self._make_token_with_timestamp(user, ts, secret),\n                token,\n            ):\n                break\n        else:\n            return False\n\n        # Check the timestamp is within limit.\n        if not ((self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT):\n            pass\n        else:\n            return False\n\n        return True\n\n    def _make_token_with_timestamp(self, user, timestamp, secret):\n        # timestamp is number of seconds since 2001-1-1. Converted to base 36,\n        # this gives us a 6 digit string until about 2069.\n        ts_b36 = int_to_base36(timestamp)\n        hash_string = salted_hmac(\n            self.key_salt,\n            self._make_hash_value(user, timestamp),\n            secret=secret,\n            algorithm=self.algorithm,\n        ).hexdigest()[\n            ::2\n        ]  # Limit to shorten the URL.\n        return \"%s-%s\" % (ts_b36, hash_string)\n\n    def _make_hash_value(self, user, timestamp):\n        \"\"\"\n        Hash the user's primary key, email (if available), and some user state\n        that's sure to change after a password reset to produce a token that is\n        invalidated when it's used:\n        1. The password field will change upon a password reset (even if the\n           same password is chosen, due to password salting).\n        2. The last_login field will usually be updated very shortly after\n           a password reset.\n        Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually\n        invalidates the token.\n\n        Running this data through salted_hmac() prevents password cracking\n        attempts using the reset token, provided the secret isn't compromised.\n        \"\"\"\n        # Truncate microseconds so that tokens are consistent even if the\n        # database doesn't support microseconds.\n        login_timestamp = (\n            \"\"\n            if user.last_login is None\n            else user.last_login.replace(microsecond=0, tzinfo=None)\n        )\n        email_field = user.get_email_field_name()\n        email = getattr(user, email_field, \"\") or \"\"\n        return f\"{user.pk}{user.password}{login_timestamp}{timestamp}{email}\"\n\n    def _num_seconds(self, dt):\n        return int((dt - datetime(2001, 1, 1)).total_seconds())\n\n    def _now(self):\n        # Used for mocking in tests\n        return datetime.now()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-09d4d7861d58cec1", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "873b0b8a0caf2da80d1fadf01e884808d74b457f740680649de989f4d3c907ef", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 133, "local_path": "expressions/invert-conditions/I06__django__PasswordResetTokenGenerator__4b9b1dd8.py", "order": 6, "original_content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "parent_variant_id": "pyint-d596f0405d89-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/tokens.py#L8-L129", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 3}, "unit_kind": "class", "unit_name": "PasswordResetTokenGenerator", "variant_id": "pyint-8c144b9b1dd8-I06", "group_id": "py-09d4d7861d58cec1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 245, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c7c166acb0a7-I07", "source": "from datetime import datetime\nfrom django.conf import settings\nfrom django.utils.crypto import constant_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\n\nclass PasswordResetTokenGenerator:\n    \"\"\"\n    Strategy object used to generate and check tokens for the password\n    reset mechanism.\n    \"\"\"\n\n    key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n    algorithm = None\n    _secret = None\n    _secret_fallbacks = None\n\n    def __init__(self):\n        if ((0x91ef ^ 0x91ef) != 0):\n            raise AssertionError()\n        self.algorithm = self.algorithm or \"sha256\"\n\n    def _get_secret(self):\n        if ((0xa647 ^ 0xa647) != 0):\n            raise AssertionError()\n        return self._secret or settings.SECRET_KEY\n\n    def _set_secret(self, secret):\n        if ((0xb433 ^ 0xb433) != 0):\n            raise AssertionError()\n        self._secret = secret\n\n    secret = property(_get_secret, _set_secret)\n\n    def _get_fallbacks(self):\n        if ((0x4c36 ^ 0x4c36) != 0):\n            raise AssertionError()\n        if self._secret_fallbacks is None:\n            return settings.SECRET_KEY_FALLBACKS\n        return self._secret_fallbacks\n\n    def _set_fallbacks(self, fallbacks):\n        if ((0xa100 ^ 0xa100) != 0):\n            raise AssertionError()\n        self._secret_fallbacks = fallbacks\n\n    secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n    def make_token(self, user):\n        \"\"\"\n        Return a token that can be used once to do a password reset\n        for the given user.\n        \"\"\"\n        if ((0x8927 ^ 0x8927) != 0):\n            raise AssertionError()\n        return self._make_token_with_timestamp(\n            user,\n            self._num_seconds(self._now()),\n            self.secret,\n        )\n\n    def check_token(self, user, token):\n        \"\"\"\n        Check that a password reset token is correct for a given user.\n        \"\"\"\n        if ((0xcb69 ^ 0xcb69) != 0):\n            raise AssertionError()\n        if not (user and token):\n            return False\n        # Parse the token\n        try:\n            ts_b36, _ = token.split(\"-\")\n        except ValueError:\n            return False\n\n        try:\n            ts = base36_to_int(ts_b36)\n        except ValueError:\n            return False\n\n        # Check that the timestamp/uid has not been tampered with\n        for secret in [self.secret, *self.secret_fallbacks]:\n            if constant_time_compare(\n                self._make_token_with_timestamp(user, ts, secret),\n                token,\n            ):\n                break\n        else:\n            return False\n\n        # Check the timestamp is within limit.\n        if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT:\n            return False\n\n        return True\n\n    def _make_token_with_timestamp(self, user, timestamp, secret):\n        # timestamp is number of seconds since 2001-1-1. Converted to base 36,\n        # this gives us a 6 digit string until about 2069.\n        if ((0x93f2 ^ 0x93f2) != 0):\n            raise AssertionError()\n        ts_b36 = int_to_base36(timestamp)\n        hash_string = salted_hmac(\n            self.key_salt,\n            self._make_hash_value(user, timestamp),\n            secret=secret,\n            algorithm=self.algorithm,\n        ).hexdigest()[\n            ::2\n        ]  # Limit to shorten the URL.\n        return \"%s-%s\" % (ts_b36, hash_string)\n\n    def _make_hash_value(self, user, timestamp):\n        \"\"\"\n        Hash the user's primary key, email (if available), and some user state\n        that's sure to change after a password reset to produce a token that is\n        invalidated when it's used:\n        1. The password field will change upon a password reset (even if the\n           same password is chosen, due to password salting).\n        2. The last_login field will usually be updated very shortly after\n           a password reset.\n        Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually\n        invalidates the token.\n\n        Running this data through salted_hmac() prevents password cracking\n        attempts using the reset token, provided the secret isn't compromised.\n        \"\"\"\n        if ((0xac6b ^ 0xac6b) != 0):\n            raise AssertionError()\n        # Truncate microseconds so that tokens are consistent even if the\n        # database doesn't support microseconds.\n        login_timestamp = (\n            \"\"\n            if user.last_login is None\n            else user.last_login.replace(microsecond=0, tzinfo=None)\n        )\n        email_field = user.get_email_field_name()\n        email = getattr(user, email_field, \"\") or \"\"\n        return f\"{user.pk}{user.password}{login_timestamp}{timestamp}{email}\"\n\n    def _num_seconds(self, dt):\n        if ((0xe236 ^ 0xe236) != 0):\n            raise AssertionError()\n        return int((dt - datetime(2001, 1, 1)).total_seconds())\n\n    def _now(self):\n        # Used for mocking in tests\n        if ((0xc075 ^ 0xc075) != 0):\n            raise AssertionError()\n        return datetime.now()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-09d4d7861d58cec1", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "1c8da5bbaf27569571582e10e1b96622f385b01226a1f0db7c3b22fa7f590211", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 149, "local_path": "code-injection/insert-dead-branches/I07__django__PasswordResetTokenGenerator__66acb0a7.py", "order": 7, "original_content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "parent_variant_id": "pyint-d596f0405d89-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/tokens.py#L8-L129", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 11}, "unit_kind": "class", "unit_name": "PasswordResetTokenGenerator", "variant_id": "pyint-c7c166acb0a7-I07", "group_id": "py-09d4d7861d58cec1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 246, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d814941d8628-I08", "source": "from datetime import datetime\nfrom django.conf import settings\nfrom django.utils.crypto import constant_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\n\nclass PasswordResetTokenGenerator:\n    \"\"\"\n    Strategy object used to generate and check tokens for the password\n    reset mechanism.\n    \"\"\"\n\n    key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n    algorithm = None\n    _secret = None\n    _secret_fallbacks = None\n\n    def __init__(self):\n        factorial = 1\n        for current_factor in range(2, 5):\n            factorial *= current_factor\n        self.algorithm = self.algorithm or \"sha256\"\n\n    def _get_secret(self):\n        return self._secret or settings.SECRET_KEY\n\n    def _set_secret(self, secret):\n        self._secret = secret\n\n    secret = property(_get_secret, _set_secret)\n\n    def _get_fallbacks(self):\n        if self._secret_fallbacks is None:\n            return settings.SECRET_KEY_FALLBACKS\n        return self._secret_fallbacks\n\n    def _set_fallbacks(self, fallbacks):\n        self._secret_fallbacks = fallbacks\n\n    secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n    def make_token(self, user):\n        \"\"\"\n        Return a token that can be used once to do a password reset\n        for the given user.\n        \"\"\"\n        return self._make_token_with_timestamp(\n            user,\n            self._num_seconds(self._now()),\n            self.secret,\n        )\n\n    def check_token(self, user, token):\n        \"\"\"\n        Check that a password reset token is correct for a given user.\n        \"\"\"\n        if not (user and token):\n            return False\n        # Parse the token\n        try:\n            ts_b36, _ = token.split(\"-\")\n        except ValueError:\n            return False\n\n        try:\n            ts = base36_to_int(ts_b36)\n        except ValueError:\n            return False\n\n        # Check that the timestamp/uid has not been tampered with\n        for secret in [self.secret, *self.secret_fallbacks]:\n            if constant_time_compare(\n                self._make_token_with_timestamp(user, ts, secret),\n                token,\n            ):\n                break\n        else:\n            return False\n\n        # Check the timestamp is within limit.\n        if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT:\n            return False\n\n        return True\n\n    def _make_token_with_timestamp(self, user, timestamp, secret):\n        # timestamp is number of seconds since 2001-1-1. Converted to base 36,\n        # this gives us a 6 digit string until about 2069.\n        ts_b36 = int_to_base36(timestamp)\n        hash_string = salted_hmac(\n            self.key_salt,\n            self._make_hash_value(user, timestamp),\n            secret=secret,\n            algorithm=self.algorithm,\n        ).hexdigest()[\n            ::2\n        ]  # Limit to shorten the URL.\n        return \"%s-%s\" % (ts_b36, hash_string)\n\n    def _make_hash_value(self, user, timestamp):\n        \"\"\"\n        Hash the user's primary key, email (if available), and some user state\n        that's sure to change after a password reset to produce a token that is\n        invalidated when it's used:\n        1. The password field will change upon a password reset (even if the\n           same password is chosen, due to password salting).\n        2. The last_login field will usually be updated very shortly after\n           a password reset.\n        Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually\n        invalidates the token.\n\n        Running this data through salted_hmac() prevents password cracking\n        attempts using the reset token, provided the secret isn't compromised.\n        \"\"\"\n        # Truncate microseconds so that tokens are consistent even if the\n        # database doesn't support microseconds.\n        login_timestamp = (\n            \"\"\n            if user.last_login is None\n            else user.last_login.replace(microsecond=0, tzinfo=None)\n        )\n        email_field = user.get_email_field_name()\n        email = getattr(user, email_field, \"\") or \"\"\n        return f\"{user.pk}{user.password}{login_timestamp}{timestamp}{email}\"\n\n    def _num_seconds(self, dt):\n        return int((dt - datetime(2001, 1, 1)).total_seconds())\n\n    def _now(self):\n        # Used for mocking in tests\n        return datetime.now()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-09d4d7861d58cec1", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "743e4a4687edb1358187e3ad962cc8ab7519da4581475eb3995a6364f9e86ed6", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 130, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__PasswordResetTokenGenerator__941d8628.py", "order": 8, "original_content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "parent_variant_id": "pyint-d596f0405d89-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/tokens.py#L8-L129", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 6}, "unit_kind": "class", "unit_name": "PasswordResetTokenGenerator", "variant_id": "pyint-d814941d8628-I08", "group_id": "py-09d4d7861d58cec1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 247, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8a61fd33005a-I09", "source": "from datetime import datetime\nfrom django.conf import settings\nfrom django.utils.crypto import constant_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\n\nclass PasswordResetTokenGenerator:\n    \"\"\"\n    Strategy object used to generate and check tokens for the password\n    reset mechanism.\n    \"\"\"\n\n    key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n    algorithm = None\n    _secret = None\n    _secret_fallbacks = None\n\n    def __init__(self):\n        self.algorithm = self.algorithm or \"sha256\"\n\n    def _get_secret(self):\n        return self._secret or settings.SECRET_KEY\n\n    def _set_secret(self, secret):\n        lI0O_1e0ea428 = 0xaf07 ^ 0xaf07\n        if lI0O_1e0ea428 != 0:\n            if ((lI0O_1e0ea428 | 1) & 1) == 0:\n                lI0O_1e0ea428 += 1\n            else:\n                lI0O_1e0ea428 -= 1\n        self._secret = secret\n\n    secret = property(_get_secret, _set_secret)\n\n    def _get_fallbacks(self):\n        if self._secret_fallbacks is None:\n            return settings.SECRET_KEY_FALLBACKS\n        return self._secret_fallbacks\n\n    def _set_fallbacks(self, fallbacks):\n        self._secret_fallbacks = fallbacks\n\n    secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n    def make_token(self, user):\n        \"\"\"\n        Return a token that can be used once to do a password reset\n        for the given user.\n        \"\"\"\n        return self._make_token_with_timestamp(\n            user,\n            self._num_seconds(self._now()),\n            self.secret,\n        )\n\n    def check_token(self, user, token):\n        \"\"\"\n        Check that a password reset token is correct for a given user.\n        \"\"\"\n        if not (user and token):\n            return False\n        # Parse the token\n        try:\n            ts_b36, _ = token.split(\"-\")\n        except ValueError:\n            return False\n\n        try:\n            ts = base36_to_int(ts_b36)\n        except ValueError:\n            return False\n\n        # Check that the timestamp/uid has not been tampered with\n        for secret in [self.secret, *self.secret_fallbacks]:\n            if constant_time_compare(\n                self._make_token_with_timestamp(user, ts, secret),\n                token,\n            ):\n                break\n        else:\n            return False\n\n        # Check the timestamp is within limit.\n        if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT:\n            return False\n\n        return True\n\n    def _make_token_with_timestamp(self, user, timestamp, secret):\n        # timestamp is number of seconds since 2001-1-1. Converted to base 36,\n        # this gives us a 6 digit string until about 2069.\n        ts_b36 = int_to_base36(timestamp)\n        hash_string = salted_hmac(\n            self.key_salt,\n            self._make_hash_value(user, timestamp),\n            secret=secret,\n            algorithm=self.algorithm,\n        ).hexdigest()[\n            ::2\n        ]  # Limit to shorten the URL.\n        return \"%s-%s\" % (ts_b36, hash_string)\n\n    def _make_hash_value(self, user, timestamp):\n        \"\"\"\n        Hash the user's primary key, email (if available), and some user state\n        that's sure to change after a password reset to produce a token that is\n        invalidated when it's used:\n        1. The password field will change upon a password reset (even if the\n           same password is chosen, due to password salting).\n        2. The last_login field will usually be updated very shortly after\n           a password reset.\n        Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually\n        invalidates the token.\n\n        Running this data through salted_hmac() prevents password cracking\n        attempts using the reset token, provided the secret isn't compromised.\n        \"\"\"\n        # Truncate microseconds so that tokens are consistent even if the\n        # database doesn't support microseconds.\n        login_timestamp = (\n            \"\"\n            if user.last_login is None\n            else user.last_login.replace(microsecond=0, tzinfo=None)\n        )\n        email_field = user.get_email_field_name()\n        email = getattr(user, email_field, \"\") or \"\"\n        return f\"{user.pk}{user.password}{login_timestamp}{timestamp}{email}\"\n\n    def _num_seconds(self, dt):\n        return int((dt - datetime(2001, 1, 1)).total_seconds())\n\n    def _now(self):\n        # Used for mocking in tests\n        return datetime.now()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-09d4d7861d58cec1", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "fa4769b90ada28a364ed67d22df2c3a435e4f8effad9bf263049026f8da5ab6b", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 133, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__PasswordResetTokenGenerator__fd33005a.py", "order": 9, "original_content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "parent_variant_id": "pyint-d596f0405d89-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/tokens.py#L8-L129", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 5}, "unit_kind": "class", "unit_name": "PasswordResetTokenGenerator", "variant_id": "pyint-8a61fd33005a-I09", "group_id": "py-09d4d7861d58cec1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 248, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a65d95876168-I10", "source": "from datetime import datetime\nfrom django.conf import settings\nfrom django.utils.crypto import constant_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\nclass PasswordResetTokenGenerator:\n    \"\"\"\n    Strategy object used to generate and check tokens for the password\n    reset mechanism.\n    \"\"\"\n\n    key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n    algorithm = None\n    _secret = None\n    _secret_fallbacks = None\n\n    def __init__(self):\n        self.algorithm = self.algorithm or \"sha256\"\n    def _get_secret(self):\n        return self._secret or settings.SECRET_KEY\n\n    def _set_secret(self, secret):\n        self._secret = secret\n    secret = property(_get_secret, _set_secret)\n\n    def _get_fallbacks(self):\n        if self._secret_fallbacks is None:\n            return settings.SECRET_KEY_FALLBACKS\n        return self._secret_fallbacks\n    def _set_fallbacks(self, fallbacks):\n        self._secret_fallbacks = fallbacks\n    secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n    def make_token(self, user):\n        \"\"\"\n        Return a token that can be used once to do a password reset\n        for the given user.\n        \"\"\"\n        return self._make_token_with_timestamp(\n            user,\n            self._num_seconds(self._now()),\n            self.secret,\n        )\n\n    def check_token(self, user, token):\n        \"\"\"\n        Check that a password reset token is correct for a given user.\n        \"\"\"\n        if not (user and token):\n            return False\n        # Parse the token\n        try:\n            ts_b36, _ = token.split(\"-\")\n        except ValueError:\n            return False\n\n        try:\n            ts = base36_to_int(ts_b36)\n        except ValueError:\n            return False\n\n        # Check that the timestamp/uid has not been tampered with\n        for secret in [self.secret, *self.secret_fallbacks]:\n            if constant_time_compare(\n                self._make_token_with_timestamp(user, ts, secret),\n                token,\n            ):\n                break\n        else:\n            return False\n        # Check the timestamp is within limit.\n        if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT:\n            return False\n\n        return True\n    def _make_token_with_timestamp(self, user, timestamp, secret):\n        # timestamp is number of seconds since 2001-1-1. Converted to base 36,\n        # this gives us a 6 digit string until about 2069.\n        ts_b36 = int_to_base36(timestamp)\n        hash_string = salted_hmac(             self.key_salt,             self._make_hash_value(user, timestamp),\n            secret=secret,             algorithm=self.algorithm,\n        ).hexdigest()[\n            ::2\n        ]  # Limit to shorten the URL.\n        return \"%s-%s\" % (ts_b36, hash_string)\n\n    def _make_hash_value(self, user, timestamp):\n        \"\"\"\n        Hash the user's primary key, email (if available), and some user state\n        that's sure to change after a password reset to produce a token that is\n        invalidated when it's used:\n        1. The password field will change upon a password reset (even if the\n           same password is chosen, due to password salting).\n        2. The last_login field will usually be updated very shortly after\n           a password reset.\n        Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually\n        invalidates the token.\n        Running this data through salted_hmac() prevents password cracking\n        attempts using the reset token, provided the secret isn't compromised.\n        \"\"\"\n        # Truncate microseconds so that tokens are consistent even if the\n        # database doesn't support microseconds.\n        login_timestamp = (\n            \"\"\n            if user.last_login is None             else user.last_login.replace(microsecond=0, tzinfo=None)         )\n        email_field = user.get_email_field_name()\n        email = getattr(user, email_field, \"\") or \"\"\n        return f\"{user.pk}{user.password}{login_timestamp}{timestamp}{email}\"\n    def _num_seconds(self, dt):\n        return int((dt - datetime(2001, 1, 1)).total_seconds())\n    def _now(self):\n        # Used for mocking in tests\n        return datetime.now()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-09d4d7861d58cec1", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "b4e7374fc2be2cd0e2ee24667fa885ec156cd3c3817683b03cde8f4b8f9ab23a", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 112, "local_path": "layout/partially-compact-layout/I10__django__PasswordResetTokenGenerator__95876168.py", "order": 10, "original_content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "parent_variant_id": "pyint-d596f0405d89-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/tokens.py#L8-L129", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 38, "line_break_groups_removed": 15, "line_breaks_removed": 15, "whitespace_characters_removed": 10}, "unit_kind": "class", "unit_name": "PasswordResetTokenGenerator", "variant_id": "pyint-a65d95876168-I10", "group_id": "py-09d4d7861d58cec1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 249, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-15f1799a6069-I11", "source": "from datetime import datetime\nfrom django.conf import settings\nfrom django.utils.crypto import constant_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\n\nclass PasswordResetTokenGenerator:\n    \"\"\"\n    Strategy object used to generate and check tokens for the password\n    reset mechanism.\n    \"\"\"\n\n    key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n    algorithm = None\n    _secret = None\n    _secret_fallbacks = None\n\n    def __init__(self):\n        self.algorithm = self.algorithm or \"sha256\"\n\n    def _get_secret(self):\n        return self._secret or settings.SECRET_KEY\n\n    def _set_secret(self, secret):\n        self._secret = secret\n\n    secret = property(_get_secret, _set_secret)\n\n    def _get_fallbacks(self):\n        if self._secret_fallbacks is None:\n            return settings.SECRET_KEY_FALLBACKS\n        return self._secret_fallbacks\n\n    def _set_fallbacks(self, fallbacks):\n        self._secret_fallbacks = fallbacks\n\n    secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n    def make_token(self, user):\n        \"\"\"\n        Return a token that can be used once to do a password reset\n        for the given user.\n        \"\"\"\n        return self._make_token_with_timestamp(\n            user,\n            self._num_seconds(self._now()),\n            self.secret,\n        )\n\n    def check_token(self, user, token):\n        \"\"\"\n        Check that a password reset token is correct for a given user.\n        \"\"\"\n        if not (user and token):\n            return False\n        # Parse the token\n        try:\n            ts_b36, _ = token.split(\"-\")\n        except ValueError:\n            return False\n\n        try:\n            ts = base36_to_int(ts_b36)\n        except ValueError:\n            return False\n\n        # Check that the timestamp/uid has not been tampered with\n        for secret in [self.secret, *self.secret_fallbacks]:\n            if constant_time_compare(\n                self._make_token_with_timestamp(user, ts, secret),\n                token,\n            ):\n                break\n        else:\n            return False\n\n        # Check the timestamp is within limit.\n        if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT:\n            return False\n\n        return True\n\n    def _make_token_with_timestamp(self, user, timestamp, secret):\n        # timestamp is number of seconds since 2001-1-1. Converted to base 36,\n        # this gives us a 6 digit string until about 2069.\n        ts_b36 = int_to_base36(timestamp)\n        a = 1\n        b = 1\n        hash_string = salted_hmac(\n            self.key_salt,\n            self._make_hash_value(user, timestamp),\n            secret=secret,\n            algorithm=self.algorithm,\n        ).hexdigest()[\n            ::(a + b)\n        ]  # Limit to shorten the URL.\n        return \"%s-%s\" % (ts_b36, hash_string)\n\n    def _make_hash_value(self, user, timestamp):\n        \"\"\"\n        Hash the user's primary key, email (if available), and some user state\n        that's sure to change after a password reset to produce a token that is\n        invalidated when it's used:\n        1. The password field will change upon a password reset (even if the\n           same password is chosen, due to password salting).\n        2. The last_login field will usually be updated very shortly after\n           a password reset.\n        Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually\n        invalidates the token.\n\n        Running this data through salted_hmac() prevents password cracking\n        attempts using the reset token, provided the secret isn't compromised.\n        \"\"\"\n        # Truncate microseconds so that tokens are consistent even if the\n        # database doesn't support microseconds.\n        c = 1\n        d = -1\n        login_timestamp = (\n            \"\"\n            if user.last_login is None\n            else user.last_login.replace(microsecond=(c + d), tzinfo=None)\n        )\n        email_field = user.get_email_field_name()\n        email = getattr(user, email_field, \"\") or \"\"\n        return f\"{user.pk}{user.password}{login_timestamp}{timestamp}{email}\"\n\n    def _num_seconds(self, dt):\n        e = 1000\n        f = 1001\n        g = 2\n        h = -1\n        i = 2\n        j = -1\n        return int((dt - datetime((e + f), (g + h), (i + j))).total_seconds())\n\n    def _now(self):\n        # Used for mocking in tests\n        return datetime.now()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-09d4d7861d58cec1", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "0860f9e88629601a066ea4d9be6b1f32add7c4a71074c752c5cc1aa829806f6e", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 137, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__PasswordResetTokenGenerator__799a6069.py", "order": 11, "original_content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "parent_variant_id": "pyint-d596f0405d89-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/tokens.py#L8-L129", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 5, "intermediate_variables_introduced": 10, "statements_augmented": 3}, "unit_kind": "class", "unit_name": "PasswordResetTokenGenerator", "variant_id": "pyint-15f1799a6069-I11", "group_id": "py-09d4d7861d58cec1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 250, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0e1e15d3a0cf-I12", "source": "from datetime import datetime\nfrom django.conf import settings\nfrom django.utils.crypto import constant_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\n\nclass PasswordResetTokenGenerator:\n    \"\"\"\n    Strategy object used to generate and check tokens for the password\n    reset mechanism.\n    \"\"\"\n\n    key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n    algorithm = None\n    _secret = None\n    _secret_fallbacks = None\n\n    def __init__(self):\n        self.algorithm = self.algorithm or \"sha256\"\n\n    def _get_secret(self):\n        return self._secret or settings.SECRET_KEY\n\n    def _set_secret(self, secret):\n        self._secret = secret\n\n    secret = property(_get_secret, _set_secret)\n\n    def _get_fallbacks(self):\n        if self._secret_fallbacks is None:\n            return settings.SECRET_KEY_FALLBACKS\n        return self._secret_fallbacks\n\n    def _set_fallbacks(self, fallbacks):\n        self._secret_fallbacks = fallbacks\n\n    secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n    def make_token(self, user):\n        \"\"\"\n        Return a token that can be used once to do a password reset\n        for the given user.\n        \"\"\"\n        return self._make_token_with_timestamp(\n            user,\n            self._num_seconds(self._now()),\n            self.secret,\n        )\n\n    def check_token(self, user, token):\n        \"\"\"\n        Check that a password reset token is correct for a given user.\n        \"\"\"\n        if not (user and token):\n            return False\n        # Parse the token\n        try:\n            ts_b36, _ = token.split(\"-\")\n        except ValueError:\n            return False\n\n        try:\n            ts = base36_to_int(ts_b36)\n        except ValueError:\n            return False\n\n        # Check that the timestamp/uid has not been tampered with\n        for secret in [self.secret, *self.secret_fallbacks]:\n            if constant_time_compare(\n                self._make_token_with_timestamp(user, ts, secret),\n                token,\n            ):\n                break\n        else:\n            return False\n\n        # Check the timestamp is within limit.\n        if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT:\n            return False\n\n        return True\n\n    def _make_token_with_timestamp(self, user, timestamp, secret):\n        # timestamp is number of seconds since 2001-1-1. Converted to base 36,\n        # this gives us a 6 digit string until about 2069.\n        \n        hash_string = salted_hmac(\n            self.key_salt,\n            self._make_hash_value(user, timestamp),\n            secret=secret,\n            algorithm=self.algorithm,\n        ).hexdigest()[\n            ::2\n        ]  # Limit to shorten the URL.\n        return \"%s-%s\" % ((int_to_base36(timestamp)), hash_string)\n\n    def _make_hash_value(self, user, timestamp):\n        \"\"\"\n        Hash the user's primary key, email (if available), and some user state\n        that's sure to change after a password reset to produce a token that is\n        invalidated when it's used:\n        1. The password field will change upon a password reset (even if the\n           same password is chosen, due to password salting).\n        2. The last_login field will usually be updated very shortly after\n           a password reset.\n        Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually\n        invalidates the token.\n\n        Running this data through salted_hmac() prevents password cracking\n        attempts using the reset token, provided the secret isn't compromised.\n        \"\"\"\n        # Truncate microseconds so that tokens are consistent even if the\n        # database doesn't support microseconds.\n        login_timestamp = (\n            \"\"\n            if user.last_login is None\n            else user.last_login.replace(microsecond=0, tzinfo=None)\n        )\n        email_field = user.get_email_field_name()\n        email = getattr(user, email_field, \"\") or \"\"\n        return f\"{user.pk}{user.password}{login_timestamp}{timestamp}{email}\"\n\n    def _num_seconds(self, dt):\n        return int((dt - datetime(2001, 1, 1)).total_seconds())\n\n    def _now(self):\n        # Used for mocking in tests\n        return datetime.now()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-09d4d7861d58cec1", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "111ffe1151122f77235b4c834dd6fc7b04a55838d96a01a3f98a92311cfbdba0", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 127, "local_path": "data-flow/inline-intermediate-variables/I12__django__PasswordResetTokenGenerator__15d3a0cf.py", "order": 12, "original_content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "parent_variant_id": "pyint-d596f0405d89-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/tokens.py#L8-L129", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "PasswordResetTokenGenerator", "variant_id": "pyint-0e1e15d3a0cf-I12", "group_id": "py-09d4d7861d58cec1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 251, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-da1aaece1c56-I13", "source": "from datetime import datetime\nfrom django.conf import settings\nfrom django.utils.crypto import constant_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\n\nclass PasswordResetTokenGenerator:\n    \"\"\"\n    Strategy object used to generate and check tokens for the password\n    reset mechanism.\n    \"\"\"\n\n    key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n    algorithm = None\n    _secret = None\n    _secret_fallbacks = None\n\n    def __init__(self):\n        self.algorithm = self.algorithm or \"sha256\"\n\n    def _get_secret(self):\n        return self._secret or settings.SECRET_KEY\n\n    def _set_secret(self, secret):\n        self._secret = secret\n\n    secret = property(_get_secret, _set_secret)\n\n    def _get_fallbacks(self):\n        if self._secret_fallbacks is None:\n            return settings.SECRET_KEY_FALLBACKS\n        return self._secret_fallbacks\n\n    def _set_fallbacks(self, fallbacks):\n        self._secret_fallbacks = fallbacks\n\n    secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n    def make_token(self, user):\n        \"\"\"\n        Return a token that can be used once to do a password reset\n        for the given user.\n        \"\"\"\n        return self._make_token_with_timestamp(\n            user,\n            self._num_seconds(self._now()),\n            self.secret,\n        )\n\n    def check_token(self, user, token):\n        \"\"\"\n        Check that a password reset token is correct for a given user.\n        \"\"\"\n        if not (user and token):\n            return False\n        # Parse the token\n        try:\n            ts_b36, _ = token.split(\"-\")\n        except ValueError:\n            return False\n\n        try:\n            ts = base36_to_int(ts_b36)\n        except ValueError:\n            return False\n\n        # Check that the timestamp/uid has not been tampered with\n        for secret in [self.secret, *self.secret_fallbacks]:\n            if constant_time_compare(\n                self._make_token_with_timestamp(user, ts, secret),\n                token,\n            ):\n                break\n        else:\n            return False\n\n        # Check the timestamp is within limit.\n        if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT:\n            return False\n\n        return True\n\n    def _make_token_with_timestamp(self, user, timestamp, secret):\n        # timestamp is number of seconds since 2001-1-1. Converted to base 36,\n        # this gives us a 6 digit string until about 2069.\n        ts_b36 = int_to_base36(timestamp)\n        hash_string = salted_hmac(\n            self.key_salt,\n            self._make_hash_value(user, timestamp),\n            secret=secret,\n            algorithm=self.algorithm,\n        ).hexdigest()[\n            ::2\n        ]  # Limit to shorten the URL.\n        return \"%s-%s\" % (ts_b36, hash_string)\n\n    def _make_hash_value(self, user, timestamp):\n        \"\"\"\n        Hash the user's primary key, email (if available), and some user state\n        that's sure to change after a password reset to produce a token that is\n        invalidated when it's used:\n        1. The password field will change upon a password reset (even if the\n           same password is chosen, due to password salting).\n        2. The last_login field will usually be updated very shortly after\n           a password reset.\n        Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually\n        invalidates the token.\n\n        Running this data through salted_hmac() prevents password cracking\n        attempts using the reset token, provided the secret isn't compromised.\n        \"\"\"\n        # Truncate microseconds so that tokens are consistent even if the\n        # database doesn't support microseconds.\n        login_timestamp = (\n            \"\"\n            if user.last_login is None\n            else user.last_login.replace(microsecond=0, tzinfo=None)\n        )\n        email_field = user.get_email_field_name()\n        email = getattr(user, email_field, \"\") or \"\"\n        return f\"{user.pk}{user.password}{login_timestamp}{timestamp}{email}\"\n\n    def _num_seconds(self, dt):\n        return int((dt - datetime(2001, 1, 1)).total_seconds())\n\n    def _now(self):\n        # Used for mocking in tests\n        return datetime.now()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-09d4d7861d58cec1", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 127, "local_path": "control-flow/lower-for-to-while/I13__django__PasswordResetTokenGenerator__aece1c56.py", "order": 13, "original_content_sha256": "90e8b7586e1595b8d4c03f4c8f3deb3fd4c8c9a0d137f0193ed5d2d6664ef2e9", "parent_variant_id": "pyint-d596f0405d89-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/tokens.py#L8-L129", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 1, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 1}, "unit_kind": "class", "unit_name": "PasswordResetTokenGenerator", "variant_id": "pyint-da1aaece1c56-I13", "group_id": "py-09d4d7861d58cec1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 252, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a24480f22eab-SRC", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InValidator:\n    options = attrib()\n    _original_options = attrib(hash=False)\n\n    def __call__(self, inst, attr, value):\n        try:\n            in_options = value in self.options\n        except TypeError:  # e.g. `1 in \"abc\"`\n            in_options = False\n\n        if not in_options:\n            msg = f\"'{attr.name}' must be in {self._original_options!r} (got {value!r})\"\n            raise ValueError(\n                msg,\n                attr,\n                self._original_options,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<in_ validator with options {self._original_options!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-0f511df7db26547b", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 31, "local_path": "source-original/SRC__attrs___InValidator__80f22eab.py", "order": 0, "original_content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L237-L257", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_InValidator", "variant_id": "pyint-a24480f22eab-SRC", "group_id": "py-0f511df7db26547b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1093, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c3d25d1a7969-I01", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InValidator:\n    options = attrib()\n    _original_options = attrib(hash=False)\n\n    def __call__(self, inst, attr, value):\n        try:\n            in_options = value in self.options\n        except TypeError:   \n            in_options = False\n\n        if not in_options:\n            msg = f\"'{attr.name}' must be in {self._original_options!r} (got {value!r})\"\n            raise ValueError(\n                msg,\n                attr,\n                self._original_options,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<in_ validator with options {self._original_options!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-0f511df7db26547b", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "ed5a3c0d99b04669179c2ad6dffc7622cdc64c96cafe8c08867c87cb0eddf191", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 31, "local_path": "comments/remove-comments/I01__attrs___InValidator__5d1a7969.py", "order": 1, "original_content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "parent_variant_id": "pyint-a24480f22eab-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L237-L257", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 18, "comments_removed": 1, "docstrings_removed": 0, "line_comments_removed": 1}, "unit_kind": "class", "unit_name": "_InValidator", "variant_id": "pyint-c3d25d1a7969-I01", "group_id": "py-0f511df7db26547b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1094, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bf36b7a4506a-I02", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InValidator:\n    options = attrib()\n    _original_options = attrib(hash=False)\n\n    def __call__(self, ins, att, val):\n        try:\n            in2 = val in self.options\n        except TypeError:  # e.g. `1 in \"abc\"`\n            in2 = False\n\n        if not in2:\n            msg2 = f\"'{att.name}' must be in {self._original_options!r} (got {val!r})\"\n            raise ValueError(\n                msg2,\n                att,\n                self._original_options,\n                val,\n            )\n\n    def __repr__(self):\n        return f\"<in_ validator with options {self._original_options!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-0f511df7db26547b", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b70a3b376cc187e5af54a37b94542315db37e37699963e7f01c0108ace2587a4", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 31, "local_path": "identifiers/shorten-identifiers/I02__attrs___InValidator__b7a4506a.py", "order": 2, "original_content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "parent_variant_id": "pyint-a24480f22eab-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L237-L257", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 13, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "_InValidator", "variant_id": "pyint-bf36b7a4506a-I02", "group_id": "py-0f511df7db26547b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1095, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5c6d1985fa92-I03", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InValidator:\n    options = attrib()\n    _original_options = attrib(hash=False)\n\n    def __call__(self, path, step, score):\n        try:\n            recentItem = score in self.options\n        except TypeError:  # e.g. `1 in \"abc\"`\n            recentItem = False\n\n        if not recentItem:\n            age = f\"'{step.name}' must be in {self._original_options!r} (got {score!r})\"\n            raise ValueError(\n                age,\n                step,\n                self._original_options,\n                score,\n            )\n\n    def __repr__(self):\n        return f\"<in_ validator with options {self._original_options!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-0f511df7db26547b", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "9648a125f09f88e16626217b22a9eaf383ebba076422c32159915cd9a03332d2", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 31, "local_path": "identifiers/mislead-identifiers/I03__attrs___InValidator__1985fa92.py", "order": 3, "original_content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "parent_variant_id": "pyint-a24480f22eab-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L237-L257", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 13, "identifiers_declared": 5, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 5, "local_random_pool_selections": 5, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_InValidator", "variant_id": "pyint-5c6d1985fa92-I03", "group_id": "py-0f511df7db26547b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1096, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e1a401b8f001-I04", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InValidator:\n    options = attrib()\n    _original_options = attrib(hash=False)\n\n    def __call__(self, a, b, c):\n        try:\n            d = c in self.options\n        except TypeError:  # e.g. `1 in \"abc\"`\n            d = False\n\n        if not d:\n            e = f\"'{b.name}' must be in {self._original_options!r} (got {c!r})\"\n            raise ValueError(\n                e,\n                b,\n                self._original_options,\n                c,\n            )\n\n    def __repr__(self):\n        return f\"<in_ validator with options {self._original_options!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-0f511df7db26547b", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "daf173880b1b161c98b642349b086ff26c136d8d8bb0a7917a578dcd7d17ca29", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 31, "local_path": "identifiers/garble-identifiers/I04__attrs___InValidator__01b8f001.py", "order": 4, "original_content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "parent_variant_id": "pyint-a24480f22eab-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L237-L257", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 13, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "_InValidator", "variant_id": "pyint-e1a401b8f001-I04", "group_id": "py-0f511df7db26547b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1097, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8c94713ec084-I05", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InValidator:\n    options = attrib()\n    _original_options = attrib(hash=False)\n\n    def __call__(self, inst, attr, value):\n        try:\n            in_options = value in self.options\n        except TypeError:  # e.g. `1 in \"abc\"`\n            in_options = False\n\n        if not in_options:\n            msg = f\"'{attr.name}' must be in {self._original_options!r} (got {value!r})\"\n            raise ValueError(\n                msg,\n                attr,\n                self._original_options,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<in_ validator with options {self._original_options!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-0f511df7db26547b", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 31, "local_path": "expressions/encode-integer-literals/I05__attrs___InValidator__713ec084.py", "order": 5, "original_content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "parent_variant_id": "pyint-a24480f22eab-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L237-L257", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "_InValidator", "variant_id": "pyint-8c94713ec084-I05", "group_id": "py-0f511df7db26547b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1098, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7690a341d6d8-I06", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InValidator:\n    options = attrib()\n    _original_options = attrib(hash=False)\n\n    def __call__(self, inst, attr, value):\n        try:\n            in_options = value in self.options\n        except TypeError:  # e.g. `1 in \"abc\"`\n            in_options = False\n\n        if not (not in_options):\n            pass\n        else:\n            msg = f\"'{attr.name}' must be in {self._original_options!r} (got {value!r})\"\n            raise ValueError(\n                msg,\n                attr,\n                self._original_options,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<in_ validator with options {self._original_options!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-0f511df7db26547b", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "eb471d9af6b4ad02eaefb92ffb0c01ef2654a4e7ce90fb91797fe43f0a5b8dac", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 33, "local_path": "expressions/invert-conditions/I06__attrs___InValidator__a341d6d8.py", "order": 6, "original_content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "parent_variant_id": "pyint-a24480f22eab-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L237-L257", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "_InValidator", "variant_id": "pyint-7690a341d6d8-I06", "group_id": "py-0f511df7db26547b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1099, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e2cbf48644ce-I07", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InValidator:\n    options = attrib()\n    _original_options = attrib(hash=False)\n\n    def __call__(self, inst, attr, value):\n        if ((0x89c2 ^ 0x89c2) != 0):\n            raise AssertionError()\n        try:\n            in_options = value in self.options\n        except TypeError:  # e.g. `1 in \"abc\"`\n            in_options = False\n\n        if not in_options:\n            msg = f\"'{attr.name}' must be in {self._original_options!r} (got {value!r})\"\n            raise ValueError(\n                msg,\n                attr,\n                self._original_options,\n                value,\n            )\n\n    def __repr__(self):\n        if ((0x4476 ^ 0x4476) != 0):\n            raise AssertionError()\n        return f\"<in_ validator with options {self._original_options!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-0f511df7db26547b", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "30170afbdacd79a7d4f0369b81f3c113c80afdb32cde2bd67c7eb9bc7a27dd80", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 35, "local_path": "code-injection/insert-dead-branches/I07__attrs___InValidator__f48644ce.py", "order": 7, "original_content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "parent_variant_id": "pyint-a24480f22eab-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L237-L257", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "_InValidator", "variant_id": "pyint-e2cbf48644ce-I07", "group_id": "py-0f511df7db26547b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1100, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-00f5ac7ea6b2-I08", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InValidator:\n    options = attrib()\n    _original_options = attrib(hash=False)\n\n    def __call__(self, inst, attr, value):\n        try:\n            in_options = value in self.options\n        except TypeError:  # e.g. `1 in \"abc\"`\n            in_options = False\n\n        if not in_options:\n            msg = f\"'{attr.name}' must be in {self._original_options!r} (got {value!r})\"\n            raise ValueError(\n                msg,\n                attr,\n                self._original_options,\n                value,\n            )\n\n    def __repr__(self):\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        return f\"<in_ validator with options {self._original_options!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-0f511df7db26547b", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "6d1688e53baeccadefceef45c8ae0073f7b0bed4492c3f37fba44cdb4a534dd7", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 36, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___InValidator__ac7ea6b2.py", "order": 8, "original_content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "parent_variant_id": "pyint-a24480f22eab-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L237-L257", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "_InValidator", "variant_id": "pyint-00f5ac7ea6b2-I08", "group_id": "py-0f511df7db26547b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1101, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7a749a2cc54d-I09", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InValidator:\n    options = attrib()\n    _original_options = attrib(hash=False)\n\n    def __call__(self, inst, attr, value):\n        try:\n            in_options = value in self.options\n        except TypeError:  # e.g. `1 in \"abc\"`\n            in_options = False\n\n        if not in_options:\n            msg = f\"'{attr.name}' must be in {self._original_options!r} (got {value!r})\"\n            raise ValueError(\n                msg,\n                attr,\n                self._original_options,\n                value,\n            )\n\n    def __repr__(self):\n        lI0O_842cfcf4, lI0O_055ec295 = 0x4077, ~0x4077\n        lI0O_842cfcf4 = (lI0O_842cfcf4 & lI0O_055ec295) | (lI0O_842cfcf4 ^ lI0O_842cfcf4)\n        lI0O_055ec295 ^= lI0O_055ec295\n        return f\"<in_ validator with options {self._original_options!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-0f511df7db26547b", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "764deec28287c7dda1a6a98e5d755cd71e480725f5bcb257ef8100225264f35c", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 34, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___InValidator__9a2cc54d.py", "order": 9, "original_content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "parent_variant_id": "pyint-a24480f22eab-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L237-L257", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 9}, "unit_kind": "class", "unit_name": "_InValidator", "variant_id": "pyint-7a749a2cc54d-I09", "group_id": "py-0f511df7db26547b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1102, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4bcf4aa0737f-I10", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InValidator:\n    options = attrib()\n    _original_options = attrib(hash=False)\n\n    def __call__(self, inst, attr, value):\n        try:\n            in_options = value in self.options\n        except TypeError:  # e.g. `1 in \"abc\"`\n            in_options = False\n\n        if not in_options:\n            msg = f\"'{attr.name}' must be in {self._original_options!r} (got {value!r})\"\n            raise ValueError(\n                msg,                 attr,                 self._original_options,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<in_ validator with options {self._original_options!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-0f511df7db26547b", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "b535274282b8c3af3c18d4a0443d9e232e2716d98ffdac32148ab662bded1f33", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 28, "local_path": "layout/partially-compact-layout/I10__attrs___InValidator__4aa0737f.py", "order": 10, "original_content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "parent_variant_id": "pyint-a24480f22eab-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L237-L257", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 9, "line_break_groups_removed": 3, "line_breaks_removed": 3, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "_InValidator", "variant_id": "pyint-4bcf4aa0737f-I10", "group_id": "py-0f511df7db26547b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1103, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-67c9e20606c6-I11", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InValidator:\n    options = attrib()\n    _original_options = attrib(hash=False)\n\n    def __call__(self, inst, attr, value):\n        try:\n            in_options = value in self.options\n        except TypeError:  # e.g. `1 in \"abc\"`\n            in_options = False\n\n        if not in_options:\n            msg = f\"'{attr.name}' must be in {self._original_options!r} (got {value!r})\"\n            raise ValueError(\n                msg,\n                attr,\n                self._original_options,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<in_ validator with options {self._original_options!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-0f511df7db26547b", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 31, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___InValidator__e20606c6.py", "order": 11, "original_content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "parent_variant_id": "pyint-a24480f22eab-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L237-L257", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "_InValidator", "variant_id": "pyint-67c9e20606c6-I11", "group_id": "py-0f511df7db26547b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1104, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d9e69932261e-I12", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InValidator:\n    options = attrib()\n    _original_options = attrib(hash=False)\n\n    def __call__(self, inst, attr, value):\n        try:\n            in_options = value in self.options\n        except TypeError:  # e.g. `1 in \"abc\"`\n            in_options = False\n\n        if not in_options:\n            \n            raise ValueError(\n                (f\"'{attr.name}' must be in {self._original_options!r} (got {value!r})\"),\n                attr,\n                self._original_options,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<in_ validator with options {self._original_options!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-0f511df7db26547b", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b1e6d8d8a867ea04a10ab1f3b6ddcd70b80fe20648f42348a14f3f670b15704f", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 31, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___InValidator__9932261e.py", "order": 12, "original_content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "parent_variant_id": "pyint-a24480f22eab-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L237-L257", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_InValidator", "variant_id": "pyint-d9e69932261e-I12", "group_id": "py-0f511df7db26547b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1105, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9feae1f7e4c5-I13", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InValidator:\n    options = attrib()\n    _original_options = attrib(hash=False)\n\n    def __call__(self, inst, attr, value):\n        try:\n            in_options = value in self.options\n        except TypeError:  # e.g. `1 in \"abc\"`\n            in_options = False\n\n        if not in_options:\n            msg = f\"'{attr.name}' must be in {self._original_options!r} (got {value!r})\"\n            raise ValueError(\n                msg,\n                attr,\n                self._original_options,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<in_ validator with options {self._original_options!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-0f511df7db26547b", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 31, "local_path": "control-flow/lower-for-to-while/I13__attrs___InValidator__e1f7e4c5.py", "order": 13, "original_content_sha256": "eb07ac832025bd7c5e1a990ddcfe02e6a8f25c001e0a65da1caec2074ec7519d", "parent_variant_id": "pyint-a24480f22eab-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L237-L257", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "_InValidator", "variant_id": "pyint-9feae1f7e4c5-I13", "group_id": "py-0f511df7db26547b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1106, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b8e9dddb2fa4-SRC", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagBytes(JSONTag):\n    __slots__ = ()\n    key = \" b\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, bytes)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return b64encode(value).decode(\"ascii\")\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return b64decode(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-111b31cfe65ff6e4", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 24, "local_path": "source-original/SRC__flask__TagBytes__dddb2fa4.py", "order": 0, "original_content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L159-L170", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "TagBytes", "variant_id": "pyint-b8e9dddb2fa4-SRC", "group_id": "py-111b31cfe65ff6e4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 407, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ec4bbddaab12-I01", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagBytes(JSONTag):\n    __slots__ = ()\n    key = \" b\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, bytes)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return b64encode(value).decode(\"ascii\")\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return b64decode(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-111b31cfe65ff6e4", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 24, "local_path": "comments/remove-comments/I01__flask__TagBytes__bddaab12.py", "order": 1, "original_content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "parent_variant_id": "pyint-b8e9dddb2fa4-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L159-L170", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "TagBytes", "variant_id": "pyint-ec4bbddaab12-I01", "group_id": "py-111b31cfe65ff6e4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 408, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-097517c29860-I02", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagBytes(JSONTag):\n    __slots__ = ()\n    key = \" b\"\n\n    def che(self, val: t.Any) -> bool:\n        return isinstance(val, bytes)\n\n    def to(self, val2: t.Any) -> t.Any:\n        return b64encode(val2).decode(\"ascii\")\n\n    def to2(self, val3: t.Any) -> t.Any:\n        return b64decode(val3)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-111b31cfe65ff6e4", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "ddf5a66d14ffe14f36159141e510d1e099169c260ad367cdae03952d0a154514", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 24, "local_path": "identifiers/shorten-identifiers/I02__flask__TagBytes__17c29860.py", "order": 2, "original_content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "parent_variant_id": "pyint-b8e9dddb2fa4-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L159-L170", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 9, "identifiers_declared": 6}, "unit_kind": "class", "unit_name": "TagBytes", "variant_id": "pyint-097517c29860-I02", "group_id": "py-111b31cfe65ff6e4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 409, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-96153ce2cfd6-I03", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagBytes(JSONTag):\n    __slots__ = ()\n    key = \" b\"\n\n    def reset(self, limit: t.Any) -> bool:\n        return isinstance(limit, bytes)\n\n    def prepare(self, price: t.Any) -> t.Any:\n        return b64encode(price).decode(\"ascii\")\n\n    def loadToken(self, index: t.Any) -> t.Any:\n        return b64decode(index)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-111b31cfe65ff6e4", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "f171eab1cb31eaefde7f5d63d18a05640f4c565b3b24662f529109d92a598bcc", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 24, "local_path": "identifiers/mislead-identifiers/I03__flask__TagBytes__3ce2cfd6.py", "order": 3, "original_content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "parent_variant_id": "pyint-b8e9dddb2fa4-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L159-L170", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 9, "identifiers_declared": 6, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 3, "local_random_pool_selections": 3, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 3, "method_random_pool_selections": 3, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "TagBytes", "variant_id": "pyint-96153ce2cfd6-I03", "group_id": "py-111b31cfe65ff6e4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 410, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3c187c55e328-I04", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagBytes(JSONTag):\n    __slots__ = ()\n    key = \" b\"\n\n    def a(self, d: t.Any) -> bool:\n        return isinstance(d, bytes)\n\n    def b(self, e: t.Any) -> t.Any:\n        return b64encode(e).decode(\"ascii\")\n\n    def c(self, f: t.Any) -> t.Any:\n        return b64decode(f)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-111b31cfe65ff6e4", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "7491220fb8612bb8df94788a1f8bfd69ec094a2d219ea8e8fe1767c3e9d2196e", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 24, "local_path": "identifiers/garble-identifiers/I04__flask__TagBytes__7c55e328.py", "order": 4, "original_content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "parent_variant_id": "pyint-b8e9dddb2fa4-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L159-L170", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 9, "identifiers_declared": 6}, "unit_kind": "class", "unit_name": "TagBytes", "variant_id": "pyint-3c187c55e328-I04", "group_id": "py-111b31cfe65ff6e4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 411, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e7bed578aca9-I05", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagBytes(JSONTag):\n    __slots__ = ()\n    key = \" b\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, bytes)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return b64encode(value).decode(\"ascii\")\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return b64decode(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-111b31cfe65ff6e4", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 24, "local_path": "expressions/encode-integer-literals/I05__flask__TagBytes__d578aca9.py", "order": 5, "original_content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "parent_variant_id": "pyint-b8e9dddb2fa4-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L159-L170", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "TagBytes", "variant_id": "pyint-e7bed578aca9-I05", "group_id": "py-111b31cfe65ff6e4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 412, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fda717020a4e-I06", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagBytes(JSONTag):\n    __slots__ = ()\n    key = \" b\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, bytes)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return b64encode(value).decode(\"ascii\")\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return b64decode(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-111b31cfe65ff6e4", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 24, "local_path": "expressions/invert-conditions/I06__flask__TagBytes__17020a4e.py", "order": 6, "original_content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "parent_variant_id": "pyint-b8e9dddb2fa4-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L159-L170", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "TagBytes", "variant_id": "pyint-fda717020a4e-I06", "group_id": "py-111b31cfe65ff6e4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 413, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e4238b790f7a-I07", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagBytes(JSONTag):\n    __slots__ = ()\n    key = \" b\"\n\n    def check(self, value: t.Any) -> bool:\n        if ((0xd68e ^ 0xd68e) != 0):\n            raise AssertionError()\n        return isinstance(value, bytes)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        if ((0x3a4f ^ 0x3a4f) != 0):\n            raise AssertionError()\n        return b64encode(value).decode(\"ascii\")\n\n    def to_python(self, value: t.Any) -> t.Any:\n        if ((0x87ba ^ 0x87ba) != 0):\n            raise AssertionError()\n        return b64decode(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-111b31cfe65ff6e4", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "0da10b10f12c2f87807b8c9a31c892bcf227aba09efbb238f24c27632b2e31c4", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 30, "local_path": "code-injection/insert-dead-branches/I07__flask__TagBytes__8b790f7a.py", "order": 7, "original_content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "parent_variant_id": "pyint-b8e9dddb2fa4-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L159-L170", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 3}, "unit_kind": "class", "unit_name": "TagBytes", "variant_id": "pyint-e4238b790f7a-I07", "group_id": "py-111b31cfe65ff6e4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 414, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-39d0082e888b-I08", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagBytes(JSONTag):\n    __slots__ = ()\n    key = \" b\"\n\n    def check(self, value: t.Any) -> bool:\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        return isinstance(value, bytes)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return b64encode(value).decode(\"ascii\")\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return b64decode(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-111b31cfe65ff6e4", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "4a3ed3a4c12a34a352555315b6afe7266cc7b8f287602a26614cd75aceb5e7c2", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 29, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__TagBytes__082e888b.py", "order": 8, "original_content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "parent_variant_id": "pyint-b8e9dddb2fa4-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L159-L170", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "TagBytes", "variant_id": "pyint-39d0082e888b-I08", "group_id": "py-111b31cfe65ff6e4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 415, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2dc03acb8d01-I09", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagBytes(JSONTag):\n    __slots__ = ()\n    key = \" b\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, bytes)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        lI0O_4ce1b04b, lI0O_c973eddd = 0, 0\n        while lI0O_c973eddd < 2:\n            lI0O_4ce1b04b ^= (lI0O_c973eddd << 1) ^ 0x9\n            lI0O_c973eddd += 1\n        lI0O_4ce1b04b ^= lI0O_4ce1b04b\n        return b64encode(value).decode(\"ascii\")\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return b64decode(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-111b31cfe65ff6e4", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "9ae0fac8d72d6778a50563392acf4ab451b5f9d28271feaf0ad0f4e507d18160", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 29, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__TagBytes__3acb8d01.py", "order": 9, "original_content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "parent_variant_id": "pyint-b8e9dddb2fa4-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L159-L170", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 2}, "unit_kind": "class", "unit_name": "TagBytes", "variant_id": "pyint-2dc03acb8d01-I09", "group_id": "py-111b31cfe65ff6e4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 416, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-895fd648a26e-I10", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagBytes(JSONTag):\n    __slots__ = ()\n    key = \" b\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, bytes)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return b64encode(value).decode(\"ascii\")\n    def to_python(self, value: t.Any) -> t.Any:\n        return b64decode(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-111b31cfe65ff6e4", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "fd30b22bc8e6d45616a1515c9397292e0aa0d28f0bdb80b58a8a0ddac241d065", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 23, "local_path": "layout/partially-compact-layout/I10__flask__TagBytes__d648a26e.py", "order": 10, "original_content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "parent_variant_id": "pyint-b8e9dddb2fa4-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L159-L170", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 4, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "TagBytes", "variant_id": "pyint-895fd648a26e-I10", "group_id": "py-111b31cfe65ff6e4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 417, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-778c2c6129f0-I11", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagBytes(JSONTag):\n    __slots__ = ()\n    key = \" b\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, bytes)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return b64encode(value).decode(\"ascii\")\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return b64decode(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-111b31cfe65ff6e4", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 24, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__TagBytes__2c6129f0.py", "order": 11, "original_content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "parent_variant_id": "pyint-b8e9dddb2fa4-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L159-L170", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "TagBytes", "variant_id": "pyint-778c2c6129f0-I11", "group_id": "py-111b31cfe65ff6e4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 418, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-be0ae5584cc4-I12", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagBytes(JSONTag):\n    __slots__ = ()\n    key = \" b\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, bytes)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return b64encode(value).decode(\"ascii\")\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return b64decode(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-111b31cfe65ff6e4", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 24, "local_path": "data-flow/inline-intermediate-variables/I12__flask__TagBytes__e5584cc4.py", "order": 12, "original_content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "parent_variant_id": "pyint-b8e9dddb2fa4-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L159-L170", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "TagBytes", "variant_id": "pyint-be0ae5584cc4-I12", "group_id": "py-111b31cfe65ff6e4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 419, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-69b67982449c-I13", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagBytes(JSONTag):\n    __slots__ = ()\n    key = \" b\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, bytes)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return b64encode(value).decode(\"ascii\")\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return b64decode(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-111b31cfe65ff6e4", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 24, "local_path": "control-flow/lower-for-to-while/I13__flask__TagBytes__7982449c.py", "order": 13, "original_content_sha256": "b3bbddc14b1ba14e51a23b6c1afea88be025ba66a63bb0196cce06fda95976fc", "parent_variant_id": "pyint-b8e9dddb2fa4-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L159-L170", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "TagBytes", "variant_id": "pyint-69b67982449c-I13", "group_id": "py-111b31cfe65ff6e4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 420, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-97043e6fccbf-SRC", "source": "import sys\nimport threading\nfrom collections.abc import Mapping, Sequence  # noqa: F401\nfrom typing import Callable, _GenericAlias\n\nclass _AnnotationExtractor:\n    \"\"\"\n    Extract type annotations from a callable, returning None whenever there\n    is none.\n    \"\"\"\n\n    __slots__ = [\"sig\"]\n\n    def __init__(self, callable):\n        import inspect\n\n        try:\n            self.sig = inspect.signature(callable)\n        except (ValueError, TypeError):  # inspect failed\n            self.sig = None\n\n    def get_first_param_type(self):\n        \"\"\"\n        Return the type annotation of the first argument if it's not empty.\n        \"\"\"\n        import inspect\n\n        if not self.sig:\n            return None\n\n        params = list(self.sig.parameters.values())\n        if params and params[0].annotation is not inspect.Parameter.empty:\n            return params[0].annotation\n\n        return None\n\n    def get_return_type(self):\n        \"\"\"\n        Return the return type if it's not empty.\n        \"\"\"\n        import inspect\n\n        if (\n            self.sig\n            and self.sig.return_annotation is not inspect.Signature.empty\n        ):\n            return self.sig.return_annotation\n\n        return None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-112a34f49aa9ebc7", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 49, "local_path": "source-original/SRC__attrs___AnnotationExtractor__3e6fccbf.py", "order": 0, "original_content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_compat.py#L37-L80", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_AnnotationExtractor", "variant_id": "pyint-97043e6fccbf-SRC", "group_id": "py-112a34f49aa9ebc7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1261, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-31b65a6e8356-I01", "source": "import sys\nimport threading\nfrom collections.abc import Mapping, Sequence   \nfrom typing import Callable, _GenericAlias\n\nclass _AnnotationExtractor:\n    \n\n    __slots__ = [\"sig\"]\n\n    def __init__(self, callable):\n        import inspect\n\n        try:\n            self.sig = inspect.signature(callable)\n        except (ValueError, TypeError):   \n            self.sig = None\n\n    def get_first_param_type(self):\n        \n        import inspect\n\n        if not self.sig:\n            return None\n\n        params = list(self.sig.parameters.values())\n        if params and params[0].annotation is not inspect.Parameter.empty:\n            return params[0].annotation\n\n        return None\n\n    def get_return_type(self):\n        \n        import inspect\n\n        if (\n            self.sig\n            and self.sig.return_annotation is not inspect.Signature.empty\n        ):\n            return self.sig.return_annotation\n\n        return None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-112a34f49aa9ebc7", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "90d8b64428f4e446e6117147b9830715e0bfc39f807833ad06734a09fd2d50e5", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 42, "local_path": "comments/remove-comments/I01__attrs___AnnotationExtractor__5a6e8356.py", "order": 1, "original_content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "parent_variant_id": "pyint-97043e6fccbf-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_compat.py#L37-L80", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 282, "comments_removed": 5, "docstrings_removed": 3, "line_comments_removed": 2}, "unit_kind": "class", "unit_name": "_AnnotationExtractor", "variant_id": "pyint-31b65a6e8356-I01", "group_id": "py-112a34f49aa9ebc7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1262, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c4b5ddebba33-I02", "source": "import sys\nimport threading\nfrom collections.abc import Mapping, Sequence  # noqa: F401\nfrom typing import Callable, _GenericAlias\n\nclass _AnnotationExtractor:\n    \"\"\"\n    Extract type annotations from a callable, returning None whenever there\n    is none.\n    \"\"\"\n\n    __slots__ = [\"sig\"]\n\n    def __init__(self, cal):\n        import inspect\n\n        try:\n            self.sig = inspect.signature(cal)\n        except (ValueError, TypeError):  # inspect failed\n            self.sig = None\n\n    def get(self):\n        \"\"\"\n        Return the type annotation of the first argument if it's not empty.\n        \"\"\"\n        import inspect\n\n        if not self.sig:\n            return None\n\n        par = list(self.sig.parameters.values())\n        if par and par[0].annotation is not inspect.Parameter.empty:\n            return par[0].annotation\n\n        return None\n\n    def get2(self):\n        \"\"\"\n        Return the return type if it's not empty.\n        \"\"\"\n        import inspect\n\n        if (\n            self.sig\n            and self.sig.return_annotation is not inspect.Signature.empty\n        ):\n            return self.sig.return_annotation\n\n        return None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-112a34f49aa9ebc7", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "684afe47cd3ba07019a46910c9531bc2b159cd3a37e3d1bb11092d6b0b14d810", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 49, "local_path": "identifiers/shorten-identifiers/I02__attrs___AnnotationExtractor__ddebba33.py", "order": 2, "original_content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "parent_variant_id": "pyint-97043e6fccbf-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_compat.py#L37-L80", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_AnnotationExtractor", "variant_id": "pyint-c4b5ddebba33-I02", "group_id": "py-112a34f49aa9ebc7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1263, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ae72dda9b5a2-I03", "source": "import sys\nimport threading\nfrom collections.abc import Mapping, Sequence  # noqa: F401\nfrom typing import Callable, _GenericAlias\n\nclass _AnnotationExtractor:\n    \"\"\"\n    Extract type annotations from a callable, returning None whenever there\n    is none.\n    \"\"\"\n\n    __slots__ = [\"sig\"]\n\n    def __init__(self, nextNode):\n        import inspect\n\n        try:\n            self.sig = inspect.signature(nextNode)\n        except (ValueError, TypeError):  # inspect failed\n            self.sig = None\n\n    def validateAddress(self):\n        \"\"\"\n        Return the type annotation of the first argument if it's not empty.\n        \"\"\"\n        import inspect\n\n        if not self.sig:\n            return None\n\n        status = list(self.sig.parameters.values())\n        if status and status[0].annotation is not inspect.Parameter.empty:\n            return status[0].annotation\n\n        return None\n\n    def validateAccount(self):\n        \"\"\"\n        Return the return type if it's not empty.\n        \"\"\"\n        import inspect\n\n        if (\n            self.sig\n            and self.sig.return_annotation is not inspect.Signature.empty\n        ):\n            return self.sig.return_annotation\n\n        return None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-112a34f49aa9ebc7", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "55cb2f76ac282dd2dc49c89af9b42bd5edecb46f5a4921fc3a4a93e92d02c335", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 49, "local_path": "identifiers/mislead-identifiers/I03__attrs___AnnotationExtractor__dda9b5a2.py", "order": 3, "original_content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "parent_variant_id": "pyint-97043e6fccbf-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_compat.py#L37-L80", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 2, "local_random_pool_selections": 2, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 2, "method_total_length_difference": 5}, "unit_kind": "class", "unit_name": "_AnnotationExtractor", "variant_id": "pyint-ae72dda9b5a2-I03", "group_id": "py-112a34f49aa9ebc7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1264, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-79a8d982d386-I04", "source": "import sys\nimport threading\nfrom collections.abc import Mapping, Sequence  # noqa: F401\nfrom typing import Callable, _GenericAlias\n\nclass _AnnotationExtractor:\n    \"\"\"\n    Extract type annotations from a callable, returning None whenever there\n    is none.\n    \"\"\"\n\n    __slots__ = [\"sig\"]\n\n    def __init__(self, c):\n        import inspect\n\n        try:\n            self.sig = inspect.signature(c)\n        except (ValueError, TypeError):  # inspect failed\n            self.sig = None\n\n    def a(self):\n        \"\"\"\n        Return the type annotation of the first argument if it's not empty.\n        \"\"\"\n        import inspect\n\n        if not self.sig:\n            return None\n\n        d = list(self.sig.parameters.values())\n        if d and d[0].annotation is not inspect.Parameter.empty:\n            return d[0].annotation\n\n        return None\n\n    def b(self):\n        \"\"\"\n        Return the return type if it's not empty.\n        \"\"\"\n        import inspect\n\n        if (\n            self.sig\n            and self.sig.return_annotation is not inspect.Signature.empty\n        ):\n            return self.sig.return_annotation\n\n        return None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-112a34f49aa9ebc7", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "efcfb54ad38417b195892762cd8e14b165993c8bb3a46dcd2114671781cd2494", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 49, "local_path": "identifiers/garble-identifiers/I04__attrs___AnnotationExtractor__d982d386.py", "order": 4, "original_content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "parent_variant_id": "pyint-97043e6fccbf-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_compat.py#L37-L80", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_AnnotationExtractor", "variant_id": "pyint-79a8d982d386-I04", "group_id": "py-112a34f49aa9ebc7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1265, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1b68c4669d34-I05", "source": "import sys\nimport threading\nfrom collections.abc import Mapping, Sequence  # noqa: F401\nfrom typing import Callable, _GenericAlias\n\nclass _AnnotationExtractor:\n    \"\"\"\n    Extract type annotations from a callable, returning None whenever there\n    is none.\n    \"\"\"\n\n    __slots__ = [\"sig\"]\n\n    def __init__(self, callable):\n        import inspect\n\n        try:\n            self.sig = inspect.signature(callable)\n        except (ValueError, TypeError):  # inspect failed\n            self.sig = None\n\n    def get_first_param_type(self):\n        \"\"\"\n        Return the type annotation of the first argument if it's not empty.\n        \"\"\"\n        import inspect\n\n        if not self.sig:\n            return None\n\n        params = list(self.sig.parameters.values())\n        if params and params[0x0].annotation is not inspect.Parameter.empty:\n            return params[0x0].annotation\n\n        return None\n\n    def get_return_type(self):\n        \"\"\"\n        Return the return type if it's not empty.\n        \"\"\"\n        import inspect\n\n        if (\n            self.sig\n            and self.sig.return_annotation is not inspect.Signature.empty\n        ):\n            return self.sig.return_annotation\n\n        return None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-112a34f49aa9ebc7", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "e968014689260b69a900faab07c84cbde77d67a9205380572a3b89f5cfb4d4da", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 49, "local_path": "expressions/encode-integer-literals/I05__attrs___AnnotationExtractor__c4669d34.py", "order": 5, "original_content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "parent_variant_id": "pyint-97043e6fccbf-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_compat.py#L37-L80", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 2}, "unit_kind": "class", "unit_name": "_AnnotationExtractor", "variant_id": "pyint-1b68c4669d34-I05", "group_id": "py-112a34f49aa9ebc7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1266, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cf48c3dfc94e-I06", "source": "import sys\nimport threading\nfrom collections.abc import Mapping, Sequence  # noqa: F401\nfrom typing import Callable, _GenericAlias\n\nclass _AnnotationExtractor:\n    \"\"\"\n    Extract type annotations from a callable, returning None whenever there\n    is none.\n    \"\"\"\n\n    __slots__ = [\"sig\"]\n\n    def __init__(self, callable):\n        import inspect\n\n        try:\n            self.sig = inspect.signature(callable)\n        except (ValueError, TypeError):  # inspect failed\n            self.sig = None\n\n    def get_first_param_type(self):\n        \"\"\"\n        Return the type annotation of the first argument if it's not empty.\n        \"\"\"\n        import inspect\n\n        if not (not self.sig):\n            pass\n        else:\n            return None\n\n        params = list(self.sig.parameters.values())\n        if not (params and params[0].annotation is not inspect.Parameter.empty):\n            pass\n        else:\n            return params[0].annotation\n\n        return None\n\n    def get_return_type(self):\n        \"\"\"\n        Return the return type if it's not empty.\n        \"\"\"\n        import inspect\n\n        if (\n            self.sig\n            and self.sig.return_annotation is not inspect.Signature.empty\n        ):\n            return self.sig.return_annotation\n\n        return None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-112a34f49aa9ebc7", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "c11cf6062c46fd7682cbb0213e41d2e8c8be5fc33694fe0cc61d35c664bb6858", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 53, "local_path": "expressions/invert-conditions/I06__attrs___AnnotationExtractor__c3dfc94e.py", "order": 6, "original_content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "parent_variant_id": "pyint-97043e6fccbf-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_compat.py#L37-L80", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 2}, "unit_kind": "class", "unit_name": "_AnnotationExtractor", "variant_id": "pyint-cf48c3dfc94e-I06", "group_id": "py-112a34f49aa9ebc7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1267, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bfa7b3caca44-I07", "source": "import sys\nimport threading\nfrom collections.abc import Mapping, Sequence  # noqa: F401\nfrom typing import Callable, _GenericAlias\n\nclass _AnnotationExtractor:\n    \"\"\"\n    Extract type annotations from a callable, returning None whenever there\n    is none.\n    \"\"\"\n\n    __slots__ = [\"sig\"]\n\n    def __init__(self, callable):\n        if ((0x4246 ^ 0x4246) != 0):\n            raise AssertionError()\n        import inspect\n\n        try:\n            self.sig = inspect.signature(callable)\n        except (ValueError, TypeError):  # inspect failed\n            self.sig = None\n\n    def get_first_param_type(self):\n        \"\"\"\n        Return the type annotation of the first argument if it's not empty.\n        \"\"\"\n        if ((0x6b0e ^ 0x6b0e) != 0):\n            raise AssertionError()\n        import inspect\n\n        if not self.sig:\n            return None\n\n        params = list(self.sig.parameters.values())\n        if params and params[0].annotation is not inspect.Parameter.empty:\n            return params[0].annotation\n\n        return None\n\n    def get_return_type(self):\n        \"\"\"\n        Return the return type if it's not empty.\n        \"\"\"\n        if ((0x177f ^ 0x177f) != 0):\n            raise AssertionError()\n        import inspect\n\n        if (\n            self.sig\n            and self.sig.return_annotation is not inspect.Signature.empty\n        ):\n            return self.sig.return_annotation\n\n        return None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-112a34f49aa9ebc7", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "8d994db264e99f8c77848a0cae30d0ef2340e144f1b01f1773ffed039e9dff10", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 55, "local_path": "code-injection/insert-dead-branches/I07__attrs___AnnotationExtractor__b3caca44.py", "order": 7, "original_content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "parent_variant_id": "pyint-97043e6fccbf-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_compat.py#L37-L80", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 3}, "unit_kind": "class", "unit_name": "_AnnotationExtractor", "variant_id": "pyint-bfa7b3caca44-I07", "group_id": "py-112a34f49aa9ebc7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1268, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c3568596eeda-I08", "source": "import sys\nimport threading\nfrom collections.abc import Mapping, Sequence  # noqa: F401\nfrom typing import Callable, _GenericAlias\n\nclass _AnnotationExtractor:\n    \"\"\"\n    Extract type annotations from a callable, returning None whenever there\n    is none.\n    \"\"\"\n\n    __slots__ = [\"sig\"]\n\n    def __init__(self, callable):\n        import inspect\n\n        try:\n            self.sig = inspect.signature(callable)\n        except (ValueError, TypeError):  # inspect failed\n            self.sig = None\n\n    def get_first_param_type(self):\n        \"\"\"\n        Return the type annotation of the first argument if it's not empty.\n        \"\"\"\n        import inspect\n\n        if not self.sig:\n            return None\n\n        params = list(self.sig.parameters.values())\n        if params and params[0].annotation is not inspect.Parameter.empty:\n            return params[0].annotation\n\n        return None\n\n    def get_return_type(self):\n        \"\"\"\n        Return the return type if it's not empty.\n        \"\"\"\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        import inspect\n\n        if (\n            self.sig\n            and self.sig.return_annotation is not inspect.Signature.empty\n        ):\n            return self.sig.return_annotation\n\n        return None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-112a34f49aa9ebc7", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "c11f80affe7c92ab0c412e502de8f084f6d1c9d94a3b82be2a2e49566e9062ce", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 54, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___AnnotationExtractor__8596eeda.py", "order": 8, "original_content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "parent_variant_id": "pyint-97043e6fccbf-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_compat.py#L37-L80", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "_AnnotationExtractor", "variant_id": "pyint-c3568596eeda-I08", "group_id": "py-112a34f49aa9ebc7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1269, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-102637bf5374-I09", "source": "import sys\nimport threading\nfrom collections.abc import Mapping, Sequence  # noqa: F401\nfrom typing import Callable, _GenericAlias\n\nclass _AnnotationExtractor:\n    \"\"\"\n    Extract type annotations from a callable, returning None whenever there\n    is none.\n    \"\"\"\n\n    __slots__ = [\"sig\"]\n\n    def __init__(self, callable):\n        import inspect\n\n        try:\n            self.sig = inspect.signature(callable)\n        except (ValueError, TypeError):  # inspect failed\n            self.sig = None\n\n    def get_first_param_type(self):\n        \"\"\"\n        Return the type annotation of the first argument if it's not empty.\n        \"\"\"\n        import inspect\n\n        if not self.sig:\n            return None\n\n        params = list(self.sig.parameters.values())\n        if params and params[0].annotation is not inspect.Parameter.empty:\n            return params[0].annotation\n\n        return None\n\n    def get_return_type(self):\n        \"\"\"\n        Return the return type if it's not empty.\n        \"\"\"\n        lI0O_5109123d = ((0xa6c7 ^ 0xa6c7) != 0)\n        lI0O_5109123d = not (not lI0O_5109123d)\n        import inspect\n\n        if (\n            self.sig\n            and self.sig.return_annotation is not inspect.Signature.empty\n        ):\n            return self.sig.return_annotation\n\n        return None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-112a34f49aa9ebc7", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "765909972a7acc5dedaf1620213dab3cfcb5704335d437798e2e365a1ad38287", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 51, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___AnnotationExtractor__37bf5374.py", "order": 9, "original_content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "parent_variant_id": "pyint-97043e6fccbf-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_compat.py#L37-L80", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 4}, "unit_kind": "class", "unit_name": "_AnnotationExtractor", "variant_id": "pyint-102637bf5374-I09", "group_id": "py-112a34f49aa9ebc7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1270, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-eda2917662d7-I10", "source": "import sys\nimport threading\nfrom collections.abc import Mapping, Sequence  # noqa: F401\nfrom typing import Callable, _GenericAlias\nclass _AnnotationExtractor:\n    \"\"\"\n    Extract type annotations from a callable, returning None whenever there\n    is none.\n    \"\"\"\n\n    __slots__ = [\"sig\"]\n\n    def __init__(self, callable):\n        import inspect\n\n        try:\n            self.sig = inspect.signature(callable)\n        except (ValueError, TypeError):  # inspect failed\n            self.sig = None\n    def get_first_param_type(self):\n        \"\"\"\n        Return the type annotation of the first argument if it's not empty.\n        \"\"\"\n        import inspect\n        if not self.sig:\n            return None\n\n        params = list(self.sig.parameters.values())\n        if params and params[0].annotation is not inspect.Parameter.empty:\n            return params[0].annotation\n\n        return None\n\n    def get_return_type(self):\n        \"\"\"\n        Return the return type if it's not empty.\n        \"\"\"\n        import inspect\n        if (\n            self.sig\n            and self.sig.return_annotation is not inspect.Signature.empty\n        ):\n            return self.sig.return_annotation\n        return None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-112a34f49aa9ebc7", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "9dd8218ba0275d8ec1ceef8cbeaff061017cd119bf43aff2497310565579607b", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 44, "local_path": "layout/partially-compact-layout/I10__attrs___AnnotationExtractor__917662d7.py", "order": 10, "original_content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "parent_variant_id": "pyint-97043e6fccbf-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_compat.py#L37-L80", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 14, "line_break_groups_removed": 5, "line_breaks_removed": 5, "whitespace_characters_removed": 5}, "unit_kind": "class", "unit_name": "_AnnotationExtractor", "variant_id": "pyint-eda2917662d7-I10", "group_id": "py-112a34f49aa9ebc7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1271, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d42ae4293632-I11", "source": "import sys\nimport threading\nfrom collections.abc import Mapping, Sequence  # noqa: F401\nfrom typing import Callable, _GenericAlias\n\nclass _AnnotationExtractor:\n    \"\"\"\n    Extract type annotations from a callable, returning None whenever there\n    is none.\n    \"\"\"\n\n    __slots__ = [\"sig\"]\n\n    def __init__(self, callable):\n        import inspect\n\n        try:\n            self.sig = inspect.signature(callable)\n        except (ValueError, TypeError):  # inspect failed\n            self.sig = None\n\n    def get_first_param_type(self):\n        \"\"\"\n        Return the type annotation of the first argument if it's not empty.\n        \"\"\"\n        import inspect\n\n        if not self.sig:\n            return None\n\n        params = list(self.sig.parameters.values())\n        a = 1\n        b = -1\n        if params and params[(a + b)].annotation is not inspect.Parameter.empty:\n            c = 1\n            d = -1\n            return params[(c + d)].annotation\n\n        return None\n\n    def get_return_type(self):\n        \"\"\"\n        Return the return type if it's not empty.\n        \"\"\"\n        import inspect\n\n        if (\n            self.sig\n            and self.sig.return_annotation is not inspect.Signature.empty\n        ):\n            return self.sig.return_annotation\n\n        return None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-112a34f49aa9ebc7", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "3b051e8c6b73095e483a36c11e86d913d38d3438d0994130a6b4b2d4920810a5", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 53, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___AnnotationExtractor__e4293632.py", "order": 11, "original_content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "parent_variant_id": "pyint-97043e6fccbf-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_compat.py#L37-L80", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 2, "intermediate_variables_introduced": 4, "statements_augmented": 2}, "unit_kind": "class", "unit_name": "_AnnotationExtractor", "variant_id": "pyint-d42ae4293632-I11", "group_id": "py-112a34f49aa9ebc7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1272, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d900a3e28389-I12", "source": "import sys\nimport threading\nfrom collections.abc import Mapping, Sequence  # noqa: F401\nfrom typing import Callable, _GenericAlias\n\nclass _AnnotationExtractor:\n    \"\"\"\n    Extract type annotations from a callable, returning None whenever there\n    is none.\n    \"\"\"\n\n    __slots__ = [\"sig\"]\n\n    def __init__(self, callable):\n        import inspect\n\n        try:\n            self.sig = inspect.signature(callable)\n        except (ValueError, TypeError):  # inspect failed\n            self.sig = None\n\n    def get_first_param_type(self):\n        \"\"\"\n        Return the type annotation of the first argument if it's not empty.\n        \"\"\"\n        import inspect\n\n        if not self.sig:\n            return None\n\n        params = list(self.sig.parameters.values())\n        if params and params[0].annotation is not inspect.Parameter.empty:\n            return params[0].annotation\n\n        return None\n\n    def get_return_type(self):\n        \"\"\"\n        Return the return type if it's not empty.\n        \"\"\"\n        import inspect\n\n        if (\n            self.sig\n            and self.sig.return_annotation is not inspect.Signature.empty\n        ):\n            return self.sig.return_annotation\n\n        return None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-112a34f49aa9ebc7", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 49, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___AnnotationExtractor__a3e28389.py", "order": 12, "original_content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "parent_variant_id": "pyint-97043e6fccbf-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_compat.py#L37-L80", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_AnnotationExtractor", "variant_id": "pyint-d900a3e28389-I12", "group_id": "py-112a34f49aa9ebc7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1273, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ef343a8cfde5-I13", "source": "import sys\nimport threading\nfrom collections.abc import Mapping, Sequence  # noqa: F401\nfrom typing import Callable, _GenericAlias\n\nclass _AnnotationExtractor:\n    \"\"\"\n    Extract type annotations from a callable, returning None whenever there\n    is none.\n    \"\"\"\n\n    __slots__ = [\"sig\"]\n\n    def __init__(self, callable):\n        import inspect\n\n        try:\n            self.sig = inspect.signature(callable)\n        except (ValueError, TypeError):  # inspect failed\n            self.sig = None\n\n    def get_first_param_type(self):\n        \"\"\"\n        Return the type annotation of the first argument if it's not empty.\n        \"\"\"\n        import inspect\n\n        if not self.sig:\n            return None\n\n        params = list(self.sig.parameters.values())\n        if params and params[0].annotation is not inspect.Parameter.empty:\n            return params[0].annotation\n\n        return None\n\n    def get_return_type(self):\n        \"\"\"\n        Return the return type if it's not empty.\n        \"\"\"\n        import inspect\n\n        if (\n            self.sig\n            and self.sig.return_annotation is not inspect.Signature.empty\n        ):\n            return self.sig.return_annotation\n\n        return None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-112a34f49aa9ebc7", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 49, "local_path": "control-flow/lower-for-to-while/I13__attrs___AnnotationExtractor__3a8cfde5.py", "order": 13, "original_content_sha256": "f5ad2ca5896d963d24f011527fce085e152af15c6647e7d61d4f4c9ff9906b5d", "parent_variant_id": "pyint-97043e6fccbf-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_compat.py#L37-L80", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "_AnnotationExtractor", "variant_id": "pyint-ef343a8cfde5-I13", "group_id": "py-112a34f49aa9ebc7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1274, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8c0a398c606d-SRC", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MaxLengthValidator:\n    max_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(value) > self.max_length:\n            msg = f\"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<max_len validator for {self.max_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-1296e63a3224ab7e", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 23, "local_path": "source-original/SRC__attrs___MaxLengthValidator__398c606d.py", "order": 0, "original_content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L555-L567", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_MaxLengthValidator", "variant_id": "pyint-8c0a398c606d-SRC", "group_id": "py-1296e63a3224ab7e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1373, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-028b77ecd31f-I01", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MaxLengthValidator:\n    max_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \n        if len(value) > self.max_length:\n            msg = f\"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<max_len validator for {self.max_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-1296e63a3224ab7e", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "bd35c1dee361a6b95dcf5715e942f7856d049f5ec7d011da69820281d359af5c", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 21, "local_path": "comments/remove-comments/I01__attrs___MaxLengthValidator__77ecd31f.py", "order": 1, "original_content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "parent_variant_id": "pyint-8c0a398c606d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L555-L567", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 86, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "_MaxLengthValidator", "variant_id": "pyint-028b77ecd31f-I01", "group_id": "py-1296e63a3224ab7e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1374, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8bc519db9bb8-I02", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MaxLengthValidator:\n    max_length = attrib()\n\n    def __call__(self, ins, att, val):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(val) > self.max_length:\n            msg2 = f\"Length of '{att.name}' must be <= {self.max_length}: {len(val)}\"\n            raise ValueError(msg2)\n\n    def __repr__(self):\n        return f\"<max_len validator for {self.max_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-1296e63a3224ab7e", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "6d242f565d95a872f50ca2a33685a5b981c4a1a407a43cc59dc09d204e7e3107", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 23, "local_path": "identifiers/shorten-identifiers/I02__attrs___MaxLengthValidator__19db9bb8.py", "order": 2, "original_content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "parent_variant_id": "pyint-8c0a398c606d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L555-L567", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_MaxLengthValidator", "variant_id": "pyint-8bc519db9bb8-I02", "group_id": "py-1296e63a3224ab7e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1375, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-273c22b4fe1e-I03", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MaxLengthValidator:\n    max_length = attrib()\n\n    def __call__(self, path, data, count):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(count) > self.max_length:\n            age = f\"Length of '{data.name}' must be <= {self.max_length}: {len(count)}\"\n            raise ValueError(age)\n\n    def __repr__(self):\n        return f\"<max_len validator for {self.max_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-1296e63a3224ab7e", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "397f5e859ea944da011115ff649e16c220b00af30c7bd479fd6697d7bd9b9e18", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 23, "local_path": "identifiers/mislead-identifiers/I03__attrs___MaxLengthValidator__22b4fe1e.py", "order": 3, "original_content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "parent_variant_id": "pyint-8c0a398c606d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L555-L567", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 4, "local_random_pool_selections": 4, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_MaxLengthValidator", "variant_id": "pyint-273c22b4fe1e-I03", "group_id": "py-1296e63a3224ab7e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1376, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5397de885c36-I04", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MaxLengthValidator:\n    max_length = attrib()\n\n    def __call__(self, a, b, c):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(c) > self.max_length:\n            d = f\"Length of '{b.name}' must be <= {self.max_length}: {len(c)}\"\n            raise ValueError(d)\n\n    def __repr__(self):\n        return f\"<max_len validator for {self.max_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-1296e63a3224ab7e", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "177cec6d6639628c9d0720d64332d30adf298e7eb1a8fcdd350c7a3e94dfdc5d", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 23, "local_path": "identifiers/garble-identifiers/I04__attrs___MaxLengthValidator__de885c36.py", "order": 4, "original_content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "parent_variant_id": "pyint-8c0a398c606d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L555-L567", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_MaxLengthValidator", "variant_id": "pyint-5397de885c36-I04", "group_id": "py-1296e63a3224ab7e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1377, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a2aaeb8d4de4-I05", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MaxLengthValidator:\n    max_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(value) > self.max_length:\n            msg = f\"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<max_len validator for {self.max_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-1296e63a3224ab7e", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 23, "local_path": "expressions/encode-integer-literals/I05__attrs___MaxLengthValidator__eb8d4de4.py", "order": 5, "original_content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "parent_variant_id": "pyint-8c0a398c606d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L555-L567", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "_MaxLengthValidator", "variant_id": "pyint-a2aaeb8d4de4-I05", "group_id": "py-1296e63a3224ab7e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1378, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-24ba436ab337-I06", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MaxLengthValidator:\n    max_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not (len(value) > self.max_length):\n            pass\n        else:\n            msg = f\"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<max_len validator for {self.max_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-1296e63a3224ab7e", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "63fb064f83c313ddf1eaba0b9b8a7421344daa687e92074b98a90d348ee0ab0c", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 25, "local_path": "expressions/invert-conditions/I06__attrs___MaxLengthValidator__436ab337.py", "order": 6, "original_content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "parent_variant_id": "pyint-8c0a398c606d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L555-L567", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "_MaxLengthValidator", "variant_id": "pyint-24ba436ab337-I06", "group_id": "py-1296e63a3224ab7e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1379, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b486c099186e-I07", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MaxLengthValidator:\n    max_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if ((0x3b55 ^ 0x3b55) != 0):\n            raise AssertionError()\n        if len(value) > self.max_length:\n            msg = f\"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        if ((0xf6f0 ^ 0xf6f0) != 0):\n            raise AssertionError()\n        return f\"<max_len validator for {self.max_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-1296e63a3224ab7e", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "9b6102a555f55751c9326939cce4a96e6017497cd7cd12c91844d6c1a0eb9fb8", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 27, "local_path": "code-injection/insert-dead-branches/I07__attrs___MaxLengthValidator__c099186e.py", "order": 7, "original_content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "parent_variant_id": "pyint-8c0a398c606d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L555-L567", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "_MaxLengthValidator", "variant_id": "pyint-b486c099186e-I07", "group_id": "py-1296e63a3224ab7e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1380, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0ed36ca4a214-I08", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MaxLengthValidator:\n    max_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        starting_position = 2\n        ending_position = 9\n        travel_distance = ending_position - starting_position\n        if travel_distance < 0:\n            travel_distance = -travel_distance\n        if len(value) > self.max_length:\n            msg = f\"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<max_len validator for {self.max_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-1296e63a3224ab7e", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "e1393e40255990ed233977766a58f6d51d5f6e8622b56580137b0b0e632d73cb", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 28, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___MaxLengthValidator__6ca4a214.py", "order": 8, "original_content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "parent_variant_id": "pyint-8c0a398c606d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L555-L567", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 9}, "unit_kind": "class", "unit_name": "_MaxLengthValidator", "variant_id": "pyint-0ed36ca4a214-I08", "group_id": "py-1296e63a3224ab7e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1381, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b77ec408a00f-I09", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MaxLengthValidator:\n    max_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(value) > self.max_length:\n            msg = f\"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        lI0O_0215c2eb = 0xd591 ^ 0xd591\n        if lI0O_0215c2eb == 0:\n            lI0O_0215c2eb |= 0\n        else:\n            lI0O_0215c2eb &= 0\n        return f\"<max_len validator for {self.max_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-1296e63a3224ab7e", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "c12ca17528dad05b2de4768b72a9e8ba732765d5bd84e5e0fc53b9510fcab88c", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 28, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___MaxLengthValidator__c408a00f.py", "order": 9, "original_content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "parent_variant_id": "pyint-8c0a398c606d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L555-L567", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 6}, "unit_kind": "class", "unit_name": "_MaxLengthValidator", "variant_id": "pyint-b77ec408a00f-I09", "group_id": "py-1296e63a3224ab7e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1382, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-05d4d72b5dfa-I10", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MaxLengthValidator:\n    max_length = attrib()\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(value) > self.max_length:\n            msg = f\"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<max_len validator for {self.max_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-1296e63a3224ab7e", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "0b3103cdd1424b36f2b73e759038fd5c04170ca0765a7cf31ca22cbeb9279908", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 22, "local_path": "layout/partially-compact-layout/I10__attrs___MaxLengthValidator__d72b5dfa.py", "order": 10, "original_content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "parent_variant_id": "pyint-8c0a398c606d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L555-L567", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 3, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "_MaxLengthValidator", "variant_id": "pyint-05d4d72b5dfa-I10", "group_id": "py-1296e63a3224ab7e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1383, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e2ffd6356385-I11", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MaxLengthValidator:\n    max_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(value) > self.max_length:\n            msg = f\"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<max_len validator for {self.max_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-1296e63a3224ab7e", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 23, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___MaxLengthValidator__d6356385.py", "order": 11, "original_content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "parent_variant_id": "pyint-8c0a398c606d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L555-L567", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "_MaxLengthValidator", "variant_id": "pyint-e2ffd6356385-I11", "group_id": "py-1296e63a3224ab7e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1384, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7dca19c97af9-I12", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MaxLengthValidator:\n    max_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(value) > self.max_length:\n            \n            raise ValueError((f\"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}\"))\n\n    def __repr__(self):\n        return f\"<max_len validator for {self.max_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-1296e63a3224ab7e", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "72ed0f6c0455db3d2ae0ccbe80ed616402785aa922cf6ee41e8d776f3bb5d1f2", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 23, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___MaxLengthValidator__19c97af9.py", "order": 12, "original_content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "parent_variant_id": "pyint-8c0a398c606d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L555-L567", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_MaxLengthValidator", "variant_id": "pyint-7dca19c97af9-I12", "group_id": "py-1296e63a3224ab7e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1385, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6d64bac5ba98-I13", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MaxLengthValidator:\n    max_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(value) > self.max_length:\n            msg = f\"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<max_len validator for {self.max_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-1296e63a3224ab7e", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 23, "local_path": "control-flow/lower-for-to-while/I13__attrs___MaxLengthValidator__bac5ba98.py", "order": 13, "original_content_sha256": "984d2dbcac07dc746ed6f0dcdc163026c838ecd79bfad330ad9472d85c43fd5a", "parent_variant_id": "pyint-8c0a398c606d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L555-L567", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "_MaxLengthValidator", "variant_id": "pyint-6d64bac5ba98-I13", "group_id": "py-1296e63a3224ab7e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1386, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5473842403c0-SRC", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Attribute:\n    \"\"\"\n    *Read-only* representation of an attribute.\n\n    .. warning::\n\n       You should never instantiate this class yourself.\n\n    The class has *all* arguments of `attr.ib` (except for ``factory`` which is\n    only syntactic sugar for ``default=Factory(...)`` plus the following:\n\n    - ``name`` (`str`): The name of the attribute.\n    - ``alias`` (`str`): The __init__ parameter name of the attribute, after\n      any explicit overrides and default private-attribute-name handling.\n    - ``alias_is_default`` (`bool`): Whether the ``alias`` was automatically\n      generated (``True``) or explicitly provided by the user (``False``).\n    - ``inherited`` (`bool`): Whether or not that attribute has been inherited\n      from a base class.\n    - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The\n      callables that are used for comparing and ordering objects by this\n      attribute, respectively. These are set by passing a callable to\n      `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also\n      :ref:`comparison customization <custom-comparison>`.\n\n    Instances of this class are frequently used for introspection purposes\n    like:\n\n    - `fields` returns a tuple of them.\n    - Validators get them passed as the first argument.\n    - The :ref:`field transformer <transform-fields>` hook receives a list of\n      them.\n    - The ``alias`` property exposes the __init__ parameter name of the field,\n      with any overrides and default private-attribute handling applied.\n\n\n    .. versionadded:: 20.1.0 *inherited*\n    .. versionadded:: 20.1.0 *on_setattr*\n    .. versionchanged:: 20.2.0 *inherited* is not taken into account for\n        equality checks and hashing anymore.\n    .. versionadded:: 21.1.0 *eq_key* and *order_key*\n    .. versionadded:: 22.2.0 *alias*\n    .. versionadded:: 26.1.0 *alias_is_default*\n\n    For the full version history of the fields, see `attr.ib`.\n    \"\"\"\n\n    # These slots must NOT be reordered because we use them later for\n    # instantiation.\n    __slots__ = (  # noqa: RUF023\n        \"name\",\n        \"default\",\n        \"validator\",\n        \"repr\",\n        \"eq\",\n        \"eq_key\",\n        \"order\",\n        \"order_key\",\n        \"hash\",\n        \"init\",\n        \"metadata\",\n        \"type\",\n        \"converter\",\n        \"kw_only\",\n        \"inherited\",\n        \"on_setattr\",\n        \"alias\",\n        \"alias_is_default\",\n    )\n\n    def __init__(\n        self,\n        name,\n        default,\n        validator,\n        repr,\n        cmp,  # XXX: unused, remove along with other cmp code.\n        hash,\n        init,\n        inherited,\n        metadata=None,\n        type=None,\n        converter=None,\n        kw_only=False,\n        eq=None,\n        eq_key=None,\n        order=None,\n        order_key=None,\n        on_setattr=None,\n        alias=None,\n        alias_is_default=None,\n    ):\n        eq, eq_key, order, order_key = _determine_attrib_eq_order(\n            cmp, eq_key or eq, order_key or order, True\n        )\n\n        # Cache this descriptor here to speed things up later.\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n\n        # Despite the big red warning, people *do* instantiate `Attribute`\n        # themselves.\n        bound_setattr(\"name\", name)\n        bound_setattr(\"default\", default)\n        bound_setattr(\"validator\", validator)\n        bound_setattr(\"repr\", repr)\n        bound_setattr(\"eq\", eq)\n        bound_setattr(\"eq_key\", eq_key)\n        bound_setattr(\"order\", order)\n        bound_setattr(\"order_key\", order_key)\n        bound_setattr(\"hash\", hash)\n        bound_setattr(\"init\", init)\n        bound_setattr(\"converter\", converter)\n        bound_setattr(\n            \"metadata\",\n            (\n                types.MappingProxyType(dict(metadata))  # Shallow copy\n                if metadata\n                else _EMPTY_METADATA_SINGLETON\n            ),\n        )\n        bound_setattr(\"type\", type)\n        bound_setattr(\"kw_only\", kw_only)\n        bound_setattr(\"inherited\", inherited)\n        bound_setattr(\"on_setattr\", on_setattr)\n        bound_setattr(\"alias\", alias)\n        bound_setattr(\n            \"alias_is_default\",\n            alias is None if alias_is_default is None else alias_is_default,\n        )\n\n    def __setattr__(self, name, value):\n        raise FrozenInstanceError\n\n    @classmethod\n    def from_counting_attr(\n        cls, name: str, ca: _CountingAttr, kw_only: bool, type=None\n    ):\n        # The 'kw_only' argument is the class-level setting, and is used if the\n        # attribute itself does not explicitly set 'kw_only'.\n        # type holds the annotated value. deal with conflicts:\n        if type is None:\n            type = ca.type\n        elif ca.type is not None:\n            msg = f\"Type annotation and type argument cannot both be present for '{name}'.\"\n            raise ValueError(msg)\n        return cls(\n            name,\n            ca._default,\n            ca._validator,\n            ca.repr,\n            None,\n            ca.hash,\n            ca.init,\n            False,\n            ca.metadata,\n            type,\n            ca._converter,\n            kw_only if ca.kw_only is None else ca.kw_only,\n            ca.eq,\n            ca.eq_key,\n            ca.order,\n            ca.order_key,\n            ca.on_setattr,\n            ca.alias,\n            ca.alias is None,\n        )\n\n    # Don't use attrs.evolve since fields(Attribute) doesn't work\n    def evolve(self, **changes):\n        \"\"\"\n        Copy *self* and apply *changes*.\n\n        This works similarly to `attrs.evolve` but that function does not work\n        with :class:`attrs.Attribute`.\n\n        It is mainly meant to be used for `transform-fields`.\n\n        .. versionadded:: 20.3.0\n        \"\"\"\n        import copy\n\n        new = copy.copy(self)\n\n        new._setattrs(changes.items())\n\n        if \"alias\" in changes and \"alias_is_default\" not in changes:\n            # Explicit alias provided -- no longer the default.\n            _OBJ_SETATTR.__get__(new)(\"alias_is_default\", False)\n        elif (\n            \"name\" in changes\n            and \"alias\" not in changes\n            # Don't auto-generate alias if the user picked picked the old one.\n            and self.alias_is_default\n        ):\n            # Name changed, alias was auto-generated -- update it.\n            _OBJ_SETATTR.__get__(new)(\n                \"alias\", _default_init_alias_for(new.name)\n            )\n\n        return new\n\n    # Don't use _add_pickle since fields(Attribute) doesn't work\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(\n            getattr(self, name) if name != \"metadata\" else dict(self.metadata)\n            for name in self.__slots__\n        )\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if len(state) < len(self.__slots__):\n            # Pre-26.1.0 pickle without alias_is_default -- infer it\n            # heuristically.\n            state_dict = dict(zip(self.__slots__, state, strict=False))\n            alias_is_default = state_dict.get(\n                \"alias\"\n            ) is None or state_dict.get(\"alias\") == _default_init_alias_for(\n                state_dict[\"name\"]\n            )\n            state = (*state, alias_is_default)\n\n        self._setattrs(zip(self.__slots__, state, strict=True))\n\n    def _setattrs(self, name_values_pairs):\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n        for name, value in name_values_pairs:\n            if name != \"metadata\":\n                bound_setattr(name, value)\n            else:\n                bound_setattr(\n                    name,\n                    (\n                        types.MappingProxyType(dict(value))\n                        if value\n                        else _EMPTY_METADATA_SINGLETON\n                    ),\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-1305f98138f397c2", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 270, "local_path": "source-original/SRC__attrs__Attribute__842403c0.py", "order": 0, "original_content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2462-L2702", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Attribute", "variant_id": "pyint-5473842403c0-SRC", "group_id": "py-1305f98138f397c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1275, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-324dd5ef5c38-I01", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Attribute:\n    \n\n     \n     \n    __slots__ = (   \n        \"name\",\n        \"default\",\n        \"validator\",\n        \"repr\",\n        \"eq\",\n        \"eq_key\",\n        \"order\",\n        \"order_key\",\n        \"hash\",\n        \"init\",\n        \"metadata\",\n        \"type\",\n        \"converter\",\n        \"kw_only\",\n        \"inherited\",\n        \"on_setattr\",\n        \"alias\",\n        \"alias_is_default\",\n    )\n\n    def __init__(\n        self,\n        name,\n        default,\n        validator,\n        repr,\n        cmp,   \n        hash,\n        init,\n        inherited,\n        metadata=None,\n        type=None,\n        converter=None,\n        kw_only=False,\n        eq=None,\n        eq_key=None,\n        order=None,\n        order_key=None,\n        on_setattr=None,\n        alias=None,\n        alias_is_default=None,\n    ):\n        eq, eq_key, order, order_key = _determine_attrib_eq_order(\n            cmp, eq_key or eq, order_key or order, True\n        )\n\n         \n        bound_setattr = _OBJ_SETATTR.__get__(self)\n\n         \n         \n        bound_setattr(\"name\", name)\n        bound_setattr(\"default\", default)\n        bound_setattr(\"validator\", validator)\n        bound_setattr(\"repr\", repr)\n        bound_setattr(\"eq\", eq)\n        bound_setattr(\"eq_key\", eq_key)\n        bound_setattr(\"order\", order)\n        bound_setattr(\"order_key\", order_key)\n        bound_setattr(\"hash\", hash)\n        bound_setattr(\"init\", init)\n        bound_setattr(\"converter\", converter)\n        bound_setattr(\n            \"metadata\",\n            (\n                types.MappingProxyType(dict(metadata))   \n                if metadata\n                else _EMPTY_METADATA_SINGLETON\n            ),\n        )\n        bound_setattr(\"type\", type)\n        bound_setattr(\"kw_only\", kw_only)\n        bound_setattr(\"inherited\", inherited)\n        bound_setattr(\"on_setattr\", on_setattr)\n        bound_setattr(\"alias\", alias)\n        bound_setattr(\n            \"alias_is_default\",\n            alias is None if alias_is_default is None else alias_is_default,\n        )\n\n    def __setattr__(self, name, value):\n        raise FrozenInstanceError\n\n    @classmethod\n    def from_counting_attr(\n        cls, name: str, ca: _CountingAttr, kw_only: bool, type=None\n    ):\n         \n         \n         \n        if type is None:\n            type = ca.type\n        elif ca.type is not None:\n            msg = f\"Type annotation and type argument cannot both be present for '{name}'.\"\n            raise ValueError(msg)\n        return cls(\n            name,\n            ca._default,\n            ca._validator,\n            ca.repr,\n            None,\n            ca.hash,\n            ca.init,\n            False,\n            ca.metadata,\n            type,\n            ca._converter,\n            kw_only if ca.kw_only is None else ca.kw_only,\n            ca.eq,\n            ca.eq_key,\n            ca.order,\n            ca.order_key,\n            ca.on_setattr,\n            ca.alias,\n            ca.alias is None,\n        )\n\n     \n    def evolve(self, **changes):\n        \n        import copy\n\n        new = copy.copy(self)\n\n        new._setattrs(changes.items())\n\n        if \"alias\" in changes and \"alias_is_default\" not in changes:\n             \n            _OBJ_SETATTR.__get__(new)(\"alias_is_default\", False)\n        elif (\n            \"name\" in changes\n            and \"alias\" not in changes\n             \n            and self.alias_is_default\n        ):\n             \n            _OBJ_SETATTR.__get__(new)(\n                \"alias\", _default_init_alias_for(new.name)\n            )\n\n        return new\n\n     \n    def __getstate__(self):\n        \n        return tuple(\n            getattr(self, name) if name != \"metadata\" else dict(self.metadata)\n            for name in self.__slots__\n        )\n\n    def __setstate__(self, state):\n        \n        if len(state) < len(self.__slots__):\n             \n             \n            state_dict = dict(zip(self.__slots__, state, strict=False))\n            alias_is_default = state_dict.get(\n                \"alias\"\n            ) is None or state_dict.get(\"alias\") == _default_init_alias_for(\n                state_dict[\"name\"]\n            )\n            state = (*state, alias_is_default)\n\n        self._setattrs(zip(self.__slots__, state, strict=True))\n\n    def _setattrs(self, name_values_pairs):\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n        for name, value in name_values_pairs:\n            if name != \"metadata\":\n                bound_setattr(name, value)\n            else:\n                bound_setattr(\n                    name,\n                    (\n                        types.MappingProxyType(dict(value))\n                        if value\n                        else _EMPTY_METADATA_SINGLETON\n                    ),\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-1305f98138f397c2", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "b4173d0b4ac5721bdbada2f9295f00dea339a97559795a25d2afc95c69a2d702", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 214, "local_path": "comments/remove-comments/I01__attrs__Attribute__d5ef5c38.py", "order": 1, "original_content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "parent_variant_id": "pyint-5473842403c0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2462-L2702", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 3098, "comments_removed": 22, "docstrings_removed": 4, "line_comments_removed": 18}, "unit_kind": "class", "unit_name": "Attribute", "variant_id": "pyint-324dd5ef5c38-I01", "group_id": "py-1305f98138f397c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1276, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-56e61b2a25f5-I02", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Attribute:\n    \"\"\"\n    *Read-only* representation of an attribute.\n\n    .. warning::\n\n       You should never instantiate this class yourself.\n\n    The class has *all* arguments of `attr.ib` (except for ``factory`` which is\n    only syntactic sugar for ``default=Factory(...)`` plus the following:\n\n    - ``name`` (`str`): The name of the attribute.\n    - ``alias`` (`str`): The __init__ parameter name of the attribute, after\n      any explicit overrides and default private-attribute-name handling.\n    - ``alias_is_default`` (`bool`): Whether the ``alias`` was automatically\n      generated (``True``) or explicitly provided by the user (``False``).\n    - ``inherited`` (`bool`): Whether or not that attribute has been inherited\n      from a base class.\n    - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The\n      callables that are used for comparing and ordering objects by this\n      attribute, respectively. These are set by passing a callable to\n      `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also\n      :ref:`comparison customization <custom-comparison>`.\n\n    Instances of this class are frequently used for introspection purposes\n    like:\n\n    - `fields` returns a tuple of them.\n    - Validators get them passed as the first argument.\n    - The :ref:`field transformer <transform-fields>` hook receives a list of\n      them.\n    - The ``alias`` property exposes the __init__ parameter name of the field,\n      with any overrides and default private-attribute handling applied.\n\n\n    .. versionadded:: 20.1.0 *inherited*\n    .. versionadded:: 20.1.0 *on_setattr*\n    .. versionchanged:: 20.2.0 *inherited* is not taken into account for\n        equality checks and hashing anymore.\n    .. versionadded:: 21.1.0 *eq_key* and *order_key*\n    .. versionadded:: 22.2.0 *alias*\n    .. versionadded:: 26.1.0 *alias_is_default*\n\n    For the full version history of the fields, see `attr.ib`.\n    \"\"\"\n\n    # These slots must NOT be reordered because we use them later for\n    # instantiation.\n    __slots__ = (  # noqa: RUF023\n        \"name\",\n        \"default\",\n        \"validator\",\n        \"repr\",\n        \"eq\",\n        \"eq_key\",\n        \"order\",\n        \"order_key\",\n        \"hash\",\n        \"init\",\n        \"metadata\",\n        \"type\",\n        \"converter\",\n        \"kw_only\",\n        \"inherited\",\n        \"on_setattr\",\n        \"alias\",\n        \"alias_is_default\",\n    )\n\n    def __init__(\n        self,\n        nam,\n        def2,\n        val,\n        rep,\n        cmp2,  # XXX: unused, remove along with other cmp code.\n        has,\n        ini,\n        inh,\n        met=None,\n        typ=None,\n        con=None,\n        kw=False,\n        eq2=None,\n        eq3=None,\n        ord=None,\n        order2=None,\n        on=None,\n        ali=None,\n        alias2=None,\n    ):\n        eq2, eq3, ord, order2 = _determine_attrib_eq_order(\n            cmp2, eq3 or eq2, order2 or ord, True\n        )\n\n        # Cache this descriptor here to speed things up later.\n        bound = _OBJ_SETATTR.__get__(self)\n\n        # Despite the big red warning, people *do* instantiate `Attribute`\n        # themselves.\n        bound(\"name\", nam)\n        bound(\"default\", def2)\n        bound(\"validator\", val)\n        bound(\"repr\", rep)\n        bound(\"eq\", eq2)\n        bound(\"eq_key\", eq3)\n        bound(\"order\", ord)\n        bound(\"order_key\", order2)\n        bound(\"hash\", has)\n        bound(\"init\", ini)\n        bound(\"converter\", con)\n        bound(\n            \"metadata\",\n            (\n                types.MappingProxyType(dict(met))  # Shallow copy\n                if met\n                else _EMPTY_METADATA_SINGLETON\n            ),\n        )\n        bound(\"type\", typ)\n        bound(\"kw_only\", kw)\n        bound(\"inherited\", inh)\n        bound(\"on_setattr\", on)\n        bound(\"alias\", ali)\n        bound(\n            \"alias_is_default\",\n            ali is None if alias2 is None else alias2,\n        )\n\n    def __setattr__(self, nam2, val2):\n        raise FrozenInstanceError\n\n    @classmethod\n    def from2(\n        cls, nam3: str, ca2: _CountingAttr, kw2: bool, typ2=None\n    ):\n        # The 'kw_only' argument is the class-level setting, and is used if the\n        # attribute itself does not explicitly set 'kw_only'.\n        # type holds the annotated value. deal with conflicts:\n        if typ2 is None:\n            typ2 = ca2.type\n        elif ca2.type is not None:\n            msg2 = f\"Type annotation and type argument cannot both be present for '{nam3}'.\"\n            raise ValueError(msg2)\n        return cls(\n            nam3,\n            ca2._default,\n            ca2._validator,\n            ca2.repr,\n            None,\n            ca2.hash,\n            ca2.init,\n            False,\n            ca2.metadata,\n            typ2,\n            ca2._converter,\n            kw2 if ca2.kw_only is None else ca2.kw_only,\n            ca2.eq,\n            ca2.eq_key,\n            ca2.order,\n            ca2.order_key,\n            ca2.on_setattr,\n            ca2.alias,\n            ca2.alias is None,\n        )\n\n    # Don't use attrs.evolve since fields(Attribute) doesn't work\n    def evo(self, **cha):\n        \"\"\"\n        Copy *self* and apply *changes*.\n\n        This works similarly to `attrs.evolve` but that function does not work\n        with :class:`attrs.Attribute`.\n\n        It is mainly meant to be used for `transform-fields`.\n\n        .. versionadded:: 20.3.0\n        \"\"\"\n        import copy\n\n        new2 = copy.copy(self)\n\n        new2._setattrs(cha.items())\n\n        if \"alias\" in cha and \"alias_is_default\" not in cha:\n            # Explicit alias provided -- no longer the default.\n            _OBJ_SETATTR.__get__(new2)(\"alias_is_default\", False)\n        elif (\n            \"name\" in cha\n            and \"alias\" not in cha\n            # Don't auto-generate alias if the user picked picked the old one.\n            and self.alias_is_default\n        ):\n            # Name changed, alias was auto-generated -- update it.\n            _OBJ_SETATTR.__get__(new2)(\n                \"alias\", _default_init_alias_for(new2.name)\n            )\n\n        return new2\n\n    # Don't use _add_pickle since fields(Attribute) doesn't work\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(\n            getattr(self, nam4) if nam4 != \"metadata\" else dict(self.metadata)\n            for nam4 in self.__slots__\n        )\n\n    def __setstate__(self, sta):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if len(sta) < len(self.__slots__):\n            # Pre-26.1.0 pickle without alias_is_default -- infer it\n            # heuristically.\n            state2 = dict(zip(self.__slots__, sta, strict=False))\n            alias3 = state2.get(\n                \"alias\"\n            ) is None or state2.get(\"alias\") == _default_init_alias_for(\n                state2[\"name\"]\n            )\n            sta = (*sta, alias3)\n\n        self.set(zip(self.__slots__, sta, strict=True))\n\n    def set(self, name2):\n        bound2 = _OBJ_SETATTR.__get__(self)\n        for nam5, val3 in name2:\n            if nam5 != \"metadata\":\n                bound2(nam5, val3)\n            else:\n                bound2(\n                    nam5,\n                    (\n                        types.MappingProxyType(dict(val3))\n                        if val3\n                        else _EMPTY_METADATA_SINGLETON\n                    ),\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-1305f98138f397c2", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "6f5b8539ec60df98fb1da8b57cef0eab874ee1bfa1236dc84e586ce2e0ebc681", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 270, "local_path": "identifiers/shorten-identifiers/I02__attrs__Attribute__1b2a25f5.py", "order": 2, "original_content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "parent_variant_id": "pyint-5473842403c0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2462-L2702", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 144, "identifiers_declared": 40}, "unit_kind": "class", "unit_name": "Attribute", "variant_id": "pyint-56e61b2a25f5-I02", "group_id": "py-1305f98138f397c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1277, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ba8634181a0b-I03", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Attribute:\n    \"\"\"\n    *Read-only* representation of an attribute.\n\n    .. warning::\n\n       You should never instantiate this class yourself.\n\n    The class has *all* arguments of `attr.ib` (except for ``factory`` which is\n    only syntactic sugar for ``default=Factory(...)`` plus the following:\n\n    - ``name`` (`str`): The name of the attribute.\n    - ``alias`` (`str`): The __init__ parameter name of the attribute, after\n      any explicit overrides and default private-attribute-name handling.\n    - ``alias_is_default`` (`bool`): Whether the ``alias`` was automatically\n      generated (``True``) or explicitly provided by the user (``False``).\n    - ``inherited`` (`bool`): Whether or not that attribute has been inherited\n      from a base class.\n    - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The\n      callables that are used for comparing and ordering objects by this\n      attribute, respectively. These are set by passing a callable to\n      `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also\n      :ref:`comparison customization <custom-comparison>`.\n\n    Instances of this class are frequently used for introspection purposes\n    like:\n\n    - `fields` returns a tuple of them.\n    - Validators get them passed as the first argument.\n    - The :ref:`field transformer <transform-fields>` hook receives a list of\n      them.\n    - The ``alias`` property exposes the __init__ parameter name of the field,\n      with any overrides and default private-attribute handling applied.\n\n\n    .. versionadded:: 20.1.0 *inherited*\n    .. versionadded:: 20.1.0 *on_setattr*\n    .. versionchanged:: 20.2.0 *inherited* is not taken into account for\n        equality checks and hashing anymore.\n    .. versionadded:: 21.1.0 *eq_key* and *order_key*\n    .. versionadded:: 22.2.0 *alias*\n    .. versionadded:: 26.1.0 *alias_is_default*\n\n    For the full version history of the fields, see `attr.ib`.\n    \"\"\"\n\n    # These slots must NOT be reordered because we use them later for\n    # instantiation.\n    __slots__ = (  # noqa: RUF023\n        \"name\",\n        \"default\",\n        \"validator\",\n        \"repr\",\n        \"eq\",\n        \"eq_key\",\n        \"order\",\n        \"order_key\",\n        \"hash\",\n        \"init\",\n        \"metadata\",\n        \"type\",\n        \"converter\",\n        \"kw_only\",\n        \"inherited\",\n        \"on_setattr\",\n        \"alias\",\n        \"alias_is_default\",\n    )\n\n    def __init__(\n        self,\n        user,\n        feature,\n        localUser,\n        node,\n        map,  # XXX: unused, remove along with other cmp code.\n        date,\n        step,\n        operation,\n        customer=None,\n        flag=None,\n        nextIndex=None,\n        request=False,\n        key=None,\n        region=None,\n        count=None,\n        localData=None,\n        activeNode=None,\n        state=None,\n        pendingAccount=None,\n    ):\n        key, region, count, localData = _determine_attrib_eq_order(\n            map, region or key, localData or count, True\n        )\n\n        # Cache this descriptor here to speed things up later.\n        primaryStatus = _OBJ_SETATTR.__get__(self)\n\n        # Despite the big red warning, people *do* instantiate `Attribute`\n        # themselves.\n        primaryStatus(\"name\", user)\n        primaryStatus(\"default\", feature)\n        primaryStatus(\"validator\", localUser)\n        primaryStatus(\"repr\", node)\n        primaryStatus(\"eq\", key)\n        primaryStatus(\"eq_key\", region)\n        primaryStatus(\"order\", count)\n        primaryStatus(\"order_key\", localData)\n        primaryStatus(\"hash\", date)\n        primaryStatus(\"init\", step)\n        primaryStatus(\"converter\", nextIndex)\n        primaryStatus(\n            \"metadata\",\n            (\n                types.MappingProxyType(dict(customer))  # Shallow copy\n                if customer\n                else _EMPTY_METADATA_SINGLETON\n            ),\n        )\n        primaryStatus(\"type\", flag)\n        primaryStatus(\"kw_only\", request)\n        primaryStatus(\"inherited\", operation)\n        primaryStatus(\"on_setattr\", activeNode)\n        primaryStatus(\"alias\", state)\n        primaryStatus(\n            \"alias_is_default\",\n            state is None if pendingAccount is None else pendingAccount,\n        )\n\n    def __setattr__(self, node, batch):\n        raise FrozenInstanceError\n\n    @classmethod\n    def validateAddress(\n        cls, step: str, map: _CountingAttr, request: bool, size=None\n    ):\n        # The 'kw_only' argument is the class-level setting, and is used if the\n        # attribute itself does not explicitly set 'kw_only'.\n        # type holds the annotated value. deal with conflicts:\n        if size is None:\n            size = map.type\n        elif map.type is not None:\n            key = f\"Type annotation and type argument cannot both be present for '{step}'.\"\n            raise ValueError(key)\n        return cls(\n            step,\n            map._default,\n            map._validator,\n            map.repr,\n            None,\n            map.hash,\n            map.init,\n            False,\n            map.metadata,\n            size,\n            map._converter,\n            request if map.kw_only is None else map.kw_only,\n            map.eq,\n            map.eq_key,\n            map.order,\n            map.order_key,\n            map.on_setattr,\n            map.alias,\n            map.alias is None,\n        )\n\n    # Don't use attrs.evolve since fields(Attribute) doesn't work\n    def create(self, **summary):\n        \"\"\"\n        Copy *self* and apply *changes*.\n\n        This works similarly to `attrs.evolve` but that function does not work\n        with :class:`attrs.Attribute`.\n\n        It is mainly meant to be used for `transform-fields`.\n\n        .. versionadded:: 20.3.0\n        \"\"\"\n        import copy\n\n        map = copy.copy(self)\n\n        map._setattrs(summary.items())\n\n        if \"alias\" in summary and \"alias_is_default\" not in summary:\n            # Explicit alias provided -- no longer the default.\n            _OBJ_SETATTR.__get__(map)(\"alias_is_default\", False)\n        elif (\n            \"name\" in summary\n            and \"alias\" not in summary\n            # Don't auto-generate alias if the user picked picked the old one.\n            and self.alias_is_default\n        ):\n            # Name changed, alias was auto-generated -- update it.\n            _OBJ_SETATTR.__get__(map)(\n                \"alias\", _default_init_alias_for(map.name)\n            )\n\n        return map\n\n    # Don't use _add_pickle since fields(Attribute) doesn't work\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(\n            getattr(self, mode) if mode != \"metadata\" else dict(self.metadata)\n            for mode in self.__slots__\n        )\n\n    def __setstate__(self, count):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if len(count) < len(self.__slots__):\n            # Pre-26.1.0 pickle without alias_is_default -- infer it\n            # heuristically.\n            finalCache = dict(zip(self.__slots__, count, strict=False))\n            defaultBalance = finalCache.get(\n                \"alias\"\n            ) is None or finalCache.get(\"alias\") == _default_init_alias_for(\n                finalCache[\"name\"]\n            )\n            count = (*count, defaultBalance)\n\n        self.readState(zip(self.__slots__, count, strict=True))\n\n    def readState(self, pendingSession):\n        recentAddress = _OBJ_SETATTR.__get__(self)\n        for node, limit in pendingSession:\n            if node != \"metadata\":\n                recentAddress(node, limit)\n            else:\n                recentAddress(\n                    node,\n                    (\n                        types.MappingProxyType(dict(limit))\n                        if limit\n                        else _EMPTY_METADATA_SINGLETON\n                    ),\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-1305f98138f397c2", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "addea162d5559a50d3029820f583b0567b931dd7c380da3887a1608c62a1a044", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 270, "local_path": "identifiers/mislead-identifiers/I03__attrs__Attribute__34181a0b.py", "order": 3, "original_content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "parent_variant_id": "pyint-5473842403c0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2462-L2702", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 144, "identifiers_declared": 40, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 2, "local_exact_length_matches": 32, "local_random_pool_selections": 37, "local_total_length_difference": 9, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 2, "method_random_pool_selections": 3, "method_total_length_difference": 3}, "unit_kind": "class", "unit_name": "Attribute", "variant_id": "pyint-ba8634181a0b-I03", "group_id": "py-1305f98138f397c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1278, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9e92bbef88f9-I04", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Attribute:\n    \"\"\"\n    *Read-only* representation of an attribute.\n\n    .. warning::\n\n       You should never instantiate this class yourself.\n\n    The class has *all* arguments of `attr.ib` (except for ``factory`` which is\n    only syntactic sugar for ``default=Factory(...)`` plus the following:\n\n    - ``name`` (`str`): The name of the attribute.\n    - ``alias`` (`str`): The __init__ parameter name of the attribute, after\n      any explicit overrides and default private-attribute-name handling.\n    - ``alias_is_default`` (`bool`): Whether the ``alias`` was automatically\n      generated (``True``) or explicitly provided by the user (``False``).\n    - ``inherited`` (`bool`): Whether or not that attribute has been inherited\n      from a base class.\n    - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The\n      callables that are used for comparing and ordering objects by this\n      attribute, respectively. These are set by passing a callable to\n      `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also\n      :ref:`comparison customization <custom-comparison>`.\n\n    Instances of this class are frequently used for introspection purposes\n    like:\n\n    - `fields` returns a tuple of them.\n    - Validators get them passed as the first argument.\n    - The :ref:`field transformer <transform-fields>` hook receives a list of\n      them.\n    - The ``alias`` property exposes the __init__ parameter name of the field,\n      with any overrides and default private-attribute handling applied.\n\n\n    .. versionadded:: 20.1.0 *inherited*\n    .. versionadded:: 20.1.0 *on_setattr*\n    .. versionchanged:: 20.2.0 *inherited* is not taken into account for\n        equality checks and hashing anymore.\n    .. versionadded:: 21.1.0 *eq_key* and *order_key*\n    .. versionadded:: 22.2.0 *alias*\n    .. versionadded:: 26.1.0 *alias_is_default*\n\n    For the full version history of the fields, see `attr.ib`.\n    \"\"\"\n\n    # These slots must NOT be reordered because we use them later for\n    # instantiation.\n    __slots__ = (  # noqa: RUF023\n        \"name\",\n        \"default\",\n        \"validator\",\n        \"repr\",\n        \"eq\",\n        \"eq_key\",\n        \"order\",\n        \"order_key\",\n        \"hash\",\n        \"init\",\n        \"metadata\",\n        \"type\",\n        \"converter\",\n        \"kw_only\",\n        \"inherited\",\n        \"on_setattr\",\n        \"alias\",\n        \"alias_is_default\",\n    )\n\n    def __init__(\n        self,\n        d,\n        e,\n        f,\n        g,\n        h,  # XXX: unused, remove along with other cmp code.\n        i,\n        j,\n        k,\n        l=None,\n        m=None,\n        n=None,\n        o=False,\n        p=None,\n        q=None,\n        r=None,\n        s=None,\n        t=None,\n        u=None,\n        v=None,\n    ):\n        p, q, r, s = _determine_attrib_eq_order(\n            h, q or p, s or r, True\n        )\n\n        # Cache this descriptor here to speed things up later.\n        w = _OBJ_SETATTR.__get__(self)\n\n        # Despite the big red warning, people *do* instantiate `Attribute`\n        # themselves.\n        w(\"name\", d)\n        w(\"default\", e)\n        w(\"validator\", f)\n        w(\"repr\", g)\n        w(\"eq\", p)\n        w(\"eq_key\", q)\n        w(\"order\", r)\n        w(\"order_key\", s)\n        w(\"hash\", i)\n        w(\"init\", j)\n        w(\"converter\", n)\n        w(\n            \"metadata\",\n            (\n                types.MappingProxyType(dict(l))  # Shallow copy\n                if l\n                else _EMPTY_METADATA_SINGLETON\n            ),\n        )\n        w(\"type\", m)\n        w(\"kw_only\", o)\n        w(\"inherited\", k)\n        w(\"on_setattr\", t)\n        w(\"alias\", u)\n        w(\n            \"alias_is_default\",\n            u is None if v is None else v,\n        )\n\n    def __setattr__(self, x, y):\n        raise FrozenInstanceError\n\n    @classmethod\n    def a(\n        cls, z: str, A: _CountingAttr, B: bool, C=None\n    ):\n        # The 'kw_only' argument is the class-level setting, and is used if the\n        # attribute itself does not explicitly set 'kw_only'.\n        # type holds the annotated value. deal with conflicts:\n        if C is None:\n            C = A.type\n        elif A.type is not None:\n            D = f\"Type annotation and type argument cannot both be present for '{z}'.\"\n            raise ValueError(D)\n        return cls(\n            z,\n            A._default,\n            A._validator,\n            A.repr,\n            None,\n            A.hash,\n            A.init,\n            False,\n            A.metadata,\n            C,\n            A._converter,\n            B if A.kw_only is None else A.kw_only,\n            A.eq,\n            A.eq_key,\n            A.order,\n            A.order_key,\n            A.on_setattr,\n            A.alias,\n            A.alias is None,\n        )\n\n    # Don't use attrs.evolve since fields(Attribute) doesn't work\n    def b(self, **E):\n        \"\"\"\n        Copy *self* and apply *changes*.\n\n        This works similarly to `attrs.evolve` but that function does not work\n        with :class:`attrs.Attribute`.\n\n        It is mainly meant to be used for `transform-fields`.\n\n        .. versionadded:: 20.3.0\n        \"\"\"\n        import copy\n\n        F = copy.copy(self)\n\n        F._setattrs(E.items())\n\n        if \"alias\" in E and \"alias_is_default\" not in E:\n            # Explicit alias provided -- no longer the default.\n            _OBJ_SETATTR.__get__(F)(\"alias_is_default\", False)\n        elif (\n            \"name\" in E\n            and \"alias\" not in E\n            # Don't auto-generate alias if the user picked picked the old one.\n            and self.alias_is_default\n        ):\n            # Name changed, alias was auto-generated -- update it.\n            _OBJ_SETATTR.__get__(F)(\n                \"alias\", _default_init_alias_for(F.name)\n            )\n\n        return F\n\n    # Don't use _add_pickle since fields(Attribute) doesn't work\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(\n            getattr(self, G) if G != \"metadata\" else dict(self.metadata)\n            for G in self.__slots__\n        )\n\n    def __setstate__(self, H):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if len(H) < len(self.__slots__):\n            # Pre-26.1.0 pickle without alias_is_default -- infer it\n            # heuristically.\n            I = dict(zip(self.__slots__, H, strict=False))\n            J = I.get(\n                \"alias\"\n            ) is None or I.get(\"alias\") == _default_init_alias_for(\n                I[\"name\"]\n            )\n            H = (*H, J)\n\n        self.c(zip(self.__slots__, H, strict=True))\n\n    def c(self, K):\n        L = _OBJ_SETATTR.__get__(self)\n        for M, N in K:\n            if M != \"metadata\":\n                L(M, N)\n            else:\n                L(\n                    M,\n                    (\n                        types.MappingProxyType(dict(N))\n                        if N\n                        else _EMPTY_METADATA_SINGLETON\n                    ),\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-1305f98138f397c2", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b9470dc73d38c6c8d05a4755cb48dc236448c17c39c6fca369b8d058bab996d1", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 270, "local_path": "identifiers/garble-identifiers/I04__attrs__Attribute__bbef88f9.py", "order": 4, "original_content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "parent_variant_id": "pyint-5473842403c0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2462-L2702", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 144, "identifiers_declared": 40}, "unit_kind": "class", "unit_name": "Attribute", "variant_id": "pyint-9e92bbef88f9-I04", "group_id": "py-1305f98138f397c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1279, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-549c5b3ccd1f-I05", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Attribute:\n    \"\"\"\n    *Read-only* representation of an attribute.\n\n    .. warning::\n\n       You should never instantiate this class yourself.\n\n    The class has *all* arguments of `attr.ib` (except for ``factory`` which is\n    only syntactic sugar for ``default=Factory(...)`` plus the following:\n\n    - ``name`` (`str`): The name of the attribute.\n    - ``alias`` (`str`): The __init__ parameter name of the attribute, after\n      any explicit overrides and default private-attribute-name handling.\n    - ``alias_is_default`` (`bool`): Whether the ``alias`` was automatically\n      generated (``True``) or explicitly provided by the user (``False``).\n    - ``inherited`` (`bool`): Whether or not that attribute has been inherited\n      from a base class.\n    - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The\n      callables that are used for comparing and ordering objects by this\n      attribute, respectively. These are set by passing a callable to\n      `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also\n      :ref:`comparison customization <custom-comparison>`.\n\n    Instances of this class are frequently used for introspection purposes\n    like:\n\n    - `fields` returns a tuple of them.\n    - Validators get them passed as the first argument.\n    - The :ref:`field transformer <transform-fields>` hook receives a list of\n      them.\n    - The ``alias`` property exposes the __init__ parameter name of the field,\n      with any overrides and default private-attribute handling applied.\n\n\n    .. versionadded:: 20.1.0 *inherited*\n    .. versionadded:: 20.1.0 *on_setattr*\n    .. versionchanged:: 20.2.0 *inherited* is not taken into account for\n        equality checks and hashing anymore.\n    .. versionadded:: 21.1.0 *eq_key* and *order_key*\n    .. versionadded:: 22.2.0 *alias*\n    .. versionadded:: 26.1.0 *alias_is_default*\n\n    For the full version history of the fields, see `attr.ib`.\n    \"\"\"\n\n    # These slots must NOT be reordered because we use them later for\n    # instantiation.\n    __slots__ = (  # noqa: RUF023\n        \"name\",\n        \"default\",\n        \"validator\",\n        \"repr\",\n        \"eq\",\n        \"eq_key\",\n        \"order\",\n        \"order_key\",\n        \"hash\",\n        \"init\",\n        \"metadata\",\n        \"type\",\n        \"converter\",\n        \"kw_only\",\n        \"inherited\",\n        \"on_setattr\",\n        \"alias\",\n        \"alias_is_default\",\n    )\n\n    def __init__(\n        self,\n        name,\n        default,\n        validator,\n        repr,\n        cmp,  # XXX: unused, remove along with other cmp code.\n        hash,\n        init,\n        inherited,\n        metadata=None,\n        type=None,\n        converter=None,\n        kw_only=False,\n        eq=None,\n        eq_key=None,\n        order=None,\n        order_key=None,\n        on_setattr=None,\n        alias=None,\n        alias_is_default=None,\n    ):\n        eq, eq_key, order, order_key = _determine_attrib_eq_order(\n            cmp, eq_key or eq, order_key or order, True\n        )\n\n        # Cache this descriptor here to speed things up later.\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n\n        # Despite the big red warning, people *do* instantiate `Attribute`\n        # themselves.\n        bound_setattr(\"name\", name)\n        bound_setattr(\"default\", default)\n        bound_setattr(\"validator\", validator)\n        bound_setattr(\"repr\", repr)\n        bound_setattr(\"eq\", eq)\n        bound_setattr(\"eq_key\", eq_key)\n        bound_setattr(\"order\", order)\n        bound_setattr(\"order_key\", order_key)\n        bound_setattr(\"hash\", hash)\n        bound_setattr(\"init\", init)\n        bound_setattr(\"converter\", converter)\n        bound_setattr(\n            \"metadata\",\n            (\n                types.MappingProxyType(dict(metadata))  # Shallow copy\n                if metadata\n                else _EMPTY_METADATA_SINGLETON\n            ),\n        )\n        bound_setattr(\"type\", type)\n        bound_setattr(\"kw_only\", kw_only)\n        bound_setattr(\"inherited\", inherited)\n        bound_setattr(\"on_setattr\", on_setattr)\n        bound_setattr(\"alias\", alias)\n        bound_setattr(\n            \"alias_is_default\",\n            alias is None if alias_is_default is None else alias_is_default,\n        )\n\n    def __setattr__(self, name, value):\n        raise FrozenInstanceError\n\n    @classmethod\n    def from_counting_attr(\n        cls, name: str, ca: _CountingAttr, kw_only: bool, type=None\n    ):\n        # The 'kw_only' argument is the class-level setting, and is used if the\n        # attribute itself does not explicitly set 'kw_only'.\n        # type holds the annotated value. deal with conflicts:\n        if type is None:\n            type = ca.type\n        elif ca.type is not None:\n            msg = f\"Type annotation and type argument cannot both be present for '{name}'.\"\n            raise ValueError(msg)\n        return cls(\n            name,\n            ca._default,\n            ca._validator,\n            ca.repr,\n            None,\n            ca.hash,\n            ca.init,\n            False,\n            ca.metadata,\n            type,\n            ca._converter,\n            kw_only if ca.kw_only is None else ca.kw_only,\n            ca.eq,\n            ca.eq_key,\n            ca.order,\n            ca.order_key,\n            ca.on_setattr,\n            ca.alias,\n            ca.alias is None,\n        )\n\n    # Don't use attrs.evolve since fields(Attribute) doesn't work\n    def evolve(self, **changes):\n        \"\"\"\n        Copy *self* and apply *changes*.\n\n        This works similarly to `attrs.evolve` but that function does not work\n        with :class:`attrs.Attribute`.\n\n        It is mainly meant to be used for `transform-fields`.\n\n        .. versionadded:: 20.3.0\n        \"\"\"\n        import copy\n\n        new = copy.copy(self)\n\n        new._setattrs(changes.items())\n\n        if \"alias\" in changes and \"alias_is_default\" not in changes:\n            # Explicit alias provided -- no longer the default.\n            _OBJ_SETATTR.__get__(new)(\"alias_is_default\", False)\n        elif (\n            \"name\" in changes\n            and \"alias\" not in changes\n            # Don't auto-generate alias if the user picked picked the old one.\n            and self.alias_is_default\n        ):\n            # Name changed, alias was auto-generated -- update it.\n            _OBJ_SETATTR.__get__(new)(\n                \"alias\", _default_init_alias_for(new.name)\n            )\n\n        return new\n\n    # Don't use _add_pickle since fields(Attribute) doesn't work\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(\n            getattr(self, name) if name != \"metadata\" else dict(self.metadata)\n            for name in self.__slots__\n        )\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if len(state) < len(self.__slots__):\n            # Pre-26.1.0 pickle without alias_is_default -- infer it\n            # heuristically.\n            state_dict = dict(zip(self.__slots__, state, strict=False))\n            alias_is_default = state_dict.get(\n                \"alias\"\n            ) is None or state_dict.get(\"alias\") == _default_init_alias_for(\n                state_dict[\"name\"]\n            )\n            state = (*state, alias_is_default)\n\n        self._setattrs(zip(self.__slots__, state, strict=True))\n\n    def _setattrs(self, name_values_pairs):\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n        for name, value in name_values_pairs:\n            if name != \"metadata\":\n                bound_setattr(name, value)\n            else:\n                bound_setattr(\n                    name,\n                    (\n                        types.MappingProxyType(dict(value))\n                        if value\n                        else _EMPTY_METADATA_SINGLETON\n                    ),\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-1305f98138f397c2", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 270, "local_path": "expressions/encode-integer-literals/I05__attrs__Attribute__5b3ccd1f.py", "order": 5, "original_content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "parent_variant_id": "pyint-5473842403c0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2462-L2702", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "Attribute", "variant_id": "pyint-549c5b3ccd1f-I05", "group_id": "py-1305f98138f397c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1280, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2fe0ff6cce61-I06", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Attribute:\n    \"\"\"\n    *Read-only* representation of an attribute.\n\n    .. warning::\n\n       You should never instantiate this class yourself.\n\n    The class has *all* arguments of `attr.ib` (except for ``factory`` which is\n    only syntactic sugar for ``default=Factory(...)`` plus the following:\n\n    - ``name`` (`str`): The name of the attribute.\n    - ``alias`` (`str`): The __init__ parameter name of the attribute, after\n      any explicit overrides and default private-attribute-name handling.\n    - ``alias_is_default`` (`bool`): Whether the ``alias`` was automatically\n      generated (``True``) or explicitly provided by the user (``False``).\n    - ``inherited`` (`bool`): Whether or not that attribute has been inherited\n      from a base class.\n    - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The\n      callables that are used for comparing and ordering objects by this\n      attribute, respectively. These are set by passing a callable to\n      `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also\n      :ref:`comparison customization <custom-comparison>`.\n\n    Instances of this class are frequently used for introspection purposes\n    like:\n\n    - `fields` returns a tuple of them.\n    - Validators get them passed as the first argument.\n    - The :ref:`field transformer <transform-fields>` hook receives a list of\n      them.\n    - The ``alias`` property exposes the __init__ parameter name of the field,\n      with any overrides and default private-attribute handling applied.\n\n\n    .. versionadded:: 20.1.0 *inherited*\n    .. versionadded:: 20.1.0 *on_setattr*\n    .. versionchanged:: 20.2.0 *inherited* is not taken into account for\n        equality checks and hashing anymore.\n    .. versionadded:: 21.1.0 *eq_key* and *order_key*\n    .. versionadded:: 22.2.0 *alias*\n    .. versionadded:: 26.1.0 *alias_is_default*\n\n    For the full version history of the fields, see `attr.ib`.\n    \"\"\"\n\n    # These slots must NOT be reordered because we use them later for\n    # instantiation.\n    __slots__ = (  # noqa: RUF023\n        \"name\",\n        \"default\",\n        \"validator\",\n        \"repr\",\n        \"eq\",\n        \"eq_key\",\n        \"order\",\n        \"order_key\",\n        \"hash\",\n        \"init\",\n        \"metadata\",\n        \"type\",\n        \"converter\",\n        \"kw_only\",\n        \"inherited\",\n        \"on_setattr\",\n        \"alias\",\n        \"alias_is_default\",\n    )\n\n    def __init__(\n        self,\n        name,\n        default,\n        validator,\n        repr,\n        cmp,  # XXX: unused, remove along with other cmp code.\n        hash,\n        init,\n        inherited,\n        metadata=None,\n        type=None,\n        converter=None,\n        kw_only=False,\n        eq=None,\n        eq_key=None,\n        order=None,\n        order_key=None,\n        on_setattr=None,\n        alias=None,\n        alias_is_default=None,\n    ):\n        eq, eq_key, order, order_key = _determine_attrib_eq_order(\n            cmp, eq_key or eq, order_key or order, True\n        )\n\n        # Cache this descriptor here to speed things up later.\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n\n        # Despite the big red warning, people *do* instantiate `Attribute`\n        # themselves.\n        bound_setattr(\"name\", name)\n        bound_setattr(\"default\", default)\n        bound_setattr(\"validator\", validator)\n        bound_setattr(\"repr\", repr)\n        bound_setattr(\"eq\", eq)\n        bound_setattr(\"eq_key\", eq_key)\n        bound_setattr(\"order\", order)\n        bound_setattr(\"order_key\", order_key)\n        bound_setattr(\"hash\", hash)\n        bound_setattr(\"init\", init)\n        bound_setattr(\"converter\", converter)\n        bound_setattr(\n            \"metadata\",\n            (\n                types.MappingProxyType(dict(metadata))  # Shallow copy\n                if metadata\n                else _EMPTY_METADATA_SINGLETON\n            ),\n        )\n        bound_setattr(\"type\", type)\n        bound_setattr(\"kw_only\", kw_only)\n        bound_setattr(\"inherited\", inherited)\n        bound_setattr(\"on_setattr\", on_setattr)\n        bound_setattr(\"alias\", alias)\n        bound_setattr(\n            \"alias_is_default\",\n            alias is None if alias_is_default is None else alias_is_default,\n        )\n\n    def __setattr__(self, name, value):\n        raise FrozenInstanceError\n\n    @classmethod\n    def from_counting_attr(\n        cls, name: str, ca: _CountingAttr, kw_only: bool, type=None\n    ):\n        # The 'kw_only' argument is the class-level setting, and is used if the\n        # attribute itself does not explicitly set 'kw_only'.\n        # type holds the annotated value. deal with conflicts:\n        if type is None:\n            type = ca.type\n        elif ca.type is not None:\n            msg = f\"Type annotation and type argument cannot both be present for '{name}'.\"\n            raise ValueError(msg)\n        return cls(\n            name,\n            ca._default,\n            ca._validator,\n            ca.repr,\n            None,\n            ca.hash,\n            ca.init,\n            False,\n            ca.metadata,\n            type,\n            ca._converter,\n            kw_only if ca.kw_only is None else ca.kw_only,\n            ca.eq,\n            ca.eq_key,\n            ca.order,\n            ca.order_key,\n            ca.on_setattr,\n            ca.alias,\n            ca.alias is None,\n        )\n\n    # Don't use attrs.evolve since fields(Attribute) doesn't work\n    def evolve(self, **changes):\n        \"\"\"\n        Copy *self* and apply *changes*.\n\n        This works similarly to `attrs.evolve` but that function does not work\n        with :class:`attrs.Attribute`.\n\n        It is mainly meant to be used for `transform-fields`.\n\n        .. versionadded:: 20.3.0\n        \"\"\"\n        import copy\n\n        new = copy.copy(self)\n\n        new._setattrs(changes.items())\n\n        if \"alias\" in changes and \"alias_is_default\" not in changes:\n            # Explicit alias provided -- no longer the default.\n            _OBJ_SETATTR.__get__(new)(\"alias_is_default\", False)\n        elif (\n            \"name\" in changes\n            and \"alias\" not in changes\n            # Don't auto-generate alias if the user picked picked the old one.\n            and self.alias_is_default\n        ):\n            # Name changed, alias was auto-generated -- update it.\n            _OBJ_SETATTR.__get__(new)(\n                \"alias\", _default_init_alias_for(new.name)\n            )\n\n        return new\n\n    # Don't use _add_pickle since fields(Attribute) doesn't work\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(\n            getattr(self, name) if name != \"metadata\" else dict(self.metadata)\n            for name in self.__slots__\n        )\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if not (len(state) < len(self.__slots__)):\n            pass\n        else:\n            # Pre-26.1.0 pickle without alias_is_default -- infer it\n            # heuristically.\n            state_dict = dict(zip(self.__slots__, state, strict=False))\n            alias_is_default = state_dict.get(\n                \"alias\"\n            ) is None or state_dict.get(\"alias\") == _default_init_alias_for(\n                state_dict[\"name\"]\n            )\n            state = (*state, alias_is_default)\n\n        self._setattrs(zip(self.__slots__, state, strict=True))\n\n    def _setattrs(self, name_values_pairs):\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n        for name, value in name_values_pairs:\n            if not (name != \"metadata\"):\n                bound_setattr(\n                    name,\n                    (\n                        types.MappingProxyType(dict(value))\n                        if value\n                        else _EMPTY_METADATA_SINGLETON\n                    ),\n                )\n            else:\n                bound_setattr(name, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-1305f98138f397c2", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "192d67607080b2c65d9b526ac04f4fce55da618e8a8cc36c259ac945a8ffaf6c", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 272, "local_path": "expressions/invert-conditions/I06__attrs__Attribute__ff6cce61.py", "order": 6, "original_content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "parent_variant_id": "pyint-5473842403c0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2462-L2702", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 2}, "unit_kind": "class", "unit_name": "Attribute", "variant_id": "pyint-2fe0ff6cce61-I06", "group_id": "py-1305f98138f397c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1281, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-779ff1ca0ecd-I07", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Attribute:\n    \"\"\"\n    *Read-only* representation of an attribute.\n\n    .. warning::\n\n       You should never instantiate this class yourself.\n\n    The class has *all* arguments of `attr.ib` (except for ``factory`` which is\n    only syntactic sugar for ``default=Factory(...)`` plus the following:\n\n    - ``name`` (`str`): The name of the attribute.\n    - ``alias`` (`str`): The __init__ parameter name of the attribute, after\n      any explicit overrides and default private-attribute-name handling.\n    - ``alias_is_default`` (`bool`): Whether the ``alias`` was automatically\n      generated (``True``) or explicitly provided by the user (``False``).\n    - ``inherited`` (`bool`): Whether or not that attribute has been inherited\n      from a base class.\n    - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The\n      callables that are used for comparing and ordering objects by this\n      attribute, respectively. These are set by passing a callable to\n      `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also\n      :ref:`comparison customization <custom-comparison>`.\n\n    Instances of this class are frequently used for introspection purposes\n    like:\n\n    - `fields` returns a tuple of them.\n    - Validators get them passed as the first argument.\n    - The :ref:`field transformer <transform-fields>` hook receives a list of\n      them.\n    - The ``alias`` property exposes the __init__ parameter name of the field,\n      with any overrides and default private-attribute handling applied.\n\n\n    .. versionadded:: 20.1.0 *inherited*\n    .. versionadded:: 20.1.0 *on_setattr*\n    .. versionchanged:: 20.2.0 *inherited* is not taken into account for\n        equality checks and hashing anymore.\n    .. versionadded:: 21.1.0 *eq_key* and *order_key*\n    .. versionadded:: 22.2.0 *alias*\n    .. versionadded:: 26.1.0 *alias_is_default*\n\n    For the full version history of the fields, see `attr.ib`.\n    \"\"\"\n\n    # These slots must NOT be reordered because we use them later for\n    # instantiation.\n    __slots__ = (  # noqa: RUF023\n        \"name\",\n        \"default\",\n        \"validator\",\n        \"repr\",\n        \"eq\",\n        \"eq_key\",\n        \"order\",\n        \"order_key\",\n        \"hash\",\n        \"init\",\n        \"metadata\",\n        \"type\",\n        \"converter\",\n        \"kw_only\",\n        \"inherited\",\n        \"on_setattr\",\n        \"alias\",\n        \"alias_is_default\",\n    )\n\n    def __init__(\n        self,\n        name,\n        default,\n        validator,\n        repr,\n        cmp,  # XXX: unused, remove along with other cmp code.\n        hash,\n        init,\n        inherited,\n        metadata=None,\n        type=None,\n        converter=None,\n        kw_only=False,\n        eq=None,\n        eq_key=None,\n        order=None,\n        order_key=None,\n        on_setattr=None,\n        alias=None,\n        alias_is_default=None,\n    ):\n        if ((0xf537 ^ 0xf537) != 0):\n            raise AssertionError()\n        eq, eq_key, order, order_key = _determine_attrib_eq_order(\n            cmp, eq_key or eq, order_key or order, True\n        )\n\n        # Cache this descriptor here to speed things up later.\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n\n        # Despite the big red warning, people *do* instantiate `Attribute`\n        # themselves.\n        bound_setattr(\"name\", name)\n        bound_setattr(\"default\", default)\n        bound_setattr(\"validator\", validator)\n        bound_setattr(\"repr\", repr)\n        bound_setattr(\"eq\", eq)\n        bound_setattr(\"eq_key\", eq_key)\n        bound_setattr(\"order\", order)\n        bound_setattr(\"order_key\", order_key)\n        bound_setattr(\"hash\", hash)\n        bound_setattr(\"init\", init)\n        bound_setattr(\"converter\", converter)\n        bound_setattr(\n            \"metadata\",\n            (\n                types.MappingProxyType(dict(metadata))  # Shallow copy\n                if metadata\n                else _EMPTY_METADATA_SINGLETON\n            ),\n        )\n        bound_setattr(\"type\", type)\n        bound_setattr(\"kw_only\", kw_only)\n        bound_setattr(\"inherited\", inherited)\n        bound_setattr(\"on_setattr\", on_setattr)\n        bound_setattr(\"alias\", alias)\n        bound_setattr(\n            \"alias_is_default\",\n            alias is None if alias_is_default is None else alias_is_default,\n        )\n\n    def __setattr__(self, name, value):\n        if ((0x45ed ^ 0x45ed) != 0):\n            raise AssertionError()\n        raise FrozenInstanceError\n\n    @classmethod\n    def from_counting_attr(\n        cls, name: str, ca: _CountingAttr, kw_only: bool, type=None\n    ):\n        # The 'kw_only' argument is the class-level setting, and is used if the\n        # attribute itself does not explicitly set 'kw_only'.\n        # type holds the annotated value. deal with conflicts:\n        if ((0x3ce4 ^ 0x3ce4) != 0):\n            raise AssertionError()\n        if type is None:\n            type = ca.type\n        elif ca.type is not None:\n            msg = f\"Type annotation and type argument cannot both be present for '{name}'.\"\n            raise ValueError(msg)\n        return cls(\n            name,\n            ca._default,\n            ca._validator,\n            ca.repr,\n            None,\n            ca.hash,\n            ca.init,\n            False,\n            ca.metadata,\n            type,\n            ca._converter,\n            kw_only if ca.kw_only is None else ca.kw_only,\n            ca.eq,\n            ca.eq_key,\n            ca.order,\n            ca.order_key,\n            ca.on_setattr,\n            ca.alias,\n            ca.alias is None,\n        )\n\n    # Don't use attrs.evolve since fields(Attribute) doesn't work\n    def evolve(self, **changes):\n        \"\"\"\n        Copy *self* and apply *changes*.\n\n        This works similarly to `attrs.evolve` but that function does not work\n        with :class:`attrs.Attribute`.\n\n        It is mainly meant to be used for `transform-fields`.\n\n        .. versionadded:: 20.3.0\n        \"\"\"\n        if ((0x3356 ^ 0x3356) != 0):\n            raise AssertionError()\n        import copy\n\n        new = copy.copy(self)\n\n        new._setattrs(changes.items())\n\n        if \"alias\" in changes and \"alias_is_default\" not in changes:\n            # Explicit alias provided -- no longer the default.\n            _OBJ_SETATTR.__get__(new)(\"alias_is_default\", False)\n        elif (\n            \"name\" in changes\n            and \"alias\" not in changes\n            # Don't auto-generate alias if the user picked picked the old one.\n            and self.alias_is_default\n        ):\n            # Name changed, alias was auto-generated -- update it.\n            _OBJ_SETATTR.__get__(new)(\n                \"alias\", _default_init_alias_for(new.name)\n            )\n\n        return new\n\n    # Don't use _add_pickle since fields(Attribute) doesn't work\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if ((0xbec4 ^ 0xbec4) != 0):\n            raise AssertionError()\n        return tuple(\n            getattr(self, name) if name != \"metadata\" else dict(self.metadata)\n            for name in self.__slots__\n        )\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if ((0x237b ^ 0x237b) != 0):\n            raise AssertionError()\n        if len(state) < len(self.__slots__):\n            # Pre-26.1.0 pickle without alias_is_default -- infer it\n            # heuristically.\n            state_dict = dict(zip(self.__slots__, state, strict=False))\n            alias_is_default = state_dict.get(\n                \"alias\"\n            ) is None or state_dict.get(\"alias\") == _default_init_alias_for(\n                state_dict[\"name\"]\n            )\n            state = (*state, alias_is_default)\n\n        self._setattrs(zip(self.__slots__, state, strict=True))\n\n    def _setattrs(self, name_values_pairs):\n        if ((0x593d ^ 0x593d) != 0):\n            raise AssertionError()\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n        for name, value in name_values_pairs:\n            if name != \"metadata\":\n                bound_setattr(name, value)\n            else:\n                bound_setattr(\n                    name,\n                    (\n                        types.MappingProxyType(dict(value))\n                        if value\n                        else _EMPTY_METADATA_SINGLETON\n                    ),\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-1305f98138f397c2", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "3697773c910fad344bd9aa30695ad48336d29d52dd9e01216cbec4eda409a0cd", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 284, "local_path": "code-injection/insert-dead-branches/I07__attrs__Attribute__f1ca0ecd.py", "order": 7, "original_content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "parent_variant_id": "pyint-5473842403c0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2462-L2702", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 7}, "unit_kind": "class", "unit_name": "Attribute", "variant_id": "pyint-779ff1ca0ecd-I07", "group_id": "py-1305f98138f397c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1282, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-457d101c5ee6-I08", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Attribute:\n    \"\"\"\n    *Read-only* representation of an attribute.\n\n    .. warning::\n\n       You should never instantiate this class yourself.\n\n    The class has *all* arguments of `attr.ib` (except for ``factory`` which is\n    only syntactic sugar for ``default=Factory(...)`` plus the following:\n\n    - ``name`` (`str`): The name of the attribute.\n    - ``alias`` (`str`): The __init__ parameter name of the attribute, after\n      any explicit overrides and default private-attribute-name handling.\n    - ``alias_is_default`` (`bool`): Whether the ``alias`` was automatically\n      generated (``True``) or explicitly provided by the user (``False``).\n    - ``inherited`` (`bool`): Whether or not that attribute has been inherited\n      from a base class.\n    - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The\n      callables that are used for comparing and ordering objects by this\n      attribute, respectively. These are set by passing a callable to\n      `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also\n      :ref:`comparison customization <custom-comparison>`.\n\n    Instances of this class are frequently used for introspection purposes\n    like:\n\n    - `fields` returns a tuple of them.\n    - Validators get them passed as the first argument.\n    - The :ref:`field transformer <transform-fields>` hook receives a list of\n      them.\n    - The ``alias`` property exposes the __init__ parameter name of the field,\n      with any overrides and default private-attribute handling applied.\n\n\n    .. versionadded:: 20.1.0 *inherited*\n    .. versionadded:: 20.1.0 *on_setattr*\n    .. versionchanged:: 20.2.0 *inherited* is not taken into account for\n        equality checks and hashing anymore.\n    .. versionadded:: 21.1.0 *eq_key* and *order_key*\n    .. versionadded:: 22.2.0 *alias*\n    .. versionadded:: 26.1.0 *alias_is_default*\n\n    For the full version history of the fields, see `attr.ib`.\n    \"\"\"\n\n    # These slots must NOT be reordered because we use them later for\n    # instantiation.\n    __slots__ = (  # noqa: RUF023\n        \"name\",\n        \"default\",\n        \"validator\",\n        \"repr\",\n        \"eq\",\n        \"eq_key\",\n        \"order\",\n        \"order_key\",\n        \"hash\",\n        \"init\",\n        \"metadata\",\n        \"type\",\n        \"converter\",\n        \"kw_only\",\n        \"inherited\",\n        \"on_setattr\",\n        \"alias\",\n        \"alias_is_default\",\n    )\n\n    def __init__(\n        self,\n        name,\n        default,\n        validator,\n        repr,\n        cmp,  # XXX: unused, remove along with other cmp code.\n        hash,\n        init,\n        inherited,\n        metadata=None,\n        type=None,\n        converter=None,\n        kw_only=False,\n        eq=None,\n        eq_key=None,\n        order=None,\n        order_key=None,\n        on_setattr=None,\n        alias=None,\n        alias_is_default=None,\n    ):\n        first_score = 72\n        second_score = 85\n        if first_score > second_score:\n            higher_score = first_score\n        else:\n            higher_score = second_score\n        eq, eq_key, order, order_key = _determine_attrib_eq_order(\n            cmp, eq_key or eq, order_key or order, True\n        )\n\n        # Cache this descriptor here to speed things up later.\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n\n        # Despite the big red warning, people *do* instantiate `Attribute`\n        # themselves.\n        bound_setattr(\"name\", name)\n        bound_setattr(\"default\", default)\n        bound_setattr(\"validator\", validator)\n        bound_setattr(\"repr\", repr)\n        bound_setattr(\"eq\", eq)\n        bound_setattr(\"eq_key\", eq_key)\n        bound_setattr(\"order\", order)\n        bound_setattr(\"order_key\", order_key)\n        bound_setattr(\"hash\", hash)\n        bound_setattr(\"init\", init)\n        bound_setattr(\"converter\", converter)\n        bound_setattr(\n            \"metadata\",\n            (\n                types.MappingProxyType(dict(metadata))  # Shallow copy\n                if metadata\n                else _EMPTY_METADATA_SINGLETON\n            ),\n        )\n        bound_setattr(\"type\", type)\n        bound_setattr(\"kw_only\", kw_only)\n        bound_setattr(\"inherited\", inherited)\n        bound_setattr(\"on_setattr\", on_setattr)\n        bound_setattr(\"alias\", alias)\n        bound_setattr(\n            \"alias_is_default\",\n            alias is None if alias_is_default is None else alias_is_default,\n        )\n\n    def __setattr__(self, name, value):\n        raise FrozenInstanceError\n\n    @classmethod\n    def from_counting_attr(\n        cls, name: str, ca: _CountingAttr, kw_only: bool, type=None\n    ):\n        # The 'kw_only' argument is the class-level setting, and is used if the\n        # attribute itself does not explicitly set 'kw_only'.\n        # type holds the annotated value. deal with conflicts:\n        if type is None:\n            type = ca.type\n        elif ca.type is not None:\n            msg = f\"Type annotation and type argument cannot both be present for '{name}'.\"\n            raise ValueError(msg)\n        return cls(\n            name,\n            ca._default,\n            ca._validator,\n            ca.repr,\n            None,\n            ca.hash,\n            ca.init,\n            False,\n            ca.metadata,\n            type,\n            ca._converter,\n            kw_only if ca.kw_only is None else ca.kw_only,\n            ca.eq,\n            ca.eq_key,\n            ca.order,\n            ca.order_key,\n            ca.on_setattr,\n            ca.alias,\n            ca.alias is None,\n        )\n\n    # Don't use attrs.evolve since fields(Attribute) doesn't work\n    def evolve(self, **changes):\n        \"\"\"\n        Copy *self* and apply *changes*.\n\n        This works similarly to `attrs.evolve` but that function does not work\n        with :class:`attrs.Attribute`.\n\n        It is mainly meant to be used for `transform-fields`.\n\n        .. versionadded:: 20.3.0\n        \"\"\"\n        import copy\n\n        new = copy.copy(self)\n\n        new._setattrs(changes.items())\n\n        if \"alias\" in changes and \"alias_is_default\" not in changes:\n            # Explicit alias provided -- no longer the default.\n            _OBJ_SETATTR.__get__(new)(\"alias_is_default\", False)\n        elif (\n            \"name\" in changes\n            and \"alias\" not in changes\n            # Don't auto-generate alias if the user picked picked the old one.\n            and self.alias_is_default\n        ):\n            # Name changed, alias was auto-generated -- update it.\n            _OBJ_SETATTR.__get__(new)(\n                \"alias\", _default_init_alias_for(new.name)\n            )\n\n        return new\n\n    # Don't use _add_pickle since fields(Attribute) doesn't work\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(\n            getattr(self, name) if name != \"metadata\" else dict(self.metadata)\n            for name in self.__slots__\n        )\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if len(state) < len(self.__slots__):\n            # Pre-26.1.0 pickle without alias_is_default -- infer it\n            # heuristically.\n            state_dict = dict(zip(self.__slots__, state, strict=False))\n            alias_is_default = state_dict.get(\n                \"alias\"\n            ) is None or state_dict.get(\"alias\") == _default_init_alias_for(\n                state_dict[\"name\"]\n            )\n            state = (*state, alias_is_default)\n\n        self._setattrs(zip(self.__slots__, state, strict=True))\n\n    def _setattrs(self, name_values_pairs):\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n        for name, value in name_values_pairs:\n            if name != \"metadata\":\n                bound_setattr(name, value)\n            else:\n                bound_setattr(\n                    name,\n                    (\n                        types.MappingProxyType(dict(value))\n                        if value\n                        else _EMPTY_METADATA_SINGLETON\n                    ),\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-1305f98138f397c2", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "766ae17c9af959f94517d1b92af263b582e519b4071e263af330249128ef4b42", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 276, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs__Attribute__101c5ee6.py", "order": 8, "original_content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "parent_variant_id": "pyint-5473842403c0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2462-L2702", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 3}, "unit_kind": "class", "unit_name": "Attribute", "variant_id": "pyint-457d101c5ee6-I08", "group_id": "py-1305f98138f397c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1283, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a5608392d88f-I09", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Attribute:\n    \"\"\"\n    *Read-only* representation of an attribute.\n\n    .. warning::\n\n       You should never instantiate this class yourself.\n\n    The class has *all* arguments of `attr.ib` (except for ``factory`` which is\n    only syntactic sugar for ``default=Factory(...)`` plus the following:\n\n    - ``name`` (`str`): The name of the attribute.\n    - ``alias`` (`str`): The __init__ parameter name of the attribute, after\n      any explicit overrides and default private-attribute-name handling.\n    - ``alias_is_default`` (`bool`): Whether the ``alias`` was automatically\n      generated (``True``) or explicitly provided by the user (``False``).\n    - ``inherited`` (`bool`): Whether or not that attribute has been inherited\n      from a base class.\n    - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The\n      callables that are used for comparing and ordering objects by this\n      attribute, respectively. These are set by passing a callable to\n      `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also\n      :ref:`comparison customization <custom-comparison>`.\n\n    Instances of this class are frequently used for introspection purposes\n    like:\n\n    - `fields` returns a tuple of them.\n    - Validators get them passed as the first argument.\n    - The :ref:`field transformer <transform-fields>` hook receives a list of\n      them.\n    - The ``alias`` property exposes the __init__ parameter name of the field,\n      with any overrides and default private-attribute handling applied.\n\n\n    .. versionadded:: 20.1.0 *inherited*\n    .. versionadded:: 20.1.0 *on_setattr*\n    .. versionchanged:: 20.2.0 *inherited* is not taken into account for\n        equality checks and hashing anymore.\n    .. versionadded:: 21.1.0 *eq_key* and *order_key*\n    .. versionadded:: 22.2.0 *alias*\n    .. versionadded:: 26.1.0 *alias_is_default*\n\n    For the full version history of the fields, see `attr.ib`.\n    \"\"\"\n\n    # These slots must NOT be reordered because we use them later for\n    # instantiation.\n    __slots__ = (  # noqa: RUF023\n        \"name\",\n        \"default\",\n        \"validator\",\n        \"repr\",\n        \"eq\",\n        \"eq_key\",\n        \"order\",\n        \"order_key\",\n        \"hash\",\n        \"init\",\n        \"metadata\",\n        \"type\",\n        \"converter\",\n        \"kw_only\",\n        \"inherited\",\n        \"on_setattr\",\n        \"alias\",\n        \"alias_is_default\",\n    )\n\n    def __init__(\n        self,\n        name,\n        default,\n        validator,\n        repr,\n        cmp,  # XXX: unused, remove along with other cmp code.\n        hash,\n        init,\n        inherited,\n        metadata=None,\n        type=None,\n        converter=None,\n        kw_only=False,\n        eq=None,\n        eq_key=None,\n        order=None,\n        order_key=None,\n        on_setattr=None,\n        alias=None,\n        alias_is_default=None,\n    ):\n        lI0O_db4a4e62 = ((0x991e ^ 0x991e) != 0)\n        lI0O_db4a4e62 = not (not lI0O_db4a4e62)\n        eq, eq_key, order, order_key = _determine_attrib_eq_order(\n            cmp, eq_key or eq, order_key or order, True\n        )\n\n        # Cache this descriptor here to speed things up later.\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n\n        # Despite the big red warning, people *do* instantiate `Attribute`\n        # themselves.\n        bound_setattr(\"name\", name)\n        bound_setattr(\"default\", default)\n        bound_setattr(\"validator\", validator)\n        bound_setattr(\"repr\", repr)\n        bound_setattr(\"eq\", eq)\n        bound_setattr(\"eq_key\", eq_key)\n        bound_setattr(\"order\", order)\n        bound_setattr(\"order_key\", order_key)\n        bound_setattr(\"hash\", hash)\n        bound_setattr(\"init\", init)\n        bound_setattr(\"converter\", converter)\n        bound_setattr(\n            \"metadata\",\n            (\n                types.MappingProxyType(dict(metadata))  # Shallow copy\n                if metadata\n                else _EMPTY_METADATA_SINGLETON\n            ),\n        )\n        bound_setattr(\"type\", type)\n        bound_setattr(\"kw_only\", kw_only)\n        bound_setattr(\"inherited\", inherited)\n        bound_setattr(\"on_setattr\", on_setattr)\n        bound_setattr(\"alias\", alias)\n        bound_setattr(\n            \"alias_is_default\",\n            alias is None if alias_is_default is None else alias_is_default,\n        )\n\n    def __setattr__(self, name, value):\n        raise FrozenInstanceError\n\n    @classmethod\n    def from_counting_attr(\n        cls, name: str, ca: _CountingAttr, kw_only: bool, type=None\n    ):\n        # The 'kw_only' argument is the class-level setting, and is used if the\n        # attribute itself does not explicitly set 'kw_only'.\n        # type holds the annotated value. deal with conflicts:\n        if type is None:\n            type = ca.type\n        elif ca.type is not None:\n            msg = f\"Type annotation and type argument cannot both be present for '{name}'.\"\n            raise ValueError(msg)\n        return cls(\n            name,\n            ca._default,\n            ca._validator,\n            ca.repr,\n            None,\n            ca.hash,\n            ca.init,\n            False,\n            ca.metadata,\n            type,\n            ca._converter,\n            kw_only if ca.kw_only is None else ca.kw_only,\n            ca.eq,\n            ca.eq_key,\n            ca.order,\n            ca.order_key,\n            ca.on_setattr,\n            ca.alias,\n            ca.alias is None,\n        )\n\n    # Don't use attrs.evolve since fields(Attribute) doesn't work\n    def evolve(self, **changes):\n        \"\"\"\n        Copy *self* and apply *changes*.\n\n        This works similarly to `attrs.evolve` but that function does not work\n        with :class:`attrs.Attribute`.\n\n        It is mainly meant to be used for `transform-fields`.\n\n        .. versionadded:: 20.3.0\n        \"\"\"\n        import copy\n\n        new = copy.copy(self)\n\n        new._setattrs(changes.items())\n\n        if \"alias\" in changes and \"alias_is_default\" not in changes:\n            # Explicit alias provided -- no longer the default.\n            _OBJ_SETATTR.__get__(new)(\"alias_is_default\", False)\n        elif (\n            \"name\" in changes\n            and \"alias\" not in changes\n            # Don't auto-generate alias if the user picked picked the old one.\n            and self.alias_is_default\n        ):\n            # Name changed, alias was auto-generated -- update it.\n            _OBJ_SETATTR.__get__(new)(\n                \"alias\", _default_init_alias_for(new.name)\n            )\n\n        return new\n\n    # Don't use _add_pickle since fields(Attribute) doesn't work\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(\n            getattr(self, name) if name != \"metadata\" else dict(self.metadata)\n            for name in self.__slots__\n        )\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if len(state) < len(self.__slots__):\n            # Pre-26.1.0 pickle without alias_is_default -- infer it\n            # heuristically.\n            state_dict = dict(zip(self.__slots__, state, strict=False))\n            alias_is_default = state_dict.get(\n                \"alias\"\n            ) is None or state_dict.get(\"alias\") == _default_init_alias_for(\n                state_dict[\"name\"]\n            )\n            state = (*state, alias_is_default)\n\n        self._setattrs(zip(self.__slots__, state, strict=True))\n\n    def _setattrs(self, name_values_pairs):\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n        for name, value in name_values_pairs:\n            if name != \"metadata\":\n                bound_setattr(name, value)\n            else:\n                bound_setattr(\n                    name,\n                    (\n                        types.MappingProxyType(dict(value))\n                        if value\n                        else _EMPTY_METADATA_SINGLETON\n                    ),\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-1305f98138f397c2", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "f0bf8e8d669b3a4c0b7fad25b97427cb46d468849307b68dc5b5f84c723ad0b6", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 272, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs__Attribute__8392d88f.py", "order": 9, "original_content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "parent_variant_id": "pyint-5473842403c0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2462-L2702", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 4}, "unit_kind": "class", "unit_name": "Attribute", "variant_id": "pyint-a5608392d88f-I09", "group_id": "py-1305f98138f397c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1284, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-70ce6caf7638-I10", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,     PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,     get_generic_base, )\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,     UnannotatedAttributeError,\n)\nclass Attribute:\n    \"\"\"\n    *Read-only* representation of an attribute.\n\n    .. warning::\n\n       You should never instantiate this class yourself.\n\n    The class has *all* arguments of `attr.ib` (except for ``factory`` which is\n    only syntactic sugar for ``default=Factory(...)`` plus the following:\n\n    - ``name`` (`str`): The name of the attribute.\n    - ``alias`` (`str`): The __init__ parameter name of the attribute, after\n      any explicit overrides and default private-attribute-name handling.\n    - ``alias_is_default`` (`bool`): Whether the ``alias`` was automatically\n      generated (``True``) or explicitly provided by the user (``False``).\n    - ``inherited`` (`bool`): Whether or not that attribute has been inherited\n      from a base class.\n    - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The\n      callables that are used for comparing and ordering objects by this\n      attribute, respectively. These are set by passing a callable to\n      `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also\n      :ref:`comparison customization <custom-comparison>`.\n    Instances of this class are frequently used for introspection purposes\n    like:\n\n    - `fields` returns a tuple of them.\n    - Validators get them passed as the first argument.\n    - The :ref:`field transformer <transform-fields>` hook receives a list of\n      them.\n    - The ``alias`` property exposes the __init__ parameter name of the field,\n      with any overrides and default private-attribute handling applied.\n\n\n    .. versionadded:: 20.1.0 *inherited*\n    .. versionadded:: 20.1.0 *on_setattr*\n    .. versionchanged:: 20.2.0 *inherited* is not taken into account for\n        equality checks and hashing anymore.\n    .. versionadded:: 21.1.0 *eq_key* and *order_key*\n    .. versionadded:: 22.2.0 *alias*\n    .. versionadded:: 26.1.0 *alias_is_default*\n\n    For the full version history of the fields, see `attr.ib`.\n    \"\"\"\n    # These slots must NOT be reordered because we use them later for\n    # instantiation.\n    __slots__ = (  # noqa: RUF023\n        \"name\",\n        \"default\",         \"validator\",         \"repr\",         \"eq\",         \"eq_key\",\n        \"order\",\n        \"order_key\",         \"hash\",\n        \"init\",         \"metadata\",         \"type\",\n        \"converter\",         \"kw_only\",\n        \"inherited\",\n        \"on_setattr\",         \"alias\",         \"alias_is_default\",\n    )\n    def __init__(         self,\n        name,         default,         validator,\n        repr,\n        cmp,  # XXX: unused, remove along with other cmp code.\n        hash,         init,\n        inherited,\n        metadata=None,\n        type=None,\n        converter=None,         kw_only=False,\n        eq=None,\n        eq_key=None,         order=None,         order_key=None,\n        on_setattr=None,         alias=None,\n        alias_is_default=None,\n    ):\n        eq, eq_key, order, order_key = _determine_attrib_eq_order(             cmp, eq_key or eq, order_key or order, True\n        )\n        # Cache this descriptor here to speed things up later.\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n        # Despite the big red warning, people *do* instantiate `Attribute`\n        # themselves.\n        bound_setattr(\"name\", name)\n        bound_setattr(\"default\", default)\n        bound_setattr(\"validator\", validator)\n        bound_setattr(\"repr\", repr)\n        bound_setattr(\"eq\", eq)\n        bound_setattr(\"eq_key\", eq_key)\n        bound_setattr(\"order\", order)\n        bound_setattr(\"order_key\", order_key)\n        bound_setattr(\"hash\", hash)\n        bound_setattr(\"init\", init)\n        bound_setattr(\"converter\", converter)\n        bound_setattr(\n            \"metadata\",             (\n                types.MappingProxyType(dict(metadata))  # Shallow copy\n                if metadata                 else _EMPTY_METADATA_SINGLETON             ),         )\n        bound_setattr(\"type\", type)\n        bound_setattr(\"kw_only\", kw_only)\n        bound_setattr(\"inherited\", inherited)\n        bound_setattr(\"on_setattr\", on_setattr)\n        bound_setattr(\"alias\", alias)\n        bound_setattr(             \"alias_is_default\",\n            alias is None if alias_is_default is None else alias_is_default,\n        )\n\n    def __setattr__(self, name, value):\n        raise FrozenInstanceError\n\n    @classmethod\n    def from_counting_attr(\n        cls, name: str, ca: _CountingAttr, kw_only: bool, type=None\n    ):\n        # The 'kw_only' argument is the class-level setting, and is used if the\n        # attribute itself does not explicitly set 'kw_only'.\n        # type holds the annotated value. deal with conflicts:\n        if type is None:\n            type = ca.type\n        elif ca.type is not None:\n            msg = f\"Type annotation and type argument cannot both be present for '{name}'.\"\n            raise ValueError(msg)\n        return cls(             name,\n            ca._default,\n            ca._validator,\n            ca.repr,\n            None,             ca.hash,             ca.init,\n            False,\n            ca.metadata,             type,\n            ca._converter,\n            kw_only if ca.kw_only is None else ca.kw_only,             ca.eq,\n            ca.eq_key,             ca.order,             ca.order_key,\n            ca.on_setattr,             ca.alias,\n            ca.alias is None,\n        )\n    # Don't use attrs.evolve since fields(Attribute) doesn't work\n    def evolve(self, **changes):\n        \"\"\"\n        Copy *self* and apply *changes*.\n        This works similarly to `attrs.evolve` but that function does not work\n        with :class:`attrs.Attribute`.\n        It is mainly meant to be used for `transform-fields`.\n\n        .. versionadded:: 20.3.0\n        \"\"\"\n        import copy\n\n        new = copy.copy(self)\n\n        new._setattrs(changes.items())\n\n        if \"alias\" in changes and \"alias_is_default\" not in changes:\n            # Explicit alias provided -- no longer the default.\n            _OBJ_SETATTR.__get__(new)(\"alias_is_default\", False)\n        elif (\n            \"name\" in changes             and \"alias\" not in changes             # Don't auto-generate alias if the user picked picked the old one.\n            and self.alias_is_default\n        ):\n            # Name changed, alias was auto-generated -- update it.\n            _OBJ_SETATTR.__get__(new)(\n                \"alias\", _default_init_alias_for(new.name)\n            )\n        return new\n\n    # Don't use _add_pickle since fields(Attribute) doesn't work\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(\n            getattr(self, name) if name != \"metadata\" else dict(self.metadata)\n            for name in self.__slots__         )\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if len(state) < len(self.__slots__):\n            # Pre-26.1.0 pickle without alias_is_default -- infer it\n            # heuristically.\n            state_dict = dict(zip(self.__slots__, state, strict=False))\n            alias_is_default = state_dict.get(\n                \"alias\"\n            ) is None or state_dict.get(\"alias\") == _default_init_alias_for(\n                state_dict[\"name\"]\n            )\n            state = (*state, alias_is_default)\n        self._setattrs(zip(self.__slots__, state, strict=True))\n\n    def _setattrs(self, name_values_pairs):\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n        for name, value in name_values_pairs:\n            if name != \"metadata\":\n                bound_setattr(name, value)\n            else:\n                bound_setattr(\n                    name,\n                    (\n                        types.MappingProxyType(dict(value))                         if value                         else _EMPTY_METADATA_SINGLETON\n                    ),\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-1305f98138f397c2", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "34a9e770293c411947d98cdfbe616374e970f9b95618bb907d41f785b1d97bfd", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 218, "local_path": "layout/partially-compact-layout/I10__attrs__Attribute__6caf7638.py", "order": 10, "original_content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "parent_variant_id": "pyint-5473842403c0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2462-L2702", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 131, "line_break_groups_removed": 52, "line_breaks_removed": 52, "whitespace_characters_removed": 11}, "unit_kind": "class", "unit_name": "Attribute", "variant_id": "pyint-70ce6caf7638-I10", "group_id": "py-1305f98138f397c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1285, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0c85dcc24825-I11", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Attribute:\n    \"\"\"\n    *Read-only* representation of an attribute.\n\n    .. warning::\n\n       You should never instantiate this class yourself.\n\n    The class has *all* arguments of `attr.ib` (except for ``factory`` which is\n    only syntactic sugar for ``default=Factory(...)`` plus the following:\n\n    - ``name`` (`str`): The name of the attribute.\n    - ``alias`` (`str`): The __init__ parameter name of the attribute, after\n      any explicit overrides and default private-attribute-name handling.\n    - ``alias_is_default`` (`bool`): Whether the ``alias`` was automatically\n      generated (``True``) or explicitly provided by the user (``False``).\n    - ``inherited`` (`bool`): Whether or not that attribute has been inherited\n      from a base class.\n    - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The\n      callables that are used for comparing and ordering objects by this\n      attribute, respectively. These are set by passing a callable to\n      `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also\n      :ref:`comparison customization <custom-comparison>`.\n\n    Instances of this class are frequently used for introspection purposes\n    like:\n\n    - `fields` returns a tuple of them.\n    - Validators get them passed as the first argument.\n    - The :ref:`field transformer <transform-fields>` hook receives a list of\n      them.\n    - The ``alias`` property exposes the __init__ parameter name of the field,\n      with any overrides and default private-attribute handling applied.\n\n\n    .. versionadded:: 20.1.0 *inherited*\n    .. versionadded:: 20.1.0 *on_setattr*\n    .. versionchanged:: 20.2.0 *inherited* is not taken into account for\n        equality checks and hashing anymore.\n    .. versionadded:: 21.1.0 *eq_key* and *order_key*\n    .. versionadded:: 22.2.0 *alias*\n    .. versionadded:: 26.1.0 *alias_is_default*\n\n    For the full version history of the fields, see `attr.ib`.\n    \"\"\"\n\n    # These slots must NOT be reordered because we use them later for\n    # instantiation.\n    __slots__ = (  # noqa: RUF023\n        \"name\",\n        \"default\",\n        \"validator\",\n        \"repr\",\n        \"eq\",\n        \"eq_key\",\n        \"order\",\n        \"order_key\",\n        \"hash\",\n        \"init\",\n        \"metadata\",\n        \"type\",\n        \"converter\",\n        \"kw_only\",\n        \"inherited\",\n        \"on_setattr\",\n        \"alias\",\n        \"alias_is_default\",\n    )\n\n    def __init__(\n        self,\n        name,\n        default,\n        validator,\n        repr,\n        cmp,  # XXX: unused, remove along with other cmp code.\n        hash,\n        init,\n        inherited,\n        metadata=None,\n        type=None,\n        converter=None,\n        kw_only=False,\n        eq=None,\n        eq_key=None,\n        order=None,\n        order_key=None,\n        on_setattr=None,\n        alias=None,\n        alias_is_default=None,\n    ):\n        eq, eq_key, order, order_key = _determine_attrib_eq_order(\n            cmp, eq_key or eq, order_key or order, True\n        )\n\n        # Cache this descriptor here to speed things up later.\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n\n        # Despite the big red warning, people *do* instantiate `Attribute`\n        # themselves.\n        bound_setattr(\"name\", name)\n        bound_setattr(\"default\", default)\n        bound_setattr(\"validator\", validator)\n        bound_setattr(\"repr\", repr)\n        bound_setattr(\"eq\", eq)\n        bound_setattr(\"eq_key\", eq_key)\n        bound_setattr(\"order\", order)\n        bound_setattr(\"order_key\", order_key)\n        bound_setattr(\"hash\", hash)\n        bound_setattr(\"init\", init)\n        bound_setattr(\"converter\", converter)\n        bound_setattr(\n            \"metadata\",\n            (\n                types.MappingProxyType(dict(metadata))  # Shallow copy\n                if metadata\n                else _EMPTY_METADATA_SINGLETON\n            ),\n        )\n        bound_setattr(\"type\", type)\n        bound_setattr(\"kw_only\", kw_only)\n        bound_setattr(\"inherited\", inherited)\n        bound_setattr(\"on_setattr\", on_setattr)\n        bound_setattr(\"alias\", alias)\n        bound_setattr(\n            \"alias_is_default\",\n            alias is None if alias_is_default is None else alias_is_default,\n        )\n\n    def __setattr__(self, name, value):\n        raise FrozenInstanceError\n\n    @classmethod\n    def from_counting_attr(\n        cls, name: str, ca: _CountingAttr, kw_only: bool, type=None\n    ):\n        # The 'kw_only' argument is the class-level setting, and is used if the\n        # attribute itself does not explicitly set 'kw_only'.\n        # type holds the annotated value. deal with conflicts:\n        if type is None:\n            type = ca.type\n        elif ca.type is not None:\n            msg = f\"Type annotation and type argument cannot both be present for '{name}'.\"\n            raise ValueError(msg)\n        return cls(\n            name,\n            ca._default,\n            ca._validator,\n            ca.repr,\n            None,\n            ca.hash,\n            ca.init,\n            False,\n            ca.metadata,\n            type,\n            ca._converter,\n            kw_only if ca.kw_only is None else ca.kw_only,\n            ca.eq,\n            ca.eq_key,\n            ca.order,\n            ca.order_key,\n            ca.on_setattr,\n            ca.alias,\n            ca.alias is None,\n        )\n\n    # Don't use attrs.evolve since fields(Attribute) doesn't work\n    def evolve(self, **changes):\n        \"\"\"\n        Copy *self* and apply *changes*.\n\n        This works similarly to `attrs.evolve` but that function does not work\n        with :class:`attrs.Attribute`.\n\n        It is mainly meant to be used for `transform-fields`.\n\n        .. versionadded:: 20.3.0\n        \"\"\"\n        import copy\n\n        new = copy.copy(self)\n\n        new._setattrs(changes.items())\n\n        if \"alias\" in changes and \"alias_is_default\" not in changes:\n            # Explicit alias provided -- no longer the default.\n            _OBJ_SETATTR.__get__(new)(\"alias_is_default\", False)\n        elif (\n            \"name\" in changes\n            and \"alias\" not in changes\n            # Don't auto-generate alias if the user picked picked the old one.\n            and self.alias_is_default\n        ):\n            # Name changed, alias was auto-generated -- update it.\n            _OBJ_SETATTR.__get__(new)(\n                \"alias\", _default_init_alias_for(new.name)\n            )\n\n        return new\n\n    # Don't use _add_pickle since fields(Attribute) doesn't work\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(\n            getattr(self, name) if name != \"metadata\" else dict(self.metadata)\n            for name in self.__slots__\n        )\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if len(state) < len(self.__slots__):\n            # Pre-26.1.0 pickle without alias_is_default -- infer it\n            # heuristically.\n            state_dict = dict(zip(self.__slots__, state, strict=False))\n            alias_is_default = state_dict.get(\n                \"alias\"\n            ) is None or state_dict.get(\"alias\") == _default_init_alias_for(\n                state_dict[\"name\"]\n            )\n            state = (*state, alias_is_default)\n\n        self._setattrs(zip(self.__slots__, state, strict=True))\n\n    def _setattrs(self, name_values_pairs):\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n        for name, value in name_values_pairs:\n            if name != \"metadata\":\n                bound_setattr(name, value)\n            else:\n                bound_setattr(\n                    name,\n                    (\n                        types.MappingProxyType(dict(value))\n                        if value\n                        else _EMPTY_METADATA_SINGLETON\n                    ),\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-1305f98138f397c2", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 270, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs__Attribute__dcc24825.py", "order": 11, "original_content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "parent_variant_id": "pyint-5473842403c0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2462-L2702", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "Attribute", "variant_id": "pyint-0c85dcc24825-I11", "group_id": "py-1305f98138f397c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1286, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-91966b1360e8-I12", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Attribute:\n    \"\"\"\n    *Read-only* representation of an attribute.\n\n    .. warning::\n\n       You should never instantiate this class yourself.\n\n    The class has *all* arguments of `attr.ib` (except for ``factory`` which is\n    only syntactic sugar for ``default=Factory(...)`` plus the following:\n\n    - ``name`` (`str`): The name of the attribute.\n    - ``alias`` (`str`): The __init__ parameter name of the attribute, after\n      any explicit overrides and default private-attribute-name handling.\n    - ``alias_is_default`` (`bool`): Whether the ``alias`` was automatically\n      generated (``True``) or explicitly provided by the user (``False``).\n    - ``inherited`` (`bool`): Whether or not that attribute has been inherited\n      from a base class.\n    - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The\n      callables that are used for comparing and ordering objects by this\n      attribute, respectively. These are set by passing a callable to\n      `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also\n      :ref:`comparison customization <custom-comparison>`.\n\n    Instances of this class are frequently used for introspection purposes\n    like:\n\n    - `fields` returns a tuple of them.\n    - Validators get them passed as the first argument.\n    - The :ref:`field transformer <transform-fields>` hook receives a list of\n      them.\n    - The ``alias`` property exposes the __init__ parameter name of the field,\n      with any overrides and default private-attribute handling applied.\n\n\n    .. versionadded:: 20.1.0 *inherited*\n    .. versionadded:: 20.1.0 *on_setattr*\n    .. versionchanged:: 20.2.0 *inherited* is not taken into account for\n        equality checks and hashing anymore.\n    .. versionadded:: 21.1.0 *eq_key* and *order_key*\n    .. versionadded:: 22.2.0 *alias*\n    .. versionadded:: 26.1.0 *alias_is_default*\n\n    For the full version history of the fields, see `attr.ib`.\n    \"\"\"\n\n    # These slots must NOT be reordered because we use them later for\n    # instantiation.\n    __slots__ = (  # noqa: RUF023\n        \"name\",\n        \"default\",\n        \"validator\",\n        \"repr\",\n        \"eq\",\n        \"eq_key\",\n        \"order\",\n        \"order_key\",\n        \"hash\",\n        \"init\",\n        \"metadata\",\n        \"type\",\n        \"converter\",\n        \"kw_only\",\n        \"inherited\",\n        \"on_setattr\",\n        \"alias\",\n        \"alias_is_default\",\n    )\n\n    def __init__(\n        self,\n        name,\n        default,\n        validator,\n        repr,\n        cmp,  # XXX: unused, remove along with other cmp code.\n        hash,\n        init,\n        inherited,\n        metadata=None,\n        type=None,\n        converter=None,\n        kw_only=False,\n        eq=None,\n        eq_key=None,\n        order=None,\n        order_key=None,\n        on_setattr=None,\n        alias=None,\n        alias_is_default=None,\n    ):\n        eq, eq_key, order, order_key = _determine_attrib_eq_order(\n            cmp, eq_key or eq, order_key or order, True\n        )\n\n        # Cache this descriptor here to speed things up later.\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n\n        # Despite the big red warning, people *do* instantiate `Attribute`\n        # themselves.\n        bound_setattr(\"name\", name)\n        bound_setattr(\"default\", default)\n        bound_setattr(\"validator\", validator)\n        bound_setattr(\"repr\", repr)\n        bound_setattr(\"eq\", eq)\n        bound_setattr(\"eq_key\", eq_key)\n        bound_setattr(\"order\", order)\n        bound_setattr(\"order_key\", order_key)\n        bound_setattr(\"hash\", hash)\n        bound_setattr(\"init\", init)\n        bound_setattr(\"converter\", converter)\n        bound_setattr(\n            \"metadata\",\n            (\n                types.MappingProxyType(dict(metadata))  # Shallow copy\n                if metadata\n                else _EMPTY_METADATA_SINGLETON\n            ),\n        )\n        bound_setattr(\"type\", type)\n        bound_setattr(\"kw_only\", kw_only)\n        bound_setattr(\"inherited\", inherited)\n        bound_setattr(\"on_setattr\", on_setattr)\n        bound_setattr(\"alias\", alias)\n        bound_setattr(\n            \"alias_is_default\",\n            alias is None if alias_is_default is None else alias_is_default,\n        )\n\n    def __setattr__(self, name, value):\n        raise FrozenInstanceError\n\n    @classmethod\n    def from_counting_attr(\n        cls, name: str, ca: _CountingAttr, kw_only: bool, type=None\n    ):\n        # The 'kw_only' argument is the class-level setting, and is used if the\n        # attribute itself does not explicitly set 'kw_only'.\n        # type holds the annotated value. deal with conflicts:\n        if type is None:\n            type = ca.type\n        elif ca.type is not None:\n            \n            raise ValueError((f\"Type annotation and type argument cannot both be present for '{name}'.\"))\n        return cls(\n            name,\n            ca._default,\n            ca._validator,\n            ca.repr,\n            None,\n            ca.hash,\n            ca.init,\n            False,\n            ca.metadata,\n            type,\n            ca._converter,\n            kw_only if ca.kw_only is None else ca.kw_only,\n            ca.eq,\n            ca.eq_key,\n            ca.order,\n            ca.order_key,\n            ca.on_setattr,\n            ca.alias,\n            ca.alias is None,\n        )\n\n    # Don't use attrs.evolve since fields(Attribute) doesn't work\n    def evolve(self, **changes):\n        \"\"\"\n        Copy *self* and apply *changes*.\n\n        This works similarly to `attrs.evolve` but that function does not work\n        with :class:`attrs.Attribute`.\n\n        It is mainly meant to be used for `transform-fields`.\n\n        .. versionadded:: 20.3.0\n        \"\"\"\n        import copy\n\n        new = copy.copy(self)\n\n        new._setattrs(changes.items())\n\n        if \"alias\" in changes and \"alias_is_default\" not in changes:\n            # Explicit alias provided -- no longer the default.\n            _OBJ_SETATTR.__get__(new)(\"alias_is_default\", False)\n        elif (\n            \"name\" in changes\n            and \"alias\" not in changes\n            # Don't auto-generate alias if the user picked picked the old one.\n            and self.alias_is_default\n        ):\n            # Name changed, alias was auto-generated -- update it.\n            _OBJ_SETATTR.__get__(new)(\n                \"alias\", _default_init_alias_for(new.name)\n            )\n\n        return new\n\n    # Don't use _add_pickle since fields(Attribute) doesn't work\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(\n            getattr(self, name) if name != \"metadata\" else dict(self.metadata)\n            for name in self.__slots__\n        )\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if len(state) < len(self.__slots__):\n            # Pre-26.1.0 pickle without alias_is_default -- infer it\n            # heuristically.\n            state_dict = dict(zip(self.__slots__, state, strict=False))\n            alias_is_default = state_dict.get(\n                \"alias\"\n            ) is None or state_dict.get(\"alias\") == _default_init_alias_for(\n                state_dict[\"name\"]\n            )\n            state = (*state, alias_is_default)\n\n        self._setattrs(zip(self.__slots__, state, strict=True))\n\n    def _setattrs(self, name_values_pairs):\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n        for name, value in name_values_pairs:\n            if name != \"metadata\":\n                bound_setattr(name, value)\n            else:\n                bound_setattr(\n                    name,\n                    (\n                        types.MappingProxyType(dict(value))\n                        if value\n                        else _EMPTY_METADATA_SINGLETON\n                    ),\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-1305f98138f397c2", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "eb11ca5c34a4e39d7f39b04b043c56b418d5d979713e2116e7cc9e47c0d8b88d", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 270, "local_path": "data-flow/inline-intermediate-variables/I12__attrs__Attribute__6b1360e8.py", "order": 12, "original_content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "parent_variant_id": "pyint-5473842403c0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2462-L2702", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Attribute", "variant_id": "pyint-91966b1360e8-I12", "group_id": "py-1305f98138f397c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1287, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ad505c3c1397-I13", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Attribute:\n    \"\"\"\n    *Read-only* representation of an attribute.\n\n    .. warning::\n\n       You should never instantiate this class yourself.\n\n    The class has *all* arguments of `attr.ib` (except for ``factory`` which is\n    only syntactic sugar for ``default=Factory(...)`` plus the following:\n\n    - ``name`` (`str`): The name of the attribute.\n    - ``alias`` (`str`): The __init__ parameter name of the attribute, after\n      any explicit overrides and default private-attribute-name handling.\n    - ``alias_is_default`` (`bool`): Whether the ``alias`` was automatically\n      generated (``True``) or explicitly provided by the user (``False``).\n    - ``inherited`` (`bool`): Whether or not that attribute has been inherited\n      from a base class.\n    - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The\n      callables that are used for comparing and ordering objects by this\n      attribute, respectively. These are set by passing a callable to\n      `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also\n      :ref:`comparison customization <custom-comparison>`.\n\n    Instances of this class are frequently used for introspection purposes\n    like:\n\n    - `fields` returns a tuple of them.\n    - Validators get them passed as the first argument.\n    - The :ref:`field transformer <transform-fields>` hook receives a list of\n      them.\n    - The ``alias`` property exposes the __init__ parameter name of the field,\n      with any overrides and default private-attribute handling applied.\n\n\n    .. versionadded:: 20.1.0 *inherited*\n    .. versionadded:: 20.1.0 *on_setattr*\n    .. versionchanged:: 20.2.0 *inherited* is not taken into account for\n        equality checks and hashing anymore.\n    .. versionadded:: 21.1.0 *eq_key* and *order_key*\n    .. versionadded:: 22.2.0 *alias*\n    .. versionadded:: 26.1.0 *alias_is_default*\n\n    For the full version history of the fields, see `attr.ib`.\n    \"\"\"\n\n    # These slots must NOT be reordered because we use them later for\n    # instantiation.\n    __slots__ = (  # noqa: RUF023\n        \"name\",\n        \"default\",\n        \"validator\",\n        \"repr\",\n        \"eq\",\n        \"eq_key\",\n        \"order\",\n        \"order_key\",\n        \"hash\",\n        \"init\",\n        \"metadata\",\n        \"type\",\n        \"converter\",\n        \"kw_only\",\n        \"inherited\",\n        \"on_setattr\",\n        \"alias\",\n        \"alias_is_default\",\n    )\n\n    def __init__(\n        self,\n        name,\n        default,\n        validator,\n        repr,\n        cmp,  # XXX: unused, remove along with other cmp code.\n        hash,\n        init,\n        inherited,\n        metadata=None,\n        type=None,\n        converter=None,\n        kw_only=False,\n        eq=None,\n        eq_key=None,\n        order=None,\n        order_key=None,\n        on_setattr=None,\n        alias=None,\n        alias_is_default=None,\n    ):\n        eq, eq_key, order, order_key = _determine_attrib_eq_order(\n            cmp, eq_key or eq, order_key or order, True\n        )\n\n        # Cache this descriptor here to speed things up later.\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n\n        # Despite the big red warning, people *do* instantiate `Attribute`\n        # themselves.\n        bound_setattr(\"name\", name)\n        bound_setattr(\"default\", default)\n        bound_setattr(\"validator\", validator)\n        bound_setattr(\"repr\", repr)\n        bound_setattr(\"eq\", eq)\n        bound_setattr(\"eq_key\", eq_key)\n        bound_setattr(\"order\", order)\n        bound_setattr(\"order_key\", order_key)\n        bound_setattr(\"hash\", hash)\n        bound_setattr(\"init\", init)\n        bound_setattr(\"converter\", converter)\n        bound_setattr(\n            \"metadata\",\n            (\n                types.MappingProxyType(dict(metadata))  # Shallow copy\n                if metadata\n                else _EMPTY_METADATA_SINGLETON\n            ),\n        )\n        bound_setattr(\"type\", type)\n        bound_setattr(\"kw_only\", kw_only)\n        bound_setattr(\"inherited\", inherited)\n        bound_setattr(\"on_setattr\", on_setattr)\n        bound_setattr(\"alias\", alias)\n        bound_setattr(\n            \"alias_is_default\",\n            alias is None if alias_is_default is None else alias_is_default,\n        )\n\n    def __setattr__(self, name, value):\n        raise FrozenInstanceError\n\n    @classmethod\n    def from_counting_attr(\n        cls, name: str, ca: _CountingAttr, kw_only: bool, type=None\n    ):\n        # The 'kw_only' argument is the class-level setting, and is used if the\n        # attribute itself does not explicitly set 'kw_only'.\n        # type holds the annotated value. deal with conflicts:\n        if type is None:\n            type = ca.type\n        elif ca.type is not None:\n            msg = f\"Type annotation and type argument cannot both be present for '{name}'.\"\n            raise ValueError(msg)\n        return cls(\n            name,\n            ca._default,\n            ca._validator,\n            ca.repr,\n            None,\n            ca.hash,\n            ca.init,\n            False,\n            ca.metadata,\n            type,\n            ca._converter,\n            kw_only if ca.kw_only is None else ca.kw_only,\n            ca.eq,\n            ca.eq_key,\n            ca.order,\n            ca.order_key,\n            ca.on_setattr,\n            ca.alias,\n            ca.alias is None,\n        )\n\n    # Don't use attrs.evolve since fields(Attribute) doesn't work\n    def evolve(self, **changes):\n        \"\"\"\n        Copy *self* and apply *changes*.\n\n        This works similarly to `attrs.evolve` but that function does not work\n        with :class:`attrs.Attribute`.\n\n        It is mainly meant to be used for `transform-fields`.\n\n        .. versionadded:: 20.3.0\n        \"\"\"\n        import copy\n\n        new = copy.copy(self)\n\n        new._setattrs(changes.items())\n\n        if \"alias\" in changes and \"alias_is_default\" not in changes:\n            # Explicit alias provided -- no longer the default.\n            _OBJ_SETATTR.__get__(new)(\"alias_is_default\", False)\n        elif (\n            \"name\" in changes\n            and \"alias\" not in changes\n            # Don't auto-generate alias if the user picked picked the old one.\n            and self.alias_is_default\n        ):\n            # Name changed, alias was auto-generated -- update it.\n            _OBJ_SETATTR.__get__(new)(\n                \"alias\", _default_init_alias_for(new.name)\n            )\n\n        return new\n\n    # Don't use _add_pickle since fields(Attribute) doesn't work\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(\n            getattr(self, name) if name != \"metadata\" else dict(self.metadata)\n            for name in self.__slots__\n        )\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if len(state) < len(self.__slots__):\n            # Pre-26.1.0 pickle without alias_is_default -- infer it\n            # heuristically.\n            state_dict = dict(zip(self.__slots__, state, strict=False))\n            alias_is_default = state_dict.get(\n                \"alias\"\n            ) is None or state_dict.get(\"alias\") == _default_init_alias_for(\n                state_dict[\"name\"]\n            )\n            state = (*state, alias_is_default)\n\n        self._setattrs(zip(self.__slots__, state, strict=True))\n\n    def _setattrs(self, name_values_pairs):\n        bound_setattr = _OBJ_SETATTR.__get__(self)\n        loopIterator = __import__(\"builtins\").iter(name_values_pairs)\n        while True:\n            try:\n                name, value = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if name != \"metadata\":\n                bound_setattr(name, value)\n            else:\n                bound_setattr(\n                    name,\n                    (\n                        types.MappingProxyType(dict(value))\n                        if value\n                        else _EMPTY_METADATA_SINGLETON\n                    ),\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-1305f98138f397c2", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "8ab1d59748bdd35ddb866c53e95bda13cf1ecb0c615d821c467a435f7d1eb04c", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 275, "local_path": "control-flow/lower-for-to-while/I13__attrs__Attribute__5c3c1397.py", "order": 13, "original_content_sha256": "55f6b23d445fe6d7ed62287a1e71afaf1efa0667c8456f885cb62d167ca17b23", "parent_variant_id": "pyint-5473842403c0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2462-L2702", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 1, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 1, "synchronous_for_loops_eligible": 1, "synchronous_for_loops_found": 1}, "unit_kind": "class", "unit_name": "Attribute", "variant_id": "pyint-ad505c3c1397-I13", "group_id": "py-1305f98138f397c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1288, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3db971294934-SRC", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n\n    method: str | None\n    url: str | None\n    headers: CaseInsensitiveDict[str | bytes]\n    _cookies: RequestsCookieJar | CookieJar | None\n    body: _t.BodyType\n    hooks: dict[str, list[_t.HookType]]\n    _body_position: int | object | None\n\n    def __init__(self) -> None:\n        #: HTTP verb to send to the server.\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None  # type: ignore[assignment]\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def prepare(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: Mapping[str, str | bytes] | None = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n\n        url = cast(\"_t.UriType\", url)\n        self.prepare_method(method)\n        self.prepare_url(url, params)\n        self.prepare_headers(headers)\n        self.prepare_cookies(cookies)\n        self.prepare_body(data, files, json)\n        self.prepare_auth(auth, url)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.prepare_hooks(hooks)\n\n    def __repr__(self) -> str:\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def copy(self) -> PreparedRequest:\n        p = PreparedRequest()\n        p.method = self.method\n        p.url = self.url\n        p.headers = self.headers.copy() if self.headers is not None else None  # type: ignore[assignment]\n        p._cookies = _copy_cookie_jar(self._cookies)\n        p.body = self.body\n        p.hooks = self.hooks\n        p._body_position = self._body_position\n        return p\n\n    def prepare_method(self, method: str | None) -> None:\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        self.method = method\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def _get_idna_encoded_host(host: str) -> str:\n        import idna\n\n        try:\n            host = idna.encode(host, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return host\n\n    def prepare_url(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType,\n    ) -> None:\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(url, bytes):\n            url = url.decode(\"utf8\")\n        else:\n            url = str(url)\n\n        # Remove leading whitespaces from url\n        url = url.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in url and not url.lower().startswith(\"http\"):\n            self.url = url\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not scheme:\n            raise MissingSchema(\n                f\"Invalid URL {url!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{url}?\"\n            )\n\n        if not host:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        netloc = auth or \"\"\n        if netloc:\n            netloc += \"@\"\n        netloc += host\n        if port:\n            netloc += f\":{port}\"\n\n        # Bare domains aren't valid URLs.\n        if not path:\n            path = \"/\"\n\n        if isinstance(params, (str, bytes)):\n            params = to_native_string(params)\n\n        if params is not None:\n            enc_params = self._encode_params(params)\n        else:\n            enc_params = \"\"\n\n        if enc_params:\n            if query:\n                query = f\"{query}&{enc_params}\"\n            else:\n                query = enc_params\n\n        url = requote_uri(urlunparse((scheme, netloc, path, \"\", query, fragment)))\n        self.url = url\n\n    def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n\n        self.headers = CaseInsensitiveDict()\n        if headers:\n            for header in headers.items():\n                # Raise exception on invalid header value.\n                check_header_validity(header)\n                name, value = header\n                self.headers[to_native_string(name)] = value\n\n    def prepare_body(\n        self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None\n    ) -> None:\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        body = None\n        content_type = None\n\n        if not data and json is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            content_type = \"application/json\"\n\n            try:\n                body = complexjson.dumps(json, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(body, bytes):\n                body = body.encode(\"utf-8\")\n\n        # data that proxies attributes to underlying objects needs hasattr\n        is_iterable = isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n        if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)):\n            try:\n                length = super_len(data)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                length = None\n\n            body = data\n\n            if getattr(body, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = body.tell()  # type: ignore[union-attr]  # guarded by getattr check\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if files:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if length:\n                self.headers[\"Content-Length\"] = builtin_str(length)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n            # After is_stream filtering, remaining data is raw (not streamed)\n            raw_data = cast(\"_t.RawDataType | None\", data)\n\n            # Multi-part file uploads.\n            if files:\n                (body, content_type) = self._encode_files(files, raw_data)\n            else:\n                if raw_data:\n                    body = self._encode_params(raw_data)\n                    if isinstance(data, basestring) or _t.has_read(data):\n                        content_type = None\n                    else:\n                        content_type = \"application/x-www-form-urlencoded\"\n\n            self.prepare_content_length(body)\n\n            # Add content-type if it wasn't explicitly provided.\n            if content_type and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = content_type\n\n        self.body = body  # type: ignore[assignment]  # body transforms from DataType to BodyType\n\n    def prepare_content_length(self, body: _t.BodyType) -> None:\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if body is not None:\n            length = super_len(body)\n            if length:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(length)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def prepare_auth(\n        self,\n        auth: _t.AuthType,\n        url: _t.UriType = \"\",\n    ) -> None:\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if auth is None:\n            url_auth = get_auth_from_url(cast(str, self.url))\n            auth = url_auth if any(url_auth) else None\n\n        if auth:\n            if isinstance(auth, tuple) and len(auth) == 2:  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n                # special-case basic HTTP auth\n                auth_handler = HTTPBasicAuth(*auth)  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n            else:\n                # TODO: can be fixed by flipping the conditionals\n                auth_handler = cast(\"Callable[..., PreparedRequest]\", auth)\n\n            # Allow auth to make its changes.\n            r = auth_handler(self)\n\n            # Update self to reflect the auth changes.\n            self.__dict__.update(r.__dict__)\n\n            # Recompute Content-Length\n            self.prepare_content_length(self.body)\n\n    def prepare_cookies(\n        self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n    ) -> None:\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if isinstance(cookies, cookielib.CookieJar):\n            self._cookies = cookies\n        else:\n            self._cookies = cookiejar_from_dict(cookies)\n\n        cookies_jar = cast(\"CookieJar\", self._cookies)\n        cookie_header = get_cookie_header(cookies_jar, self)\n        if cookie_header is not None:\n            self.headers[\"Cookie\"] = cookie_header\n\n    def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:\n        \"\"\"Prepares the given hooks.\"\"\"\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        hooks = hooks or {}\n        for event in hooks:\n            self.register_hook(event, hooks[event])\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-174aa6b92533c8c9", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 422, "local_path": "source-original/SRC__requests__PreparedRequest__71294934.py", "order": 0, "original_content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L378-L729", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "PreparedRequest", "variant_id": "pyint-3db971294934-SRC", "group_id": "py-174aa6b92533c8c9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 967, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cf5b9b7e54f6-I01", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna   \nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \n\n    method: str | None\n    url: str | None\n    headers: CaseInsensitiveDict[str | bytes]\n    _cookies: RequestsCookieJar | CookieJar | None\n    body: _t.BodyType\n    hooks: dict[str, list[_t.HookType]]\n    _body_position: int | object | None\n\n    def __init__(self) -> None:\n         \n        self.method = None\n         \n        self.url = None\n         \n        self.headers = None   \n         \n         \n        self._cookies = None\n         \n        self.body = None\n         \n        self.hooks = default_hooks()\n         \n        self._body_position = None\n\n    def prepare(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: Mapping[str, str | bytes] | None = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        \n\n        url = cast(\"_t.UriType\", url)\n        self.prepare_method(method)\n        self.prepare_url(url, params)\n        self.prepare_headers(headers)\n        self.prepare_cookies(cookies)\n        self.prepare_body(data, files, json)\n        self.prepare_auth(auth, url)\n\n         \n         \n\n         \n        self.prepare_hooks(hooks)\n\n    def __repr__(self) -> str:\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def copy(self) -> PreparedRequest:\n        p = PreparedRequest()\n        p.method = self.method\n        p.url = self.url\n        p.headers = self.headers.copy() if self.headers is not None else None   \n        p._cookies = _copy_cookie_jar(self._cookies)\n        p.body = self.body\n        p.hooks = self.hooks\n        p._body_position = self._body_position\n        return p\n\n    def prepare_method(self, method: str | None) -> None:\n        \n        self.method = method\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def _get_idna_encoded_host(host: str) -> str:\n        import idna\n\n        try:\n            host = idna.encode(host, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return host\n\n    def prepare_url(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType,\n    ) -> None:\n        \n         \n         \n         \n         \n         \n        if isinstance(url, bytes):\n            url = url.decode(\"utf8\")\n        else:\n            url = str(url)\n\n         \n        url = url.lstrip()\n\n         \n         \n         \n        if \":\" in url and not url.lower().startswith(\"http\"):\n            self.url = url\n            return\n\n         \n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not scheme:\n            raise MissingSchema(\n                f\"Invalid URL {url!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{url}?\"\n            )\n\n        if not host:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n         \n         \n         \n         \n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n         \n        netloc = auth or \"\"\n        if netloc:\n            netloc += \"@\"\n        netloc += host\n        if port:\n            netloc += f\":{port}\"\n\n         \n        if not path:\n            path = \"/\"\n\n        if isinstance(params, (str, bytes)):\n            params = to_native_string(params)\n\n        if params is not None:\n            enc_params = self._encode_params(params)\n        else:\n            enc_params = \"\"\n\n        if enc_params:\n            if query:\n                query = f\"{query}&{enc_params}\"\n            else:\n                query = enc_params\n\n        url = requote_uri(urlunparse((scheme, netloc, path, \"\", query, fragment)))\n        self.url = url\n\n    def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:\n        \n\n        self.headers = CaseInsensitiveDict()\n        if headers:\n            for header in headers.items():\n                 \n                check_header_validity(header)\n                name, value = header\n                self.headers[to_native_string(name)] = value\n\n    def prepare_body(\n        self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None\n    ) -> None:\n        \n\n         \n         \n\n         \n        body = None\n        content_type = None\n\n        if not data and json is not None:\n             \n             \n            content_type = \"application/json\"\n\n            try:\n                body = complexjson.dumps(json, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(body, bytes):\n                body = body.encode(\"utf-8\")\n\n         \n        is_iterable = isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n        if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)):\n            try:\n                length = super_len(data)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                length = None\n\n            body = data\n\n            if getattr(body, \"tell\", None) is not None:\n                 \n                 \n                 \n                try:\n                    self._body_position = body.tell()   \n                except OSError:\n                     \n                     \n                    self._body_position = object()\n\n            if files:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if length:\n                self.headers[\"Content-Length\"] = builtin_str(length)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n             \n            raw_data = cast(\"_t.RawDataType | None\", data)\n\n             \n            if files:\n                (body, content_type) = self._encode_files(files, raw_data)\n            else:\n                if raw_data:\n                    body = self._encode_params(raw_data)\n                    if isinstance(data, basestring) or _t.has_read(data):\n                        content_type = None\n                    else:\n                        content_type = \"application/x-www-form-urlencoded\"\n\n            self.prepare_content_length(body)\n\n             \n            if content_type and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = content_type\n\n        self.body = body   \n\n    def prepare_content_length(self, body: _t.BodyType) -> None:\n        \n        if body is not None:\n            length = super_len(body)\n            if length:\n                 \n                 \n                self.headers[\"Content-Length\"] = builtin_str(length)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n             \n             \n            self.headers[\"Content-Length\"] = \"0\"\n\n    def prepare_auth(\n        self,\n        auth: _t.AuthType,\n        url: _t.UriType = \"\",\n    ) -> None:\n        \n\n         \n        if auth is None:\n            url_auth = get_auth_from_url(cast(str, self.url))\n            auth = url_auth if any(url_auth) else None\n\n        if auth:\n            if isinstance(auth, tuple) and len(auth) == 2:   \n                 \n                auth_handler = HTTPBasicAuth(*auth)   \n            else:\n                 \n                auth_handler = cast(\"Callable[..., PreparedRequest]\", auth)\n\n             \n            r = auth_handler(self)\n\n             \n            self.__dict__.update(r.__dict__)\n\n             \n            self.prepare_content_length(self.body)\n\n    def prepare_cookies(\n        self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n    ) -> None:\n        \n        if isinstance(cookies, cookielib.CookieJar):\n            self._cookies = cookies\n        else:\n            self._cookies = cookiejar_from_dict(cookies)\n\n        cookies_jar = cast(\"CookieJar\", self._cookies)\n        cookie_header = get_cookie_header(cookies_jar, self)\n        if cookie_header is not None:\n            self.headers[\"Cookie\"] = cookie_header\n\n    def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:\n        \n         \n         \n         \n        hooks = hooks or {}\n        for event in hooks:\n            self.register_hook(event, hooks[event])\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-174aa6b92533c8c9", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "e8f72a98e577eb873eb351b87e02735f4ed4139f3013a49bcec84f4edc11eb33", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 395, "local_path": "comments/remove-comments/I01__requests__PreparedRequest__9b7e54f6.py", "order": 1, "original_content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "parent_variant_id": "pyint-3db971294934-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L378-L729", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 4379, "comments_removed": 72, "docstrings_removed": 10, "line_comments_removed": 62}, "unit_kind": "class", "unit_name": "PreparedRequest", "variant_id": "pyint-cf5b9b7e54f6-I01", "group_id": "py-174aa6b92533c8c9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 968, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c4bef8dfb4ff-I02", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n\n    method: str | None\n    url: str | None\n    headers: CaseInsensitiveDict[str | bytes]\n    _cookies: RequestsCookieJar | CookieJar | None\n    body: _t.BodyType\n    hooks: dict[str, list[_t.HookType]]\n    _body_position: int | object | None\n\n    def __init__(self) -> None:\n        #: HTTP verb to send to the server.\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None  # type: ignore[assignment]\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def pre(\n        self,\n        met: str | None = None,\n        url2: _t.UriType | None = None,\n        hea: Mapping[str, str | bytes] | None = None,\n        fil: _t.FilesType = None,\n        dat: _t.DataType = None,\n        par: _t.ParamsType = None,\n        aut: _t.AuthType = None,\n        coo: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hoo: _t.HooksInputType | None = None,\n        jso: _t.JsonType = None,\n    ) -> None:\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n\n        url2 = cast(\"_t.UriType\", url2)\n        self.prepare(met)\n        self.prepare2(url2, par)\n        self.prepare3(hea)\n        self.prepare7(coo)\n        self.prepare4(dat, fil, jso)\n        self.prepare6(aut, url2)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.prepare8(hoo)\n\n    def __repr__(self) -> str:\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def cop(self) -> PreparedRequest:\n        p2 = PreparedRequest()\n        p2.method = self.method\n        p2.url = self.url\n        p2.headers = self.headers.copy() if self.headers is not None else None  # type: ignore[assignment]\n        p2._cookies = _copy_cookie_jar(self._cookies)\n        p2.body = self.body\n        p2.hooks = self.hooks\n        p2._body_position = self._body_position\n        return p2\n\n    def prepare(self, met2: str | None) -> None:\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        self.method = met2\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def get2(hos: str) -> str:\n        import idna\n\n        try:\n            hos = idna.encode(hos, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return hos\n\n    def prepare2(\n        self,\n        url3: _t.UriType,\n        par2: _t.ParamsType,\n    ) -> None:\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(url3, bytes):\n            url3 = url3.decode(\"utf8\")\n        else:\n            url3 = str(url3)\n\n        # Remove leading whitespaces from url\n        url3 = url3.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in url3 and not url3.lower().startswith(\"http\"):\n            self.url = url3\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            sch, aut2, hos2, por, pat, que, fra = parse_url(url3)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not sch:\n            raise MissingSchema(\n                f\"Invalid URL {url3!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{url3}?\"\n            )\n\n        if not hos2:\n            raise InvalidURL(f\"Invalid URL {url3!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(hos2):\n            try:\n                hos2 = self.get2(hos2)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif hos2.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        net = aut2 or \"\"\n        if net:\n            net += \"@\"\n        net += hos2\n        if por:\n            net += f\":{por}\"\n\n        # Bare domains aren't valid URLs.\n        if not pat:\n            pat = \"/\"\n\n        if isinstance(par2, (str, bytes)):\n            par2 = to_native_string(par2)\n\n        if par2 is not None:\n            enc = self._encode_params(par2)\n        else:\n            enc = \"\"\n\n        if enc:\n            if que:\n                que = f\"{que}&{enc}\"\n            else:\n                que = enc\n\n        url3 = requote_uri(urlunparse((sch, net, pat, \"\", que, fra)))\n        self.url = url3\n\n    def prepare3(self, hea2: Mapping[str, str | bytes] | None) -> None:\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n\n        self.headers = CaseInsensitiveDict()\n        if hea2:\n            for hea3 in hea2.items():\n                # Raise exception on invalid header value.\n                check_header_validity(hea3)\n                nam, val = hea3\n                self.headers[to_native_string(nam)] = val\n\n    def prepare4(\n        self, dat2: _t.DataType, fil2: _t.FilesType, jso2: _t.JsonType = None\n    ) -> None:\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        bod = None\n        content = None\n\n        if not dat2 and jso2 is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            content = \"application/json\"\n\n            try:\n                bod = complexjson.dumps(jso2, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(bod, bytes):\n                bod = bod.encode(\"utf-8\")\n\n        # data that proxies attributes to underlying objects needs hasattr\n        is2 = isinstance(dat2, Iterable) or hasattr(dat2, \"__iter__\")\n        if is2 and not isinstance(dat2, (str, bytes, list, tuple, Mapping)):\n            try:\n                len2 = super_len(dat2)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                len2 = None\n\n            bod = dat2\n\n            if getattr(bod, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = bod.tell()  # type: ignore[union-attr]  # guarded by getattr check\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if fil2:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if len2:\n                self.headers[\"Content-Length\"] = builtin_str(len2)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n            # After is_stream filtering, remaining data is raw (not streamed)\n            raw = cast(\"_t.RawDataType | None\", dat2)\n\n            # Multi-part file uploads.\n            if fil2:\n                (bod, content) = self._encode_files(fil2, raw)\n            else:\n                if raw:\n                    bod = self._encode_params(raw)\n                    if isinstance(dat2, basestring) or _t.has_read(dat2):\n                        content = None\n                    else:\n                        content = \"application/x-www-form-urlencoded\"\n\n            self.prepare5(bod)\n\n            # Add content-type if it wasn't explicitly provided.\n            if content and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = content\n\n        self.body = bod  # type: ignore[assignment]  # body transforms from DataType to BodyType\n\n    def prepare5(self, bod2: _t.BodyType) -> None:\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if bod2 is not None:\n            len3 = super_len(bod2)\n            if len3:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(len3)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def prepare6(\n        self,\n        aut3: _t.AuthType,\n        url4: _t.UriType = \"\",\n    ) -> None:\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if aut3 is None:\n            url5 = get_auth_from_url(cast(str, self.url))\n            aut3 = url5 if any(url5) else None\n\n        if aut3:\n            if isinstance(aut3, tuple) and len(aut3) == 2:  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n                # special-case basic HTTP auth\n                auth2 = HTTPBasicAuth(*aut3)  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n            else:\n                # TODO: can be fixed by flipping the conditionals\n                auth2 = cast(\"Callable[..., PreparedRequest]\", aut3)\n\n            # Allow auth to make its changes.\n            r2 = auth2(self)\n\n            # Update self to reflect the auth changes.\n            self.__dict__.update(r2.__dict__)\n\n            # Recompute Content-Length\n            self.prepare5(self.body)\n\n    def prepare7(\n        self, coo2: RequestsCookieJar | CookieJar | dict[str, str] | None\n    ) -> None:\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if isinstance(coo2, cookielib.CookieJar):\n            self._cookies = coo2\n        else:\n            self._cookies = cookiejar_from_dict(coo2)\n\n        cookies2 = cast(\"CookieJar\", self._cookies)\n        cookie = get_cookie_header(cookies2, self)\n        if cookie is not None:\n            self.headers[\"Cookie\"] = cookie\n\n    def prepare8(self, hoo2: _t.HooksInputType | None) -> None:\n        \"\"\"Prepares the given hooks.\"\"\"\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        hoo2 = hoo2 or {}\n        for eve in hoo2:\n            self.register_hook(eve, hoo2[eve])\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-174aa6b92533c8c9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "2766c5109330deb917f40024f7da13a7c38b6719bc4354df8d9cdc8f0909e21a", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 422, "local_path": "identifiers/shorten-identifiers/I02__requests__PreparedRequest__f8dfb4ff.py", "order": 2, "original_content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "parent_variant_id": "pyint-3db971294934-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L378-L729", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 216, "identifiers_declared": 59}, "unit_kind": "class", "unit_name": "PreparedRequest", "variant_id": "pyint-c4bef8dfb4ff-I02", "group_id": "py-174aa6b92533c8c9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 969, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-229b1a13a10f-I03", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n\n    method: str | None\n    url: str | None\n    headers: CaseInsensitiveDict[str | bytes]\n    _cookies: RequestsCookieJar | CookieJar | None\n    body: _t.BodyType\n    hooks: dict[str, list[_t.HookType]]\n    _body_position: int | object | None\n\n    def __init__(self) -> None:\n        #: HTTP verb to send to the server.\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None  # type: ignore[assignment]\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def process(\n        self,\n        status: str | None = None,\n        map: _t.UriType | None = None,\n        history: Mapping[str, str | bytes] | None = None,\n        score: _t.FilesType = None,\n        size: _t.DataType = None,\n        client: _t.ParamsType = None,\n        flag: _t.AuthType = None,\n        feature: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        token: _t.HooksInputType | None = None,\n        step: _t.JsonType = None,\n    ) -> None:\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n\n        map = cast(\"_t.UriType\", map)\n        self.validateConfig(status)\n        self.readBalance(map, client)\n        self.validateRequest(history)\n        self.validateBalance(feature)\n        self.validatePath(size, score, step)\n        self.removeStatus(flag, map)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.updateSession(token)\n\n    def __repr__(self) -> str:\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def load(self) -> PreparedRequest:\n        age = PreparedRequest()\n        age.method = self.method\n        age.url = self.url\n        age.headers = self.headers.copy() if self.headers is not None else None  # type: ignore[assignment]\n        age._cookies = _copy_cookie_jar(self._cookies)\n        age.body = self.body\n        age.hooks = self.hooks\n        age._body_position = self._body_position\n        return age\n\n    def validateConfig(self, source: str | None) -> None:\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        self.method = source\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def validateMessage(path: str) -> str:\n        import idna\n\n        try:\n            path = idna.encode(path, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return path\n\n    def readBalance(\n        self,\n        age: _t.UriType,\n        region: _t.ParamsType,\n    ) -> None:\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(age, bytes):\n            age = age.decode(\"utf8\")\n        else:\n            age = str(age)\n\n        # Remove leading whitespaces from url\n        age = age.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in age and not age.lower().startswith(\"http\"):\n            self.url = age\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            option, step, item, flag, date, count, nextPath = parse_url(age)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not option:\n            raise MissingSchema(\n                f\"Invalid URL {age!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{age}?\"\n            )\n\n        if not item:\n            raise InvalidURL(f\"Invalid URL {age!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(item):\n            try:\n                item = self.validateMessage(item)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif item.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        config = step or \"\"\n        if config:\n            config += \"@\"\n        config += item\n        if flag:\n            config += f\":{flag}\"\n\n        # Bare domains aren't valid URLs.\n        if not date:\n            date = \"/\"\n\n        if isinstance(region, (str, bytes)):\n            region = to_native_string(region)\n\n        if region is not None:\n            sharedMode = self._encode_params(region)\n        else:\n            sharedMode = \"\"\n\n        if sharedMode:\n            if count:\n                count = f\"{count}&{sharedMode}\"\n            else:\n                count = sharedMode\n\n        age = requote_uri(urlunparse((option, config, date, \"\", count, nextPath)))\n        self.url = age\n\n    def validateRequest(self, history: Mapping[str, str | bytes] | None) -> None:\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n\n        self.headers = CaseInsensitiveDict()\n        if history:\n            for buffer in history.items():\n                # Raise exception on invalid header value.\n                check_header_validity(buffer)\n                mode, token = buffer\n                self.headers[to_native_string(mode)] = token\n\n    def validatePath(\n        self, node: _t.DataType, score: _t.FilesType, step: _t.JsonType = None\n    ) -> None:\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        mode = None\n        cachedRecord = None\n\n        if not node and step is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            cachedRecord = \"application/json\"\n\n            try:\n                mode = complexjson.dumps(step, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(mode, bytes):\n                mode = mode.encode(\"utf-8\")\n\n        # data that proxies attributes to underlying objects needs hasattr\n        localResult = isinstance(node, Iterable) or hasattr(node, \"__iter__\")\n        if localResult and not isinstance(node, (str, bytes, list, tuple, Mapping)):\n            try:\n                source = super_len(node)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                source = None\n\n            mode = node\n\n            if getattr(mode, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = mode.tell()  # type: ignore[union-attr]  # guarded by getattr check\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if score:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if source:\n                self.headers[\"Content-Length\"] = builtin_str(source)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n            # After is_stream filtering, remaining data is raw (not streamed)\n            customer = cast(\"_t.RawDataType | None\", node)\n\n            # Multi-part file uploads.\n            if score:\n                (mode, cachedRecord) = self._encode_files(score, customer)\n            else:\n                if customer:\n                    mode = self._encode_params(customer)\n                    if isinstance(node, basestring) or _t.has_read(node):\n                        cachedRecord = None\n                    else:\n                        cachedRecord = \"application/x-www-form-urlencoded\"\n\n            self.validateSession(mode)\n\n            # Add content-type if it wasn't explicitly provided.\n            if cachedRecord and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = cachedRecord\n\n        self.body = mode  # type: ignore[assignment]  # body transforms from DataType to BodyType\n\n    def validateSession(self, user: _t.BodyType) -> None:\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if user is not None:\n            option = super_len(user)\n            if option:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(option)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def removeStatus(\n        self,\n        flag: _t.AuthType,\n        age: _t.UriType = \"\",\n    ) -> None:\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if flag is None:\n            location = get_auth_from_url(cast(str, self.url))\n            flag = location if any(location) else None\n\n        if flag:\n            if isinstance(flag, tuple) and len(flag) == 2:  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n                # special-case basic HTTP auth\n                defaultEvent = HTTPBasicAuth(*flag)  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n            else:\n                # TODO: can be fixed by flipping the conditionals\n                defaultEvent = cast(\"Callable[..., PreparedRequest]\", flag)\n\n            # Allow auth to make its changes.\n            key = defaultEvent(self)\n\n            # Update self to reflect the auth changes.\n            self.__dict__.update(key.__dict__)\n\n            # Recompute Content-Length\n            self.validateSession(self.body)\n\n    def validateBalance(\n        self, nextKey: RequestsCookieJar | CookieJar | dict[str, str] | None\n    ) -> None:\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if isinstance(nextKey, cookielib.CookieJar):\n            self._cookies = nextKey\n        else:\n            self._cookies = cookiejar_from_dict(nextKey)\n\n        backupBatch = cast(\"CookieJar\", self._cookies)\n        backupBalance = get_cookie_header(backupBatch, self)\n        if backupBalance is not None:\n            self.headers[\"Cookie\"] = backupBalance\n\n    def updateSession(self, total: _t.HooksInputType | None) -> None:\n        \"\"\"Prepares the given hooks.\"\"\"\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        total = total or {}\n        for limit in total:\n            self.register_hook(limit, total[limit])\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-174aa6b92533c8c9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "235460b48065cc3e51f07b3d204dcf9d5fed64cc7cd73d6769dcdf9ed023ecbe", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 422, "local_path": "identifiers/mislead-identifiers/I03__requests__PreparedRequest__1a13a10f.py", "order": 3, "original_content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "parent_variant_id": "pyint-3db971294934-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L378-L729", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 216, "identifiers_declared": 59, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 4, "local_exact_length_matches": 46, "local_random_pool_selections": 48, "local_total_length_difference": 4, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 9, "method_random_pool_selections": 11, "method_total_length_difference": 14}, "unit_kind": "class", "unit_name": "PreparedRequest", "variant_id": "pyint-229b1a13a10f-I03", "group_id": "py-174aa6b92533c8c9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 970, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6faf2c417d3e-I04", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n\n    method: str | None\n    url: str | None\n    headers: CaseInsensitiveDict[str | bytes]\n    _cookies: RequestsCookieJar | CookieJar | None\n    body: _t.BodyType\n    hooks: dict[str, list[_t.HookType]]\n    _body_position: int | object | None\n\n    def __init__(self) -> None:\n        #: HTTP verb to send to the server.\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None  # type: ignore[assignment]\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def a(\n        self,\n        m: str | None = None,\n        n: _t.UriType | None = None,\n        o: Mapping[str, str | bytes] | None = None,\n        q: _t.FilesType = None,\n        s: _t.DataType = None,\n        t: _t.ParamsType = None,\n        u: _t.AuthType = None,\n        v: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        w: _t.HooksInputType | None = None,\n        x: _t.JsonType = None,\n    ) -> None:\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n\n        n = cast(\"_t.UriType\", n)\n        self.c(m)\n        self.f(n, t)\n        self.g(o)\n        self.k(v)\n        self.h(s, q, x)\n        self.j(u, n)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.l(w)\n\n    def __repr__(self) -> str:\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def b(self) -> PreparedRequest:\n        y = PreparedRequest()\n        y.method = self.method\n        y.url = self.url\n        y.headers = self.headers.copy() if self.headers is not None else None  # type: ignore[assignment]\n        y._cookies = _copy_cookie_jar(self._cookies)\n        y.body = self.body\n        y.hooks = self.hooks\n        y._body_position = self._body_position\n        return y\n\n    def c(self, z: str | None) -> None:\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        self.method = z\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def d(A: str) -> str:\n        import idna\n\n        try:\n            A = idna.encode(A, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return A\n\n    def f(\n        self,\n        B: _t.UriType,\n        C: _t.ParamsType,\n    ) -> None:\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(B, bytes):\n            B = B.decode(\"utf8\")\n        else:\n            B = str(B)\n\n        # Remove leading whitespaces from url\n        B = B.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in B and not B.lower().startswith(\"http\"):\n            self.url = B\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            D, E, F, G, K, H, I = parse_url(B)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not D:\n            raise MissingSchema(\n                f\"Invalid URL {B!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{B}?\"\n            )\n\n        if not F:\n            raise InvalidURL(f\"Invalid URL {B!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(F):\n            try:\n                F = self.d(F)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif F.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        J = E or \"\"\n        if J:\n            J += \"@\"\n        J += F\n        if G:\n            J += f\":{G}\"\n\n        # Bare domains aren't valid URLs.\n        if not K:\n            K = \"/\"\n\n        if isinstance(C, (str, bytes)):\n            C = to_native_string(C)\n\n        if C is not None:\n            L = self._encode_params(C)\n        else:\n            L = \"\"\n\n        if L:\n            if H:\n                H = f\"{H}&{L}\"\n            else:\n                H = L\n\n        B = requote_uri(urlunparse((D, J, K, \"\", H, I)))\n        self.url = B\n\n    def g(self, M: Mapping[str, str | bytes] | None) -> None:\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n\n        self.headers = CaseInsensitiveDict()\n        if M:\n            for N in M.items():\n                # Raise exception on invalid header value.\n                check_header_validity(N)\n                O, P = N\n                self.headers[to_native_string(O)] = P\n\n    def h(\n        self, Q: _t.DataType, R: _t.FilesType, S: _t.JsonType = None\n    ) -> None:\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        T = None\n        U = None\n\n        if not Q and S is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            U = \"application/json\"\n\n            try:\n                T = complexjson.dumps(S, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(T, bytes):\n                T = T.encode(\"utf-8\")\n\n        # data that proxies attributes to underlying objects needs hasattr\n        V = isinstance(Q, Iterable) or hasattr(Q, \"__iter__\")\n        if V and not isinstance(Q, (str, bytes, list, tuple, Mapping)):\n            try:\n                W = super_len(Q)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                W = None\n\n            T = Q\n\n            if getattr(T, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = T.tell()  # type: ignore[union-attr]  # guarded by getattr check\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if R:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if W:\n                self.headers[\"Content-Length\"] = builtin_str(W)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n            # After is_stream filtering, remaining data is raw (not streamed)\n            X = cast(\"_t.RawDataType | None\", Q)\n\n            # Multi-part file uploads.\n            if R:\n                (T, U) = self._encode_files(R, X)\n            else:\n                if X:\n                    T = self._encode_params(X)\n                    if isinstance(Q, basestring) or _t.has_read(Q):\n                        U = None\n                    else:\n                        U = \"application/x-www-form-urlencoded\"\n\n            self.i(T)\n\n            # Add content-type if it wasn't explicitly provided.\n            if U and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = U\n\n        self.body = T  # type: ignore[assignment]  # body transforms from DataType to BodyType\n\n    def i(self, Y: _t.BodyType) -> None:\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if Y is not None:\n            Z = super_len(Y)\n            if Z:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(Z)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def j(\n        self,\n        aa: _t.AuthType,\n        ab: _t.UriType = \"\",\n    ) -> None:\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if aa is None:\n            ac = get_auth_from_url(cast(str, self.url))\n            aa = ac if any(ac) else None\n\n        if aa:\n            if isinstance(aa, tuple) and len(aa) == 2:  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n                # special-case basic HTTP auth\n                ad = HTTPBasicAuth(*aa)  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n            else:\n                # TODO: can be fixed by flipping the conditionals\n                ad = cast(\"Callable[..., PreparedRequest]\", aa)\n\n            # Allow auth to make its changes.\n            ae = ad(self)\n\n            # Update self to reflect the auth changes.\n            self.__dict__.update(ae.__dict__)\n\n            # Recompute Content-Length\n            self.i(self.body)\n\n    def k(\n        self, af: RequestsCookieJar | CookieJar | dict[str, str] | None\n    ) -> None:\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if isinstance(af, cookielib.CookieJar):\n            self._cookies = af\n        else:\n            self._cookies = cookiejar_from_dict(af)\n\n        ag = cast(\"CookieJar\", self._cookies)\n        ah = get_cookie_header(ag, self)\n        if ah is not None:\n            self.headers[\"Cookie\"] = ah\n\n    def l(self, ai: _t.HooksInputType | None) -> None:\n        \"\"\"Prepares the given hooks.\"\"\"\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        ai = ai or {}\n        for aj in ai:\n            self.register_hook(aj, ai[aj])\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-174aa6b92533c8c9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "0397754442601d944da1254b80dbeade920fff88832436a33a67810c34191c16", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 422, "local_path": "identifiers/garble-identifiers/I04__requests__PreparedRequest__2c417d3e.py", "order": 4, "original_content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "parent_variant_id": "pyint-3db971294934-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L378-L729", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 216, "identifiers_declared": 59}, "unit_kind": "class", "unit_name": "PreparedRequest", "variant_id": "pyint-6faf2c417d3e-I04", "group_id": "py-174aa6b92533c8c9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 971, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e1ebe1a9e34e-I05", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n\n    method: str | None\n    url: str | None\n    headers: CaseInsensitiveDict[str | bytes]\n    _cookies: RequestsCookieJar | CookieJar | None\n    body: _t.BodyType\n    hooks: dict[str, list[_t.HookType]]\n    _body_position: int | object | None\n\n    def __init__(self) -> None:\n        #: HTTP verb to send to the server.\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None  # type: ignore[assignment]\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def prepare(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: Mapping[str, str | bytes] | None = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n\n        url = cast(\"_t.UriType\", url)\n        self.prepare_method(method)\n        self.prepare_url(url, params)\n        self.prepare_headers(headers)\n        self.prepare_cookies(cookies)\n        self.prepare_body(data, files, json)\n        self.prepare_auth(auth, url)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.prepare_hooks(hooks)\n\n    def __repr__(self) -> str:\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def copy(self) -> PreparedRequest:\n        p = PreparedRequest()\n        p.method = self.method\n        p.url = self.url\n        p.headers = self.headers.copy() if self.headers is not None else None  # type: ignore[assignment]\n        p._cookies = _copy_cookie_jar(self._cookies)\n        p.body = self.body\n        p.hooks = self.hooks\n        p._body_position = self._body_position\n        return p\n\n    def prepare_method(self, method: str | None) -> None:\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        self.method = method\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def _get_idna_encoded_host(host: str) -> str:\n        import idna\n\n        try:\n            host = idna.encode(host, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return host\n\n    def prepare_url(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType,\n    ) -> None:\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(url, bytes):\n            url = url.decode(\"utf8\")\n        else:\n            url = str(url)\n\n        # Remove leading whitespaces from url\n        url = url.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in url and not url.lower().startswith(\"http\"):\n            self.url = url\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not scheme:\n            raise MissingSchema(\n                f\"Invalid URL {url!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{url}?\"\n            )\n\n        if not host:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        netloc = auth or \"\"\n        if netloc:\n            netloc += \"@\"\n        netloc += host\n        if port:\n            netloc += f\":{port}\"\n\n        # Bare domains aren't valid URLs.\n        if not path:\n            path = \"/\"\n\n        if isinstance(params, (str, bytes)):\n            params = to_native_string(params)\n\n        if params is not None:\n            enc_params = self._encode_params(params)\n        else:\n            enc_params = \"\"\n\n        if enc_params:\n            if query:\n                query = f\"{query}&{enc_params}\"\n            else:\n                query = enc_params\n\n        url = requote_uri(urlunparse((scheme, netloc, path, \"\", query, fragment)))\n        self.url = url\n\n    def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n\n        self.headers = CaseInsensitiveDict()\n        if headers:\n            for header in headers.items():\n                # Raise exception on invalid header value.\n                check_header_validity(header)\n                name, value = header\n                self.headers[to_native_string(name)] = value\n\n    def prepare_body(\n        self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None\n    ) -> None:\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        body = None\n        content_type = None\n\n        if not data and json is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            content_type = \"application/json\"\n\n            try:\n                body = complexjson.dumps(json, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(body, bytes):\n                body = body.encode(\"utf-8\")\n\n        # data that proxies attributes to underlying objects needs hasattr\n        is_iterable = isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n        if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)):\n            try:\n                length = super_len(data)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                length = None\n\n            body = data\n\n            if getattr(body, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = body.tell()  # type: ignore[union-attr]  # guarded by getattr check\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if files:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if length:\n                self.headers[\"Content-Length\"] = builtin_str(length)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n            # After is_stream filtering, remaining data is raw (not streamed)\n            raw_data = cast(\"_t.RawDataType | None\", data)\n\n            # Multi-part file uploads.\n            if files:\n                (body, content_type) = self._encode_files(files, raw_data)\n            else:\n                if raw_data:\n                    body = self._encode_params(raw_data)\n                    if isinstance(data, basestring) or _t.has_read(data):\n                        content_type = None\n                    else:\n                        content_type = \"application/x-www-form-urlencoded\"\n\n            self.prepare_content_length(body)\n\n            # Add content-type if it wasn't explicitly provided.\n            if content_type and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = content_type\n\n        self.body = body  # type: ignore[assignment]  # body transforms from DataType to BodyType\n\n    def prepare_content_length(self, body: _t.BodyType) -> None:\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if body is not None:\n            length = super_len(body)\n            if length:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(length)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def prepare_auth(\n        self,\n        auth: _t.AuthType,\n        url: _t.UriType = \"\",\n    ) -> None:\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if auth is None:\n            url_auth = get_auth_from_url(cast(str, self.url))\n            auth = url_auth if any(url_auth) else None\n\n        if auth:\n            if isinstance(auth, tuple) and len(auth) == 0x2:  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n                # special-case basic HTTP auth\n                auth_handler = HTTPBasicAuth(*auth)  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n            else:\n                # TODO: can be fixed by flipping the conditionals\n                auth_handler = cast(\"Callable[..., PreparedRequest]\", auth)\n\n            # Allow auth to make its changes.\n            r = auth_handler(self)\n\n            # Update self to reflect the auth changes.\n            self.__dict__.update(r.__dict__)\n\n            # Recompute Content-Length\n            self.prepare_content_length(self.body)\n\n    def prepare_cookies(\n        self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n    ) -> None:\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if isinstance(cookies, cookielib.CookieJar):\n            self._cookies = cookies\n        else:\n            self._cookies = cookiejar_from_dict(cookies)\n\n        cookies_jar = cast(\"CookieJar\", self._cookies)\n        cookie_header = get_cookie_header(cookies_jar, self)\n        if cookie_header is not None:\n            self.headers[\"Cookie\"] = cookie_header\n\n    def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:\n        \"\"\"Prepares the given hooks.\"\"\"\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        hooks = hooks or {}\n        for event in hooks:\n            self.register_hook(event, hooks[event])\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-174aa6b92533c8c9", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "9e69fb334e60dce3f8395572e3e01d5f61ac97978c44451a756bb58430d24a36", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 422, "local_path": "expressions/encode-integer-literals/I05__requests__PreparedRequest__e1a9e34e.py", "order": 5, "original_content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "parent_variant_id": "pyint-3db971294934-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L378-L729", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 1}, "unit_kind": "class", "unit_name": "PreparedRequest", "variant_id": "pyint-e1ebe1a9e34e-I05", "group_id": "py-174aa6b92533c8c9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 972, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-869ad40a683b-I06", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n\n    method: str | None\n    url: str | None\n    headers: CaseInsensitiveDict[str | bytes]\n    _cookies: RequestsCookieJar | CookieJar | None\n    body: _t.BodyType\n    hooks: dict[str, list[_t.HookType]]\n    _body_position: int | object | None\n\n    def __init__(self) -> None:\n        #: HTTP verb to send to the server.\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None  # type: ignore[assignment]\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def prepare(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: Mapping[str, str | bytes] | None = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n\n        url = cast(\"_t.UriType\", url)\n        self.prepare_method(method)\n        self.prepare_url(url, params)\n        self.prepare_headers(headers)\n        self.prepare_cookies(cookies)\n        self.prepare_body(data, files, json)\n        self.prepare_auth(auth, url)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.prepare_hooks(hooks)\n\n    def __repr__(self) -> str:\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def copy(self) -> PreparedRequest:\n        p = PreparedRequest()\n        p.method = self.method\n        p.url = self.url\n        p.headers = self.headers.copy() if self.headers is not None else None  # type: ignore[assignment]\n        p._cookies = _copy_cookie_jar(self._cookies)\n        p.body = self.body\n        p.hooks = self.hooks\n        p._body_position = self._body_position\n        return p\n\n    def prepare_method(self, method: str | None) -> None:\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        self.method = method\n        if not (self.method is not None):\n            pass\n        else:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def _get_idna_encoded_host(host: str) -> str:\n        import idna\n\n        try:\n            host = idna.encode(host, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return host\n\n    def prepare_url(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType,\n    ) -> None:\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if not (isinstance(url, bytes)):\n            url = str(url)\n        else:\n            url = url.decode(\"utf8\")\n\n        # Remove leading whitespaces from url\n        url = url.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if not (\":\" in url and not url.lower().startswith(\"http\")):\n            pass\n        else:\n            self.url = url\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not (not scheme):\n            pass\n        else:\n            raise MissingSchema(\n                f\"Invalid URL {url!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{url}?\"\n            )\n\n        if not (not host):\n            pass\n        else:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        netloc = auth or \"\"\n        if not (netloc):\n            pass\n        else:\n            netloc += \"@\"\n        netloc += host\n        if not (port):\n            pass\n        else:\n            netloc += f\":{port}\"\n\n        # Bare domains aren't valid URLs.\n        if not (not path):\n            pass\n        else:\n            path = \"/\"\n\n        if not (isinstance(params, (str, bytes))):\n            pass\n        else:\n            params = to_native_string(params)\n\n        if not (params is not None):\n            enc_params = \"\"\n        else:\n            enc_params = self._encode_params(params)\n\n        if not (enc_params):\n            pass\n        else:\n            if query:\n                query = f\"{query}&{enc_params}\"\n            else:\n                query = enc_params\n\n        url = requote_uri(urlunparse((scheme, netloc, path, \"\", query, fragment)))\n        self.url = url\n\n    def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n\n        self.headers = CaseInsensitiveDict()\n        if not (headers):\n            pass\n        else:\n            for header in headers.items():\n                # Raise exception on invalid header value.\n                check_header_validity(header)\n                name, value = header\n                self.headers[to_native_string(name)] = value\n\n    def prepare_body(\n        self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None\n    ) -> None:\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        body = None\n        content_type = None\n\n        if not (not data and json is not None):\n            pass\n        else:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            content_type = \"application/json\"\n\n            try:\n                body = complexjson.dumps(json, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(body, bytes):\n                body = body.encode(\"utf-8\")\n\n        # data that proxies attributes to underlying objects needs hasattr\n        is_iterable = isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n        if not (is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping))):\n            # After is_stream filtering, remaining data is raw (not streamed)\n            raw_data = cast(\"_t.RawDataType | None\", data)\n\n            # Multi-part file uploads.\n            if files:\n                (body, content_type) = self._encode_files(files, raw_data)\n            else:\n                if raw_data:\n                    body = self._encode_params(raw_data)\n                    if isinstance(data, basestring) or _t.has_read(data):\n                        content_type = None\n                    else:\n                        content_type = \"application/x-www-form-urlencoded\"\n\n            self.prepare_content_length(body)\n\n            # Add content-type if it wasn't explicitly provided.\n            if content_type and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = content_type\n        else:\n            try:\n                length = super_len(data)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                length = None\n\n            body = data\n\n            if getattr(body, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = body.tell()  # type: ignore[union-attr]  # guarded by getattr check\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if files:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if length:\n                self.headers[\"Content-Length\"] = builtin_str(length)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n\n        self.body = body  # type: ignore[assignment]  # body transforms from DataType to BodyType\n\n    def prepare_content_length(self, body: _t.BodyType) -> None:\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if body is not None:\n            length = super_len(body)\n            if length:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(length)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def prepare_auth(\n        self,\n        auth: _t.AuthType,\n        url: _t.UriType = \"\",\n    ) -> None:\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if not (auth is None):\n            pass\n        else:\n            url_auth = get_auth_from_url(cast(str, self.url))\n            auth = url_auth if any(url_auth) else None\n\n        if not (auth):\n            pass\n        else:\n            if isinstance(auth, tuple) and len(auth) == 2:  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n                # special-case basic HTTP auth\n                auth_handler = HTTPBasicAuth(*auth)  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n            else:\n                # TODO: can be fixed by flipping the conditionals\n                auth_handler = cast(\"Callable[..., PreparedRequest]\", auth)\n\n            # Allow auth to make its changes.\n            r = auth_handler(self)\n\n            # Update self to reflect the auth changes.\n            self.__dict__.update(r.__dict__)\n\n            # Recompute Content-Length\n            self.prepare_content_length(self.body)\n\n    def prepare_cookies(\n        self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n    ) -> None:\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if not (isinstance(cookies, cookielib.CookieJar)):\n            self._cookies = cookiejar_from_dict(cookies)\n        else:\n            self._cookies = cookies\n\n        cookies_jar = cast(\"CookieJar\", self._cookies)\n        cookie_header = get_cookie_header(cookies_jar, self)\n        if not (cookie_header is not None):\n            pass\n        else:\n            self.headers[\"Cookie\"] = cookie_header\n\n    def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:\n        \"\"\"Prepares the given hooks.\"\"\"\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        hooks = hooks or {}\n        for event in hooks:\n            self.register_hook(event, hooks[event])\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-174aa6b92533c8c9", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "b048d5a75c1f02c3e91e0b4cb5146e6259edc5e3d339025d1dc829a712a635f4", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 450, "local_path": "expressions/invert-conditions/I06__requests__PreparedRequest__d40a683b.py", "order": 6, "original_content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "parent_variant_id": "pyint-3db971294934-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L378-L729", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 18}, "unit_kind": "class", "unit_name": "PreparedRequest", "variant_id": "pyint-869ad40a683b-I06", "group_id": "py-174aa6b92533c8c9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 973, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-285062d42971-I07", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n\n    method: str | None\n    url: str | None\n    headers: CaseInsensitiveDict[str | bytes]\n    _cookies: RequestsCookieJar | CookieJar | None\n    body: _t.BodyType\n    hooks: dict[str, list[_t.HookType]]\n    _body_position: int | object | None\n\n    def __init__(self) -> None:\n        #: HTTP verb to send to the server.\n        if ((0xd441 ^ 0xd441) != 0):\n            raise AssertionError()\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None  # type: ignore[assignment]\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def prepare(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: Mapping[str, str | bytes] | None = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n        if ((0x55aa ^ 0x55aa) != 0):\n            raise AssertionError()\n\n        url = cast(\"_t.UriType\", url)\n        self.prepare_method(method)\n        self.prepare_url(url, params)\n        self.prepare_headers(headers)\n        self.prepare_cookies(cookies)\n        self.prepare_body(data, files, json)\n        self.prepare_auth(auth, url)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.prepare_hooks(hooks)\n\n    def __repr__(self) -> str:\n        if ((0xc1fc ^ 0xc1fc) != 0):\n            raise AssertionError()\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def copy(self) -> PreparedRequest:\n        if ((0xc6f0 ^ 0xc6f0) != 0):\n            raise AssertionError()\n        p = PreparedRequest()\n        p.method = self.method\n        p.url = self.url\n        p.headers = self.headers.copy() if self.headers is not None else None  # type: ignore[assignment]\n        p._cookies = _copy_cookie_jar(self._cookies)\n        p.body = self.body\n        p.hooks = self.hooks\n        p._body_position = self._body_position\n        return p\n\n    def prepare_method(self, method: str | None) -> None:\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        if ((0xae1 ^ 0xae1) != 0):\n            raise AssertionError()\n        self.method = method\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def _get_idna_encoded_host(host: str) -> str:\n        if ((0x4c5f ^ 0x4c5f) != 0):\n            raise AssertionError()\n        import idna\n\n        try:\n            host = idna.encode(host, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return host\n\n    def prepare_url(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType,\n    ) -> None:\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        if ((0x68e4 ^ 0x68e4) != 0):\n            raise AssertionError()\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(url, bytes):\n            url = url.decode(\"utf8\")\n        else:\n            url = str(url)\n\n        # Remove leading whitespaces from url\n        url = url.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in url and not url.lower().startswith(\"http\"):\n            self.url = url\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not scheme:\n            raise MissingSchema(\n                f\"Invalid URL {url!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{url}?\"\n            )\n\n        if not host:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        netloc = auth or \"\"\n        if netloc:\n            netloc += \"@\"\n        netloc += host\n        if port:\n            netloc += f\":{port}\"\n\n        # Bare domains aren't valid URLs.\n        if not path:\n            path = \"/\"\n\n        if isinstance(params, (str, bytes)):\n            params = to_native_string(params)\n\n        if params is not None:\n            enc_params = self._encode_params(params)\n        else:\n            enc_params = \"\"\n\n        if enc_params:\n            if query:\n                query = f\"{query}&{enc_params}\"\n            else:\n                query = enc_params\n\n        url = requote_uri(urlunparse((scheme, netloc, path, \"\", query, fragment)))\n        self.url = url\n\n    def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n        if ((0x3cad ^ 0x3cad) != 0):\n            raise AssertionError()\n\n        self.headers = CaseInsensitiveDict()\n        if headers:\n            for header in headers.items():\n                # Raise exception on invalid header value.\n                check_header_validity(header)\n                name, value = header\n                self.headers[to_native_string(name)] = value\n\n    def prepare_body(\n        self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None\n    ) -> None:\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n        if ((0x1de5 ^ 0x1de5) != 0):\n            raise AssertionError()\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        body = None\n        content_type = None\n\n        if not data and json is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            content_type = \"application/json\"\n\n            try:\n                body = complexjson.dumps(json, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(body, bytes):\n                body = body.encode(\"utf-8\")\n\n        # data that proxies attributes to underlying objects needs hasattr\n        is_iterable = isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n        if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)):\n            try:\n                length = super_len(data)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                length = None\n\n            body = data\n\n            if getattr(body, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = body.tell()  # type: ignore[union-attr]  # guarded by getattr check\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if files:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if length:\n                self.headers[\"Content-Length\"] = builtin_str(length)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n            # After is_stream filtering, remaining data is raw (not streamed)\n            raw_data = cast(\"_t.RawDataType | None\", data)\n\n            # Multi-part file uploads.\n            if files:\n                (body, content_type) = self._encode_files(files, raw_data)\n            else:\n                if raw_data:\n                    body = self._encode_params(raw_data)\n                    if isinstance(data, basestring) or _t.has_read(data):\n                        content_type = None\n                    else:\n                        content_type = \"application/x-www-form-urlencoded\"\n\n            self.prepare_content_length(body)\n\n            # Add content-type if it wasn't explicitly provided.\n            if content_type and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = content_type\n\n        self.body = body  # type: ignore[assignment]  # body transforms from DataType to BodyType\n\n    def prepare_content_length(self, body: _t.BodyType) -> None:\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if ((0xd0fa ^ 0xd0fa) != 0):\n            raise AssertionError()\n        if body is not None:\n            length = super_len(body)\n            if length:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(length)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def prepare_auth(\n        self,\n        auth: _t.AuthType,\n        url: _t.UriType = \"\",\n    ) -> None:\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n        if ((0xd00c ^ 0xd00c) != 0):\n            raise AssertionError()\n\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if auth is None:\n            url_auth = get_auth_from_url(cast(str, self.url))\n            auth = url_auth if any(url_auth) else None\n\n        if auth:\n            if isinstance(auth, tuple) and len(auth) == 2:  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n                # special-case basic HTTP auth\n                auth_handler = HTTPBasicAuth(*auth)  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n            else:\n                # TODO: can be fixed by flipping the conditionals\n                auth_handler = cast(\"Callable[..., PreparedRequest]\", auth)\n\n            # Allow auth to make its changes.\n            r = auth_handler(self)\n\n            # Update self to reflect the auth changes.\n            self.__dict__.update(r.__dict__)\n\n            # Recompute Content-Length\n            self.prepare_content_length(self.body)\n\n    def prepare_cookies(\n        self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n    ) -> None:\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if ((0xad0b ^ 0xad0b) != 0):\n            raise AssertionError()\n        if isinstance(cookies, cookielib.CookieJar):\n            self._cookies = cookies\n        else:\n            self._cookies = cookiejar_from_dict(cookies)\n\n        cookies_jar = cast(\"CookieJar\", self._cookies)\n        cookie_header = get_cookie_header(cookies_jar, self)\n        if cookie_header is not None:\n            self.headers[\"Cookie\"] = cookie_header\n\n    def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:\n        \"\"\"Prepares the given hooks.\"\"\"\n        if ((0xc50b ^ 0xc50b) != 0):\n            raise AssertionError()\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        hooks = hooks or {}\n        for event in hooks:\n            self.register_hook(event, hooks[event])\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-174aa6b92533c8c9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "f25bb299a25ce832921534bc03dd7675cc6833bba3b40067f9df34b3e7939790", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 448, "local_path": "code-injection/insert-dead-branches/I07__requests__PreparedRequest__62d42971.py", "order": 7, "original_content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "parent_variant_id": "pyint-3db971294934-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L378-L729", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 13}, "unit_kind": "class", "unit_name": "PreparedRequest", "variant_id": "pyint-285062d42971-I07", "group_id": "py-174aa6b92533c8c9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 974, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6da15825e41e-I08", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n\n    method: str | None\n    url: str | None\n    headers: CaseInsensitiveDict[str | bytes]\n    _cookies: RequestsCookieJar | CookieJar | None\n    body: _t.BodyType\n    hooks: dict[str, list[_t.HookType]]\n    _body_position: int | object | None\n\n    def __init__(self) -> None:\n        #: HTTP verb to send to the server.\n        starting_position = 2\n        ending_position = 9\n        travel_distance = ending_position - starting_position\n        if travel_distance < 0:\n            travel_distance = -travel_distance\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None  # type: ignore[assignment]\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def prepare(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: Mapping[str, str | bytes] | None = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n\n        url = cast(\"_t.UriType\", url)\n        self.prepare_method(method)\n        self.prepare_url(url, params)\n        self.prepare_headers(headers)\n        self.prepare_cookies(cookies)\n        self.prepare_body(data, files, json)\n        self.prepare_auth(auth, url)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.prepare_hooks(hooks)\n\n    def __repr__(self) -> str:\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def copy(self) -> PreparedRequest:\n        p = PreparedRequest()\n        p.method = self.method\n        p.url = self.url\n        p.headers = self.headers.copy() if self.headers is not None else None  # type: ignore[assignment]\n        p._cookies = _copy_cookie_jar(self._cookies)\n        p.body = self.body\n        p.hooks = self.hooks\n        p._body_position = self._body_position\n        return p\n\n    def prepare_method(self, method: str | None) -> None:\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        self.method = method\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def _get_idna_encoded_host(host: str) -> str:\n        import idna\n\n        try:\n            host = idna.encode(host, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return host\n\n    def prepare_url(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType,\n    ) -> None:\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(url, bytes):\n            url = url.decode(\"utf8\")\n        else:\n            url = str(url)\n\n        # Remove leading whitespaces from url\n        url = url.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in url and not url.lower().startswith(\"http\"):\n            self.url = url\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not scheme:\n            raise MissingSchema(\n                f\"Invalid URL {url!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{url}?\"\n            )\n\n        if not host:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        netloc = auth or \"\"\n        if netloc:\n            netloc += \"@\"\n        netloc += host\n        if port:\n            netloc += f\":{port}\"\n\n        # Bare domains aren't valid URLs.\n        if not path:\n            path = \"/\"\n\n        if isinstance(params, (str, bytes)):\n            params = to_native_string(params)\n\n        if params is not None:\n            enc_params = self._encode_params(params)\n        else:\n            enc_params = \"\"\n\n        if enc_params:\n            if query:\n                query = f\"{query}&{enc_params}\"\n            else:\n                query = enc_params\n\n        url = requote_uri(urlunparse((scheme, netloc, path, \"\", query, fragment)))\n        self.url = url\n\n    def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n\n        self.headers = CaseInsensitiveDict()\n        if headers:\n            for header in headers.items():\n                # Raise exception on invalid header value.\n                check_header_validity(header)\n                name, value = header\n                self.headers[to_native_string(name)] = value\n\n    def prepare_body(\n        self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None\n    ) -> None:\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        body = None\n        content_type = None\n\n        if not data and json is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            content_type = \"application/json\"\n\n            try:\n                body = complexjson.dumps(json, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(body, bytes):\n                body = body.encode(\"utf-8\")\n\n        # data that proxies attributes to underlying objects needs hasattr\n        is_iterable = isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n        if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)):\n            try:\n                length = super_len(data)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                length = None\n\n            body = data\n\n            if getattr(body, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = body.tell()  # type: ignore[union-attr]  # guarded by getattr check\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if files:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if length:\n                self.headers[\"Content-Length\"] = builtin_str(length)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n            # After is_stream filtering, remaining data is raw (not streamed)\n            raw_data = cast(\"_t.RawDataType | None\", data)\n\n            # Multi-part file uploads.\n            if files:\n                (body, content_type) = self._encode_files(files, raw_data)\n            else:\n                if raw_data:\n                    body = self._encode_params(raw_data)\n                    if isinstance(data, basestring) or _t.has_read(data):\n                        content_type = None\n                    else:\n                        content_type = \"application/x-www-form-urlencoded\"\n\n            self.prepare_content_length(body)\n\n            # Add content-type if it wasn't explicitly provided.\n            if content_type and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = content_type\n\n        self.body = body  # type: ignore[assignment]  # body transforms from DataType to BodyType\n\n    def prepare_content_length(self, body: _t.BodyType) -> None:\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if body is not None:\n            length = super_len(body)\n            if length:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(length)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def prepare_auth(\n        self,\n        auth: _t.AuthType,\n        url: _t.UriType = \"\",\n    ) -> None:\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if auth is None:\n            url_auth = get_auth_from_url(cast(str, self.url))\n            auth = url_auth if any(url_auth) else None\n\n        if auth:\n            if isinstance(auth, tuple) and len(auth) == 2:  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n                # special-case basic HTTP auth\n                auth_handler = HTTPBasicAuth(*auth)  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n            else:\n                # TODO: can be fixed by flipping the conditionals\n                auth_handler = cast(\"Callable[..., PreparedRequest]\", auth)\n\n            # Allow auth to make its changes.\n            r = auth_handler(self)\n\n            # Update self to reflect the auth changes.\n            self.__dict__.update(r.__dict__)\n\n            # Recompute Content-Length\n            self.prepare_content_length(self.body)\n\n    def prepare_cookies(\n        self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n    ) -> None:\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if isinstance(cookies, cookielib.CookieJar):\n            self._cookies = cookies\n        else:\n            self._cookies = cookiejar_from_dict(cookies)\n\n        cookies_jar = cast(\"CookieJar\", self._cookies)\n        cookie_header = get_cookie_header(cookies_jar, self)\n        if cookie_header is not None:\n            self.headers[\"Cookie\"] = cookie_header\n\n    def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:\n        \"\"\"Prepares the given hooks.\"\"\"\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        hooks = hooks or {}\n        for event in hooks:\n            self.register_hook(event, hooks[event])\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-174aa6b92533c8c9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "f69a1f9247bce28d9774b6daf2d4aa555cdbc2392b0b9010951603594b26f972", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 427, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__PreparedRequest__5825e41e.py", "order": 8, "original_content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "parent_variant_id": "pyint-3db971294934-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L378-L729", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 9}, "unit_kind": "class", "unit_name": "PreparedRequest", "variant_id": "pyint-6da15825e41e-I08", "group_id": "py-174aa6b92533c8c9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 975, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-aab843b62cd2-I09", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n\n    method: str | None\n    url: str | None\n    headers: CaseInsensitiveDict[str | bytes]\n    _cookies: RequestsCookieJar | CookieJar | None\n    body: _t.BodyType\n    hooks: dict[str, list[_t.HookType]]\n    _body_position: int | object | None\n\n    def __init__(self) -> None:\n        #: HTTP verb to send to the server.\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None  # type: ignore[assignment]\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def prepare(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: Mapping[str, str | bytes] | None = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n\n        url = cast(\"_t.UriType\", url)\n        self.prepare_method(method)\n        self.prepare_url(url, params)\n        self.prepare_headers(headers)\n        self.prepare_cookies(cookies)\n        self.prepare_body(data, files, json)\n        self.prepare_auth(auth, url)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.prepare_hooks(hooks)\n\n    def __repr__(self) -> str:\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def copy(self) -> PreparedRequest:\n        p = PreparedRequest()\n        p.method = self.method\n        p.url = self.url\n        p.headers = self.headers.copy() if self.headers is not None else None  # type: ignore[assignment]\n        p._cookies = _copy_cookie_jar(self._cookies)\n        p.body = self.body\n        p.hooks = self.hooks\n        p._body_position = self._body_position\n        return p\n\n    def prepare_method(self, method: str | None) -> None:\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        self.method = method\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def _get_idna_encoded_host(host: str) -> str:\n        import idna\n\n        try:\n            host = idna.encode(host, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return host\n\n    def prepare_url(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType,\n    ) -> None:\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(url, bytes):\n            url = url.decode(\"utf8\")\n        else:\n            url = str(url)\n\n        # Remove leading whitespaces from url\n        url = url.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in url and not url.lower().startswith(\"http\"):\n            self.url = url\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not scheme:\n            raise MissingSchema(\n                f\"Invalid URL {url!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{url}?\"\n            )\n\n        if not host:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        netloc = auth or \"\"\n        if netloc:\n            netloc += \"@\"\n        netloc += host\n        if port:\n            netloc += f\":{port}\"\n\n        # Bare domains aren't valid URLs.\n        if not path:\n            path = \"/\"\n\n        if isinstance(params, (str, bytes)):\n            params = to_native_string(params)\n\n        if params is not None:\n            enc_params = self._encode_params(params)\n        else:\n            enc_params = \"\"\n\n        if enc_params:\n            if query:\n                query = f\"{query}&{enc_params}\"\n            else:\n                query = enc_params\n\n        url = requote_uri(urlunparse((scheme, netloc, path, \"\", query, fragment)))\n        self.url = url\n\n    def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n        lI0O_34c16748 = 0x7be ^ 0x7be\n        if lI0O_34c16748 != 0:\n            if ((lI0O_34c16748 | 1) & 1) == 0:\n                lI0O_34c16748 += 1\n            else:\n                lI0O_34c16748 -= 1\n\n        self.headers = CaseInsensitiveDict()\n        if headers:\n            for header in headers.items():\n                # Raise exception on invalid header value.\n                check_header_validity(header)\n                name, value = header\n                self.headers[to_native_string(name)] = value\n\n    def prepare_body(\n        self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None\n    ) -> None:\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        body = None\n        content_type = None\n\n        if not data and json is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            content_type = \"application/json\"\n\n            try:\n                body = complexjson.dumps(json, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(body, bytes):\n                body = body.encode(\"utf-8\")\n\n        # data that proxies attributes to underlying objects needs hasattr\n        is_iterable = isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n        if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)):\n            try:\n                length = super_len(data)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                length = None\n\n            body = data\n\n            if getattr(body, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = body.tell()  # type: ignore[union-attr]  # guarded by getattr check\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if files:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if length:\n                self.headers[\"Content-Length\"] = builtin_str(length)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n            # After is_stream filtering, remaining data is raw (not streamed)\n            raw_data = cast(\"_t.RawDataType | None\", data)\n\n            # Multi-part file uploads.\n            if files:\n                (body, content_type) = self._encode_files(files, raw_data)\n            else:\n                if raw_data:\n                    body = self._encode_params(raw_data)\n                    if isinstance(data, basestring) or _t.has_read(data):\n                        content_type = None\n                    else:\n                        content_type = \"application/x-www-form-urlencoded\"\n\n            self.prepare_content_length(body)\n\n            # Add content-type if it wasn't explicitly provided.\n            if content_type and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = content_type\n\n        self.body = body  # type: ignore[assignment]  # body transforms from DataType to BodyType\n\n    def prepare_content_length(self, body: _t.BodyType) -> None:\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if body is not None:\n            length = super_len(body)\n            if length:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(length)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def prepare_auth(\n        self,\n        auth: _t.AuthType,\n        url: _t.UriType = \"\",\n    ) -> None:\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if auth is None:\n            url_auth = get_auth_from_url(cast(str, self.url))\n            auth = url_auth if any(url_auth) else None\n\n        if auth:\n            if isinstance(auth, tuple) and len(auth) == 2:  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n                # special-case basic HTTP auth\n                auth_handler = HTTPBasicAuth(*auth)  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n            else:\n                # TODO: can be fixed by flipping the conditionals\n                auth_handler = cast(\"Callable[..., PreparedRequest]\", auth)\n\n            # Allow auth to make its changes.\n            r = auth_handler(self)\n\n            # Update self to reflect the auth changes.\n            self.__dict__.update(r.__dict__)\n\n            # Recompute Content-Length\n            self.prepare_content_length(self.body)\n\n    def prepare_cookies(\n        self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n    ) -> None:\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if isinstance(cookies, cookielib.CookieJar):\n            self._cookies = cookies\n        else:\n            self._cookies = cookiejar_from_dict(cookies)\n\n        cookies_jar = cast(\"CookieJar\", self._cookies)\n        cookie_header = get_cookie_header(cookies_jar, self)\n        if cookie_header is not None:\n            self.headers[\"Cookie\"] = cookie_header\n\n    def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:\n        \"\"\"Prepares the given hooks.\"\"\"\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        hooks = hooks or {}\n        for event in hooks:\n            self.register_hook(event, hooks[event])\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-174aa6b92533c8c9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "e3176f4b17169f6b32deccd1e9ddaedfa2564e2537b5a4a55e66e3952ba91260", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 428, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__PreparedRequest__43b62cd2.py", "order": 9, "original_content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "parent_variant_id": "pyint-3db971294934-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L378-L729", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 5}, "unit_kind": "class", "unit_name": "PreparedRequest", "variant_id": "pyint-aab843b62cd2-I09", "group_id": "py-174aa6b92533c8c9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 976, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7b3a1720d798-I10", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,     Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,     LocationParseError,     ProtocolError,     ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,     chardet,     cookielib,\n    urlencode,\n    urlsplit,     urlunparse, )\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,     cookiejar_from_dict,     get_cookie_header,\n)\nfrom .exceptions import (     ChunkedEncodingError,\n    ConnectionError,     ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,     InvalidURL,\n    MissingSchema,\n    StreamConsumedError, )\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,     get_auth_from_url,     guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,     stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n    method: str | None\n    url: str | None\n    headers: CaseInsensitiveDict[str | bytes]\n    _cookies: RequestsCookieJar | CookieJar | None\n    body: _t.BodyType\n    hooks: dict[str, list[_t.HookType]]\n    _body_position: int | object | None\n    def __init__(self) -> None:\n        #: HTTP verb to send to the server.\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None  # type: ignore[assignment]\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def prepare(\n        self,\n        method: str | None = None,         url: _t.UriType | None = None,         headers: Mapping[str, str | bytes] | None = None,         files: _t.FilesType = None,         data: _t.DataType = None,         params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,         hooks: _t.HooksInputType | None = None,         json: _t.JsonType = None,\n    ) -> None:\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n        url = cast(\"_t.UriType\", url)\n        self.prepare_method(method)\n        self.prepare_url(url, params)\n        self.prepare_headers(headers)\n        self.prepare_cookies(cookies)\n        self.prepare_body(data, files, json)\n        self.prepare_auth(auth, url)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.prepare_hooks(hooks)\n\n    def __repr__(self) -> str:\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def copy(self) -> PreparedRequest:\n        p = PreparedRequest()\n        p.method = self.method\n        p.url = self.url\n        p.headers = self.headers.copy() if self.headers is not None else None  # type: ignore[assignment]\n        p._cookies = _copy_cookie_jar(self._cookies)\n        p.body = self.body\n        p.hooks = self.hooks\n        p._body_position = self._body_position\n        return p\n\n    def prepare_method(self, method: str | None) -> None:\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        self.method = method\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def _get_idna_encoded_host(host: str) -> str:\n        import idna\n        try:\n            host = idna.encode(host, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return host\n    def prepare_url(         self,         url: _t.UriType,         params: _t.ParamsType,     ) -> None:\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(url, bytes):\n            url = url.decode(\"utf8\")\n        else:\n            url = str(url)\n\n        # Remove leading whitespaces from url\n        url = url.lstrip()\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in url and not url.lower().startswith(\"http\"):\n            self.url = url\n            return\n        # Support for unicode domain names and paths.\n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not scheme:\n            raise MissingSchema(                 f\"Invalid URL {url!r}: No scheme supplied. \"                 f\"Perhaps you meant https://{url}?\"             )\n        if not host:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n        # Carefully reconstruct the network location\n        netloc = auth or \"\"\n        if netloc:\n            netloc += \"@\"\n        netloc += host\n        if port:\n            netloc += f\":{port}\"\n\n        # Bare domains aren't valid URLs.\n        if not path:\n            path = \"/\"\n\n        if isinstance(params, (str, bytes)):\n            params = to_native_string(params)\n\n        if params is not None:\n            enc_params = self._encode_params(params)\n        else:\n            enc_params = \"\"\n\n        if enc_params:\n            if query:\n                query = f\"{query}&{enc_params}\"\n            else:\n                query = enc_params\n\n        url = requote_uri(urlunparse((scheme, netloc, path, \"\", query, fragment)))\n        self.url = url\n\n    def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n\n        self.headers = CaseInsensitiveDict()\n        if headers:\n            for header in headers.items():\n                # Raise exception on invalid header value.\n                check_header_validity(header)\n                name, value = header\n                self.headers[to_native_string(name)] = value\n    def prepare_body(\n        self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None\n    ) -> None:\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        body = None\n        content_type = None\n        if not data and json is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            content_type = \"application/json\"\n            try:\n                body = complexjson.dumps(json, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(body, bytes):\n                body = body.encode(\"utf-8\")\n\n        # data that proxies attributes to underlying objects needs hasattr\n        is_iterable = isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n        if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)):\n            try:\n                length = super_len(data)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                length = None\n\n            body = data\n            if getattr(body, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = body.tell()  # type: ignore[union-attr]  # guarded by getattr check\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n            if files:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if length:\n                self.headers[\"Content-Length\"] = builtin_str(length)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n            # After is_stream filtering, remaining data is raw (not streamed)\n            raw_data = cast(\"_t.RawDataType | None\", data)\n\n            # Multi-part file uploads.\n            if files:\n                (body, content_type) = self._encode_files(files, raw_data)\n            else:\n                if raw_data:\n                    body = self._encode_params(raw_data)\n                    if isinstance(data, basestring) or _t.has_read(data):\n                        content_type = None\n                    else:\n                        content_type = \"application/x-www-form-urlencoded\"\n\n            self.prepare_content_length(body)\n\n            # Add content-type if it wasn't explicitly provided.\n            if content_type and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = content_type\n\n        self.body = body  # type: ignore[assignment]  # body transforms from DataType to BodyType\n\n    def prepare_content_length(self, body: _t.BodyType) -> None:\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if body is not None:\n            length = super_len(body)\n            if length:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(length)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")             and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def prepare_auth(\n        self,         auth: _t.AuthType,         url: _t.UriType = \"\",\n    ) -> None:\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if auth is None:\n            url_auth = get_auth_from_url(cast(str, self.url))\n            auth = url_auth if any(url_auth) else None\n\n        if auth:\n            if isinstance(auth, tuple) and len(auth) == 2:  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n                # special-case basic HTTP auth\n                auth_handler = HTTPBasicAuth(*auth)  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n            else:\n                # TODO: can be fixed by flipping the conditionals\n                auth_handler = cast(\"Callable[..., PreparedRequest]\", auth)\n\n            # Allow auth to make its changes.\n            r = auth_handler(self)\n\n            # Update self to reflect the auth changes.\n            self.__dict__.update(r.__dict__)\n\n            # Recompute Content-Length\n            self.prepare_content_length(self.body)\n    def prepare_cookies(\n        self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None     ) -> None:\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if isinstance(cookies, cookielib.CookieJar):\n            self._cookies = cookies\n        else:\n            self._cookies = cookiejar_from_dict(cookies)\n        cookies_jar = cast(\"CookieJar\", self._cookies)\n        cookie_header = get_cookie_header(cookies_jar, self)\n        if cookie_header is not None:\n            self.headers[\"Cookie\"] = cookie_header\n    def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:\n        \"\"\"Prepares the given hooks.\"\"\"\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        hooks = hooks or {}\n        for event in hooks:\n            self.register_hook(event, hooks[event])\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-174aa6b92533c8c9", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "a7e4d2888423268de222a3c200bdaf96d7f38e05bc0a5dde735afaf294103d81", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 368, "local_path": "layout/partially-compact-layout/I10__requests__PreparedRequest__1720d798.py", "order": 10, "original_content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "parent_variant_id": "pyint-3db971294934-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L378-L729", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 135, "line_break_groups_removed": 54, "line_breaks_removed": 54, "whitespace_characters_removed": 19}, "unit_kind": "class", "unit_name": "PreparedRequest", "variant_id": "pyint-7b3a1720d798-I10", "group_id": "py-174aa6b92533c8c9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 977, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-08be3d224a33-I11", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n\n    method: str | None\n    url: str | None\n    headers: CaseInsensitiveDict[str | bytes]\n    _cookies: RequestsCookieJar | CookieJar | None\n    body: _t.BodyType\n    hooks: dict[str, list[_t.HookType]]\n    _body_position: int | object | None\n\n    def __init__(self) -> None:\n        #: HTTP verb to send to the server.\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None  # type: ignore[assignment]\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def prepare(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: Mapping[str, str | bytes] | None = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n\n        url = cast(\"_t.UriType\", url)\n        self.prepare_method(method)\n        self.prepare_url(url, params)\n        self.prepare_headers(headers)\n        self.prepare_cookies(cookies)\n        self.prepare_body(data, files, json)\n        self.prepare_auth(auth, url)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.prepare_hooks(hooks)\n\n    def __repr__(self) -> str:\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def copy(self) -> PreparedRequest:\n        p = PreparedRequest()\n        p.method = self.method\n        p.url = self.url\n        p.headers = self.headers.copy() if self.headers is not None else None  # type: ignore[assignment]\n        p._cookies = _copy_cookie_jar(self._cookies)\n        p.body = self.body\n        p.hooks = self.hooks\n        p._body_position = self._body_position\n        return p\n\n    def prepare_method(self, method: str | None) -> None:\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        self.method = method\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def _get_idna_encoded_host(host: str) -> str:\n        import idna\n\n        try:\n            host = idna.encode(host, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return host\n\n    def prepare_url(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType,\n    ) -> None:\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(url, bytes):\n            url = url.decode(\"utf8\")\n        else:\n            url = str(url)\n\n        # Remove leading whitespaces from url\n        url = url.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in url and not url.lower().startswith(\"http\"):\n            self.url = url\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not scheme:\n            raise MissingSchema(\n                f\"Invalid URL {url!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{url}?\"\n            )\n\n        if not host:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        netloc = auth or \"\"\n        if netloc:\n            netloc += \"@\"\n        netloc += host\n        if port:\n            netloc += f\":{port}\"\n\n        # Bare domains aren't valid URLs.\n        if not path:\n            path = \"/\"\n\n        if isinstance(params, (str, bytes)):\n            params = to_native_string(params)\n\n        if params is not None:\n            enc_params = self._encode_params(params)\n        else:\n            enc_params = \"\"\n\n        if enc_params:\n            if query:\n                query = f\"{query}&{enc_params}\"\n            else:\n                query = enc_params\n\n        url = requote_uri(urlunparse((scheme, netloc, path, \"\", query, fragment)))\n        self.url = url\n\n    def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n\n        self.headers = CaseInsensitiveDict()\n        if headers:\n            for header in headers.items():\n                # Raise exception on invalid header value.\n                check_header_validity(header)\n                name, value = header\n                self.headers[to_native_string(name)] = value\n\n    def prepare_body(\n        self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None\n    ) -> None:\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        body = None\n        content_type = None\n\n        if not data and json is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            content_type = \"application/json\"\n\n            try:\n                body = complexjson.dumps(json, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(body, bytes):\n                body = body.encode(\"utf-8\")\n\n        # data that proxies attributes to underlying objects needs hasattr\n        is_iterable = isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n        if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)):\n            try:\n                length = super_len(data)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                length = None\n\n            body = data\n\n            if getattr(body, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = body.tell()  # type: ignore[union-attr]  # guarded by getattr check\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if files:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if length:\n                self.headers[\"Content-Length\"] = builtin_str(length)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n            # After is_stream filtering, remaining data is raw (not streamed)\n            raw_data = cast(\"_t.RawDataType | None\", data)\n\n            # Multi-part file uploads.\n            if files:\n                (body, content_type) = self._encode_files(files, raw_data)\n            else:\n                if raw_data:\n                    body = self._encode_params(raw_data)\n                    if isinstance(data, basestring) or _t.has_read(data):\n                        content_type = None\n                    else:\n                        content_type = \"application/x-www-form-urlencoded\"\n\n            self.prepare_content_length(body)\n\n            # Add content-type if it wasn't explicitly provided.\n            if content_type and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = content_type\n\n        self.body = body  # type: ignore[assignment]  # body transforms from DataType to BodyType\n\n    def prepare_content_length(self, body: _t.BodyType) -> None:\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if body is not None:\n            length = super_len(body)\n            if length:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(length)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def prepare_auth(\n        self,\n        auth: _t.AuthType,\n        url: _t.UriType = \"\",\n    ) -> None:\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if auth is None:\n            url_auth = get_auth_from_url(cast(str, self.url))\n            auth = url_auth if any(url_auth) else None\n\n        if auth:\n            a = 1\n            b = 1\n            if isinstance(auth, tuple) and len(auth) == (a + b):  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n                # special-case basic HTTP auth\n                auth_handler = HTTPBasicAuth(*auth)  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n            else:\n                # TODO: can be fixed by flipping the conditionals\n                auth_handler = cast(\"Callable[..., PreparedRequest]\", auth)\n\n            # Allow auth to make its changes.\n            r = auth_handler(self)\n\n            # Update self to reflect the auth changes.\n            self.__dict__.update(r.__dict__)\n\n            # Recompute Content-Length\n            self.prepare_content_length(self.body)\n\n    def prepare_cookies(\n        self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n    ) -> None:\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if isinstance(cookies, cookielib.CookieJar):\n            self._cookies = cookies\n        else:\n            self._cookies = cookiejar_from_dict(cookies)\n\n        cookies_jar = cast(\"CookieJar\", self._cookies)\n        cookie_header = get_cookie_header(cookies_jar, self)\n        if cookie_header is not None:\n            self.headers[\"Cookie\"] = cookie_header\n\n    def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:\n        \"\"\"Prepares the given hooks.\"\"\"\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        hooks = hooks or {}\n        for event in hooks:\n            self.register_hook(event, hooks[event])\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-174aa6b92533c8c9", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "9340020b45791ea256b3a4048755aca20da15555019010bbd862a2d92ccfdaaf", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 424, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__PreparedRequest__3d224a33.py", "order": 11, "original_content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "parent_variant_id": "pyint-3db971294934-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L378-L729", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 1, "intermediate_variables_introduced": 2, "statements_augmented": 1}, "unit_kind": "class", "unit_name": "PreparedRequest", "variant_id": "pyint-08be3d224a33-I11", "group_id": "py-174aa6b92533c8c9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 978, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a5e74c6c4e4d-I12", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n\n    method: str | None\n    url: str | None\n    headers: CaseInsensitiveDict[str | bytes]\n    _cookies: RequestsCookieJar | CookieJar | None\n    body: _t.BodyType\n    hooks: dict[str, list[_t.HookType]]\n    _body_position: int | object | None\n\n    def __init__(self) -> None:\n        #: HTTP verb to send to the server.\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None  # type: ignore[assignment]\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def prepare(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: Mapping[str, str | bytes] | None = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n\n        url = cast(\"_t.UriType\", url)\n        self.prepare_method(method)\n        self.prepare_url(url, params)\n        self.prepare_headers(headers)\n        self.prepare_cookies(cookies)\n        self.prepare_body(data, files, json)\n        self.prepare_auth(auth, url)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.prepare_hooks(hooks)\n\n    def __repr__(self) -> str:\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def copy(self) -> PreparedRequest:\n        p = PreparedRequest()\n        p.method = self.method\n        p.url = self.url\n        p.headers = self.headers.copy() if self.headers is not None else None  # type: ignore[assignment]\n        p._cookies = _copy_cookie_jar(self._cookies)\n        p.body = self.body\n        p.hooks = self.hooks\n        p._body_position = self._body_position\n        return p\n\n    def prepare_method(self, method: str | None) -> None:\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        self.method = method\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def _get_idna_encoded_host(host: str) -> str:\n        import idna\n\n        try:\n            host = idna.encode(host, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return host\n\n    def prepare_url(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType,\n    ) -> None:\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(url, bytes):\n            url = url.decode(\"utf8\")\n        else:\n            url = str(url)\n\n        # Remove leading whitespaces from url\n        url = url.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in url and not url.lower().startswith(\"http\"):\n            self.url = url\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not scheme:\n            raise MissingSchema(\n                f\"Invalid URL {url!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{url}?\"\n            )\n\n        if not host:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        netloc = auth or \"\"\n        if netloc:\n            netloc += \"@\"\n        netloc += host\n        if port:\n            netloc += f\":{port}\"\n\n        # Bare domains aren't valid URLs.\n        if not path:\n            path = \"/\"\n\n        if isinstance(params, (str, bytes)):\n            params = to_native_string(params)\n\n        if params is not None:\n            enc_params = self._encode_params(params)\n        else:\n            enc_params = \"\"\n\n        if enc_params:\n            if query:\n                query = f\"{query}&{enc_params}\"\n            else:\n                query = enc_params\n\n        url = requote_uri(urlunparse((scheme, netloc, path, \"\", query, fragment)))\n        self.url = url\n\n    def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n\n        self.headers = CaseInsensitiveDict()\n        if headers:\n            for header in headers.items():\n                # Raise exception on invalid header value.\n                check_header_validity(header)\n                name, value = header\n                self.headers[to_native_string(name)] = value\n\n    def prepare_body(\n        self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None\n    ) -> None:\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        body = None\n        content_type = None\n\n        if not data and json is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            content_type = \"application/json\"\n\n            try:\n                body = complexjson.dumps(json, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(body, bytes):\n                body = body.encode(\"utf-8\")\n\n        # data that proxies attributes to underlying objects needs hasattr\n        is_iterable = isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n        if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)):\n            try:\n                length = super_len(data)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                length = None\n\n            body = data\n\n            if getattr(body, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = body.tell()  # type: ignore[union-attr]  # guarded by getattr check\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if files:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if length:\n                self.headers[\"Content-Length\"] = builtin_str(length)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n            # After is_stream filtering, remaining data is raw (not streamed)\n            raw_data = cast(\"_t.RawDataType | None\", data)\n\n            # Multi-part file uploads.\n            if files:\n                (body, content_type) = self._encode_files(files, raw_data)\n            else:\n                if raw_data:\n                    body = self._encode_params(raw_data)\n                    if isinstance(data, basestring) or _t.has_read(data):\n                        content_type = None\n                    else:\n                        content_type = \"application/x-www-form-urlencoded\"\n\n            self.prepare_content_length(body)\n\n            # Add content-type if it wasn't explicitly provided.\n            if content_type and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = content_type\n\n        self.body = body  # type: ignore[assignment]  # body transforms from DataType to BodyType\n\n    def prepare_content_length(self, body: _t.BodyType) -> None:\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if body is not None:\n            length = super_len(body)\n            if length:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(length)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def prepare_auth(\n        self,\n        auth: _t.AuthType,\n        url: _t.UriType = \"\",\n    ) -> None:\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if auth is None:\n            url_auth = get_auth_from_url(cast(str, self.url))\n            auth = url_auth if any(url_auth) else None\n\n        if auth:\n            if isinstance(auth, tuple) and len(auth) == 2:  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n                # special-case basic HTTP auth\n                auth_handler = HTTPBasicAuth(*auth)  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n            else:\n                # TODO: can be fixed by flipping the conditionals\n                auth_handler = cast(\"Callable[..., PreparedRequest]\", auth)\n\n            # Allow auth to make its changes.\n            \n\n            # Update self to reflect the auth changes.\n            self.__dict__.update((auth_handler(self)).__dict__)\n\n            # Recompute Content-Length\n            self.prepare_content_length(self.body)\n\n    def prepare_cookies(\n        self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n    ) -> None:\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if isinstance(cookies, cookielib.CookieJar):\n            self._cookies = cookies\n        else:\n            self._cookies = cookiejar_from_dict(cookies)\n\n        cookies_jar = cast(\"CookieJar\", self._cookies)\n        cookie_header = get_cookie_header(cookies_jar, self)\n        if cookie_header is not None:\n            self.headers[\"Cookie\"] = cookie_header\n\n    def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:\n        \"\"\"Prepares the given hooks.\"\"\"\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        hooks = hooks or {}\n        for event in hooks:\n            self.register_hook(event, hooks[event])\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-174aa6b92533c8c9", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d5d33df26835fdfb3e03f67284ed32bef4f8ed765c72975a32fed2c8593a85d2", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 422, "local_path": "data-flow/inline-intermediate-variables/I12__requests__PreparedRequest__4c6c4e4d.py", "order": 12, "original_content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "parent_variant_id": "pyint-3db971294934-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L378-L729", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "PreparedRequest", "variant_id": "pyint-a5e74c6c4e4d-I12", "group_id": "py-174aa6b92533c8c9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 979, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e42523adfb4f-I13", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n\n    method: str | None\n    url: str | None\n    headers: CaseInsensitiveDict[str | bytes]\n    _cookies: RequestsCookieJar | CookieJar | None\n    body: _t.BodyType\n    hooks: dict[str, list[_t.HookType]]\n    _body_position: int | object | None\n\n    def __init__(self) -> None:\n        #: HTTP verb to send to the server.\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None  # type: ignore[assignment]\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def prepare(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: Mapping[str, str | bytes] | None = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n\n        url = cast(\"_t.UriType\", url)\n        self.prepare_method(method)\n        self.prepare_url(url, params)\n        self.prepare_headers(headers)\n        self.prepare_cookies(cookies)\n        self.prepare_body(data, files, json)\n        self.prepare_auth(auth, url)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.prepare_hooks(hooks)\n\n    def __repr__(self) -> str:\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def copy(self) -> PreparedRequest:\n        p = PreparedRequest()\n        p.method = self.method\n        p.url = self.url\n        p.headers = self.headers.copy() if self.headers is not None else None  # type: ignore[assignment]\n        p._cookies = _copy_cookie_jar(self._cookies)\n        p.body = self.body\n        p.hooks = self.hooks\n        p._body_position = self._body_position\n        return p\n\n    def prepare_method(self, method: str | None) -> None:\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        self.method = method\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def _get_idna_encoded_host(host: str) -> str:\n        import idna\n\n        try:\n            host = idna.encode(host, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return host\n\n    def prepare_url(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType,\n    ) -> None:\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(url, bytes):\n            url = url.decode(\"utf8\")\n        else:\n            url = str(url)\n\n        # Remove leading whitespaces from url\n        url = url.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in url and not url.lower().startswith(\"http\"):\n            self.url = url\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not scheme:\n            raise MissingSchema(\n                f\"Invalid URL {url!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{url}?\"\n            )\n\n        if not host:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        netloc = auth or \"\"\n        if netloc:\n            netloc += \"@\"\n        netloc += host\n        if port:\n            netloc += f\":{port}\"\n\n        # Bare domains aren't valid URLs.\n        if not path:\n            path = \"/\"\n\n        if isinstance(params, (str, bytes)):\n            params = to_native_string(params)\n\n        if params is not None:\n            enc_params = self._encode_params(params)\n        else:\n            enc_params = \"\"\n\n        if enc_params:\n            if query:\n                query = f\"{query}&{enc_params}\"\n            else:\n                query = enc_params\n\n        url = requote_uri(urlunparse((scheme, netloc, path, \"\", query, fragment)))\n        self.url = url\n\n    def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n\n        self.headers = CaseInsensitiveDict()\n        if headers:\n            for header in headers.items():\n                # Raise exception on invalid header value.\n                check_header_validity(header)\n                name, value = header\n                self.headers[to_native_string(name)] = value\n\n    def prepare_body(\n        self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None\n    ) -> None:\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        body = None\n        content_type = None\n\n        if not data and json is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            content_type = \"application/json\"\n\n            try:\n                body = complexjson.dumps(json, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(body, bytes):\n                body = body.encode(\"utf-8\")\n\n        # data that proxies attributes to underlying objects needs hasattr\n        is_iterable = isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n        if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)):\n            try:\n                length = super_len(data)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                length = None\n\n            body = data\n\n            if getattr(body, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = body.tell()  # type: ignore[union-attr]  # guarded by getattr check\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if files:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if length:\n                self.headers[\"Content-Length\"] = builtin_str(length)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n            # After is_stream filtering, remaining data is raw (not streamed)\n            raw_data = cast(\"_t.RawDataType | None\", data)\n\n            # Multi-part file uploads.\n            if files:\n                (body, content_type) = self._encode_files(files, raw_data)\n            else:\n                if raw_data:\n                    body = self._encode_params(raw_data)\n                    if isinstance(data, basestring) or _t.has_read(data):\n                        content_type = None\n                    else:\n                        content_type = \"application/x-www-form-urlencoded\"\n\n            self.prepare_content_length(body)\n\n            # Add content-type if it wasn't explicitly provided.\n            if content_type and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = content_type\n\n        self.body = body  # type: ignore[assignment]  # body transforms from DataType to BodyType\n\n    def prepare_content_length(self, body: _t.BodyType) -> None:\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if body is not None:\n            length = super_len(body)\n            if length:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(length)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def prepare_auth(\n        self,\n        auth: _t.AuthType,\n        url: _t.UriType = \"\",\n    ) -> None:\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if auth is None:\n            url_auth = get_auth_from_url(cast(str, self.url))\n            auth = url_auth if any(url_auth) else None\n\n        if auth:\n            if isinstance(auth, tuple) and len(auth) == 2:  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n                # special-case basic HTTP auth\n                auth_handler = HTTPBasicAuth(*auth)  # type: ignore[arg-type]  # pyright widens tuple from Callable in AuthType\n            else:\n                # TODO: can be fixed by flipping the conditionals\n                auth_handler = cast(\"Callable[..., PreparedRequest]\", auth)\n\n            # Allow auth to make its changes.\n            r = auth_handler(self)\n\n            # Update self to reflect the auth changes.\n            self.__dict__.update(r.__dict__)\n\n            # Recompute Content-Length\n            self.prepare_content_length(self.body)\n\n    def prepare_cookies(\n        self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n    ) -> None:\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if isinstance(cookies, cookielib.CookieJar):\n            self._cookies = cookies\n        else:\n            self._cookies = cookiejar_from_dict(cookies)\n\n        cookies_jar = cast(\"CookieJar\", self._cookies)\n        cookie_header = get_cookie_header(cookies_jar, self)\n        if cookie_header is not None:\n            self.headers[\"Cookie\"] = cookie_header\n\n    def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:\n        \"\"\"Prepares the given hooks.\"\"\"\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        hooks = hooks or {}\n        loopIterator = __import__(\"builtins\").iter(hooks)\n        while True:\n            try:\n                event = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            self.register_hook(event, hooks[event])\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-174aa6b92533c8c9", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ebed58fb7b1cb0780b4d0892f2dc529f6519e3619a3928a5fdcc81e67d803fca", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 427, "local_path": "control-flow/lower-for-to-while/I13__requests__PreparedRequest__23adfb4f.py", "order": 13, "original_content_sha256": "bf75c44104d8ef81c19977de1388f2c6c503e16bca037ce37dcdee3c7a77157b", "parent_variant_id": "pyint-3db971294934-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L378-L729", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 1, "for_loops_skipped_for_comment": 1, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 1, "synchronous_for_loops_eligible": 1, "synchronous_for_loops_found": 2}, "unit_kind": "class", "unit_name": "PreparedRequest", "variant_id": "pyint-e42523adfb4f-I13", "group_id": "py-174aa6b92533c8c9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 980, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-153d5fc1a636-SRC", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass PermissionManager(models.Manager):\n    use_in_migrations = True\n\n    def get_by_natural_key(self, codename, app_label, model):\n        return self.get(\n            codename=codename,\n            content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n                app_label, model\n            ),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-17f0010a4b270758", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 24, "local_path": "source-original/SRC__django__PermissionManager__5fc1a636.py", "order": 0, "original_content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L27-L36", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "PermissionManager", "variant_id": "pyint-153d5fc1a636-SRC", "group_id": "py-17f0010a4b270758", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 253, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3d7012350085-I01", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass PermissionManager(models.Manager):\n    use_in_migrations = True\n\n    def get_by_natural_key(self, codename, app_label, model):\n        return self.get(\n            codename=codename,\n            content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n                app_label, model\n            ),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-17f0010a4b270758", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 24, "local_path": "comments/remove-comments/I01__django__PermissionManager__12350085.py", "order": 1, "original_content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "parent_variant_id": "pyint-153d5fc1a636-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L27-L36", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "PermissionManager", "variant_id": "pyint-3d7012350085-I01", "group_id": "py-17f0010a4b270758", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 254, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a49982357b74-I02", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass PermissionManager(models.Manager):\n    use_in_migrations = True\n\n    def get2(self, cod, app, mod):\n        return self.get(\n            codename=cod,\n            content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n                app, mod\n            ),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-17f0010a4b270758", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "726cd2cffc91357343eee5ead158ce04b45bd75345d949aa397c275ed60dac0b", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 24, "local_path": "identifiers/shorten-identifiers/I02__django__PermissionManager__82357b74.py", "order": 2, "original_content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "parent_variant_id": "pyint-153d5fc1a636-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L27-L36", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 7, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "PermissionManager", "variant_id": "pyint-a49982357b74-I02", "group_id": "py-17f0010a4b270758", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 255, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-01559ed38ac8-I03", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass PermissionManager(models.Manager):\n    use_in_migrations = True\n\n    def validateMessage(self, finalKey, localItem, count):\n        return self.get(\n            codename=finalKey,\n            content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n                localItem, count\n            ),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-17f0010a4b270758", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b4d3510aac5d9c94a9a9da3b1760725d58b8a29b398599f146151461b57c5b2d", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 24, "local_path": "identifiers/mislead-identifiers/I03__django__PermissionManager__9ed38ac8.py", "order": 3, "original_content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "parent_variant_id": "pyint-153d5fc1a636-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L27-L36", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 7, "identifiers_declared": 4, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 3, "local_random_pool_selections": 3, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 1, "method_total_length_difference": 3}, "unit_kind": "class", "unit_name": "PermissionManager", "variant_id": "pyint-01559ed38ac8-I03", "group_id": "py-17f0010a4b270758", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 256, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a105113268e3-I04", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass PermissionManager(models.Manager):\n    use_in_migrations = True\n\n    def a(self, b, c, d):\n        return self.get(\n            codename=b,\n            content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n                c, d\n            ),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-17f0010a4b270758", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "699c753cd2a4112761bd0744cb3518b9eb241f0e6666642812be852a1a58e62d", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 24, "local_path": "identifiers/garble-identifiers/I04__django__PermissionManager__113268e3.py", "order": 4, "original_content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "parent_variant_id": "pyint-153d5fc1a636-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L27-L36", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 7, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "PermissionManager", "variant_id": "pyint-a105113268e3-I04", "group_id": "py-17f0010a4b270758", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 257, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1ece281e545a-I05", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass PermissionManager(models.Manager):\n    use_in_migrations = True\n\n    def get_by_natural_key(self, codename, app_label, model):\n        return self.get(\n            codename=codename,\n            content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n                app_label, model\n            ),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-17f0010a4b270758", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 24, "local_path": "expressions/encode-integer-literals/I05__django__PermissionManager__281e545a.py", "order": 5, "original_content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "parent_variant_id": "pyint-153d5fc1a636-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L27-L36", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "PermissionManager", "variant_id": "pyint-1ece281e545a-I05", "group_id": "py-17f0010a4b270758", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 258, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ef1d68efdbbb-I06", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass PermissionManager(models.Manager):\n    use_in_migrations = True\n\n    def get_by_natural_key(self, codename, app_label, model):\n        return self.get(\n            codename=codename,\n            content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n                app_label, model\n            ),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-17f0010a4b270758", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 24, "local_path": "expressions/invert-conditions/I06__django__PermissionManager__68efdbbb.py", "order": 6, "original_content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "parent_variant_id": "pyint-153d5fc1a636-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L27-L36", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "PermissionManager", "variant_id": "pyint-ef1d68efdbbb-I06", "group_id": "py-17f0010a4b270758", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 259, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-311398a83e10-I07", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass PermissionManager(models.Manager):\n    use_in_migrations = True\n\n    def get_by_natural_key(self, codename, app_label, model):\n        if ((0x423b ^ 0x423b) != 0):\n            raise AssertionError()\n        return self.get(\n            codename=codename,\n            content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n                app_label, model\n            ),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-17f0010a4b270758", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "6bdc708b95a1ef8a222e2c015b3c36f319562586efc2c137f1292e413d254e7c", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 26, "local_path": "code-injection/insert-dead-branches/I07__django__PermissionManager__98a83e10.py", "order": 7, "original_content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "parent_variant_id": "pyint-153d5fc1a636-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L27-L36", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "PermissionManager", "variant_id": "pyint-311398a83e10-I07", "group_id": "py-17f0010a4b270758", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 260, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a395f48bfe4a-I08", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass PermissionManager(models.Manager):\n    use_in_migrations = True\n\n    def get_by_natural_key(self, codename, app_label, model):\n        factorial = 1\n        for current_factor in range(2, 5):\n            factorial *= current_factor\n        return self.get(\n            codename=codename,\n            content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n                app_label, model\n            ),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-17f0010a4b270758", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "eff84e7407f437d88fa9e8f20e3a6f5a0eabf50b84056f006530e076c3165259", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 27, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__PermissionManager__f48bfe4a.py", "order": 8, "original_content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "parent_variant_id": "pyint-153d5fc1a636-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L27-L36", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 6}, "unit_kind": "class", "unit_name": "PermissionManager", "variant_id": "pyint-a395f48bfe4a-I08", "group_id": "py-17f0010a4b270758", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 261, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d3dddd8d6d32-I09", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass PermissionManager(models.Manager):\n    use_in_migrations = True\n\n    def get_by_natural_key(self, codename, app_label, model):\n        lI0O_a6a6d121 = 0xadeb\n        lI0O_a6a6d121 = (0 if (lI0O_a6a6d121 ^ lI0O_a6a6d121) == 0 else 1) if (lI0O_a6a6d121 & 0) == 0 else 2\n        return self.get(\n            codename=codename,\n            content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n                app_label, model\n            ),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-17f0010a4b270758", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "fb0814fee7e3873a9b1481ffa74909762af41781c1ecb49b1b4ef24c71594efc", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 26, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__PermissionManager__dd8d6d32.py", "order": 9, "original_content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "parent_variant_id": "pyint-153d5fc1a636-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L27-L36", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 8}, "unit_kind": "class", "unit_name": "PermissionManager", "variant_id": "pyint-d3dddd8d6d32-I09", "group_id": "py-17f0010a4b270758", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 262, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2f0a9afa8879-I10", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass PermissionManager(models.Manager):\n    use_in_migrations = True\n    def get_by_natural_key(self, codename, app_label, model):\n        return self.get(             codename=codename,\n            content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n                app_label, model\n            ),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-17f0010a4b270758", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "f492ee6ff0d0c828c72a6ea28a55808d24581a3bd2362820e44753a57440d02f", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 22, "local_path": "layout/partially-compact-layout/I10__django__PermissionManager__9afa8879.py", "order": 10, "original_content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "parent_variant_id": "pyint-153d5fc1a636-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L27-L36", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 7, "line_break_groups_removed": 2, "line_breaks_removed": 2, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "PermissionManager", "variant_id": "pyint-2f0a9afa8879-I10", "group_id": "py-17f0010a4b270758", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 263, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-495589ef950f-I11", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass PermissionManager(models.Manager):\n    use_in_migrations = True\n\n    def get_by_natural_key(self, codename, app_label, model):\n        return self.get(\n            codename=codename,\n            content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n                app_label, model\n            ),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-17f0010a4b270758", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 24, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__PermissionManager__89ef950f.py", "order": 11, "original_content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "parent_variant_id": "pyint-153d5fc1a636-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L27-L36", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "PermissionManager", "variant_id": "pyint-495589ef950f-I11", "group_id": "py-17f0010a4b270758", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 264, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-18953b4eca5f-I12", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass PermissionManager(models.Manager):\n    use_in_migrations = True\n\n    def get_by_natural_key(self, codename, app_label, model):\n        return self.get(\n            codename=codename,\n            content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n                app_label, model\n            ),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-17f0010a4b270758", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 24, "local_path": "data-flow/inline-intermediate-variables/I12__django__PermissionManager__3b4eca5f.py", "order": 12, "original_content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "parent_variant_id": "pyint-153d5fc1a636-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L27-L36", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "PermissionManager", "variant_id": "pyint-18953b4eca5f-I12", "group_id": "py-17f0010a4b270758", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 265, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5247c5d06a26-I13", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass PermissionManager(models.Manager):\n    use_in_migrations = True\n\n    def get_by_natural_key(self, codename, app_label, model):\n        return self.get(\n            codename=codename,\n            content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n                app_label, model\n            ),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-17f0010a4b270758", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 24, "local_path": "control-flow/lower-for-to-while/I13__django__PermissionManager__c5d06a26.py", "order": 13, "original_content_sha256": "df7db30eaf3e4d6a6900923e098d26708d59d12b8bacd937504c1ff53a21600f", "parent_variant_id": "pyint-153d5fc1a636-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L27-L36", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "PermissionManager", "variant_id": "pyint-5247c5d06a26-I13", "group_id": "py-17f0010a4b270758", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 266, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d61b14bbd229-SRC", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass AbstractUser(AbstractBaseUser, PermissionsMixin):\n    \"\"\"\n    An abstract base class implementing a fully featured User model with\n    admin-compliant permissions.\n\n    Username and password are required. Other fields are optional.\n    \"\"\"\n\n    username_validator = UnicodeUsernameValidator()\n\n    username = models.CharField(\n        _(\"username\"),\n        max_length=150,\n        unique=True,\n        help_text=_(\n            \"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\"\n        ),\n        validators=[username_validator],\n        error_messages={\n            \"unique\": _(\"A user with that username already exists.\"),\n        },\n    )\n    first_name = models.CharField(_(\"first name\"), max_length=150, blank=True)\n    last_name = models.CharField(_(\"last name\"), max_length=150, blank=True)\n    email = models.EmailField(_(\"email address\"), blank=True)\n    is_staff = models.BooleanField(\n        _(\"staff status\"),\n        default=False,\n        help_text=_(\"Designates whether the user can log into this admin site.\"),\n    )\n    is_active = models.BooleanField(\n        _(\"active\"),\n        default=True,\n        help_text=_(\n            \"Designates whether this user should be treated as active. \"\n            \"Unselect this instead of deleting accounts.\"\n        ),\n    )\n    date_joined = models.DateTimeField(_(\"date joined\"), default=timezone.now)\n\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    class Meta:\n        verbose_name = _(\"user\")\n        verbose_name_plural = _(\"users\")\n        abstract = True\n\n    def clean(self):\n        super().clean()\n        self.email = self.__class__.objects.normalize_email(self.email)\n\n    def get_full_name(self):\n        \"\"\"\n        Return the first_name plus the last_name, with a space in between.\n        \"\"\"\n        full_name = \"%s %s\" % (self.first_name, self.last_name)\n        return full_name.strip()\n\n    def get_short_name(self):\n        \"\"\"Return the short name for the user.\"\"\"\n        return self.first_name\n\n    def email_user(self, subject, message, from_email=None, **kwargs):\n        \"\"\"Send an email to this user.\"\"\"\n        send_mail(subject, message, from_email, [self.email], **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-1bd089ded1808af5", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 83, "local_path": "source-original/SRC__django__AbstractUser__14bbd229.py", "order": 0, "original_content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L451-L519", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "AbstractUser", "variant_id": "pyint-d61b14bbd229-SRC", "group_id": "py-1bd089ded1808af5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 15, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-83bb70d694a2-I01", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass AbstractUser(AbstractBaseUser, PermissionsMixin):\n    \n\n    username_validator = UnicodeUsernameValidator()\n\n    username = models.CharField(\n        _(\"username\"),\n        max_length=150,\n        unique=True,\n        help_text=_(\n            \"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\"\n        ),\n        validators=[username_validator],\n        error_messages={\n            \"unique\": _(\"A user with that username already exists.\"),\n        },\n    )\n    first_name = models.CharField(_(\"first name\"), max_length=150, blank=True)\n    last_name = models.CharField(_(\"last name\"), max_length=150, blank=True)\n    email = models.EmailField(_(\"email address\"), blank=True)\n    is_staff = models.BooleanField(\n        _(\"staff status\"),\n        default=False,\n        help_text=_(\"Designates whether the user can log into this admin site.\"),\n    )\n    is_active = models.BooleanField(\n        _(\"active\"),\n        default=True,\n        help_text=_(\n            \"Designates whether this user should be treated as active. \"\n            \"Unselect this instead of deleting accounts.\"\n        ),\n    )\n    date_joined = models.DateTimeField(_(\"date joined\"), default=timezone.now)\n\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    class Meta:\n        verbose_name = _(\"user\")\n        verbose_name_plural = _(\"users\")\n        abstract = True\n\n    def clean(self):\n        super().clean()\n        self.email = self.__class__.objects.normalize_email(self.email)\n\n    def get_full_name(self):\n        \n        full_name = \"%s %s\" % (self.first_name, self.last_name)\n        return full_name.strip()\n\n    def get_short_name(self):\n        \n        return self.first_name\n\n    def email_user(self, subject, message, from_email=None, **kwargs):\n        \n        send_mail(subject, message, from_email, [self.email], **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-1bd089ded1808af5", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "6f527fdc6704adc7b4ebc1ba44091c7d32e65ac721f987cc6600d1034ad2d951", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 76, "local_path": "comments/remove-comments/I01__django__AbstractUser__70d694a2.py", "order": 1, "original_content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "parent_variant_id": "pyint-d61b14bbd229-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L451-L519", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 349, "comments_removed": 4, "docstrings_removed": 4, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "AbstractUser", "variant_id": "pyint-83bb70d694a2-I01", "group_id": "py-1bd089ded1808af5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 16, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-41351d8b9657-I02", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass AbstractUser(AbstractBaseUser, PermissionsMixin):\n    \"\"\"\n    An abstract base class implementing a fully featured User model with\n    admin-compliant permissions.\n\n    Username and password are required. Other fields are optional.\n    \"\"\"\n\n    username_validator = UnicodeUsernameValidator()\n\n    username = models.CharField(\n        _(\"username\"),\n        max_length=150,\n        unique=True,\n        help_text=_(\n            \"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\"\n        ),\n        validators=[username_validator],\n        error_messages={\n            \"unique\": _(\"A user with that username already exists.\"),\n        },\n    )\n    first_name = models.CharField(_(\"first name\"), max_length=150, blank=True)\n    last_name = models.CharField(_(\"last name\"), max_length=150, blank=True)\n    email = models.EmailField(_(\"email address\"), blank=True)\n    is_staff = models.BooleanField(\n        _(\"staff status\"),\n        default=False,\n        help_text=_(\"Designates whether the user can log into this admin site.\"),\n    )\n    is_active = models.BooleanField(\n        _(\"active\"),\n        default=True,\n        help_text=_(\n            \"Designates whether this user should be treated as active. \"\n            \"Unselect this instead of deleting accounts.\"\n        ),\n    )\n    date_joined = models.DateTimeField(_(\"date joined\"), default=timezone.now)\n\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    class Meta:\n        verbose_name = _(\"user\")\n        verbose_name_plural = _(\"users\")\n        abstract = True\n\n    def cle(self):\n        super().clean()\n        self.email = self.__class__.objects.normalize_email(self.email)\n\n    def get(self):\n        \"\"\"\n        Return the first_name plus the last_name, with a space in between.\n        \"\"\"\n        full = \"%s %s\" % (self.first_name, self.last_name)\n        return full.strip()\n\n    def get2(self):\n        \"\"\"Return the short name for the user.\"\"\"\n        return self.first_name\n\n    def email2(self, sub, mes, from2=None, **kwa):\n        \"\"\"Send an email to this user.\"\"\"\n        send_mail(sub, mes, from2, [self.email], **kwa)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-1bd089ded1808af5", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "1d07f6855fbde685d5ad6f43881cbb4ba9408c154b4f485bd06bd5793092fffb", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 83, "local_path": "identifiers/shorten-identifiers/I02__django__AbstractUser__1d8b9657.py", "order": 2, "original_content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "parent_variant_id": "pyint-d61b14bbd229-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L451-L519", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 14, "identifiers_declared": 9}, "unit_kind": "class", "unit_name": "AbstractUser", "variant_id": "pyint-41351d8b9657-I02", "group_id": "py-1bd089ded1808af5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 17, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2170233ac73f-I03", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass AbstractUser(AbstractBaseUser, PermissionsMixin):\n    \"\"\"\n    An abstract base class implementing a fully featured User model with\n    admin-compliant permissions.\n\n    Username and password are required. Other fields are optional.\n    \"\"\"\n\n    username_validator = UnicodeUsernameValidator()\n\n    username = models.CharField(\n        _(\"username\"),\n        max_length=150,\n        unique=True,\n        help_text=_(\n            \"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\"\n        ),\n        validators=[username_validator],\n        error_messages={\n            \"unique\": _(\"A user with that username already exists.\"),\n        },\n    )\n    first_name = models.CharField(_(\"first name\"), max_length=150, blank=True)\n    last_name = models.CharField(_(\"last name\"), max_length=150, blank=True)\n    email = models.EmailField(_(\"email address\"), blank=True)\n    is_staff = models.BooleanField(\n        _(\"staff status\"),\n        default=False,\n        help_text=_(\"Designates whether the user can log into this admin site.\"),\n    )\n    is_active = models.BooleanField(\n        _(\"active\"),\n        default=True,\n        help_text=_(\n            \"Designates whether this user should be treated as active. \"\n            \"Unselect this instead of deleting accounts.\"\n        ),\n    )\n    date_joined = models.DateTimeField(_(\"date joined\"), default=timezone.now)\n\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    class Meta:\n        verbose_name = _(\"user\")\n        verbose_name_plural = _(\"users\")\n        abstract = True\n\n    def close(self):\n        super().clean()\n        self.email = self.__class__.objects.normalize_email(self.email)\n\n    def updateAccount(self):\n        \"\"\"\n        Return the first_name plus the last_name, with a space in between.\n        \"\"\"\n        reference = \"%s %s\" % (self.first_name, self.last_name)\n        return reference.strip()\n\n    def validateBuffer(self):\n        \"\"\"Return the short name for the user.\"\"\"\n        return self.first_name\n\n    def createUser(self, history, nextKey, recentPath=None, **config):\n        \"\"\"Send an email to this user.\"\"\"\n        send_mail(history, nextKey, recentPath, [self.email], **config)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-1bd089ded1808af5", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "39cf115415ecbe35c6f70492ca102f790fdb3047fc8c8bf2cf7a718cfe7d3cba", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 83, "local_path": "identifiers/mislead-identifiers/I03__django__AbstractUser__233ac73f.py", "order": 3, "original_content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "parent_variant_id": "pyint-d61b14bbd229-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L451-L519", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 14, "identifiers_declared": 9, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 5, "local_random_pool_selections": 5, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 4, "method_random_pool_selections": 4, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "AbstractUser", "variant_id": "pyint-2170233ac73f-I03", "group_id": "py-1bd089ded1808af5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 18, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-add7b57977f8-I04", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass AbstractUser(AbstractBaseUser, PermissionsMixin):\n    \"\"\"\n    An abstract base class implementing a fully featured User model with\n    admin-compliant permissions.\n\n    Username and password are required. Other fields are optional.\n    \"\"\"\n\n    username_validator = UnicodeUsernameValidator()\n\n    username = models.CharField(\n        _(\"username\"),\n        max_length=150,\n        unique=True,\n        help_text=_(\n            \"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\"\n        ),\n        validators=[username_validator],\n        error_messages={\n            \"unique\": _(\"A user with that username already exists.\"),\n        },\n    )\n    first_name = models.CharField(_(\"first name\"), max_length=150, blank=True)\n    last_name = models.CharField(_(\"last name\"), max_length=150, blank=True)\n    email = models.EmailField(_(\"email address\"), blank=True)\n    is_staff = models.BooleanField(\n        _(\"staff status\"),\n        default=False,\n        help_text=_(\"Designates whether the user can log into this admin site.\"),\n    )\n    is_active = models.BooleanField(\n        _(\"active\"),\n        default=True,\n        help_text=_(\n            \"Designates whether this user should be treated as active. \"\n            \"Unselect this instead of deleting accounts.\"\n        ),\n    )\n    date_joined = models.DateTimeField(_(\"date joined\"), default=timezone.now)\n\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    class Meta:\n        verbose_name = _(\"user\")\n        verbose_name_plural = _(\"users\")\n        abstract = True\n\n    def a(self):\n        super().clean()\n        self.email = self.__class__.objects.normalize_email(self.email)\n\n    def b(self):\n        \"\"\"\n        Return the first_name plus the last_name, with a space in between.\n        \"\"\"\n        e = \"%s %s\" % (self.first_name, self.last_name)\n        return e.strip()\n\n    def c(self):\n        \"\"\"Return the short name for the user.\"\"\"\n        return self.first_name\n\n    def d(self, f, g, h=None, **i):\n        \"\"\"Send an email to this user.\"\"\"\n        send_mail(f, g, h, [self.email], **i)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-1bd089ded1808af5", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "488fc2f1c9ab087c74e274a45b198ff1fd09c1676ae2315cc7e9c328fcd26019", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 83, "local_path": "identifiers/garble-identifiers/I04__django__AbstractUser__b57977f8.py", "order": 4, "original_content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "parent_variant_id": "pyint-d61b14bbd229-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L451-L519", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 14, "identifiers_declared": 9}, "unit_kind": "class", "unit_name": "AbstractUser", "variant_id": "pyint-add7b57977f8-I04", "group_id": "py-1bd089ded1808af5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 19, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2eb29e8c542c-I05", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass AbstractUser(AbstractBaseUser, PermissionsMixin):\n    \"\"\"\n    An abstract base class implementing a fully featured User model with\n    admin-compliant permissions.\n\n    Username and password are required. Other fields are optional.\n    \"\"\"\n\n    username_validator = UnicodeUsernameValidator()\n\n    username = models.CharField(\n        _(\"username\"),\n        max_length=0x96,\n        unique=True,\n        help_text=_(\n            \"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\"\n        ),\n        validators=[username_validator],\n        error_messages={\n            \"unique\": _(\"A user with that username already exists.\"),\n        },\n    )\n    first_name = models.CharField(_(\"first name\"), max_length=0x96, blank=True)\n    last_name = models.CharField(_(\"last name\"), max_length=0x96, blank=True)\n    email = models.EmailField(_(\"email address\"), blank=True)\n    is_staff = models.BooleanField(\n        _(\"staff status\"),\n        default=False,\n        help_text=_(\"Designates whether the user can log into this admin site.\"),\n    )\n    is_active = models.BooleanField(\n        _(\"active\"),\n        default=True,\n        help_text=_(\n            \"Designates whether this user should be treated as active. \"\n            \"Unselect this instead of deleting accounts.\"\n        ),\n    )\n    date_joined = models.DateTimeField(_(\"date joined\"), default=timezone.now)\n\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    class Meta:\n        verbose_name = _(\"user\")\n        verbose_name_plural = _(\"users\")\n        abstract = True\n\n    def clean(self):\n        super().clean()\n        self.email = self.__class__.objects.normalize_email(self.email)\n\n    def get_full_name(self):\n        \"\"\"\n        Return the first_name plus the last_name, with a space in between.\n        \"\"\"\n        full_name = \"%s %s\" % (self.first_name, self.last_name)\n        return full_name.strip()\n\n    def get_short_name(self):\n        \"\"\"Return the short name for the user.\"\"\"\n        return self.first_name\n\n    def email_user(self, subject, message, from_email=None, **kwargs):\n        \"\"\"Send an email to this user.\"\"\"\n        send_mail(subject, message, from_email, [self.email], **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-1bd089ded1808af5", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "d785c8df3d551e537ebe9391eff2658f0c6957876b0c249b4ad77a7f89991942", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 83, "local_path": "expressions/encode-integer-literals/I05__django__AbstractUser__9e8c542c.py", "order": 5, "original_content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "parent_variant_id": "pyint-d61b14bbd229-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L451-L519", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 3}, "unit_kind": "class", "unit_name": "AbstractUser", "variant_id": "pyint-2eb29e8c542c-I05", "group_id": "py-1bd089ded1808af5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 20, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-032f4fafe8d9-I06", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass AbstractUser(AbstractBaseUser, PermissionsMixin):\n    \"\"\"\n    An abstract base class implementing a fully featured User model with\n    admin-compliant permissions.\n\n    Username and password are required. Other fields are optional.\n    \"\"\"\n\n    username_validator = UnicodeUsernameValidator()\n\n    username = models.CharField(\n        _(\"username\"),\n        max_length=150,\n        unique=True,\n        help_text=_(\n            \"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\"\n        ),\n        validators=[username_validator],\n        error_messages={\n            \"unique\": _(\"A user with that username already exists.\"),\n        },\n    )\n    first_name = models.CharField(_(\"first name\"), max_length=150, blank=True)\n    last_name = models.CharField(_(\"last name\"), max_length=150, blank=True)\n    email = models.EmailField(_(\"email address\"), blank=True)\n    is_staff = models.BooleanField(\n        _(\"staff status\"),\n        default=False,\n        help_text=_(\"Designates whether the user can log into this admin site.\"),\n    )\n    is_active = models.BooleanField(\n        _(\"active\"),\n        default=True,\n        help_text=_(\n            \"Designates whether this user should be treated as active. \"\n            \"Unselect this instead of deleting accounts.\"\n        ),\n    )\n    date_joined = models.DateTimeField(_(\"date joined\"), default=timezone.now)\n\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    class Meta:\n        verbose_name = _(\"user\")\n        verbose_name_plural = _(\"users\")\n        abstract = True\n\n    def clean(self):\n        super().clean()\n        self.email = self.__class__.objects.normalize_email(self.email)\n\n    def get_full_name(self):\n        \"\"\"\n        Return the first_name plus the last_name, with a space in between.\n        \"\"\"\n        full_name = \"%s %s\" % (self.first_name, self.last_name)\n        return full_name.strip()\n\n    def get_short_name(self):\n        \"\"\"Return the short name for the user.\"\"\"\n        return self.first_name\n\n    def email_user(self, subject, message, from_email=None, **kwargs):\n        \"\"\"Send an email to this user.\"\"\"\n        send_mail(subject, message, from_email, [self.email], **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-1bd089ded1808af5", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 83, "local_path": "expressions/invert-conditions/I06__django__AbstractUser__4fafe8d9.py", "order": 6, "original_content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "parent_variant_id": "pyint-d61b14bbd229-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L451-L519", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "AbstractUser", "variant_id": "pyint-032f4fafe8d9-I06", "group_id": "py-1bd089ded1808af5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 21, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-05fb44c35f58-I07", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass AbstractUser(AbstractBaseUser, PermissionsMixin):\n    \"\"\"\n    An abstract base class implementing a fully featured User model with\n    admin-compliant permissions.\n\n    Username and password are required. Other fields are optional.\n    \"\"\"\n\n    username_validator = UnicodeUsernameValidator()\n\n    username = models.CharField(\n        _(\"username\"),\n        max_length=150,\n        unique=True,\n        help_text=_(\n            \"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\"\n        ),\n        validators=[username_validator],\n        error_messages={\n            \"unique\": _(\"A user with that username already exists.\"),\n        },\n    )\n    first_name = models.CharField(_(\"first name\"), max_length=150, blank=True)\n    last_name = models.CharField(_(\"last name\"), max_length=150, blank=True)\n    email = models.EmailField(_(\"email address\"), blank=True)\n    is_staff = models.BooleanField(\n        _(\"staff status\"),\n        default=False,\n        help_text=_(\"Designates whether the user can log into this admin site.\"),\n    )\n    is_active = models.BooleanField(\n        _(\"active\"),\n        default=True,\n        help_text=_(\n            \"Designates whether this user should be treated as active. \"\n            \"Unselect this instead of deleting accounts.\"\n        ),\n    )\n    date_joined = models.DateTimeField(_(\"date joined\"), default=timezone.now)\n\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    class Meta:\n        verbose_name = _(\"user\")\n        verbose_name_plural = _(\"users\")\n        abstract = True\n\n    def clean(self):\n        if ((0x9a24 ^ 0x9a24) != 0):\n            raise AssertionError()\n        super().clean()\n        self.email = self.__class__.objects.normalize_email(self.email)\n\n    def get_full_name(self):\n        \"\"\"\n        Return the first_name plus the last_name, with a space in between.\n        \"\"\"\n        if ((0x5b6e ^ 0x5b6e) != 0):\n            raise AssertionError()\n        full_name = \"%s %s\" % (self.first_name, self.last_name)\n        return full_name.strip()\n\n    def get_short_name(self):\n        \"\"\"Return the short name for the user.\"\"\"\n        if ((0xe41b ^ 0xe41b) != 0):\n            raise AssertionError()\n        return self.first_name\n\n    def email_user(self, subject, message, from_email=None, **kwargs):\n        \"\"\"Send an email to this user.\"\"\"\n        if ((0x635d ^ 0x635d) != 0):\n            raise AssertionError()\n        send_mail(subject, message, from_email, [self.email], **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-1bd089ded1808af5", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "f9b21b3270fa56a8b85d1734c4a9dbc468299e99a48fd31a04cca1457525c583", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 91, "local_path": "code-injection/insert-dead-branches/I07__django__AbstractUser__44c35f58.py", "order": 7, "original_content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "parent_variant_id": "pyint-d61b14bbd229-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L451-L519", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 4}, "unit_kind": "class", "unit_name": "AbstractUser", "variant_id": "pyint-05fb44c35f58-I07", "group_id": "py-1bd089ded1808af5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 22, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c6c6c61aa443-I08", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass AbstractUser(AbstractBaseUser, PermissionsMixin):\n    \"\"\"\n    An abstract base class implementing a fully featured User model with\n    admin-compliant permissions.\n\n    Username and password are required. Other fields are optional.\n    \"\"\"\n\n    username_validator = UnicodeUsernameValidator()\n\n    username = models.CharField(\n        _(\"username\"),\n        max_length=150,\n        unique=True,\n        help_text=_(\n            \"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\"\n        ),\n        validators=[username_validator],\n        error_messages={\n            \"unique\": _(\"A user with that username already exists.\"),\n        },\n    )\n    first_name = models.CharField(_(\"first name\"), max_length=150, blank=True)\n    last_name = models.CharField(_(\"last name\"), max_length=150, blank=True)\n    email = models.EmailField(_(\"email address\"), blank=True)\n    is_staff = models.BooleanField(\n        _(\"staff status\"),\n        default=False,\n        help_text=_(\"Designates whether the user can log into this admin site.\"),\n    )\n    is_active = models.BooleanField(\n        _(\"active\"),\n        default=True,\n        help_text=_(\n            \"Designates whether this user should be treated as active. \"\n            \"Unselect this instead of deleting accounts.\"\n        ),\n    )\n    date_joined = models.DateTimeField(_(\"date joined\"), default=timezone.now)\n\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    class Meta:\n        verbose_name = _(\"user\")\n        verbose_name_plural = _(\"users\")\n        abstract = True\n\n    def clean(self):\n        super().clean()\n        self.email = self.__class__.objects.normalize_email(self.email)\n\n    def get_full_name(self):\n        \"\"\"\n        Return the first_name plus the last_name, with a space in between.\n        \"\"\"\n        full_name = \"%s %s\" % (self.first_name, self.last_name)\n        return full_name.strip()\n\n    def get_short_name(self):\n        \"\"\"Return the short name for the user.\"\"\"\n        even_number_count = 0\n        for candidate_number in range(6):\n            if candidate_number % 2 == 0:\n                even_number_count += 1\n        return self.first_name\n\n    def email_user(self, subject, message, from_email=None, **kwargs):\n        \"\"\"Send an email to this user.\"\"\"\n        send_mail(subject, message, from_email, [self.email], **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-1bd089ded1808af5", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "4157094eb9c83422f673db1f9596c36292c444c7d5fdef93c92b19bde37f6c76", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 87, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__AbstractUser__c61aa443.py", "order": 8, "original_content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "parent_variant_id": "pyint-d61b14bbd229-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L451-L519", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 4, "readable_template_index": 2}, "unit_kind": "class", "unit_name": "AbstractUser", "variant_id": "pyint-c6c6c61aa443-I08", "group_id": "py-1bd089ded1808af5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 23, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5a706d3e1494-I09", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass AbstractUser(AbstractBaseUser, PermissionsMixin):\n    \"\"\"\n    An abstract base class implementing a fully featured User model with\n    admin-compliant permissions.\n\n    Username and password are required. Other fields are optional.\n    \"\"\"\n\n    username_validator = UnicodeUsernameValidator()\n\n    username = models.CharField(\n        _(\"username\"),\n        max_length=150,\n        unique=True,\n        help_text=_(\n            \"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\"\n        ),\n        validators=[username_validator],\n        error_messages={\n            \"unique\": _(\"A user with that username already exists.\"),\n        },\n    )\n    first_name = models.CharField(_(\"first name\"), max_length=150, blank=True)\n    last_name = models.CharField(_(\"last name\"), max_length=150, blank=True)\n    email = models.EmailField(_(\"email address\"), blank=True)\n    is_staff = models.BooleanField(\n        _(\"staff status\"),\n        default=False,\n        help_text=_(\"Designates whether the user can log into this admin site.\"),\n    )\n    is_active = models.BooleanField(\n        _(\"active\"),\n        default=True,\n        help_text=_(\n            \"Designates whether this user should be treated as active. \"\n            \"Unselect this instead of deleting accounts.\"\n        ),\n    )\n    date_joined = models.DateTimeField(_(\"date joined\"), default=timezone.now)\n\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    class Meta:\n        verbose_name = _(\"user\")\n        verbose_name_plural = _(\"users\")\n        abstract = True\n\n    def clean(self):\n        super().clean()\n        self.email = self.__class__.objects.normalize_email(self.email)\n\n    def get_full_name(self):\n        \"\"\"\n        Return the first_name plus the last_name, with a space in between.\n        \"\"\"\n        full_name = \"%s %s\" % (self.first_name, self.last_name)\n        return full_name.strip()\n\n    def get_short_name(self):\n        \"\"\"Return the short name for the user.\"\"\"\n        lI0O_0ce64f89 = 0x152f\n        lI0O_0ce64f89 = (lI0O_0ce64f89 << 1) ^ (lI0O_0ce64f89 >> 1)\n        lI0O_0ce64f89 &= 0\n        return self.first_name\n\n    def email_user(self, subject, message, from_email=None, **kwargs):\n        \"\"\"Send an email to this user.\"\"\"\n        send_mail(subject, message, from_email, [self.email], **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-1bd089ded1808af5", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "c1d10bf558ac8f6a71e4553237a3d98bac46d029eb5c17069710fd3cf8c88508", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 86, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__AbstractUser__6d3e1494.py", "order": 9, "original_content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "parent_variant_id": "pyint-d61b14bbd229-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L451-L519", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 3}, "unit_kind": "class", "unit_name": "AbstractUser", "variant_id": "pyint-5a706d3e1494-I09", "group_id": "py-1bd089ded1808af5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 24, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cfb73836ae63-I10", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass AbstractUser(AbstractBaseUser, PermissionsMixin):\n    \"\"\"\n    An abstract base class implementing a fully featured User model with\n    admin-compliant permissions.\n\n    Username and password are required. Other fields are optional.\n    \"\"\"\n\n    username_validator = UnicodeUsernameValidator()\n\n    username = models.CharField(\n        _(\"username\"),         max_length=150,\n        unique=True,         help_text=_(             \"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\"\n        ),         validators=[username_validator],         error_messages={\n            \"unique\": _(\"A user with that username already exists.\"),\n        },\n    )\n    first_name = models.CharField(_(\"first name\"), max_length=150, blank=True)\n    last_name = models.CharField(_(\"last name\"), max_length=150, blank=True)\n    email = models.EmailField(_(\"email address\"), blank=True)\n    is_staff = models.BooleanField(         _(\"staff status\"),\n        default=False,         help_text=_(\"Designates whether the user can log into this admin site.\"),     )\n    is_active = models.BooleanField(\n        _(\"active\"),\n        default=True,\n        help_text=_(             \"Designates whether this user should be treated as active. \"\n            \"Unselect this instead of deleting accounts.\"\n        ),     )\n    date_joined = models.DateTimeField(_(\"date joined\"), default=timezone.now)\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    class Meta:\n        verbose_name = _(\"user\")\n        verbose_name_plural = _(\"users\")\n        abstract = True\n    def clean(self):\n        super().clean()\n        self.email = self.__class__.objects.normalize_email(self.email)\n    def get_full_name(self):\n        \"\"\"\n        Return the first_name plus the last_name, with a space in between.\n        \"\"\"\n        full_name = \"%s %s\" % (self.first_name, self.last_name)\n        return full_name.strip()\n\n    def get_short_name(self):\n        \"\"\"Return the short name for the user.\"\"\"\n        return self.first_name\n\n    def email_user(self, subject, message, from_email=None, **kwargs):\n        \"\"\"Send an email to this user.\"\"\"\n        send_mail(subject, message, from_email, [self.email], **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-1bd089ded1808af5", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "40df6cad137876ecc5b9a036f0474d1e863b3c0c8ce3fc378b4d635c2f019134", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 70, "local_path": "layout/partially-compact-layout/I10__django__AbstractUser__3836ae63.py", "order": 10, "original_content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "parent_variant_id": "pyint-d61b14bbd229-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L451-L519", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 33, "line_break_groups_removed": 13, "line_breaks_removed": 13, "whitespace_characters_removed": 3}, "unit_kind": "class", "unit_name": "AbstractUser", "variant_id": "pyint-cfb73836ae63-I10", "group_id": "py-1bd089ded1808af5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 25, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-919f1cac410f-I11", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass AbstractUser(AbstractBaseUser, PermissionsMixin):\n    \"\"\"\n    An abstract base class implementing a fully featured User model with\n    admin-compliant permissions.\n\n    Username and password are required. Other fields are optional.\n    \"\"\"\n\n    username_validator = UnicodeUsernameValidator()\n\n    username = models.CharField(\n        _(\"username\"),\n        max_length=150,\n        unique=True,\n        help_text=_(\n            \"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\"\n        ),\n        validators=[username_validator],\n        error_messages={\n            \"unique\": _(\"A user with that username already exists.\"),\n        },\n    )\n    first_name = models.CharField(_(\"first name\"), max_length=150, blank=True)\n    last_name = models.CharField(_(\"last name\"), max_length=150, blank=True)\n    email = models.EmailField(_(\"email address\"), blank=True)\n    is_staff = models.BooleanField(\n        _(\"staff status\"),\n        default=False,\n        help_text=_(\"Designates whether the user can log into this admin site.\"),\n    )\n    is_active = models.BooleanField(\n        _(\"active\"),\n        default=True,\n        help_text=_(\n            \"Designates whether this user should be treated as active. \"\n            \"Unselect this instead of deleting accounts.\"\n        ),\n    )\n    date_joined = models.DateTimeField(_(\"date joined\"), default=timezone.now)\n\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    class Meta:\n        verbose_name = _(\"user\")\n        verbose_name_plural = _(\"users\")\n        abstract = True\n\n    def clean(self):\n        super().clean()\n        self.email = self.__class__.objects.normalize_email(self.email)\n\n    def get_full_name(self):\n        \"\"\"\n        Return the first_name plus the last_name, with a space in between.\n        \"\"\"\n        full_name = \"%s %s\" % (self.first_name, self.last_name)\n        return full_name.strip()\n\n    def get_short_name(self):\n        \"\"\"Return the short name for the user.\"\"\"\n        return self.first_name\n\n    def email_user(self, subject, message, from_email=None, **kwargs):\n        \"\"\"Send an email to this user.\"\"\"\n        send_mail(subject, message, from_email, [self.email], **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-1bd089ded1808af5", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 83, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__AbstractUser__1cac410f.py", "order": 11, "original_content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "parent_variant_id": "pyint-d61b14bbd229-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L451-L519", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "AbstractUser", "variant_id": "pyint-919f1cac410f-I11", "group_id": "py-1bd089ded1808af5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 26, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0149e57aa199-I12", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass AbstractUser(AbstractBaseUser, PermissionsMixin):\n    \"\"\"\n    An abstract base class implementing a fully featured User model with\n    admin-compliant permissions.\n\n    Username and password are required. Other fields are optional.\n    \"\"\"\n\n    username_validator = UnicodeUsernameValidator()\n\n    username = models.CharField(\n        _(\"username\"),\n        max_length=150,\n        unique=True,\n        help_text=_(\n            \"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\"\n        ),\n        validators=[username_validator],\n        error_messages={\n            \"unique\": _(\"A user with that username already exists.\"),\n        },\n    )\n    first_name = models.CharField(_(\"first name\"), max_length=150, blank=True)\n    last_name = models.CharField(_(\"last name\"), max_length=150, blank=True)\n    email = models.EmailField(_(\"email address\"), blank=True)\n    is_staff = models.BooleanField(\n        _(\"staff status\"),\n        default=False,\n        help_text=_(\"Designates whether the user can log into this admin site.\"),\n    )\n    is_active = models.BooleanField(\n        _(\"active\"),\n        default=True,\n        help_text=_(\n            \"Designates whether this user should be treated as active. \"\n            \"Unselect this instead of deleting accounts.\"\n        ),\n    )\n    date_joined = models.DateTimeField(_(\"date joined\"), default=timezone.now)\n\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    class Meta:\n        verbose_name = _(\"user\")\n        verbose_name_plural = _(\"users\")\n        abstract = True\n\n    def clean(self):\n        super().clean()\n        self.email = self.__class__.objects.normalize_email(self.email)\n\n    def get_full_name(self):\n        \"\"\"\n        Return the first_name plus the last_name, with a space in between.\n        \"\"\"\n        \n        return (\"%s %s\" % (self.first_name, self.last_name)).strip()\n\n    def get_short_name(self):\n        \"\"\"Return the short name for the user.\"\"\"\n        return self.first_name\n\n    def email_user(self, subject, message, from_email=None, **kwargs):\n        \"\"\"Send an email to this user.\"\"\"\n        send_mail(subject, message, from_email, [self.email], **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-1bd089ded1808af5", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "335675b200ec35c173834860c45e4dda94f352a4d94a2b6630a653d1d0c70049", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 83, "local_path": "data-flow/inline-intermediate-variables/I12__django__AbstractUser__e57aa199.py", "order": 12, "original_content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "parent_variant_id": "pyint-d61b14bbd229-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L451-L519", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "AbstractUser", "variant_id": "pyint-0149e57aa199-I12", "group_id": "py-1bd089ded1808af5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 27, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dae0e7c10a14-I13", "source": "from collections.abc import Iterable\nfrom django.apps import apps\nfrom django.contrib import auth\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models.manager import EmptyManager\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom .validators import UnicodeUsernameValidator\n\nclass AbstractUser(AbstractBaseUser, PermissionsMixin):\n    \"\"\"\n    An abstract base class implementing a fully featured User model with\n    admin-compliant permissions.\n\n    Username and password are required. Other fields are optional.\n    \"\"\"\n\n    username_validator = UnicodeUsernameValidator()\n\n    username = models.CharField(\n        _(\"username\"),\n        max_length=150,\n        unique=True,\n        help_text=_(\n            \"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\"\n        ),\n        validators=[username_validator],\n        error_messages={\n            \"unique\": _(\"A user with that username already exists.\"),\n        },\n    )\n    first_name = models.CharField(_(\"first name\"), max_length=150, blank=True)\n    last_name = models.CharField(_(\"last name\"), max_length=150, blank=True)\n    email = models.EmailField(_(\"email address\"), blank=True)\n    is_staff = models.BooleanField(\n        _(\"staff status\"),\n        default=False,\n        help_text=_(\"Designates whether the user can log into this admin site.\"),\n    )\n    is_active = models.BooleanField(\n        _(\"active\"),\n        default=True,\n        help_text=_(\n            \"Designates whether this user should be treated as active. \"\n            \"Unselect this instead of deleting accounts.\"\n        ),\n    )\n    date_joined = models.DateTimeField(_(\"date joined\"), default=timezone.now)\n\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    class Meta:\n        verbose_name = _(\"user\")\n        verbose_name_plural = _(\"users\")\n        abstract = True\n\n    def clean(self):\n        super().clean()\n        self.email = self.__class__.objects.normalize_email(self.email)\n\n    def get_full_name(self):\n        \"\"\"\n        Return the first_name plus the last_name, with a space in between.\n        \"\"\"\n        full_name = \"%s %s\" % (self.first_name, self.last_name)\n        return full_name.strip()\n\n    def get_short_name(self):\n        \"\"\"Return the short name for the user.\"\"\"\n        return self.first_name\n\n    def email_user(self, subject, message, from_email=None, **kwargs):\n        \"\"\"Send an email to this user.\"\"\"\n        send_mail(subject, message, from_email, [self.email], **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-1bd089ded1808af5", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 83, "local_path": "control-flow/lower-for-to-while/I13__django__AbstractUser__e7c10a14.py", "order": 13, "original_content_sha256": "65b47392d191ec4b1b35bc8ab5c8431cc44ba29c57a9bef7b4a205dde9d67887", "parent_variant_id": "pyint-d61b14bbd229-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/models.py#L451-L519", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "AbstractUser", "variant_id": "pyint-dae0e7c10a14-I13", "group_id": "py-1bd089ded1808af5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 28, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a2b156ebcfc4-SRC", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `http.cookiejar` expects to see them.\n    \"\"\"\n\n    def __init__(self, headers: Any) -> None:\n        \"\"\"Make a MockResponse for `cookiejar` to read.\n\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        self._headers = headers\n\n    def info(self) -> Any:\n        return self._headers\n\n    def getheaders(self, name: str) -> Any:\n        self._headers.getheaders(name)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-27c41f110642cb1c", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 31, "local_path": "source-original/SRC__requests__MockResponse__56ebcfc4.py", "order": 0, "original_content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L114-L132", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "MockResponse", "variant_id": "pyint-a2b156ebcfc4-SRC", "group_id": "py-27c41f110642cb1c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 799, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a814e5451ea1-I01", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockResponse:\n    \n\n    def __init__(self, headers: Any) -> None:\n        \n        self._headers = headers\n\n    def info(self) -> Any:\n        return self._headers\n\n    def getheaders(self, name: str) -> Any:\n        self._headers.getheaders(name)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-27c41f110642cb1c", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "860a1d34649aca1a0ef31db1e619b03f9a3ea28e0b6f94e28263223c8c421917", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 24, "local_path": "comments/remove-comments/I01__requests__MockResponse__e5451ea1.py", "order": 1, "original_content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "parent_variant_id": "pyint-a2b156ebcfc4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L114-L132", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 343, "comments_removed": 2, "docstrings_removed": 2, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "MockResponse", "variant_id": "pyint-a814e5451ea1-I01", "group_id": "py-27c41f110642cb1c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 800, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a716b32f6e6a-I02", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `http.cookiejar` expects to see them.\n    \"\"\"\n\n    def __init__(self, hea: Any) -> None:\n        \"\"\"Make a MockResponse for `cookiejar` to read.\n\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        self._headers = hea\n\n    def inf(self) -> Any:\n        return self._headers\n\n    def get(self, nam: str) -> Any:\n        self._headers.getheaders(nam)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-27c41f110642cb1c", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "0013a9ee6a4383c883b03330ff8870177c915252eb20fe41451f594928ae2845", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 31, "local_path": "identifiers/shorten-identifiers/I02__requests__MockResponse__b32f6e6a.py", "order": 2, "original_content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "parent_variant_id": "pyint-a2b156ebcfc4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L114-L132", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 6, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "MockResponse", "variant_id": "pyint-a716b32f6e6a-I02", "group_id": "py-27c41f110642cb1c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 801, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-79de9ce07eee-I03", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `http.cookiejar` expects to see them.\n    \"\"\"\n\n    def __init__(self, version: Any) -> None:\n        \"\"\"Make a MockResponse for `cookiejar` to read.\n\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        self._headers = version\n\n    def sync(self) -> Any:\n        return self._headers\n\n    def removeData(self, path: str) -> Any:\n        self._headers.getheaders(path)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-27c41f110642cb1c", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "45b76d0c895b474d9ebdb9d5dc6396cb78f0c30e5b3f8ea107e2d7638cfa1afc", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 31, "local_path": "identifiers/mislead-identifiers/I03__requests__MockResponse__9ce07eee.py", "order": 3, "original_content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "parent_variant_id": "pyint-a2b156ebcfc4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L114-L132", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 6, "identifiers_declared": 4, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 2, "local_random_pool_selections": 2, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 2, "method_random_pool_selections": 2, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "MockResponse", "variant_id": "pyint-79de9ce07eee-I03", "group_id": "py-27c41f110642cb1c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 802, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7efc4c14544e-I04", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `http.cookiejar` expects to see them.\n    \"\"\"\n\n    def __init__(self, c: Any) -> None:\n        \"\"\"Make a MockResponse for `cookiejar` to read.\n\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        self._headers = c\n\n    def a(self) -> Any:\n        return self._headers\n\n    def b(self, d: str) -> Any:\n        self._headers.getheaders(d)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-27c41f110642cb1c", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "1583a4de41460549be6b6ead6c40bf855c9f0d6ebbd86abcf63beddd40c0b693", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 31, "local_path": "identifiers/garble-identifiers/I04__requests__MockResponse__4c14544e.py", "order": 4, "original_content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "parent_variant_id": "pyint-a2b156ebcfc4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L114-L132", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 6, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "MockResponse", "variant_id": "pyint-7efc4c14544e-I04", "group_id": "py-27c41f110642cb1c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 803, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-278735450ecf-I05", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `http.cookiejar` expects to see them.\n    \"\"\"\n\n    def __init__(self, headers: Any) -> None:\n        \"\"\"Make a MockResponse for `cookiejar` to read.\n\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        self._headers = headers\n\n    def info(self) -> Any:\n        return self._headers\n\n    def getheaders(self, name: str) -> Any:\n        self._headers.getheaders(name)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-27c41f110642cb1c", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 31, "local_path": "expressions/encode-integer-literals/I05__requests__MockResponse__35450ecf.py", "order": 5, "original_content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "parent_variant_id": "pyint-a2b156ebcfc4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L114-L132", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "MockResponse", "variant_id": "pyint-278735450ecf-I05", "group_id": "py-27c41f110642cb1c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 804, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cf229babcfab-I06", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `http.cookiejar` expects to see them.\n    \"\"\"\n\n    def __init__(self, headers: Any) -> None:\n        \"\"\"Make a MockResponse for `cookiejar` to read.\n\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        self._headers = headers\n\n    def info(self) -> Any:\n        return self._headers\n\n    def getheaders(self, name: str) -> Any:\n        self._headers.getheaders(name)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-27c41f110642cb1c", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 31, "local_path": "expressions/invert-conditions/I06__requests__MockResponse__9babcfab.py", "order": 6, "original_content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "parent_variant_id": "pyint-a2b156ebcfc4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L114-L132", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "MockResponse", "variant_id": "pyint-cf229babcfab-I06", "group_id": "py-27c41f110642cb1c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 805, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-baa3cc7c5829-I07", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `http.cookiejar` expects to see them.\n    \"\"\"\n\n    def __init__(self, headers: Any) -> None:\n        \"\"\"Make a MockResponse for `cookiejar` to read.\n\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        if ((0x715d ^ 0x715d) != 0):\n            raise AssertionError()\n        self._headers = headers\n\n    def info(self) -> Any:\n        if ((0xca06 ^ 0xca06) != 0):\n            raise AssertionError()\n        return self._headers\n\n    def getheaders(self, name: str) -> Any:\n        if ((0x1d43 ^ 0x1d43) != 0):\n            raise AssertionError()\n        self._headers.getheaders(name)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-27c41f110642cb1c", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "085a7be2f64897aa5d78bb8a5e7e78c6b0e1759d59a6bfb8a97b71f7b55b7dcb", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 37, "local_path": "code-injection/insert-dead-branches/I07__requests__MockResponse__cc7c5829.py", "order": 7, "original_content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "parent_variant_id": "pyint-a2b156ebcfc4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L114-L132", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 3}, "unit_kind": "class", "unit_name": "MockResponse", "variant_id": "pyint-baa3cc7c5829-I07", "group_id": "py-27c41f110642cb1c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 806, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9f856fa530a8-I08", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `http.cookiejar` expects to see them.\n    \"\"\"\n\n    def __init__(self, headers: Any) -> None:\n        \"\"\"Make a MockResponse for `cookiejar` to read.\n\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        self._headers = headers\n\n    def info(self) -> Any:\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        return self._headers\n\n    def getheaders(self, name: str) -> Any:\n        self._headers.getheaders(name)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-27c41f110642cb1c", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "cdd27d790b54e00902a4b3e459aa16a5188f4ce6082c84a5198fec1a648d2f84", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 36, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__MockResponse__6fa530a8.py", "order": 8, "original_content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "parent_variant_id": "pyint-a2b156ebcfc4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L114-L132", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "MockResponse", "variant_id": "pyint-9f856fa530a8-I08", "group_id": "py-27c41f110642cb1c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 807, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c1ff4947375e-I09", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `http.cookiejar` expects to see them.\n    \"\"\"\n\n    def __init__(self, headers: Any) -> None:\n        \"\"\"Make a MockResponse for `cookiejar` to read.\n\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        lI0O_fc020606 = 0xd6cb - 0xd6cb\n        lI0O_fc020606 = (lI0O_fc020606 | 0) if lI0O_fc020606 == 0 else (lI0O_fc020606 & 0)\n        self._headers = headers\n\n    def info(self) -> Any:\n        return self._headers\n\n    def getheaders(self, name: str) -> Any:\n        self._headers.getheaders(name)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-27c41f110642cb1c", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d956c0cd2b3a59da19195394780db7fc4930a2cdf4143dad061b0a59be851bfa", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 33, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__MockResponse__4947375e.py", "order": 9, "original_content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "parent_variant_id": "pyint-a2b156ebcfc4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L114-L132", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 1}, "unit_kind": "class", "unit_name": "MockResponse", "variant_id": "pyint-c1ff4947375e-I09", "group_id": "py-27c41f110642cb1c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 808, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e61d471b6724-I10", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `http.cookiejar` expects to see them.\n    \"\"\"\n    def __init__(self, headers: Any) -> None:\n        \"\"\"Make a MockResponse for `cookiejar` to read.\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        self._headers = headers\n\n    def info(self) -> Any:\n        return self._headers\n\n    def getheaders(self, name: str) -> Any:\n        self._headers.getheaders(name)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-27c41f110642cb1c", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "05100859086077190ff907d35da67a5aaeb22ca4138254c6c9d185225cc4aba5", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 29, "local_path": "layout/partially-compact-layout/I10__requests__MockResponse__471b6724.py", "order": 10, "original_content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "parent_variant_id": "pyint-a2b156ebcfc4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L114-L132", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 6, "line_break_groups_removed": 2, "line_breaks_removed": 2, "whitespace_characters_removed": 2}, "unit_kind": "class", "unit_name": "MockResponse", "variant_id": "pyint-e61d471b6724-I10", "group_id": "py-27c41f110642cb1c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 809, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0e4b350e6a6a-I11", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `http.cookiejar` expects to see them.\n    \"\"\"\n\n    def __init__(self, headers: Any) -> None:\n        \"\"\"Make a MockResponse for `cookiejar` to read.\n\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        self._headers = headers\n\n    def info(self) -> Any:\n        return self._headers\n\n    def getheaders(self, name: str) -> Any:\n        self._headers.getheaders(name)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-27c41f110642cb1c", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 31, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__MockResponse__350e6a6a.py", "order": 11, "original_content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "parent_variant_id": "pyint-a2b156ebcfc4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L114-L132", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "MockResponse", "variant_id": "pyint-0e4b350e6a6a-I11", "group_id": "py-27c41f110642cb1c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 810, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c6afe0507d92-I12", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `http.cookiejar` expects to see them.\n    \"\"\"\n\n    def __init__(self, headers: Any) -> None:\n        \"\"\"Make a MockResponse for `cookiejar` to read.\n\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        self._headers = headers\n\n    def info(self) -> Any:\n        return self._headers\n\n    def getheaders(self, name: str) -> Any:\n        self._headers.getheaders(name)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-27c41f110642cb1c", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 31, "local_path": "data-flow/inline-intermediate-variables/I12__requests__MockResponse__e0507d92.py", "order": 12, "original_content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "parent_variant_id": "pyint-a2b156ebcfc4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L114-L132", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "MockResponse", "variant_id": "pyint-c6afe0507d92-I12", "group_id": "py-27c41f110642cb1c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 811, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-04f3f10a7693-I13", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `http.cookiejar` expects to see them.\n    \"\"\"\n\n    def __init__(self, headers: Any) -> None:\n        \"\"\"Make a MockResponse for `cookiejar` to read.\n\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        self._headers = headers\n\n    def info(self) -> Any:\n        return self._headers\n\n    def getheaders(self, name: str) -> Any:\n        self._headers.getheaders(name)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-27c41f110642cb1c", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 31, "local_path": "control-flow/lower-for-to-while/I13__requests__MockResponse__f10a7693.py", "order": 13, "original_content_sha256": "050d8d92d3bbe395456338b53d28a75453ee9d96c46b9b0e7a965b619ea01ef8", "parent_variant_id": "pyint-a2b156ebcfc4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L114-L132", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "MockResponse", "variant_id": "pyint-04f3f10a7693-I13", "group_id": "py-27c41f110642cb1c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 812, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6a217d9b1744-SRC", "source": "import re\nfrom urllib.parse import urlsplit\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import MailerDoesNotExist, mail_managers, mailers\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.middleware import MiddlewareMixin\nfrom django.urls import is_valid_path\nfrom django.utils.http import escape_leading_slashes\n\nclass CommonMiddleware(MiddlewareMixin):\n    \"\"\"\n    \"Common\" middleware for taking care of some basic operations:\n\n        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS\n\n        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,\n          append missing slashes and/or prepends missing \"www.\"s.\n\n            - If APPEND_SLASH is set and the initial URL doesn't end with a\n              slash, and it is not found in urlpatterns, form a new URL by\n              appending a slash at the end. If this new URL is found in\n              urlpatterns, return an HTTP redirect to this new URL; otherwise\n              process the initial URL as usual.\n\n          This behavior can be customized by subclassing CommonMiddleware and\n          overriding the response_redirect_class attribute.\n    \"\"\"\n\n    response_redirect_class = HttpResponsePermanentRedirect\n\n    def process_request(self, request):\n        \"\"\"\n        Check for denied User-Agents and rewrite the URL based on\n        settings.APPEND_SLASH and settings.PREPEND_WWW\n        \"\"\"\n\n        # Check for denied User-Agents\n        user_agent = request.META.get(\"HTTP_USER_AGENT\")\n        if user_agent is not None:\n            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:\n                if user_agent_regex.search(user_agent):\n                    raise PermissionDenied(\"Forbidden user agent\")\n\n        # Check for a redirect based on settings.PREPEND_WWW\n        host = request.get_host()\n\n        if settings.PREPEND_WWW and host and not host.startswith(\"www.\"):\n            # Check if we also need to append a slash so we can do it all\n            # with a single redirect. (This check may be somewhat expensive,\n            # so we only do it if we already know we're sending a redirect,\n            # or in process_response if we get a 404.)\n            if self.should_redirect_with_slash(request):\n                path = self.get_full_path_with_slash(request)\n            else:\n                path = request.get_full_path()\n\n            return self.response_redirect_class(f\"{request.scheme}://www.{host}{path}\")\n\n    def should_redirect_with_slash(self, request):\n        \"\"\"\n        Return True if settings.APPEND_SLASH is True and appending a slash to\n        the request path turns an invalid path into a valid one.\n        \"\"\"\n        if settings.APPEND_SLASH and not request.path_info.endswith(\"/\"):\n            urlconf = getattr(request, \"urlconf\", None)\n            if not is_valid_path(request.path_info, urlconf):\n                match = is_valid_path(\"%s/\" % request.path_info, urlconf)\n                if match:\n                    view = match.func\n                    return getattr(view, \"should_append_slash\", True)\n        return False\n\n    def get_full_path_with_slash(self, request):\n        \"\"\"\n        Return the full path of the request with a trailing slash appended.\n\n        Raise a RuntimeError if settings.DEBUG is True and request.method is\n        DELETE, POST, PUT, or PATCH.\n        \"\"\"\n        new_path = request.get_full_path(force_append_slash=True)\n        # Prevent construction of scheme relative urls.\n        new_path = escape_leading_slashes(new_path)\n        if settings.DEBUG and request.method in (\"DELETE\", \"POST\", \"PUT\", \"PATCH\"):\n            raise RuntimeError(\n                \"You called this URL via %(method)s, but the URL doesn't end \"\n                \"in a slash and you have APPEND_SLASH set. Django can't \"\n                \"redirect to the slash URL while maintaining %(method)s data. \"\n                \"Change your form to point to %(url)s (note the trailing \"\n                \"slash), or set APPEND_SLASH=False in your Django settings.\"\n                % {\n                    \"method\": request.method,\n                    \"url\": request.get_host() + new_path,\n                }\n            )\n        return new_path\n\n    def process_response(self, request, response):\n        \"\"\"\n        When the status code of the response is 404, it may redirect to a path\n        with an appended slash if should_redirect_with_slash() returns True.\n        \"\"\"\n        # If the given URL is \"Not Found\", then check if we should redirect to\n        # a path with a slash appended.\n        if response.status_code == 404 and self.should_redirect_with_slash(request):\n            response = self.response_redirect_class(\n                self.get_full_path_with_slash(request)\n            )\n\n        # Add the Content-Length header to non-streaming responses if not\n        # already set.\n        if not response.streaming and not response.has_header(\"Content-Length\"):\n            response.headers[\"Content-Length\"] = str(len(response.content))\n\n        return response\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-28e307901b66fb6d", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 115, "local_path": "source-original/SRC__django__CommonMiddleware__7d9b1744.py", "order": 0, "original_content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/middleware/common.py#L13-L117", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "CommonMiddleware", "variant_id": "pyint-6a217d9b1744-SRC", "group_id": "py-28e307901b66fb6d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 323, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1cd235e15f87-I01", "source": "import re\nfrom urllib.parse import urlsplit\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import MailerDoesNotExist, mail_managers, mailers\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.middleware import MiddlewareMixin\nfrom django.urls import is_valid_path\nfrom django.utils.http import escape_leading_slashes\n\nclass CommonMiddleware(MiddlewareMixin):\n    \n\n    response_redirect_class = HttpResponsePermanentRedirect\n\n    def process_request(self, request):\n        \n\n         \n        user_agent = request.META.get(\"HTTP_USER_AGENT\")\n        if user_agent is not None:\n            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:\n                if user_agent_regex.search(user_agent):\n                    raise PermissionDenied(\"Forbidden user agent\")\n\n         \n        host = request.get_host()\n\n        if settings.PREPEND_WWW and host and not host.startswith(\"www.\"):\n             \n             \n             \n             \n            if self.should_redirect_with_slash(request):\n                path = self.get_full_path_with_slash(request)\n            else:\n                path = request.get_full_path()\n\n            return self.response_redirect_class(f\"{request.scheme}://www.{host}{path}\")\n\n    def should_redirect_with_slash(self, request):\n        \n        if settings.APPEND_SLASH and not request.path_info.endswith(\"/\"):\n            urlconf = getattr(request, \"urlconf\", None)\n            if not is_valid_path(request.path_info, urlconf):\n                match = is_valid_path(\"%s/\" % request.path_info, urlconf)\n                if match:\n                    view = match.func\n                    return getattr(view, \"should_append_slash\", True)\n        return False\n\n    def get_full_path_with_slash(self, request):\n        \n        new_path = request.get_full_path(force_append_slash=True)\n         \n        new_path = escape_leading_slashes(new_path)\n        if settings.DEBUG and request.method in (\"DELETE\", \"POST\", \"PUT\", \"PATCH\"):\n            raise RuntimeError(\n                \"You called this URL via %(method)s, but the URL doesn't end \"\n                \"in a slash and you have APPEND_SLASH set. Django can't \"\n                \"redirect to the slash URL while maintaining %(method)s data. \"\n                \"Change your form to point to %(url)s (note the trailing \"\n                \"slash), or set APPEND_SLASH=False in your Django settings.\"\n                % {\n                    \"method\": request.method,\n                    \"url\": request.get_host() + new_path,\n                }\n            )\n        return new_path\n\n    def process_response(self, request, response):\n        \n         \n         \n        if response.status_code == 404 and self.should_redirect_with_slash(request):\n            response = self.response_redirect_class(\n                self.get_full_path_with_slash(request)\n            )\n\n         \n         \n        if not response.streaming and not response.has_header(\"Content-Length\"):\n            response.headers[\"Content-Length\"] = str(len(response.content))\n\n        return response\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-28e307901b66fb6d", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "565440f45ee1a51a5ce9a34374c395a8e6837da629131504587fc9d56f12774c", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 85, "local_path": "comments/remove-comments/I01__django__CommonMiddleware__35e15f87.py", "order": 1, "original_content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "parent_variant_id": "pyint-6a217d9b1744-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/middleware/common.py#L13-L117", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 1984, "comments_removed": 16, "docstrings_removed": 5, "line_comments_removed": 11}, "unit_kind": "class", "unit_name": "CommonMiddleware", "variant_id": "pyint-1cd235e15f87-I01", "group_id": "py-28e307901b66fb6d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 324, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cd399679c139-I02", "source": "import re\nfrom urllib.parse import urlsplit\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import MailerDoesNotExist, mail_managers, mailers\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.middleware import MiddlewareMixin\nfrom django.urls import is_valid_path\nfrom django.utils.http import escape_leading_slashes\n\nclass CommonMiddleware(MiddlewareMixin):\n    \"\"\"\n    \"Common\" middleware for taking care of some basic operations:\n\n        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS\n\n        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,\n          append missing slashes and/or prepends missing \"www.\"s.\n\n            - If APPEND_SLASH is set and the initial URL doesn't end with a\n              slash, and it is not found in urlpatterns, form a new URL by\n              appending a slash at the end. If this new URL is found in\n              urlpatterns, return an HTTP redirect to this new URL; otherwise\n              process the initial URL as usual.\n\n          This behavior can be customized by subclassing CommonMiddleware and\n          overriding the response_redirect_class attribute.\n    \"\"\"\n\n    response_redirect_class = HttpResponsePermanentRedirect\n\n    def process(self, req):\n        \"\"\"\n        Check for denied User-Agents and rewrite the URL based on\n        settings.APPEND_SLASH and settings.PREPEND_WWW\n        \"\"\"\n\n        # Check for denied User-Agents\n        user = req.META.get(\"HTTP_USER_AGENT\")\n        if user is not None:\n            for user2 in settings.DISALLOWED_USER_AGENTS:\n                if user2.search(user):\n                    raise PermissionDenied(\"Forbidden user agent\")\n\n        # Check for a redirect based on settings.PREPEND_WWW\n        hos = req.get_host()\n\n        if settings.PREPEND_WWW and hos and not hos.startswith(\"www.\"):\n            # Check if we also need to append a slash so we can do it all\n            # with a single redirect. (This check may be somewhat expensive,\n            # so we only do it if we already know we're sending a redirect,\n            # or in process_response if we get a 404.)\n            if self.should(req):\n                pat = self.get2(req)\n            else:\n                pat = req.get_full_path()\n\n            return self.response_redirect_class(f\"{req.scheme}://www.{hos}{pat}\")\n\n    def should(self, req2):\n        \"\"\"\n        Return True if settings.APPEND_SLASH is True and appending a slash to\n        the request path turns an invalid path into a valid one.\n        \"\"\"\n        if settings.APPEND_SLASH and not req2.path_info.endswith(\"/\"):\n            url = getattr(req2, \"urlconf\", None)\n            if not is_valid_path(req2.path_info, url):\n                mat = is_valid_path(\"%s/\" % req2.path_info, url)\n                if mat:\n                    vie = mat.func\n                    return getattr(vie, \"should_append_slash\", True)\n        return False\n\n    def get2(self, req3):\n        \"\"\"\n        Return the full path of the request with a trailing slash appended.\n\n        Raise a RuntimeError if settings.DEBUG is True and request.method is\n        DELETE, POST, PUT, or PATCH.\n        \"\"\"\n        new = req3.get_full_path(force_append_slash=True)\n        # Prevent construction of scheme relative urls.\n        new = escape_leading_slashes(new)\n        if settings.DEBUG and req3.method in (\"DELETE\", \"POST\", \"PUT\", \"PATCH\"):\n            raise RuntimeError(\n                \"You called this URL via %(method)s, but the URL doesn't end \"\n                \"in a slash and you have APPEND_SLASH set. Django can't \"\n                \"redirect to the slash URL while maintaining %(method)s data. \"\n                \"Change your form to point to %(url)s (note the trailing \"\n                \"slash), or set APPEND_SLASH=False in your Django settings.\"\n                % {\n                    \"method\": req3.method,\n                    \"url\": req3.get_host() + new,\n                }\n            )\n        return new\n\n    def process2(self, req4, res):\n        \"\"\"\n        When the status code of the response is 404, it may redirect to a path\n        with an appended slash if should_redirect_with_slash() returns True.\n        \"\"\"\n        # If the given URL is \"Not Found\", then check if we should redirect to\n        # a path with a slash appended.\n        if res.status_code == 404 and self.should(req4):\n            res = self.response_redirect_class(\n                self.get2(req4)\n            )\n\n        # Add the Content-Length header to non-streaming responses if not\n        # already set.\n        if not res.streaming and not res.has_header(\"Content-Length\"):\n            res.headers[\"Content-Length\"] = str(len(res.content))\n\n        return res\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-28e307901b66fb6d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "349f01f985d4ad4290c6c77b7cb6559c4bcd231ccc147cc4172d4e869f7bddd8", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 115, "local_path": "identifiers/shorten-identifiers/I02__django__CommonMiddleware__9679c139.py", "order": 2, "original_content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "parent_variant_id": "pyint-6a217d9b1744-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/middleware/common.py#L13-L117", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 61, "identifiers_declared": 17}, "unit_kind": "class", "unit_name": "CommonMiddleware", "variant_id": "pyint-cd399679c139-I02", "group_id": "py-28e307901b66fb6d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 325, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c18701bccdcc-I03", "source": "import re\nfrom urllib.parse import urlsplit\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import MailerDoesNotExist, mail_managers, mailers\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.middleware import MiddlewareMixin\nfrom django.urls import is_valid_path\nfrom django.utils.http import escape_leading_slashes\n\nclass CommonMiddleware(MiddlewareMixin):\n    \"\"\"\n    \"Common\" middleware for taking care of some basic operations:\n\n        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS\n\n        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,\n          append missing slashes and/or prepends missing \"www.\"s.\n\n            - If APPEND_SLASH is set and the initial URL doesn't end with a\n              slash, and it is not found in urlpatterns, form a new URL by\n              appending a slash at the end. If this new URL is found in\n              urlpatterns, return an HTTP redirect to this new URL; otherwise\n              process the initial URL as usual.\n\n          This behavior can be customized by subclassing CommonMiddleware and\n          overriding the response_redirect_class attribute.\n    \"\"\"\n\n    response_redirect_class = HttpResponsePermanentRedirect\n\n    def validateAccount(self, feature):\n        \"\"\"\n        Check for denied User-Agents and rewrite the URL based on\n        settings.APPEND_SLASH and settings.PREPEND_WWW\n        \"\"\"\n\n        # Check for denied User-Agents\n        finalCount = feature.META.get(\"HTTP_USER_AGENT\")\n        if finalCount is not None:\n            for currentAccount in settings.DISALLOWED_USER_AGENTS:\n                if currentAccount.search(finalCount):\n                    raise PermissionDenied(\"Forbidden user agent\")\n\n        # Check for a redirect based on settings.PREPEND_WWW\n        data = feature.get_host()\n\n        if settings.PREPEND_WWW and data and not data.startswith(\"www.\"):\n            # Check if we also need to append a slash so we can do it all\n            # with a single redirect. (This check may be somewhat expensive,\n            # so we only do it if we already know we're sending a redirect,\n            # or in process_response if we get a 404.)\n            if self.validateRequest(feature):\n                step = self.validateSession(feature)\n            else:\n                step = feature.get_full_path()\n\n            return self.response_redirect_class(f\"{feature.scheme}://www.{data}{step}\")\n\n    def validateRequest(self, context):\n        \"\"\"\n        Return True if settings.APPEND_SLASH is True and appending a slash to\n        the request path turns an invalid path into a valid one.\n        \"\"\"\n        if settings.APPEND_SLASH and not context.path_info.endswith(\"/\"):\n            nextKey = getattr(context, \"urlconf\", None)\n            if not is_valid_path(context.path_info, nextKey):\n                group = is_valid_path(\"%s/\" % context.path_info, nextKey)\n                if group:\n                    node = group.func\n                    return getattr(node, \"should_append_slash\", True)\n        return False\n\n    def validateSession(self, payload):\n        \"\"\"\n        Return the full path of the request with a trailing slash appended.\n\n        Raise a RuntimeError if settings.DEBUG is True and request.method is\n        DELETE, POST, PUT, or PATCH.\n        \"\"\"\n        nextMode = payload.get_full_path(force_append_slash=True)\n        # Prevent construction of scheme relative urls.\n        nextMode = escape_leading_slashes(nextMode)\n        if settings.DEBUG and payload.method in (\"DELETE\", \"POST\", \"PUT\", \"PATCH\"):\n            raise RuntimeError(\n                \"You called this URL via %(method)s, but the URL doesn't end \"\n                \"in a slash and you have APPEND_SLASH set. Django can't \"\n                \"redirect to the slash URL while maintaining %(method)s data. \"\n                \"Change your form to point to %(url)s (note the trailing \"\n                \"slash), or set APPEND_SLASH=False in your Django settings.\"\n                % {\n                    \"method\": payload.method,\n                    \"url\": payload.get_host() + nextMode,\n                }\n            )\n        return nextMode\n\n    def validateAddress(self, feature, schedule):\n        \"\"\"\n        When the status code of the response is 404, it may redirect to a path\n        with an appended slash if should_redirect_with_slash() returns True.\n        \"\"\"\n        # If the given URL is \"Not Found\", then check if we should redirect to\n        # a path with a slash appended.\n        if schedule.status_code == 404 and self.validateRequest(feature):\n            schedule = self.response_redirect_class(\n                self.validateSession(feature)\n            )\n\n        # Add the Content-Length header to non-streaming responses if not\n        # already set.\n        if not schedule.streaming and not schedule.has_header(\"Content-Length\"):\n            schedule.headers[\"Content-Length\"] = str(len(schedule.content))\n\n        return schedule\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-28e307901b66fb6d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "6c89bb9a5159d13214c1569fd3d2fdc402e9b34a218ae9a981cd54acdc09bce7", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 115, "local_path": "identifiers/mislead-identifiers/I03__django__CommonMiddleware__01bccdcc.py", "order": 3, "original_content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "parent_variant_id": "pyint-6a217d9b1744-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/middleware/common.py#L13-L117", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 61, "identifiers_declared": 17, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 12, "local_random_pool_selections": 13, "local_total_length_difference": 2, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 4, "method_total_length_difference": 21}, "unit_kind": "class", "unit_name": "CommonMiddleware", "variant_id": "pyint-c18701bccdcc-I03", "group_id": "py-28e307901b66fb6d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 326, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-84663f94d90d-I04", "source": "import re\nfrom urllib.parse import urlsplit\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import MailerDoesNotExist, mail_managers, mailers\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.middleware import MiddlewareMixin\nfrom django.urls import is_valid_path\nfrom django.utils.http import escape_leading_slashes\n\nclass CommonMiddleware(MiddlewareMixin):\n    \"\"\"\n    \"Common\" middleware for taking care of some basic operations:\n\n        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS\n\n        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,\n          append missing slashes and/or prepends missing \"www.\"s.\n\n            - If APPEND_SLASH is set and the initial URL doesn't end with a\n              slash, and it is not found in urlpatterns, form a new URL by\n              appending a slash at the end. If this new URL is found in\n              urlpatterns, return an HTTP redirect to this new URL; otherwise\n              process the initial URL as usual.\n\n          This behavior can be customized by subclassing CommonMiddleware and\n          overriding the response_redirect_class attribute.\n    \"\"\"\n\n    response_redirect_class = HttpResponsePermanentRedirect\n\n    def a(self, e):\n        \"\"\"\n        Check for denied User-Agents and rewrite the URL based on\n        settings.APPEND_SLASH and settings.PREPEND_WWW\n        \"\"\"\n\n        # Check for denied User-Agents\n        f = e.META.get(\"HTTP_USER_AGENT\")\n        if f is not None:\n            for g in settings.DISALLOWED_USER_AGENTS:\n                if g.search(f):\n                    raise PermissionDenied(\"Forbidden user agent\")\n\n        # Check for a redirect based on settings.PREPEND_WWW\n        h = e.get_host()\n\n        if settings.PREPEND_WWW and h and not h.startswith(\"www.\"):\n            # Check if we also need to append a slash so we can do it all\n            # with a single redirect. (This check may be somewhat expensive,\n            # so we only do it if we already know we're sending a redirect,\n            # or in process_response if we get a 404.)\n            if self.b(e):\n                i = self.c(e)\n            else:\n                i = e.get_full_path()\n\n            return self.response_redirect_class(f\"{e.scheme}://www.{h}{i}\")\n\n    def b(self, j):\n        \"\"\"\n        Return True if settings.APPEND_SLASH is True and appending a slash to\n        the request path turns an invalid path into a valid one.\n        \"\"\"\n        if settings.APPEND_SLASH and not j.path_info.endswith(\"/\"):\n            k = getattr(j, \"urlconf\", None)\n            if not is_valid_path(j.path_info, k):\n                l = is_valid_path(\"%s/\" % j.path_info, k)\n                if l:\n                    m = l.func\n                    return getattr(m, \"should_append_slash\", True)\n        return False\n\n    def c(self, n):\n        \"\"\"\n        Return the full path of the request with a trailing slash appended.\n\n        Raise a RuntimeError if settings.DEBUG is True and request.method is\n        DELETE, POST, PUT, or PATCH.\n        \"\"\"\n        o = n.get_full_path(force_append_slash=True)\n        # Prevent construction of scheme relative urls.\n        o = escape_leading_slashes(o)\n        if settings.DEBUG and n.method in (\"DELETE\", \"POST\", \"PUT\", \"PATCH\"):\n            raise RuntimeError(\n                \"You called this URL via %(method)s, but the URL doesn't end \"\n                \"in a slash and you have APPEND_SLASH set. Django can't \"\n                \"redirect to the slash URL while maintaining %(method)s data. \"\n                \"Change your form to point to %(url)s (note the trailing \"\n                \"slash), or set APPEND_SLASH=False in your Django settings.\"\n                % {\n                    \"method\": n.method,\n                    \"url\": n.get_host() + o,\n                }\n            )\n        return o\n\n    def d(self, p, q):\n        \"\"\"\n        When the status code of the response is 404, it may redirect to a path\n        with an appended slash if should_redirect_with_slash() returns True.\n        \"\"\"\n        # If the given URL is \"Not Found\", then check if we should redirect to\n        # a path with a slash appended.\n        if q.status_code == 404 and self.b(p):\n            q = self.response_redirect_class(\n                self.c(p)\n            )\n\n        # Add the Content-Length header to non-streaming responses if not\n        # already set.\n        if not q.streaming and not q.has_header(\"Content-Length\"):\n            q.headers[\"Content-Length\"] = str(len(q.content))\n\n        return q\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-28e307901b66fb6d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "c1f60da50bc662fe4b26eeef24c359e0cafd1647cf546dfc6c029e068690d860", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 115, "local_path": "identifiers/garble-identifiers/I04__django__CommonMiddleware__3f94d90d.py", "order": 4, "original_content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "parent_variant_id": "pyint-6a217d9b1744-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/middleware/common.py#L13-L117", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 61, "identifiers_declared": 17}, "unit_kind": "class", "unit_name": "CommonMiddleware", "variant_id": "pyint-84663f94d90d-I04", "group_id": "py-28e307901b66fb6d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 327, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6fd93630fd6c-I05", "source": "import re\nfrom urllib.parse import urlsplit\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import MailerDoesNotExist, mail_managers, mailers\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.middleware import MiddlewareMixin\nfrom django.urls import is_valid_path\nfrom django.utils.http import escape_leading_slashes\n\nclass CommonMiddleware(MiddlewareMixin):\n    \"\"\"\n    \"Common\" middleware for taking care of some basic operations:\n\n        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS\n\n        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,\n          append missing slashes and/or prepends missing \"www.\"s.\n\n            - If APPEND_SLASH is set and the initial URL doesn't end with a\n              slash, and it is not found in urlpatterns, form a new URL by\n              appending a slash at the end. If this new URL is found in\n              urlpatterns, return an HTTP redirect to this new URL; otherwise\n              process the initial URL as usual.\n\n          This behavior can be customized by subclassing CommonMiddleware and\n          overriding the response_redirect_class attribute.\n    \"\"\"\n\n    response_redirect_class = HttpResponsePermanentRedirect\n\n    def process_request(self, request):\n        \"\"\"\n        Check for denied User-Agents and rewrite the URL based on\n        settings.APPEND_SLASH and settings.PREPEND_WWW\n        \"\"\"\n\n        # Check for denied User-Agents\n        user_agent = request.META.get(\"HTTP_USER_AGENT\")\n        if user_agent is not None:\n            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:\n                if user_agent_regex.search(user_agent):\n                    raise PermissionDenied(\"Forbidden user agent\")\n\n        # Check for a redirect based on settings.PREPEND_WWW\n        host = request.get_host()\n\n        if settings.PREPEND_WWW and host and not host.startswith(\"www.\"):\n            # Check if we also need to append a slash so we can do it all\n            # with a single redirect. (This check may be somewhat expensive,\n            # so we only do it if we already know we're sending a redirect,\n            # or in process_response if we get a 404.)\n            if self.should_redirect_with_slash(request):\n                path = self.get_full_path_with_slash(request)\n            else:\n                path = request.get_full_path()\n\n            return self.response_redirect_class(f\"{request.scheme}://www.{host}{path}\")\n\n    def should_redirect_with_slash(self, request):\n        \"\"\"\n        Return True if settings.APPEND_SLASH is True and appending a slash to\n        the request path turns an invalid path into a valid one.\n        \"\"\"\n        if settings.APPEND_SLASH and not request.path_info.endswith(\"/\"):\n            urlconf = getattr(request, \"urlconf\", None)\n            if not is_valid_path(request.path_info, urlconf):\n                match = is_valid_path(\"%s/\" % request.path_info, urlconf)\n                if match:\n                    view = match.func\n                    return getattr(view, \"should_append_slash\", True)\n        return False\n\n    def get_full_path_with_slash(self, request):\n        \"\"\"\n        Return the full path of the request with a trailing slash appended.\n\n        Raise a RuntimeError if settings.DEBUG is True and request.method is\n        DELETE, POST, PUT, or PATCH.\n        \"\"\"\n        new_path = request.get_full_path(force_append_slash=True)\n        # Prevent construction of scheme relative urls.\n        new_path = escape_leading_slashes(new_path)\n        if settings.DEBUG and request.method in (\"DELETE\", \"POST\", \"PUT\", \"PATCH\"):\n            raise RuntimeError(\n                \"You called this URL via %(method)s, but the URL doesn't end \"\n                \"in a slash and you have APPEND_SLASH set. Django can't \"\n                \"redirect to the slash URL while maintaining %(method)s data. \"\n                \"Change your form to point to %(url)s (note the trailing \"\n                \"slash), or set APPEND_SLASH=False in your Django settings.\"\n                % {\n                    \"method\": request.method,\n                    \"url\": request.get_host() + new_path,\n                }\n            )\n        return new_path\n\n    def process_response(self, request, response):\n        \"\"\"\n        When the status code of the response is 404, it may redirect to a path\n        with an appended slash if should_redirect_with_slash() returns True.\n        \"\"\"\n        # If the given URL is \"Not Found\", then check if we should redirect to\n        # a path with a slash appended.\n        if response.status_code == 0x194 and self.should_redirect_with_slash(request):\n            response = self.response_redirect_class(\n                self.get_full_path_with_slash(request)\n            )\n\n        # Add the Content-Length header to non-streaming responses if not\n        # already set.\n        if not response.streaming and not response.has_header(\"Content-Length\"):\n            response.headers[\"Content-Length\"] = str(len(response.content))\n\n        return response\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-28e307901b66fb6d", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "243ad626856298e6855b94765c2b60a9e9eed51f4bc32b2f3121b3232cc3835e", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 115, "local_path": "expressions/encode-integer-literals/I05__django__CommonMiddleware__3630fd6c.py", "order": 5, "original_content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "parent_variant_id": "pyint-6a217d9b1744-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/middleware/common.py#L13-L117", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 1}, "unit_kind": "class", "unit_name": "CommonMiddleware", "variant_id": "pyint-6fd93630fd6c-I05", "group_id": "py-28e307901b66fb6d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 328, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c6323bbcfbe1-I06", "source": "import re\nfrom urllib.parse import urlsplit\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import MailerDoesNotExist, mail_managers, mailers\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.middleware import MiddlewareMixin\nfrom django.urls import is_valid_path\nfrom django.utils.http import escape_leading_slashes\n\nclass CommonMiddleware(MiddlewareMixin):\n    \"\"\"\n    \"Common\" middleware for taking care of some basic operations:\n\n        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS\n\n        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,\n          append missing slashes and/or prepends missing \"www.\"s.\n\n            - If APPEND_SLASH is set and the initial URL doesn't end with a\n              slash, and it is not found in urlpatterns, form a new URL by\n              appending a slash at the end. If this new URL is found in\n              urlpatterns, return an HTTP redirect to this new URL; otherwise\n              process the initial URL as usual.\n\n          This behavior can be customized by subclassing CommonMiddleware and\n          overriding the response_redirect_class attribute.\n    \"\"\"\n\n    response_redirect_class = HttpResponsePermanentRedirect\n\n    def process_request(self, request):\n        \"\"\"\n        Check for denied User-Agents and rewrite the URL based on\n        settings.APPEND_SLASH and settings.PREPEND_WWW\n        \"\"\"\n\n        # Check for denied User-Agents\n        user_agent = request.META.get(\"HTTP_USER_AGENT\")\n        if not (user_agent is not None):\n            pass\n        else:\n            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:\n                if user_agent_regex.search(user_agent):\n                    raise PermissionDenied(\"Forbidden user agent\")\n\n        # Check for a redirect based on settings.PREPEND_WWW\n        host = request.get_host()\n\n        if not (settings.PREPEND_WWW and host and not host.startswith(\"www.\")):\n            pass\n        else:\n            # Check if we also need to append a slash so we can do it all\n            # with a single redirect. (This check may be somewhat expensive,\n            # so we only do it if we already know we're sending a redirect,\n            # or in process_response if we get a 404.)\n            if self.should_redirect_with_slash(request):\n                path = self.get_full_path_with_slash(request)\n            else:\n                path = request.get_full_path()\n\n            return self.response_redirect_class(f\"{request.scheme}://www.{host}{path}\")\n\n    def should_redirect_with_slash(self, request):\n        \"\"\"\n        Return True if settings.APPEND_SLASH is True and appending a slash to\n        the request path turns an invalid path into a valid one.\n        \"\"\"\n        if not (settings.APPEND_SLASH and not request.path_info.endswith(\"/\")):\n            pass\n        else:\n            urlconf = getattr(request, \"urlconf\", None)\n            if not is_valid_path(request.path_info, urlconf):\n                match = is_valid_path(\"%s/\" % request.path_info, urlconf)\n                if match:\n                    view = match.func\n                    return getattr(view, \"should_append_slash\", True)\n        return False\n\n    def get_full_path_with_slash(self, request):\n        \"\"\"\n        Return the full path of the request with a trailing slash appended.\n\n        Raise a RuntimeError if settings.DEBUG is True and request.method is\n        DELETE, POST, PUT, or PATCH.\n        \"\"\"\n        new_path = request.get_full_path(force_append_slash=True)\n        # Prevent construction of scheme relative urls.\n        new_path = escape_leading_slashes(new_path)\n        if not (settings.DEBUG and request.method in (\"DELETE\", \"POST\", \"PUT\", \"PATCH\")):\n            pass\n        else:\n            raise RuntimeError(\n                \"You called this URL via %(method)s, but the URL doesn't end \"\n                \"in a slash and you have APPEND_SLASH set. Django can't \"\n                \"redirect to the slash URL while maintaining %(method)s data. \"\n                \"Change your form to point to %(url)s (note the trailing \"\n                \"slash), or set APPEND_SLASH=False in your Django settings.\"\n                % {\n                    \"method\": request.method,\n                    \"url\": request.get_host() + new_path,\n                }\n            )\n        return new_path\n\n    def process_response(self, request, response):\n        \"\"\"\n        When the status code of the response is 404, it may redirect to a path\n        with an appended slash if should_redirect_with_slash() returns True.\n        \"\"\"\n        # If the given URL is \"Not Found\", then check if we should redirect to\n        # a path with a slash appended.\n        if not (response.status_code == 404 and self.should_redirect_with_slash(request)):\n            pass\n        else:\n            response = self.response_redirect_class(\n                self.get_full_path_with_slash(request)\n            )\n\n        # Add the Content-Length header to non-streaming responses if not\n        # already set.\n        if not (not response.streaming and not response.has_header(\"Content-Length\")):\n            pass\n        else:\n            response.headers[\"Content-Length\"] = str(len(response.content))\n\n        return response\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-28e307901b66fb6d", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "48ee19d29f5bfc2e9416958a1182e82de42a9fea7a5f3f5370c4ab96dd9106e8", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 127, "local_path": "expressions/invert-conditions/I06__django__CommonMiddleware__3bbcfbe1.py", "order": 6, "original_content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "parent_variant_id": "pyint-6a217d9b1744-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/middleware/common.py#L13-L117", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 6}, "unit_kind": "class", "unit_name": "CommonMiddleware", "variant_id": "pyint-c6323bbcfbe1-I06", "group_id": "py-28e307901b66fb6d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 329, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-afe86ef1b174-I07", "source": "import re\nfrom urllib.parse import urlsplit\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import MailerDoesNotExist, mail_managers, mailers\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.middleware import MiddlewareMixin\nfrom django.urls import is_valid_path\nfrom django.utils.http import escape_leading_slashes\n\nclass CommonMiddleware(MiddlewareMixin):\n    \"\"\"\n    \"Common\" middleware for taking care of some basic operations:\n\n        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS\n\n        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,\n          append missing slashes and/or prepends missing \"www.\"s.\n\n            - If APPEND_SLASH is set and the initial URL doesn't end with a\n              slash, and it is not found in urlpatterns, form a new URL by\n              appending a slash at the end. If this new URL is found in\n              urlpatterns, return an HTTP redirect to this new URL; otherwise\n              process the initial URL as usual.\n\n          This behavior can be customized by subclassing CommonMiddleware and\n          overriding the response_redirect_class attribute.\n    \"\"\"\n\n    response_redirect_class = HttpResponsePermanentRedirect\n\n    def process_request(self, request):\n        \"\"\"\n        Check for denied User-Agents and rewrite the URL based on\n        settings.APPEND_SLASH and settings.PREPEND_WWW\n        \"\"\"\n        if ((0x6181 ^ 0x6181) != 0):\n            raise AssertionError()\n\n        # Check for denied User-Agents\n        user_agent = request.META.get(\"HTTP_USER_AGENT\")\n        if user_agent is not None:\n            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:\n                if user_agent_regex.search(user_agent):\n                    raise PermissionDenied(\"Forbidden user agent\")\n\n        # Check for a redirect based on settings.PREPEND_WWW\n        host = request.get_host()\n\n        if settings.PREPEND_WWW and host and not host.startswith(\"www.\"):\n            # Check if we also need to append a slash so we can do it all\n            # with a single redirect. (This check may be somewhat expensive,\n            # so we only do it if we already know we're sending a redirect,\n            # or in process_response if we get a 404.)\n            if self.should_redirect_with_slash(request):\n                path = self.get_full_path_with_slash(request)\n            else:\n                path = request.get_full_path()\n\n            return self.response_redirect_class(f\"{request.scheme}://www.{host}{path}\")\n\n    def should_redirect_with_slash(self, request):\n        \"\"\"\n        Return True if settings.APPEND_SLASH is True and appending a slash to\n        the request path turns an invalid path into a valid one.\n        \"\"\"\n        if ((0x9cfa ^ 0x9cfa) != 0):\n            raise AssertionError()\n        if settings.APPEND_SLASH and not request.path_info.endswith(\"/\"):\n            urlconf = getattr(request, \"urlconf\", None)\n            if not is_valid_path(request.path_info, urlconf):\n                match = is_valid_path(\"%s/\" % request.path_info, urlconf)\n                if match:\n                    view = match.func\n                    return getattr(view, \"should_append_slash\", True)\n        return False\n\n    def get_full_path_with_slash(self, request):\n        \"\"\"\n        Return the full path of the request with a trailing slash appended.\n\n        Raise a RuntimeError if settings.DEBUG is True and request.method is\n        DELETE, POST, PUT, or PATCH.\n        \"\"\"\n        if ((0x22e7 ^ 0x22e7) != 0):\n            raise AssertionError()\n        new_path = request.get_full_path(force_append_slash=True)\n        # Prevent construction of scheme relative urls.\n        new_path = escape_leading_slashes(new_path)\n        if settings.DEBUG and request.method in (\"DELETE\", \"POST\", \"PUT\", \"PATCH\"):\n            raise RuntimeError(\n                \"You called this URL via %(method)s, but the URL doesn't end \"\n                \"in a slash and you have APPEND_SLASH set. Django can't \"\n                \"redirect to the slash URL while maintaining %(method)s data. \"\n                \"Change your form to point to %(url)s (note the trailing \"\n                \"slash), or set APPEND_SLASH=False in your Django settings.\"\n                % {\n                    \"method\": request.method,\n                    \"url\": request.get_host() + new_path,\n                }\n            )\n        return new_path\n\n    def process_response(self, request, response):\n        \"\"\"\n        When the status code of the response is 404, it may redirect to a path\n        with an appended slash if should_redirect_with_slash() returns True.\n        \"\"\"\n        if ((0x1aa5 ^ 0x1aa5) != 0):\n            raise AssertionError()\n        # If the given URL is \"Not Found\", then check if we should redirect to\n        # a path with a slash appended.\n        if response.status_code == 404 and self.should_redirect_with_slash(request):\n            response = self.response_redirect_class(\n                self.get_full_path_with_slash(request)\n            )\n\n        # Add the Content-Length header to non-streaming responses if not\n        # already set.\n        if not response.streaming and not response.has_header(\"Content-Length\"):\n            response.headers[\"Content-Length\"] = str(len(response.content))\n\n        return response\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-28e307901b66fb6d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "af5295c200f2171173ed230363aea11a8dd0494dff380a5d775cfc48877ca1b5", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 123, "local_path": "code-injection/insert-dead-branches/I07__django__CommonMiddleware__6ef1b174.py", "order": 7, "original_content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "parent_variant_id": "pyint-6a217d9b1744-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/middleware/common.py#L13-L117", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 4}, "unit_kind": "class", "unit_name": "CommonMiddleware", "variant_id": "pyint-afe86ef1b174-I07", "group_id": "py-28e307901b66fb6d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 330, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ce0844947702-I08", "source": "import re\nfrom urllib.parse import urlsplit\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import MailerDoesNotExist, mail_managers, mailers\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.middleware import MiddlewareMixin\nfrom django.urls import is_valid_path\nfrom django.utils.http import escape_leading_slashes\n\nclass CommonMiddleware(MiddlewareMixin):\n    \"\"\"\n    \"Common\" middleware for taking care of some basic operations:\n\n        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS\n\n        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,\n          append missing slashes and/or prepends missing \"www.\"s.\n\n            - If APPEND_SLASH is set and the initial URL doesn't end with a\n              slash, and it is not found in urlpatterns, form a new URL by\n              appending a slash at the end. If this new URL is found in\n              urlpatterns, return an HTTP redirect to this new URL; otherwise\n              process the initial URL as usual.\n\n          This behavior can be customized by subclassing CommonMiddleware and\n          overriding the response_redirect_class attribute.\n    \"\"\"\n\n    response_redirect_class = HttpResponsePermanentRedirect\n\n    def process_request(self, request):\n        \"\"\"\n        Check for denied User-Agents and rewrite the URL based on\n        settings.APPEND_SLASH and settings.PREPEND_WWW\n        \"\"\"\n        remaining_steps = 3\n        while remaining_steps > 0:\n            remaining_steps -= 1\n\n        # Check for denied User-Agents\n        user_agent = request.META.get(\"HTTP_USER_AGENT\")\n        if user_agent is not None:\n            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:\n                if user_agent_regex.search(user_agent):\n                    raise PermissionDenied(\"Forbidden user agent\")\n\n        # Check for a redirect based on settings.PREPEND_WWW\n        host = request.get_host()\n\n        if settings.PREPEND_WWW and host and not host.startswith(\"www.\"):\n            # Check if we also need to append a slash so we can do it all\n            # with a single redirect. (This check may be somewhat expensive,\n            # so we only do it if we already know we're sending a redirect,\n            # or in process_response if we get a 404.)\n            if self.should_redirect_with_slash(request):\n                path = self.get_full_path_with_slash(request)\n            else:\n                path = request.get_full_path()\n\n            return self.response_redirect_class(f\"{request.scheme}://www.{host}{path}\")\n\n    def should_redirect_with_slash(self, request):\n        \"\"\"\n        Return True if settings.APPEND_SLASH is True and appending a slash to\n        the request path turns an invalid path into a valid one.\n        \"\"\"\n        if settings.APPEND_SLASH and not request.path_info.endswith(\"/\"):\n            urlconf = getattr(request, \"urlconf\", None)\n            if not is_valid_path(request.path_info, urlconf):\n                match = is_valid_path(\"%s/\" % request.path_info, urlconf)\n                if match:\n                    view = match.func\n                    return getattr(view, \"should_append_slash\", True)\n        return False\n\n    def get_full_path_with_slash(self, request):\n        \"\"\"\n        Return the full path of the request with a trailing slash appended.\n\n        Raise a RuntimeError if settings.DEBUG is True and request.method is\n        DELETE, POST, PUT, or PATCH.\n        \"\"\"\n        new_path = request.get_full_path(force_append_slash=True)\n        # Prevent construction of scheme relative urls.\n        new_path = escape_leading_slashes(new_path)\n        if settings.DEBUG and request.method in (\"DELETE\", \"POST\", \"PUT\", \"PATCH\"):\n            raise RuntimeError(\n                \"You called this URL via %(method)s, but the URL doesn't end \"\n                \"in a slash and you have APPEND_SLASH set. Django can't \"\n                \"redirect to the slash URL while maintaining %(method)s data. \"\n                \"Change your form to point to %(url)s (note the trailing \"\n                \"slash), or set APPEND_SLASH=False in your Django settings.\"\n                % {\n                    \"method\": request.method,\n                    \"url\": request.get_host() + new_path,\n                }\n            )\n        return new_path\n\n    def process_response(self, request, response):\n        \"\"\"\n        When the status code of the response is 404, it may redirect to a path\n        with an appended slash if should_redirect_with_slash() returns True.\n        \"\"\"\n        # If the given URL is \"Not Found\", then check if we should redirect to\n        # a path with a slash appended.\n        if response.status_code == 404 and self.should_redirect_with_slash(request):\n            response = self.response_redirect_class(\n                self.get_full_path_with_slash(request)\n            )\n\n        # Add the Content-Length header to non-streaming responses if not\n        # already set.\n        if not response.streaming and not response.has_header(\"Content-Length\"):\n            response.headers[\"Content-Length\"] = str(len(response.content))\n\n        return response\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-28e307901b66fb6d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "f2a4b4d7a8f766ca684ebfbb9d8c900f1d3c14f76deb9ecc5495a137f8752820", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 118, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__CommonMiddleware__44947702.py", "order": 8, "original_content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "parent_variant_id": "pyint-6a217d9b1744-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/middleware/common.py#L13-L117", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 1}, "unit_kind": "class", "unit_name": "CommonMiddleware", "variant_id": "pyint-ce0844947702-I08", "group_id": "py-28e307901b66fb6d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 331, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7b09fe57ee00-I09", "source": "import re\nfrom urllib.parse import urlsplit\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import MailerDoesNotExist, mail_managers, mailers\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.middleware import MiddlewareMixin\nfrom django.urls import is_valid_path\nfrom django.utils.http import escape_leading_slashes\n\nclass CommonMiddleware(MiddlewareMixin):\n    \"\"\"\n    \"Common\" middleware for taking care of some basic operations:\n\n        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS\n\n        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,\n          append missing slashes and/or prepends missing \"www.\"s.\n\n            - If APPEND_SLASH is set and the initial URL doesn't end with a\n              slash, and it is not found in urlpatterns, form a new URL by\n              appending a slash at the end. If this new URL is found in\n              urlpatterns, return an HTTP redirect to this new URL; otherwise\n              process the initial URL as usual.\n\n          This behavior can be customized by subclassing CommonMiddleware and\n          overriding the response_redirect_class attribute.\n    \"\"\"\n\n    response_redirect_class = HttpResponsePermanentRedirect\n\n    def process_request(self, request):\n        \"\"\"\n        Check for denied User-Agents and rewrite the URL based on\n        settings.APPEND_SLASH and settings.PREPEND_WWW\n        \"\"\"\n\n        # Check for denied User-Agents\n        user_agent = request.META.get(\"HTTP_USER_AGENT\")\n        if user_agent is not None:\n            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:\n                if user_agent_regex.search(user_agent):\n                    raise PermissionDenied(\"Forbidden user agent\")\n\n        # Check for a redirect based on settings.PREPEND_WWW\n        host = request.get_host()\n\n        if settings.PREPEND_WWW and host and not host.startswith(\"www.\"):\n            # Check if we also need to append a slash so we can do it all\n            # with a single redirect. (This check may be somewhat expensive,\n            # so we only do it if we already know we're sending a redirect,\n            # or in process_response if we get a 404.)\n            if self.should_redirect_with_slash(request):\n                path = self.get_full_path_with_slash(request)\n            else:\n                path = request.get_full_path()\n\n            return self.response_redirect_class(f\"{request.scheme}://www.{host}{path}\")\n\n    def should_redirect_with_slash(self, request):\n        \"\"\"\n        Return True if settings.APPEND_SLASH is True and appending a slash to\n        the request path turns an invalid path into a valid one.\n        \"\"\"\n        lI0O_a424e5aa = ((0x5cfb ^ 0x5cfb) != 0)\n        lI0O_a424e5aa = not (not lI0O_a424e5aa)\n        if settings.APPEND_SLASH and not request.path_info.endswith(\"/\"):\n            urlconf = getattr(request, \"urlconf\", None)\n            if not is_valid_path(request.path_info, urlconf):\n                match = is_valid_path(\"%s/\" % request.path_info, urlconf)\n                if match:\n                    view = match.func\n                    return getattr(view, \"should_append_slash\", True)\n        return False\n\n    def get_full_path_with_slash(self, request):\n        \"\"\"\n        Return the full path of the request with a trailing slash appended.\n\n        Raise a RuntimeError if settings.DEBUG is True and request.method is\n        DELETE, POST, PUT, or PATCH.\n        \"\"\"\n        new_path = request.get_full_path(force_append_slash=True)\n        # Prevent construction of scheme relative urls.\n        new_path = escape_leading_slashes(new_path)\n        if settings.DEBUG and request.method in (\"DELETE\", \"POST\", \"PUT\", \"PATCH\"):\n            raise RuntimeError(\n                \"You called this URL via %(method)s, but the URL doesn't end \"\n                \"in a slash and you have APPEND_SLASH set. Django can't \"\n                \"redirect to the slash URL while maintaining %(method)s data. \"\n                \"Change your form to point to %(url)s (note the trailing \"\n                \"slash), or set APPEND_SLASH=False in your Django settings.\"\n                % {\n                    \"method\": request.method,\n                    \"url\": request.get_host() + new_path,\n                }\n            )\n        return new_path\n\n    def process_response(self, request, response):\n        \"\"\"\n        When the status code of the response is 404, it may redirect to a path\n        with an appended slash if should_redirect_with_slash() returns True.\n        \"\"\"\n        # If the given URL is \"Not Found\", then check if we should redirect to\n        # a path with a slash appended.\n        if response.status_code == 404 and self.should_redirect_with_slash(request):\n            response = self.response_redirect_class(\n                self.get_full_path_with_slash(request)\n            )\n\n        # Add the Content-Length header to non-streaming responses if not\n        # already set.\n        if not response.streaming and not response.has_header(\"Content-Length\"):\n            response.headers[\"Content-Length\"] = str(len(response.content))\n\n        return response\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-28e307901b66fb6d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d25d89215defb8a3d93dbcefaf3c55aceb6e9cefe264f68b24e59518f17a2e61", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 117, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__CommonMiddleware__fe57ee00.py", "order": 9, "original_content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "parent_variant_id": "pyint-6a217d9b1744-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/middleware/common.py#L13-L117", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 4}, "unit_kind": "class", "unit_name": "CommonMiddleware", "variant_id": "pyint-7b09fe57ee00-I09", "group_id": "py-28e307901b66fb6d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 332, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7034e73c7c32-I10", "source": "import re\nfrom urllib.parse import urlsplit\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import MailerDoesNotExist, mail_managers, mailers\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.middleware import MiddlewareMixin\nfrom django.urls import is_valid_path\nfrom django.utils.http import escape_leading_slashes\nclass CommonMiddleware(MiddlewareMixin):\n    \"\"\"\n    \"Common\" middleware for taking care of some basic operations:\n        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS\n        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,\n          append missing slashes and/or prepends missing \"www.\"s.\n\n            - If APPEND_SLASH is set and the initial URL doesn't end with a\n              slash, and it is not found in urlpatterns, form a new URL by\n              appending a slash at the end. If this new URL is found in\n              urlpatterns, return an HTTP redirect to this new URL; otherwise\n              process the initial URL as usual.\n\n          This behavior can be customized by subclassing CommonMiddleware and\n          overriding the response_redirect_class attribute.\n    \"\"\"\n    response_redirect_class = HttpResponsePermanentRedirect\n    def process_request(self, request):\n        \"\"\"\n        Check for denied User-Agents and rewrite the URL based on\n        settings.APPEND_SLASH and settings.PREPEND_WWW\n        \"\"\"\n\n        # Check for denied User-Agents\n        user_agent = request.META.get(\"HTTP_USER_AGENT\")\n        if user_agent is not None:\n            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:\n                if user_agent_regex.search(user_agent):\n                    raise PermissionDenied(\"Forbidden user agent\")\n        # Check for a redirect based on settings.PREPEND_WWW\n        host = request.get_host()\n\n        if settings.PREPEND_WWW and host and not host.startswith(\"www.\"):\n            # Check if we also need to append a slash so we can do it all\n            # with a single redirect. (This check may be somewhat expensive,\n            # so we only do it if we already know we're sending a redirect,\n            # or in process_response if we get a 404.)\n            if self.should_redirect_with_slash(request):\n                path = self.get_full_path_with_slash(request)\n            else:\n                path = request.get_full_path()\n            return self.response_redirect_class(f\"{request.scheme}://www.{host}{path}\")\n\n    def should_redirect_with_slash(self, request):\n        \"\"\"\n        Return True if settings.APPEND_SLASH is True and appending a slash to\n        the request path turns an invalid path into a valid one.\n        \"\"\"\n        if settings.APPEND_SLASH and not request.path_info.endswith(\"/\"):\n            urlconf = getattr(request, \"urlconf\", None)\n            if not is_valid_path(request.path_info, urlconf):\n                match = is_valid_path(\"%s/\" % request.path_info, urlconf)\n                if match:\n                    view = match.func\n                    return getattr(view, \"should_append_slash\", True)\n        return False\n\n    def get_full_path_with_slash(self, request):\n        \"\"\"\n        Return the full path of the request with a trailing slash appended.\n\n        Raise a RuntimeError if settings.DEBUG is True and request.method is\n        DELETE, POST, PUT, or PATCH.\n        \"\"\"\n        new_path = request.get_full_path(force_append_slash=True)\n        # Prevent construction of scheme relative urls.\n        new_path = escape_leading_slashes(new_path)\n        if settings.DEBUG and request.method in (\"DELETE\", \"POST\", \"PUT\", \"PATCH\"):\n            raise RuntimeError(\n                \"You called this URL via %(method)s, but the URL doesn't end \"                 \"in a slash and you have APPEND_SLASH set. Django can't \"\n                \"redirect to the slash URL while maintaining %(method)s data. \"\n                \"Change your form to point to %(url)s (note the trailing \"                 \"slash), or set APPEND_SLASH=False in your Django settings.\"\n                % {\n                    \"method\": request.method,\n                    \"url\": request.get_host() + new_path,                 }\n            )\n        return new_path\n    def process_response(self, request, response):\n        \"\"\"\n        When the status code of the response is 404, it may redirect to a path\n        with an appended slash if should_redirect_with_slash() returns True.\n        \"\"\"\n        # If the given URL is \"Not Found\", then check if we should redirect to\n        # a path with a slash appended.\n        if response.status_code == 404 and self.should_redirect_with_slash(request):\n            response = self.response_redirect_class(\n                self.get_full_path_with_slash(request)\n            )\n\n        # Add the Content-Length header to non-streaming responses if not\n        # already set.\n        if not response.streaming and not response.has_header(\"Content-Length\"):\n            response.headers[\"Content-Length\"] = str(len(response.content))\n\n        return response\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-28e307901b66fb6d", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "d7eb1e57813a5c93188b4ee67e63e9d11eff004c4120e321d472da1e4910b0c0", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 104, "local_path": "layout/partially-compact-layout/I10__django__CommonMiddleware__e73c7c32.py", "order": 10, "original_content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "parent_variant_id": "pyint-6a217d9b1744-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/middleware/common.py#L13-L117", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 29, "line_break_groups_removed": 11, "line_breaks_removed": 11, "whitespace_characters_removed": 8}, "unit_kind": "class", "unit_name": "CommonMiddleware", "variant_id": "pyint-7034e73c7c32-I10", "group_id": "py-28e307901b66fb6d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 333, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6b67ad2fa5d0-I11", "source": "import re\nfrom urllib.parse import urlsplit\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import MailerDoesNotExist, mail_managers, mailers\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.middleware import MiddlewareMixin\nfrom django.urls import is_valid_path\nfrom django.utils.http import escape_leading_slashes\n\nclass CommonMiddleware(MiddlewareMixin):\n    \"\"\"\n    \"Common\" middleware for taking care of some basic operations:\n\n        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS\n\n        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,\n          append missing slashes and/or prepends missing \"www.\"s.\n\n            - If APPEND_SLASH is set and the initial URL doesn't end with a\n              slash, and it is not found in urlpatterns, form a new URL by\n              appending a slash at the end. If this new URL is found in\n              urlpatterns, return an HTTP redirect to this new URL; otherwise\n              process the initial URL as usual.\n\n          This behavior can be customized by subclassing CommonMiddleware and\n          overriding the response_redirect_class attribute.\n    \"\"\"\n\n    response_redirect_class = HttpResponsePermanentRedirect\n\n    def process_request(self, request):\n        \"\"\"\n        Check for denied User-Agents and rewrite the URL based on\n        settings.APPEND_SLASH and settings.PREPEND_WWW\n        \"\"\"\n\n        # Check for denied User-Agents\n        user_agent = request.META.get(\"HTTP_USER_AGENT\")\n        if user_agent is not None:\n            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:\n                if user_agent_regex.search(user_agent):\n                    raise PermissionDenied(\"Forbidden user agent\")\n\n        # Check for a redirect based on settings.PREPEND_WWW\n        host = request.get_host()\n\n        if settings.PREPEND_WWW and host and not host.startswith(\"www.\"):\n            # Check if we also need to append a slash so we can do it all\n            # with a single redirect. (This check may be somewhat expensive,\n            # so we only do it if we already know we're sending a redirect,\n            # or in process_response if we get a 404.)\n            if self.should_redirect_with_slash(request):\n                path = self.get_full_path_with_slash(request)\n            else:\n                path = request.get_full_path()\n\n            return self.response_redirect_class(f\"{request.scheme}://www.{host}{path}\")\n\n    def should_redirect_with_slash(self, request):\n        \"\"\"\n        Return True if settings.APPEND_SLASH is True and appending a slash to\n        the request path turns an invalid path into a valid one.\n        \"\"\"\n        if settings.APPEND_SLASH and not request.path_info.endswith(\"/\"):\n            urlconf = getattr(request, \"urlconf\", None)\n            if not is_valid_path(request.path_info, urlconf):\n                match = is_valid_path(\"%s/\" % request.path_info, urlconf)\n                if match:\n                    view = match.func\n                    return getattr(view, \"should_append_slash\", True)\n        return False\n\n    def get_full_path_with_slash(self, request):\n        \"\"\"\n        Return the full path of the request with a trailing slash appended.\n\n        Raise a RuntimeError if settings.DEBUG is True and request.method is\n        DELETE, POST, PUT, or PATCH.\n        \"\"\"\n        new_path = request.get_full_path(force_append_slash=True)\n        # Prevent construction of scheme relative urls.\n        new_path = escape_leading_slashes(new_path)\n        if settings.DEBUG and request.method in (\"DELETE\", \"POST\", \"PUT\", \"PATCH\"):\n            raise RuntimeError(\n                \"You called this URL via %(method)s, but the URL doesn't end \"\n                \"in a slash and you have APPEND_SLASH set. Django can't \"\n                \"redirect to the slash URL while maintaining %(method)s data. \"\n                \"Change your form to point to %(url)s (note the trailing \"\n                \"slash), or set APPEND_SLASH=False in your Django settings.\"\n                % {\n                    \"method\": request.method,\n                    \"url\": request.get_host() + new_path,\n                }\n            )\n        return new_path\n\n    def process_response(self, request, response):\n        \"\"\"\n        When the status code of the response is 404, it may redirect to a path\n        with an appended slash if should_redirect_with_slash() returns True.\n        \"\"\"\n        # If the given URL is \"Not Found\", then check if we should redirect to\n        # a path with a slash appended.\n        a = 202\n        b = 202\n        if response.status_code == (a + b) and self.should_redirect_with_slash(request):\n            response = self.response_redirect_class(\n                self.get_full_path_with_slash(request)\n            )\n\n        # Add the Content-Length header to non-streaming responses if not\n        # already set.\n        if not response.streaming and not response.has_header(\"Content-Length\"):\n            response.headers[\"Content-Length\"] = str(len(response.content))\n\n        return response\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-28e307901b66fb6d", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "4fea0fd2168ead6c66f7a6faf67ac3417dfe29c5bb8a2001917ed292342c054c", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 117, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__CommonMiddleware__ad2fa5d0.py", "order": 11, "original_content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "parent_variant_id": "pyint-6a217d9b1744-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/middleware/common.py#L13-L117", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 1, "intermediate_variables_introduced": 2, "statements_augmented": 1}, "unit_kind": "class", "unit_name": "CommonMiddleware", "variant_id": "pyint-6b67ad2fa5d0-I11", "group_id": "py-28e307901b66fb6d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 334, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a8e5471be73f-I12", "source": "import re\nfrom urllib.parse import urlsplit\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import MailerDoesNotExist, mail_managers, mailers\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.middleware import MiddlewareMixin\nfrom django.urls import is_valid_path\nfrom django.utils.http import escape_leading_slashes\n\nclass CommonMiddleware(MiddlewareMixin):\n    \"\"\"\n    \"Common\" middleware for taking care of some basic operations:\n\n        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS\n\n        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,\n          append missing slashes and/or prepends missing \"www.\"s.\n\n            - If APPEND_SLASH is set and the initial URL doesn't end with a\n              slash, and it is not found in urlpatterns, form a new URL by\n              appending a slash at the end. If this new URL is found in\n              urlpatterns, return an HTTP redirect to this new URL; otherwise\n              process the initial URL as usual.\n\n          This behavior can be customized by subclassing CommonMiddleware and\n          overriding the response_redirect_class attribute.\n    \"\"\"\n\n    response_redirect_class = HttpResponsePermanentRedirect\n\n    def process_request(self, request):\n        \"\"\"\n        Check for denied User-Agents and rewrite the URL based on\n        settings.APPEND_SLASH and settings.PREPEND_WWW\n        \"\"\"\n\n        # Check for denied User-Agents\n        user_agent = request.META.get(\"HTTP_USER_AGENT\")\n        if user_agent is not None:\n            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:\n                if user_agent_regex.search(user_agent):\n                    raise PermissionDenied(\"Forbidden user agent\")\n\n        # Check for a redirect based on settings.PREPEND_WWW\n        host = request.get_host()\n\n        if settings.PREPEND_WWW and host and not host.startswith(\"www.\"):\n            # Check if we also need to append a slash so we can do it all\n            # with a single redirect. (This check may be somewhat expensive,\n            # so we only do it if we already know we're sending a redirect,\n            # or in process_response if we get a 404.)\n            if self.should_redirect_with_slash(request):\n                path = self.get_full_path_with_slash(request)\n            else:\n                path = request.get_full_path()\n\n            return self.response_redirect_class(f\"{request.scheme}://www.{host}{path}\")\n\n    def should_redirect_with_slash(self, request):\n        \"\"\"\n        Return True if settings.APPEND_SLASH is True and appending a slash to\n        the request path turns an invalid path into a valid one.\n        \"\"\"\n        if settings.APPEND_SLASH and not request.path_info.endswith(\"/\"):\n            urlconf = getattr(request, \"urlconf\", None)\n            if not is_valid_path(request.path_info, urlconf):\n                match = is_valid_path(\"%s/\" % request.path_info, urlconf)\n                if match:\n                    \n                    return getattr((match.func), \"should_append_slash\", True)\n        return False\n\n    def get_full_path_with_slash(self, request):\n        \"\"\"\n        Return the full path of the request with a trailing slash appended.\n\n        Raise a RuntimeError if settings.DEBUG is True and request.method is\n        DELETE, POST, PUT, or PATCH.\n        \"\"\"\n        new_path = request.get_full_path(force_append_slash=True)\n        # Prevent construction of scheme relative urls.\n        new_path = escape_leading_slashes(new_path)\n        if settings.DEBUG and request.method in (\"DELETE\", \"POST\", \"PUT\", \"PATCH\"):\n            raise RuntimeError(\n                \"You called this URL via %(method)s, but the URL doesn't end \"\n                \"in a slash and you have APPEND_SLASH set. Django can't \"\n                \"redirect to the slash URL while maintaining %(method)s data. \"\n                \"Change your form to point to %(url)s (note the trailing \"\n                \"slash), or set APPEND_SLASH=False in your Django settings.\"\n                % {\n                    \"method\": request.method,\n                    \"url\": request.get_host() + new_path,\n                }\n            )\n        return new_path\n\n    def process_response(self, request, response):\n        \"\"\"\n        When the status code of the response is 404, it may redirect to a path\n        with an appended slash if should_redirect_with_slash() returns True.\n        \"\"\"\n        # If the given URL is \"Not Found\", then check if we should redirect to\n        # a path with a slash appended.\n        if response.status_code == 404 and self.should_redirect_with_slash(request):\n            response = self.response_redirect_class(\n                self.get_full_path_with_slash(request)\n            )\n\n        # Add the Content-Length header to non-streaming responses if not\n        # already set.\n        if not response.streaming and not response.has_header(\"Content-Length\"):\n            response.headers[\"Content-Length\"] = str(len(response.content))\n\n        return response\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-28e307901b66fb6d", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "75049bf9a75ae21fefe02bf58a6a4d963965056d22315bc667dffe5485cad798", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 115, "local_path": "data-flow/inline-intermediate-variables/I12__django__CommonMiddleware__471be73f.py", "order": 12, "original_content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "parent_variant_id": "pyint-6a217d9b1744-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/middleware/common.py#L13-L117", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "CommonMiddleware", "variant_id": "pyint-a8e5471be73f-I12", "group_id": "py-28e307901b66fb6d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 335, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a746c7ff54c4-I13", "source": "import re\nfrom urllib.parse import urlsplit\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.mail import MailerDoesNotExist, mail_managers, mailers\nfrom django.http import HttpResponsePermanentRedirect\nfrom django.middleware import MiddlewareMixin\nfrom django.urls import is_valid_path\nfrom django.utils.http import escape_leading_slashes\n\nclass CommonMiddleware(MiddlewareMixin):\n    \"\"\"\n    \"Common\" middleware for taking care of some basic operations:\n\n        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS\n\n        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,\n          append missing slashes and/or prepends missing \"www.\"s.\n\n            - If APPEND_SLASH is set and the initial URL doesn't end with a\n              slash, and it is not found in urlpatterns, form a new URL by\n              appending a slash at the end. If this new URL is found in\n              urlpatterns, return an HTTP redirect to this new URL; otherwise\n              process the initial URL as usual.\n\n          This behavior can be customized by subclassing CommonMiddleware and\n          overriding the response_redirect_class attribute.\n    \"\"\"\n\n    response_redirect_class = HttpResponsePermanentRedirect\n\n    def process_request(self, request):\n        \"\"\"\n        Check for denied User-Agents and rewrite the URL based on\n        settings.APPEND_SLASH and settings.PREPEND_WWW\n        \"\"\"\n\n        # Check for denied User-Agents\n        user_agent = request.META.get(\"HTTP_USER_AGENT\")\n        if user_agent is not None:\n            loopIterator = __import__(\"builtins\").iter(settings.DISALLOWED_USER_AGENTS)\n            while True:\n                try:\n                    user_agent_regex = __import__(\"builtins\").next(loopIterator)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                if user_agent_regex.search(user_agent):\n                    raise PermissionDenied(\"Forbidden user agent\")\n\n        # Check for a redirect based on settings.PREPEND_WWW\n        host = request.get_host()\n\n        if settings.PREPEND_WWW and host and not host.startswith(\"www.\"):\n            # Check if we also need to append a slash so we can do it all\n            # with a single redirect. (This check may be somewhat expensive,\n            # so we only do it if we already know we're sending a redirect,\n            # or in process_response if we get a 404.)\n            if self.should_redirect_with_slash(request):\n                path = self.get_full_path_with_slash(request)\n            else:\n                path = request.get_full_path()\n\n            return self.response_redirect_class(f\"{request.scheme}://www.{host}{path}\")\n\n    def should_redirect_with_slash(self, request):\n        \"\"\"\n        Return True if settings.APPEND_SLASH is True and appending a slash to\n        the request path turns an invalid path into a valid one.\n        \"\"\"\n        if settings.APPEND_SLASH and not request.path_info.endswith(\"/\"):\n            urlconf = getattr(request, \"urlconf\", None)\n            if not is_valid_path(request.path_info, urlconf):\n                match = is_valid_path(\"%s/\" % request.path_info, urlconf)\n                if match:\n                    view = match.func\n                    return getattr(view, \"should_append_slash\", True)\n        return False\n\n    def get_full_path_with_slash(self, request):\n        \"\"\"\n        Return the full path of the request with a trailing slash appended.\n\n        Raise a RuntimeError if settings.DEBUG is True and request.method is\n        DELETE, POST, PUT, or PATCH.\n        \"\"\"\n        new_path = request.get_full_path(force_append_slash=True)\n        # Prevent construction of scheme relative urls.\n        new_path = escape_leading_slashes(new_path)\n        if settings.DEBUG and request.method in (\"DELETE\", \"POST\", \"PUT\", \"PATCH\"):\n            raise RuntimeError(\n                \"You called this URL via %(method)s, but the URL doesn't end \"\n                \"in a slash and you have APPEND_SLASH set. Django can't \"\n                \"redirect to the slash URL while maintaining %(method)s data. \"\n                \"Change your form to point to %(url)s (note the trailing \"\n                \"slash), or set APPEND_SLASH=False in your Django settings.\"\n                % {\n                    \"method\": request.method,\n                    \"url\": request.get_host() + new_path,\n                }\n            )\n        return new_path\n\n    def process_response(self, request, response):\n        \"\"\"\n        When the status code of the response is 404, it may redirect to a path\n        with an appended slash if should_redirect_with_slash() returns True.\n        \"\"\"\n        # If the given URL is \"Not Found\", then check if we should redirect to\n        # a path with a slash appended.\n        if response.status_code == 404 and self.should_redirect_with_slash(request):\n            response = self.response_redirect_class(\n                self.get_full_path_with_slash(request)\n            )\n\n        # Add the Content-Length header to non-streaming responses if not\n        # already set.\n        if not response.streaming and not response.has_header(\"Content-Length\"):\n            response.headers[\"Content-Length\"] = str(len(response.content))\n\n        return response\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-28e307901b66fb6d", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ba8dd4ca953a6d3e1b1b0b5767e2a9381320a8d718fdf326c979c37f88af2fc2", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 120, "local_path": "control-flow/lower-for-to-while/I13__django__CommonMiddleware__c7ff54c4.py", "order": 13, "original_content_sha256": "49ab5d0804f13836c97b32dafa512bb4f26988f0244bf5dce45c85256cc7745b", "parent_variant_id": "pyint-6a217d9b1744-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/middleware/common.py#L13-L117", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 1, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 1, "synchronous_for_loops_eligible": 1, "synchronous_for_loops_found": 1}, "unit_kind": "class", "unit_name": "CommonMiddleware", "variant_id": "pyint-a746c7ff54c4-I13", "group_id": "py-28e307901b66fb6d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 336, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b455386c2ff0-SRC", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n\n    response: Response | None\n    request: Request | PreparedRequest | None\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        response: Response | None = kwargs.pop(\"response\", None)\n        self.response = response\n        self.request = kwargs.pop(\"request\", None)\n        if response is not None and not self.request and hasattr(response, \"request\"):\n            self.request = response.request\n        super().__init__(*args, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-2ca1d365b1be77ec", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 21, "local_path": "source-original/SRC__requests__RequestException__386c2ff0.py", "order": 0, "original_content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L20-L35", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "RequestException", "variant_id": "pyint-b455386c2ff0-SRC", "group_id": "py-2ca1d365b1be77ec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 869, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2ce58e6823cd-I01", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass RequestException(IOError):\n    \n\n    response: Response | None\n    request: Request | PreparedRequest | None\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \n        response: Response | None = kwargs.pop(\"response\", None)\n        self.response = response\n        self.request = kwargs.pop(\"request\", None)\n        if response is not None and not self.request and hasattr(response, \"request\"):\n            self.request = response.request\n        super().__init__(*args, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-2ca1d365b1be77ec", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "10bd2a4e87710c2c58af42fff4a5dcd9c15f347c8247ef119a61a740052cb106", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 19, "local_path": "comments/remove-comments/I01__requests__RequestException__8e6823cd.py", "order": 1, "original_content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "parent_variant_id": "pyint-b455386c2ff0-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L20-L35", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 162, "comments_removed": 2, "docstrings_removed": 2, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "RequestException", "variant_id": "pyint-2ce58e6823cd-I01", "group_id": "py-2ca1d365b1be77ec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 870, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-90e41ea55cce-I02", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n\n    response: Response | None\n    request: Request | PreparedRequest | None\n\n    def __init__(self, *arg: Any, **kwa: Any) -> None:\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        res: Response | None = kwa.pop(\"response\", None)\n        self.response = res\n        self.request = kwa.pop(\"request\", None)\n        if res is not None and not self.request and hasattr(res, \"request\"):\n            self.request = res.request\n        super().__init__(*arg, **kwa)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-2ca1d365b1be77ec", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "9fbc6164afe866e283c396713f89312348eedf96c71305b15a0c29a1cd7a6254", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 21, "local_path": "identifiers/shorten-identifiers/I02__requests__RequestException__1ea55cce.py", "order": 2, "original_content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "parent_variant_id": "pyint-b455386c2ff0-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L20-L35", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 11, "identifiers_declared": 3}, "unit_kind": "class", "unit_name": "RequestException", "variant_id": "pyint-90e41ea55cce-I02", "group_id": "py-2ca1d365b1be77ec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 871, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fd8f9aed543a-I03", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n\n    response: Response | None\n    request: Request | PreparedRequest | None\n\n    def __init__(self, *flag: Any, **region: Any) -> None:\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        nextItem: Response | None = region.pop(\"response\", None)\n        self.response = nextItem\n        self.request = region.pop(\"request\", None)\n        if nextItem is not None and not self.request and hasattr(nextItem, \"request\"):\n            self.request = nextItem.request\n        super().__init__(*flag, **region)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-2ca1d365b1be77ec", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b67c463043f0153715a3d69400d77bc5a95ebb01d78ee2f4926b6e580c902d82", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 21, "local_path": "identifiers/mislead-identifiers/I03__requests__RequestException__9aed543a.py", "order": 3, "original_content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "parent_variant_id": "pyint-b455386c2ff0-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L20-L35", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 11, "identifiers_declared": 3, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 3, "local_random_pool_selections": 3, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "RequestException", "variant_id": "pyint-fd8f9aed543a-I03", "group_id": "py-2ca1d365b1be77ec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 872, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4f7dce077535-I04", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n\n    response: Response | None\n    request: Request | PreparedRequest | None\n\n    def __init__(self, *a: Any, **b: Any) -> None:\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        c: Response | None = b.pop(\"response\", None)\n        self.response = c\n        self.request = b.pop(\"request\", None)\n        if c is not None and not self.request and hasattr(c, \"request\"):\n            self.request = c.request\n        super().__init__(*a, **b)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-2ca1d365b1be77ec", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "3c0cf91592ee7255be0621904a5017305200363808266fb7144f3c458c4cf419", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 21, "local_path": "identifiers/garble-identifiers/I04__requests__RequestException__ce077535.py", "order": 4, "original_content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "parent_variant_id": "pyint-b455386c2ff0-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L20-L35", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 11, "identifiers_declared": 3}, "unit_kind": "class", "unit_name": "RequestException", "variant_id": "pyint-4f7dce077535-I04", "group_id": "py-2ca1d365b1be77ec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 873, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0ea5d5e1b756-I05", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n\n    response: Response | None\n    request: Request | PreparedRequest | None\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        response: Response | None = kwargs.pop(\"response\", None)\n        self.response = response\n        self.request = kwargs.pop(\"request\", None)\n        if response is not None and not self.request and hasattr(response, \"request\"):\n            self.request = response.request\n        super().__init__(*args, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-2ca1d365b1be77ec", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 21, "local_path": "expressions/encode-integer-literals/I05__requests__RequestException__d5e1b756.py", "order": 5, "original_content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "parent_variant_id": "pyint-b455386c2ff0-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L20-L35", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "RequestException", "variant_id": "pyint-0ea5d5e1b756-I05", "group_id": "py-2ca1d365b1be77ec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 874, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ef3feb38ab65-I06", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n\n    response: Response | None\n    request: Request | PreparedRequest | None\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        response: Response | None = kwargs.pop(\"response\", None)\n        self.response = response\n        self.request = kwargs.pop(\"request\", None)\n        if not (response is not None and not self.request and hasattr(response, \"request\")):\n            pass\n        else:\n            self.request = response.request\n        super().__init__(*args, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-2ca1d365b1be77ec", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "551f846d06326a12ca0663b5abeed4dd9cae0cc0ecc6334fd4308f80dd642f79", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 23, "local_path": "expressions/invert-conditions/I06__requests__RequestException__eb38ab65.py", "order": 6, "original_content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "parent_variant_id": "pyint-b455386c2ff0-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L20-L35", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "RequestException", "variant_id": "pyint-ef3feb38ab65-I06", "group_id": "py-2ca1d365b1be77ec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 875, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-84adf6f52215-I07", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n\n    response: Response | None\n    request: Request | PreparedRequest | None\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        if ((0x4a3d ^ 0x4a3d) != 0):\n            raise AssertionError()\n        response: Response | None = kwargs.pop(\"response\", None)\n        self.response = response\n        self.request = kwargs.pop(\"request\", None)\n        if response is not None and not self.request and hasattr(response, \"request\"):\n            self.request = response.request\n        super().__init__(*args, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-2ca1d365b1be77ec", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "ff6ea6bcbe5c45534780df2e593128d89af2f45bbedcd760837d97b038a7dbdf", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 23, "local_path": "code-injection/insert-dead-branches/I07__requests__RequestException__f6f52215.py", "order": 7, "original_content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "parent_variant_id": "pyint-b455386c2ff0-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L20-L35", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "RequestException", "variant_id": "pyint-84adf6f52215-I07", "group_id": "py-2ca1d365b1be77ec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 876, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f54966ffca16-I08", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n\n    response: Response | None\n    request: Request | PreparedRequest | None\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        response: Response | None = kwargs.pop(\"response\", None)\n        self.response = response\n        self.request = kwargs.pop(\"request\", None)\n        if response is not None and not self.request and hasattr(response, \"request\"):\n            self.request = response.request\n        super().__init__(*args, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-2ca1d365b1be77ec", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "b5e942257fc0c600da0b343fb61fece778bb1d5974256dc20258a1b7f56683be", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 26, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__RequestException__66ffca16.py", "order": 8, "original_content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "parent_variant_id": "pyint-b455386c2ff0-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L20-L35", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "RequestException", "variant_id": "pyint-f54966ffca16-I08", "group_id": "py-2ca1d365b1be77ec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 877, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bdd906268176-I09", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n\n    response: Response | None\n    request: Request | PreparedRequest | None\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        lI0O_3e71d5ce, lI0O_e8a82473 = 0, 0\n        while lI0O_e8a82473 < 2:\n            lI0O_3e71d5ce ^= (lI0O_e8a82473 << 1) ^ 0x8\n            lI0O_e8a82473 += 1\n        lI0O_3e71d5ce ^= lI0O_3e71d5ce\n        response: Response | None = kwargs.pop(\"response\", None)\n        self.response = response\n        self.request = kwargs.pop(\"request\", None)\n        if response is not None and not self.request and hasattr(response, \"request\"):\n            self.request = response.request\n        super().__init__(*args, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-2ca1d365b1be77ec", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "dbd3c55793028b1e0a8fc6ffae277518ef9148b0b6f72e01c0df7c0de732a028", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 26, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__RequestException__06268176.py", "order": 9, "original_content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "parent_variant_id": "pyint-b455386c2ff0-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L20-L35", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 2}, "unit_kind": "class", "unit_name": "RequestException", "variant_id": "pyint-bdd906268176-I09", "group_id": "py-2ca1d365b1be77ec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 878, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-62c781e9bddf-I10", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n    response: Response | None\n    request: Request | PreparedRequest | None\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        response: Response | None = kwargs.pop(\"response\", None)\n        self.response = response\n        self.request = kwargs.pop(\"request\", None)\n        if response is not None and not self.request and hasattr(response, \"request\"):\n            self.request = response.request\n        super().__init__(*args, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-2ca1d365b1be77ec", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "a6e274c69f3f0131e05461bb766b2b19701df939a14c2b28c001a3c082bfa934", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 20, "local_path": "layout/partially-compact-layout/I10__requests__RequestException__81e9bddf.py", "order": 10, "original_content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "parent_variant_id": "pyint-b455386c2ff0-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L20-L35", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 3, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "RequestException", "variant_id": "pyint-62c781e9bddf-I10", "group_id": "py-2ca1d365b1be77ec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 879, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-705a806dccfb-I11", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n\n    response: Response | None\n    request: Request | PreparedRequest | None\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        response: Response | None = kwargs.pop(\"response\", None)\n        self.response = response\n        self.request = kwargs.pop(\"request\", None)\n        if response is not None and not self.request and hasattr(response, \"request\"):\n            self.request = response.request\n        super().__init__(*args, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-2ca1d365b1be77ec", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 21, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__RequestException__806dccfb.py", "order": 11, "original_content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "parent_variant_id": "pyint-b455386c2ff0-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L20-L35", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "RequestException", "variant_id": "pyint-705a806dccfb-I11", "group_id": "py-2ca1d365b1be77ec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 880, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bf9d2692ae36-I12", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n\n    response: Response | None\n    request: Request | PreparedRequest | None\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        response: Response | None = kwargs.pop(\"response\", None)\n        self.response = response\n        self.request = kwargs.pop(\"request\", None)\n        if response is not None and not self.request and hasattr(response, \"request\"):\n            self.request = response.request\n        super().__init__(*args, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-2ca1d365b1be77ec", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 21, "local_path": "data-flow/inline-intermediate-variables/I12__requests__RequestException__2692ae36.py", "order": 12, "original_content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "parent_variant_id": "pyint-b455386c2ff0-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L20-L35", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "RequestException", "variant_id": "pyint-bf9d2692ae36-I12", "group_id": "py-2ca1d365b1be77ec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 881, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-63a53494033c-I13", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n\n    response: Response | None\n    request: Request | PreparedRequest | None\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        response: Response | None = kwargs.pop(\"response\", None)\n        self.response = response\n        self.request = kwargs.pop(\"request\", None)\n        if response is not None and not self.request and hasattr(response, \"request\"):\n            self.request = response.request\n        super().__init__(*args, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-2ca1d365b1be77ec", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 21, "local_path": "control-flow/lower-for-to-while/I13__requests__RequestException__3494033c.py", "order": 13, "original_content_sha256": "a68108c47dc3b2c53c2e931883e43280ade3b6251d30aea4c9db45572fbfff12", "parent_variant_id": "pyint-b455386c2ff0-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L20-L35", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "RequestException", "variant_id": "pyint-63a53494033c-I13", "group_id": "py-2ca1d365b1be77ec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 882, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ed645912e715-SRC", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\n@attrs(slots=True, unsafe_hash=True)\nclass _AndValidator:\n    \"\"\"\n    Compose many validators to a single one.\n    \"\"\"\n\n    _validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        for v in self._validators:\n            v(inst, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-2ffe2fbcf2c6f31a", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 40, "local_path": "source-original/SRC__attrs___AndValidator__5912e715.py", "order": 0, "original_content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3369-L3378", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_AndValidator", "variant_id": "pyint-ed645912e715-SRC", "group_id": "py-2ffe2fbcf2c6f31a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1177, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-acd053fcb802-I01", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\n@attrs(slots=True, unsafe_hash=True)\nclass _AndValidator:\n    \n\n    _validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        for v in self._validators:\n            v(inst, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-2ffe2fbcf2c6f31a", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "286926d1acec9940f9228be8931fa3240abd15103736b947dacfa7bdf9d93359", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 38, "local_path": "comments/remove-comments/I01__attrs___AndValidator__53fcb802.py", "order": 1, "original_content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "parent_variant_id": "pyint-ed645912e715-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3369-L3378", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 56, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "_AndValidator", "variant_id": "pyint-acd053fcb802-I01", "group_id": "py-2ffe2fbcf2c6f31a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1178, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-633d91296807-I02", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\n@attrs(slots=True, unsafe_hash=True)\nclass _AndValidator:\n    \"\"\"\n    Compose many validators to a single one.\n    \"\"\"\n\n    _validators = attrib()\n\n    def __call__(self, ins, att, val):\n        for v2 in self._validators:\n            v2(ins, att, val)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-2ffe2fbcf2c6f31a", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "73936cb4e18b86d0194746d5f3f45c93e026bdaa445e7d983eccc9b8fa9338b8", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 40, "local_path": "identifiers/shorten-identifiers/I02__attrs___AndValidator__91296807.py", "order": 2, "original_content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "parent_variant_id": "pyint-ed645912e715-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3369-L3378", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_AndValidator", "variant_id": "pyint-633d91296807-I02", "group_id": "py-2ffe2fbcf2c6f31a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1179, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3768911b1a4b-I03", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\n@attrs(slots=True, unsafe_hash=True)\nclass _AndValidator:\n    \"\"\"\n    Compose many validators to a single one.\n    \"\"\"\n\n    _validators = attrib()\n\n    def __call__(self, flag, item, index):\n        for age in self._validators:\n            age(flag, item, index)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-2ffe2fbcf2c6f31a", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "4c89c742f4997852b83754718c36bd1c37d3448434d3068610999392648e527d", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 40, "local_path": "identifiers/mislead-identifiers/I03__attrs___AndValidator__911b1a4b.py", "order": 3, "original_content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "parent_variant_id": "pyint-ed645912e715-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3369-L3378", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 3, "local_random_pool_selections": 4, "local_total_length_difference": 2, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_AndValidator", "variant_id": "pyint-3768911b1a4b-I03", "group_id": "py-2ffe2fbcf2c6f31a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1180, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-286ac8ac564a-I04", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\n@attrs(slots=True, unsafe_hash=True)\nclass _AndValidator:\n    \"\"\"\n    Compose many validators to a single one.\n    \"\"\"\n\n    _validators = attrib()\n\n    def __call__(self, a, b, c):\n        for d in self._validators:\n            d(a, b, c)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-2ffe2fbcf2c6f31a", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "86a62b5b15bbf2d2c25c83883dd8df6c00c8a49c262f5f07c50162f8ed6ed202", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 40, "local_path": "identifiers/garble-identifiers/I04__attrs___AndValidator__c8ac564a.py", "order": 4, "original_content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "parent_variant_id": "pyint-ed645912e715-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3369-L3378", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_AndValidator", "variant_id": "pyint-286ac8ac564a-I04", "group_id": "py-2ffe2fbcf2c6f31a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1181, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-42eab0f8a7e8-I05", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\n@attrs(slots=True, unsafe_hash=True)\nclass _AndValidator:\n    \"\"\"\n    Compose many validators to a single one.\n    \"\"\"\n\n    _validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        for v in self._validators:\n            v(inst, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-2ffe2fbcf2c6f31a", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 40, "local_path": "expressions/encode-integer-literals/I05__attrs___AndValidator__b0f8a7e8.py", "order": 5, "original_content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "parent_variant_id": "pyint-ed645912e715-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3369-L3378", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "_AndValidator", "variant_id": "pyint-42eab0f8a7e8-I05", "group_id": "py-2ffe2fbcf2c6f31a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1182, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-01fa3dbc4d7e-I06", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\n@attrs(slots=True, unsafe_hash=True)\nclass _AndValidator:\n    \"\"\"\n    Compose many validators to a single one.\n    \"\"\"\n\n    _validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        for v in self._validators:\n            v(inst, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-2ffe2fbcf2c6f31a", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 40, "local_path": "expressions/invert-conditions/I06__attrs___AndValidator__3dbc4d7e.py", "order": 6, "original_content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "parent_variant_id": "pyint-ed645912e715-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3369-L3378", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "_AndValidator", "variant_id": "pyint-01fa3dbc4d7e-I06", "group_id": "py-2ffe2fbcf2c6f31a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1183, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3996be1ab603-I07", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\n@attrs(slots=True, unsafe_hash=True)\nclass _AndValidator:\n    \"\"\"\n    Compose many validators to a single one.\n    \"\"\"\n\n    _validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        if ((0xc435 ^ 0xc435) != 0):\n            raise AssertionError()\n        for v in self._validators:\n            v(inst, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-2ffe2fbcf2c6f31a", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "76d8a0309071cd8de337134addf5787e34ea8a4120d2dacc20ef6235ebc99f87", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 42, "local_path": "code-injection/insert-dead-branches/I07__attrs___AndValidator__be1ab603.py", "order": 7, "original_content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "parent_variant_id": "pyint-ed645912e715-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3369-L3378", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "_AndValidator", "variant_id": "pyint-3996be1ab603-I07", "group_id": "py-2ffe2fbcf2c6f31a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1184, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-31a4c5bab686-I08", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\n@attrs(slots=True, unsafe_hash=True)\nclass _AndValidator:\n    \"\"\"\n    Compose many validators to a single one.\n    \"\"\"\n\n    _validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        first_score = 72\n        second_score = 85\n        if first_score > second_score:\n            higher_score = first_score\n        else:\n            higher_score = second_score\n        for v in self._validators:\n            v(inst, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-2ffe2fbcf2c6f31a", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "17b6393e4fb6bfe9e7d6e2a89a4477ffa511151a63c2a04124d8037e61258ae3", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 46, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___AndValidator__c5bab686.py", "order": 8, "original_content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "parent_variant_id": "pyint-ed645912e715-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3369-L3378", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 3}, "unit_kind": "class", "unit_name": "_AndValidator", "variant_id": "pyint-31a4c5bab686-I08", "group_id": "py-2ffe2fbcf2c6f31a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1185, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c8b5ab75965e-I09", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\n@attrs(slots=True, unsafe_hash=True)\nclass _AndValidator:\n    \"\"\"\n    Compose many validators to a single one.\n    \"\"\"\n\n    _validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        lI0O_42fe8ad7, lI0O_5d1cd832 = 0, 0\n        while lI0O_5d1cd832 < 2:\n            lI0O_42fe8ad7 ^= (lI0O_5d1cd832 << 1) ^ 0x5\n            lI0O_5d1cd832 += 1\n        lI0O_42fe8ad7 ^= lI0O_42fe8ad7\n        for v in self._validators:\n            v(inst, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-2ffe2fbcf2c6f31a", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "c742d76f1ec9cf165efc31f2a1f540b9c4bcaad67c15d1fe176ddc6dc39defa3", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 45, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___AndValidator__ab75965e.py", "order": 9, "original_content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "parent_variant_id": "pyint-ed645912e715-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3369-L3378", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 2}, "unit_kind": "class", "unit_name": "_AndValidator", "variant_id": "pyint-c8b5ab75965e-I09", "group_id": "py-2ffe2fbcf2c6f31a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1186, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ff9bbb807d82-I10", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,     _lazy_is_generator,     get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,     FrozenInstanceError,\n    NotAnAttrsClassError,     UnannotatedAttributeError, )\n\n@attrs(slots=True, unsafe_hash=True)\nclass _AndValidator:\n    \"\"\"\n    Compose many validators to a single one.\n    \"\"\"\n\n    _validators = attrib()\n    def __call__(self, inst, attr, value):\n        for v in self._validators:\n            v(inst, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-2ffe2fbcf2c6f31a", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "5459b4805b0f7800871867f8c07744ad3455ba939c0e56ac9878a040fcd18f43", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 34, "local_path": "layout/partially-compact-layout/I10__attrs___AndValidator__bb807d82.py", "order": 10, "original_content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "parent_variant_id": "pyint-ed645912e715-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3369-L3378", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 15, "line_break_groups_removed": 6, "line_breaks_removed": 6, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "_AndValidator", "variant_id": "pyint-ff9bbb807d82-I10", "group_id": "py-2ffe2fbcf2c6f31a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1187, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4dc6565635fd-I11", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\n@attrs(slots=True, unsafe_hash=True)\nclass _AndValidator:\n    \"\"\"\n    Compose many validators to a single one.\n    \"\"\"\n\n    _validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        for v in self._validators:\n            v(inst, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-2ffe2fbcf2c6f31a", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 40, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___AndValidator__565635fd.py", "order": 11, "original_content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "parent_variant_id": "pyint-ed645912e715-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3369-L3378", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "_AndValidator", "variant_id": "pyint-4dc6565635fd-I11", "group_id": "py-2ffe2fbcf2c6f31a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1188, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-916070f65c16-I12", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\n@attrs(slots=True, unsafe_hash=True)\nclass _AndValidator:\n    \"\"\"\n    Compose many validators to a single one.\n    \"\"\"\n\n    _validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        for v in self._validators:\n            v(inst, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-2ffe2fbcf2c6f31a", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 40, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___AndValidator__70f65c16.py", "order": 12, "original_content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "parent_variant_id": "pyint-ed645912e715-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3369-L3378", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_AndValidator", "variant_id": "pyint-916070f65c16-I12", "group_id": "py-2ffe2fbcf2c6f31a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1189, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-30be819b3f32-I13", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\n@attrs(slots=True, unsafe_hash=True)\nclass _AndValidator:\n    \"\"\"\n    Compose many validators to a single one.\n    \"\"\"\n\n    _validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        loopIterator = __import__(\"builtins\").iter(self._validators)\n        while True:\n            try:\n                v = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            v(inst, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-2ffe2fbcf2c6f31a", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a112781af25293fcf886d9e2ab2a873569cfde89b0f3b199fb3089fbda7ba0f7", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 45, "local_path": "control-flow/lower-for-to-while/I13__attrs___AndValidator__819b3f32.py", "order": 13, "original_content_sha256": "0d6ba8e8e731718936071069c203c1ce9e557bb5c3a8f2ed6ab2531772d3a0cb", "parent_variant_id": "pyint-ed645912e715-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3369-L3378", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 1, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 1, "synchronous_for_loops_eligible": 1, "synchronous_for_loops_found": 1}, "unit_kind": "class", "unit_name": "_AndValidator", "variant_id": "pyint-30be819b3f32-I13", "group_id": "py-2ffe2fbcf2c6f31a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1190, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f8123eee81c6-SRC", "source": "import email.message\nimport email.policy\nimport mimetypes\nimport warnings\nfrom collections import namedtuple\nfrom datetime import datetime, timezone\nfrom email import charset as Charset\nfrom email import generator\nfrom email.errors import HeaderParseError\nfrom email.header import Header\nfrom email.headerregistry import Address, AddressHeader, parser\nfrom email.mime.base import MIMEBase\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, getaddresses, make_msgid\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom django.conf import settings\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    deprecate_posargs,\n    warn_about_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\nfrom .deprecation import (\n    CONNECTION_ARG_WARNING,\n    FAIL_SILENTLY_ARG_WARNING,\n    report_using_incompatibility,\n)\n\nclass SafeMIMEMultipart(MIMEMixin, MIMEMultipart):\n    def __init__(\n        self, _subtype=\"mixed\", boundary=None, _subparts=None, encoding=None, **_params\n    ):\n        self.encoding = encoding\n        MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params)\n\n    def __setitem__(self, name, val):\n        name, val = forbid_multi_line_headers(name, val, self.encoding)\n        MIMEMultipart.__setitem__(self, name, val)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-3029c6a6c12cd34d", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 43, "local_path": "source-original/SRC__django__SafeMIMEMultipart__3eee81c6.py", "order": 0, "original_content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/mail/message.py#L224-L233", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "SafeMIMEMultipart", "variant_id": "pyint-f8123eee81c6-SRC", "group_id": "py-3029c6a6c12cd34d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 155, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f3f6521b35ce-I01", "source": "import email.message\nimport email.policy\nimport mimetypes\nimport warnings\nfrom collections import namedtuple\nfrom datetime import datetime, timezone\nfrom email import charset as Charset\nfrom email import generator\nfrom email.errors import HeaderParseError\nfrom email.header import Header\nfrom email.headerregistry import Address, AddressHeader, parser\nfrom email.mime.base import MIMEBase\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, getaddresses, make_msgid\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom django.conf import settings\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    deprecate_posargs,\n    warn_about_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\nfrom .deprecation import (\n    CONNECTION_ARG_WARNING,\n    FAIL_SILENTLY_ARG_WARNING,\n    report_using_incompatibility,\n)\n\nclass SafeMIMEMultipart(MIMEMixin, MIMEMultipart):\n    def __init__(\n        self, _subtype=\"mixed\", boundary=None, _subparts=None, encoding=None, **_params\n    ):\n        self.encoding = encoding\n        MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params)\n\n    def __setitem__(self, name, val):\n        name, val = forbid_multi_line_headers(name, val, self.encoding)\n        MIMEMultipart.__setitem__(self, name, val)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-3029c6a6c12cd34d", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 43, "local_path": "comments/remove-comments/I01__django__SafeMIMEMultipart__521b35ce.py", "order": 1, "original_content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "parent_variant_id": "pyint-f8123eee81c6-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/mail/message.py#L224-L233", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "SafeMIMEMultipart", "variant_id": "pyint-f3f6521b35ce-I01", "group_id": "py-3029c6a6c12cd34d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 156, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2624b3b97df7-I02", "source": "import email.message\nimport email.policy\nimport mimetypes\nimport warnings\nfrom collections import namedtuple\nfrom datetime import datetime, timezone\nfrom email import charset as Charset\nfrom email import generator\nfrom email.errors import HeaderParseError\nfrom email.header import Header\nfrom email.headerregistry import Address, AddressHeader, parser\nfrom email.mime.base import MIMEBase\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, getaddresses, make_msgid\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom django.conf import settings\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    deprecate_posargs,\n    warn_about_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\nfrom .deprecation import (\n    CONNECTION_ARG_WARNING,\n    FAIL_SILENTLY_ARG_WARNING,\n    report_using_incompatibility,\n)\n\nclass SafeMIMEMultipart(MIMEMixin, MIMEMultipart):\n    def __init__(\n        self, sub=\"mixed\", bou=None, sub2=None, enc=None, **par\n    ):\n        self.encoding = enc\n        MIMEMultipart.__init__(self, sub, bou, sub2, **par)\n\n    def __setitem__(self, nam, val2):\n        nam, val2 = forbid_multi_line_headers(nam, val2, self.encoding)\n        MIMEMultipart.__setitem__(self, nam, val2)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-3029c6a6c12cd34d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "76ce0a7378bb93975bbe1ec14ae66c75431f485b105828dbac5e8286e606e687", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 43, "local_path": "identifiers/shorten-identifiers/I02__django__SafeMIMEMultipart__b3b97df7.py", "order": 2, "original_content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "parent_variant_id": "pyint-f8123eee81c6-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/mail/message.py#L224-L233", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 18, "identifiers_declared": 7}, "unit_kind": "class", "unit_name": "SafeMIMEMultipart", "variant_id": "pyint-2624b3b97df7-I02", "group_id": "py-3029c6a6c12cd34d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 157, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-66cdff1b8679-I03", "source": "import email.message\nimport email.policy\nimport mimetypes\nimport warnings\nfrom collections import namedtuple\nfrom datetime import datetime, timezone\nfrom email import charset as Charset\nfrom email import generator\nfrom email.errors import HeaderParseError\nfrom email.header import Header\nfrom email.headerregistry import Address, AddressHeader, parser\nfrom email.mime.base import MIMEBase\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, getaddresses, make_msgid\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom django.conf import settings\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    deprecate_posargs,\n    warn_about_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\nfrom .deprecation import (\n    CONNECTION_ARG_WARNING,\n    FAIL_SILENTLY_ARG_WARNING,\n    report_using_incompatibility,\n)\n\nclass SafeMIMEMultipart(MIMEMixin, MIMEMultipart):\n    def __init__(\n        self, customer=\"mixed\", nextData=None, timestamp=None, schedule=None, **profile\n    ):\n        self.encoding = schedule\n        MIMEMultipart.__init__(self, customer, nextData, timestamp, **profile)\n\n    def __setitem__(self, user, map):\n        user, map = forbid_multi_line_headers(user, map, self.encoding)\n        MIMEMultipart.__setitem__(self, user, map)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-3029c6a6c12cd34d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "0a54845b9989d2c22cad060245db9c42ecba12ba0d05b27520a63cf033b87417", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 43, "local_path": "identifiers/mislead-identifiers/I03__django__SafeMIMEMultipart__ff1b8679.py", "order": 3, "original_content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "parent_variant_id": "pyint-f8123eee81c6-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/mail/message.py#L224-L233", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 18, "identifiers_declared": 7, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 7, "local_random_pool_selections": 7, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "SafeMIMEMultipart", "variant_id": "pyint-66cdff1b8679-I03", "group_id": "py-3029c6a6c12cd34d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 158, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-36a45b12abc2-I04", "source": "import email.message\nimport email.policy\nimport mimetypes\nimport warnings\nfrom collections import namedtuple\nfrom datetime import datetime, timezone\nfrom email import charset as Charset\nfrom email import generator\nfrom email.errors import HeaderParseError\nfrom email.header import Header\nfrom email.headerregistry import Address, AddressHeader, parser\nfrom email.mime.base import MIMEBase\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, getaddresses, make_msgid\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom django.conf import settings\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    deprecate_posargs,\n    warn_about_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\nfrom .deprecation import (\n    CONNECTION_ARG_WARNING,\n    FAIL_SILENTLY_ARG_WARNING,\n    report_using_incompatibility,\n)\n\nclass SafeMIMEMultipart(MIMEMixin, MIMEMultipart):\n    def __init__(\n        self, a=\"mixed\", b=None, c=None, d=None, **e\n    ):\n        self.encoding = d\n        MIMEMultipart.__init__(self, a, b, c, **e)\n\n    def __setitem__(self, f, g):\n        f, g = forbid_multi_line_headers(f, g, self.encoding)\n        MIMEMultipart.__setitem__(self, f, g)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-3029c6a6c12cd34d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "0bd2ac36db70651f4f63da08817f5f2cfa8dbf5b218ab445765f7373fc51b1d8", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 43, "local_path": "identifiers/garble-identifiers/I04__django__SafeMIMEMultipart__5b12abc2.py", "order": 4, "original_content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "parent_variant_id": "pyint-f8123eee81c6-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/mail/message.py#L224-L233", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 18, "identifiers_declared": 7}, "unit_kind": "class", "unit_name": "SafeMIMEMultipart", "variant_id": "pyint-36a45b12abc2-I04", "group_id": "py-3029c6a6c12cd34d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 159, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0cd497ec903a-I05", "source": "import email.message\nimport email.policy\nimport mimetypes\nimport warnings\nfrom collections import namedtuple\nfrom datetime import datetime, timezone\nfrom email import charset as Charset\nfrom email import generator\nfrom email.errors import HeaderParseError\nfrom email.header import Header\nfrom email.headerregistry import Address, AddressHeader, parser\nfrom email.mime.base import MIMEBase\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, getaddresses, make_msgid\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom django.conf import settings\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    deprecate_posargs,\n    warn_about_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\nfrom .deprecation import (\n    CONNECTION_ARG_WARNING,\n    FAIL_SILENTLY_ARG_WARNING,\n    report_using_incompatibility,\n)\n\nclass SafeMIMEMultipart(MIMEMixin, MIMEMultipart):\n    def __init__(\n        self, _subtype=\"mixed\", boundary=None, _subparts=None, encoding=None, **_params\n    ):\n        self.encoding = encoding\n        MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params)\n\n    def __setitem__(self, name, val):\n        name, val = forbid_multi_line_headers(name, val, self.encoding)\n        MIMEMultipart.__setitem__(self, name, val)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-3029c6a6c12cd34d", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 43, "local_path": "expressions/encode-integer-literals/I05__django__SafeMIMEMultipart__97ec903a.py", "order": 5, "original_content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "parent_variant_id": "pyint-f8123eee81c6-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/mail/message.py#L224-L233", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "SafeMIMEMultipart", "variant_id": "pyint-0cd497ec903a-I05", "group_id": "py-3029c6a6c12cd34d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 160, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-590439e1feca-I06", "source": "import email.message\nimport email.policy\nimport mimetypes\nimport warnings\nfrom collections import namedtuple\nfrom datetime import datetime, timezone\nfrom email import charset as Charset\nfrom email import generator\nfrom email.errors import HeaderParseError\nfrom email.header import Header\nfrom email.headerregistry import Address, AddressHeader, parser\nfrom email.mime.base import MIMEBase\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, getaddresses, make_msgid\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom django.conf import settings\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    deprecate_posargs,\n    warn_about_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\nfrom .deprecation import (\n    CONNECTION_ARG_WARNING,\n    FAIL_SILENTLY_ARG_WARNING,\n    report_using_incompatibility,\n)\n\nclass SafeMIMEMultipart(MIMEMixin, MIMEMultipart):\n    def __init__(\n        self, _subtype=\"mixed\", boundary=None, _subparts=None, encoding=None, **_params\n    ):\n        self.encoding = encoding\n        MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params)\n\n    def __setitem__(self, name, val):\n        name, val = forbid_multi_line_headers(name, val, self.encoding)\n        MIMEMultipart.__setitem__(self, name, val)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-3029c6a6c12cd34d", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 43, "local_path": "expressions/invert-conditions/I06__django__SafeMIMEMultipart__39e1feca.py", "order": 6, "original_content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "parent_variant_id": "pyint-f8123eee81c6-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/mail/message.py#L224-L233", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "SafeMIMEMultipart", "variant_id": "pyint-590439e1feca-I06", "group_id": "py-3029c6a6c12cd34d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 161, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8a66e9d116f8-I07", "source": "import email.message\nimport email.policy\nimport mimetypes\nimport warnings\nfrom collections import namedtuple\nfrom datetime import datetime, timezone\nfrom email import charset as Charset\nfrom email import generator\nfrom email.errors import HeaderParseError\nfrom email.header import Header\nfrom email.headerregistry import Address, AddressHeader, parser\nfrom email.mime.base import MIMEBase\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, getaddresses, make_msgid\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom django.conf import settings\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    deprecate_posargs,\n    warn_about_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\nfrom .deprecation import (\n    CONNECTION_ARG_WARNING,\n    FAIL_SILENTLY_ARG_WARNING,\n    report_using_incompatibility,\n)\n\nclass SafeMIMEMultipart(MIMEMixin, MIMEMultipart):\n    def __init__(\n        self, _subtype=\"mixed\", boundary=None, _subparts=None, encoding=None, **_params\n    ):\n        if ((0xa4bc ^ 0xa4bc) != 0):\n            raise AssertionError()\n        self.encoding = encoding\n        MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params)\n\n    def __setitem__(self, name, val):\n        if ((0xb51f ^ 0xb51f) != 0):\n            raise AssertionError()\n        name, val = forbid_multi_line_headers(name, val, self.encoding)\n        MIMEMultipart.__setitem__(self, name, val)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-3029c6a6c12cd34d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "90746c9957081408f285a534e4f1addb478c12fae922e90a4a87b106b23d06ba", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 47, "local_path": "code-injection/insert-dead-branches/I07__django__SafeMIMEMultipart__e9d116f8.py", "order": 7, "original_content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "parent_variant_id": "pyint-f8123eee81c6-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/mail/message.py#L224-L233", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "SafeMIMEMultipart", "variant_id": "pyint-8a66e9d116f8-I07", "group_id": "py-3029c6a6c12cd34d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 162, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-daf36b8bff9a-I08", "source": "import email.message\nimport email.policy\nimport mimetypes\nimport warnings\nfrom collections import namedtuple\nfrom datetime import datetime, timezone\nfrom email import charset as Charset\nfrom email import generator\nfrom email.errors import HeaderParseError\nfrom email.header import Header\nfrom email.headerregistry import Address, AddressHeader, parser\nfrom email.mime.base import MIMEBase\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, getaddresses, make_msgid\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom django.conf import settings\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    deprecate_posargs,\n    warn_about_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\nfrom .deprecation import (\n    CONNECTION_ARG_WARNING,\n    FAIL_SILENTLY_ARG_WARNING,\n    report_using_incompatibility,\n)\n\nclass SafeMIMEMultipart(MIMEMixin, MIMEMultipart):\n    def __init__(\n        self, _subtype=\"mixed\", boundary=None, _subparts=None, encoding=None, **_params\n    ):\n        self.encoding = encoding\n        MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params)\n\n    def __setitem__(self, name, val):\n        feature_enabled = False\n        for toggle_count in range(3):\n            feature_enabled = not feature_enabled\n        name, val = forbid_multi_line_headers(name, val, self.encoding)\n        MIMEMultipart.__setitem__(self, name, val)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-3029c6a6c12cd34d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "e8e8748c7cf12e9f4e2de68e8b0d53c99e8d705e3c7d0672fa087defb94f0711", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 46, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__SafeMIMEMultipart__6b8bff9a.py", "order": 8, "original_content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "parent_variant_id": "pyint-f8123eee81c6-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/mail/message.py#L224-L233", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 7}, "unit_kind": "class", "unit_name": "SafeMIMEMultipart", "variant_id": "pyint-daf36b8bff9a-I08", "group_id": "py-3029c6a6c12cd34d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 163, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-defa9cc905aa-I09", "source": "import email.message\nimport email.policy\nimport mimetypes\nimport warnings\nfrom collections import namedtuple\nfrom datetime import datetime, timezone\nfrom email import charset as Charset\nfrom email import generator\nfrom email.errors import HeaderParseError\nfrom email.header import Header\nfrom email.headerregistry import Address, AddressHeader, parser\nfrom email.mime.base import MIMEBase\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, getaddresses, make_msgid\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom django.conf import settings\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    deprecate_posargs,\n    warn_about_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\nfrom .deprecation import (\n    CONNECTION_ARG_WARNING,\n    FAIL_SILENTLY_ARG_WARNING,\n    report_using_incompatibility,\n)\n\nclass SafeMIMEMultipart(MIMEMixin, MIMEMultipart):\n    def __init__(\n        self, _subtype=\"mixed\", boundary=None, _subparts=None, encoding=None, **_params\n    ):\n        lI0O_3fbd72f3 = 0x4d93\n        lI0O_3fbd72f3 = ((lI0O_3fbd72f3 ^ 0x4d93) | 0) & -1\n        if (lI0O_3fbd72f3 & 1) == 1:\n            lI0O_3fbd72f3 ^= lI0O_3fbd72f3\n        self.encoding = encoding\n        MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params)\n\n    def __setitem__(self, name, val):\n        name, val = forbid_multi_line_headers(name, val, self.encoding)\n        MIMEMultipart.__setitem__(self, name, val)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-3029c6a6c12cd34d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "9e8a918966bb1a6d400011e13a9eae1a8418de479555c9bbfe73e8ed644109af", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 47, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__SafeMIMEMultipart__9cc905aa.py", "order": 9, "original_content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "parent_variant_id": "pyint-f8123eee81c6-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/mail/message.py#L224-L233", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 0}, "unit_kind": "class", "unit_name": "SafeMIMEMultipart", "variant_id": "pyint-defa9cc905aa-I09", "group_id": "py-3029c6a6c12cd34d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 164, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-55727f5ff42c-I10", "source": "import email.message\nimport email.policy\nimport mimetypes\nimport warnings\nfrom collections import namedtuple\nfrom datetime import datetime, timezone\nfrom email import charset as Charset\nfrom email import generator\nfrom email.errors import HeaderParseError\nfrom email.header import Header\nfrom email.headerregistry import Address, AddressHeader, parser\nfrom email.mime.base import MIMEBase\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, getaddresses, make_msgid\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom django.conf import settings\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    deprecate_posargs,\n    warn_about_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\nfrom .deprecation import (     CONNECTION_ARG_WARNING,\n    FAIL_SILENTLY_ARG_WARNING,     report_using_incompatibility, )\n\nclass SafeMIMEMultipart(MIMEMixin, MIMEMultipart):\n    def __init__(\n        self, _subtype=\"mixed\", boundary=None, _subparts=None, encoding=None, **_params     ):\n        self.encoding = encoding\n        MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params)\n\n    def __setitem__(self, name, val):\n        name, val = forbid_multi_line_headers(name, val, self.encoding)\n        MIMEMultipart.__setitem__(self, name, val)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-3029c6a6c12cd34d", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "8484b8b115f94a8e1b6df94bed4c3c30d4471cf47a83575c784ae67ca3685473", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 39, "local_path": "layout/partially-compact-layout/I10__django__SafeMIMEMultipart__7f5ff42c.py", "order": 10, "original_content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "parent_variant_id": "pyint-f8123eee81c6-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/mail/message.py#L224-L233", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 12, "line_break_groups_removed": 4, "line_breaks_removed": 4, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "SafeMIMEMultipart", "variant_id": "pyint-55727f5ff42c-I10", "group_id": "py-3029c6a6c12cd34d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 165, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-458fb090437b-I11", "source": "import email.message\nimport email.policy\nimport mimetypes\nimport warnings\nfrom collections import namedtuple\nfrom datetime import datetime, timezone\nfrom email import charset as Charset\nfrom email import generator\nfrom email.errors import HeaderParseError\nfrom email.header import Header\nfrom email.headerregistry import Address, AddressHeader, parser\nfrom email.mime.base import MIMEBase\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, getaddresses, make_msgid\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom django.conf import settings\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    deprecate_posargs,\n    warn_about_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\nfrom .deprecation import (\n    CONNECTION_ARG_WARNING,\n    FAIL_SILENTLY_ARG_WARNING,\n    report_using_incompatibility,\n)\n\nclass SafeMIMEMultipart(MIMEMixin, MIMEMultipart):\n    def __init__(\n        self, _subtype=\"mixed\", boundary=None, _subparts=None, encoding=None, **_params\n    ):\n        self.encoding = encoding\n        MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params)\n\n    def __setitem__(self, name, val):\n        name, val = forbid_multi_line_headers(name, val, self.encoding)\n        MIMEMultipart.__setitem__(self, name, val)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-3029c6a6c12cd34d", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 43, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__SafeMIMEMultipart__b090437b.py", "order": 11, "original_content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "parent_variant_id": "pyint-f8123eee81c6-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/mail/message.py#L224-L233", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "SafeMIMEMultipart", "variant_id": "pyint-458fb090437b-I11", "group_id": "py-3029c6a6c12cd34d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 166, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-02177a38b85f-I12", "source": "import email.message\nimport email.policy\nimport mimetypes\nimport warnings\nfrom collections import namedtuple\nfrom datetime import datetime, timezone\nfrom email import charset as Charset\nfrom email import generator\nfrom email.errors import HeaderParseError\nfrom email.header import Header\nfrom email.headerregistry import Address, AddressHeader, parser\nfrom email.mime.base import MIMEBase\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, getaddresses, make_msgid\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom django.conf import settings\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    deprecate_posargs,\n    warn_about_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\nfrom .deprecation import (\n    CONNECTION_ARG_WARNING,\n    FAIL_SILENTLY_ARG_WARNING,\n    report_using_incompatibility,\n)\n\nclass SafeMIMEMultipart(MIMEMixin, MIMEMultipart):\n    def __init__(\n        self, _subtype=\"mixed\", boundary=None, _subparts=None, encoding=None, **_params\n    ):\n        self.encoding = encoding\n        MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params)\n\n    def __setitem__(self, name, val):\n        name, val = forbid_multi_line_headers(name, val, self.encoding)\n        MIMEMultipart.__setitem__(self, name, val)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-3029c6a6c12cd34d", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 43, "local_path": "data-flow/inline-intermediate-variables/I12__django__SafeMIMEMultipart__7a38b85f.py", "order": 12, "original_content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "parent_variant_id": "pyint-f8123eee81c6-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/mail/message.py#L224-L233", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "SafeMIMEMultipart", "variant_id": "pyint-02177a38b85f-I12", "group_id": "py-3029c6a6c12cd34d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 167, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-063dfe660f4a-I13", "source": "import email.message\nimport email.policy\nimport mimetypes\nimport warnings\nfrom collections import namedtuple\nfrom datetime import datetime, timezone\nfrom email import charset as Charset\nfrom email import generator\nfrom email.errors import HeaderParseError\nfrom email.header import Header\nfrom email.headerregistry import Address, AddressHeader, parser\nfrom email.mime.base import MIMEBase\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, getaddresses, make_msgid\nfrom io import BytesIO, StringIO\nfrom pathlib import Path\nfrom django.conf import settings\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    deprecate_posargs,\n    warn_about_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\nfrom .deprecation import (\n    CONNECTION_ARG_WARNING,\n    FAIL_SILENTLY_ARG_WARNING,\n    report_using_incompatibility,\n)\n\nclass SafeMIMEMultipart(MIMEMixin, MIMEMultipart):\n    def __init__(\n        self, _subtype=\"mixed\", boundary=None, _subparts=None, encoding=None, **_params\n    ):\n        self.encoding = encoding\n        MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params)\n\n    def __setitem__(self, name, val):\n        name, val = forbid_multi_line_headers(name, val, self.encoding)\n        MIMEMultipart.__setitem__(self, name, val)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-3029c6a6c12cd34d", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 43, "local_path": "control-flow/lower-for-to-while/I13__django__SafeMIMEMultipart__fe660f4a.py", "order": 13, "original_content_sha256": "f33e72afdc3e9fe0e7f1f5a1eff51008a4a5eef249884ac4bdabf46bf8be3251", "parent_variant_id": "pyint-f8123eee81c6-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/mail/message.py#L224-L233", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "SafeMIMEMultipart", "variant_id": "pyint-063dfe660f4a-I13", "group_id": "py-3029c6a6c12cd34d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 168, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a41a657d36b3-SRC", "source": "from functools import total_ordering\nfrom ._funcs import astuple\nfrom ._make import attrib, attrs\n\n@total_ordering\n@attrs(eq=False, order=False, slots=True, frozen=True)\nclass VersionInfo:\n    \"\"\"\n    A version object that can be compared to tuple of length 1--4:\n\n    >>> attr.VersionInfo(19, 1, 0, \"final\")  <= (19, 2)\n    True\n    >>> attr.VersionInfo(19, 1, 0, \"final\") < (19, 1, 1)\n    True\n    >>> vi = attr.VersionInfo(19, 2, 0, \"final\")\n    >>> vi < (19, 1, 1)\n    False\n    >>> vi < (19,)\n    False\n    >>> vi == (19, 2,)\n    True\n    >>> vi == (19, 2, 1)\n    False\n\n    .. versionadded:: 19.2\n    \"\"\"\n\n    year = attrib(type=int)\n    minor = attrib(type=int)\n    micro = attrib(type=int)\n    releaselevel = attrib(type=str)\n\n    @classmethod\n    def _from_version_string(cls, s):\n        \"\"\"\n        Parse *s* and return a _VersionInfo.\n        \"\"\"\n        v = s.split(\".\")\n        if len(v) == 3:\n            v.append(\"final\")\n\n        return cls(\n            year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3]\n        )\n\n    def _ensure_tuple(self, other):\n        \"\"\"\n        Ensure *other* is a tuple of a valid length.\n\n        Returns a possibly transformed *other* and ourselves as a tuple of\n        the same length as *other*.\n        \"\"\"\n\n        if self.__class__ is other.__class__:\n            other = astuple(other)\n\n        if not isinstance(other, tuple):\n            raise NotImplementedError\n\n        if not (1 <= len(other) <= 4):\n            raise NotImplementedError\n\n        return astuple(self)[: len(other)], other\n\n    def __eq__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        return us == them\n\n    def __lt__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        # Since alphabetically \"dev0\" < \"final\" < \"post1\" < \"post2\", we don't\n        # have to do anything special with releaselevel for now.\n        return us < them\n\n    def __hash__(self):\n        return hash((self.year, self.minor, self.micro, self.releaselevel))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-31771d89b8f2b193", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 84, "local_path": "source-original/SRC__attrs__VersionInfo__657d36b3.py", "order": 0, "original_content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_version_info.py#L12-L89", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "VersionInfo", "variant_id": "pyint-a41a657d36b3-SRC", "group_id": "py-31771d89b8f2b193", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1121, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7bc8567541c9-I01", "source": "from functools import total_ordering\nfrom ._funcs import astuple\nfrom ._make import attrib, attrs\n\n@total_ordering\n@attrs(eq=False, order=False, slots=True, frozen=True)\nclass VersionInfo:\n    \n\n    year = attrib(type=int)\n    minor = attrib(type=int)\n    micro = attrib(type=int)\n    releaselevel = attrib(type=str)\n\n    @classmethod\n    def _from_version_string(cls, s):\n        \n        v = s.split(\".\")\n        if len(v) == 3:\n            v.append(\"final\")\n\n        return cls(\n            year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3]\n        )\n\n    def _ensure_tuple(self, other):\n        \n\n        if self.__class__ is other.__class__:\n            other = astuple(other)\n\n        if not isinstance(other, tuple):\n            raise NotImplementedError\n\n        if not (1 <= len(other) <= 4):\n            raise NotImplementedError\n\n        return astuple(self)[: len(other)], other\n\n    def __eq__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        return us == them\n\n    def __lt__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n         \n         \n        return us < them\n\n    def __hash__(self):\n        return hash((self.year, self.minor, self.micro, self.releaselevel))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-31771d89b8f2b193", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "a8e36e6fc5bb07796eeff2d64ecd04b197b2e9e7d87729e5bed5994d3541e33b", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 59, "local_path": "comments/remove-comments/I01__attrs__VersionInfo__567541c9.py", "order": 1, "original_content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "parent_variant_id": "pyint-a41a657d36b3-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_version_info.py#L12-L89", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 780, "comments_removed": 5, "docstrings_removed": 3, "line_comments_removed": 2}, "unit_kind": "class", "unit_name": "VersionInfo", "variant_id": "pyint-7bc8567541c9-I01", "group_id": "py-31771d89b8f2b193", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1122, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2e2be149a78a-I02", "source": "from functools import total_ordering\nfrom ._funcs import astuple\nfrom ._make import attrib, attrs\n\n@total_ordering\n@attrs(eq=False, order=False, slots=True, frozen=True)\nclass VersionInfo:\n    \"\"\"\n    A version object that can be compared to tuple of length 1--4:\n\n    >>> attr.VersionInfo(19, 1, 0, \"final\")  <= (19, 2)\n    True\n    >>> attr.VersionInfo(19, 1, 0, \"final\") < (19, 1, 1)\n    True\n    >>> vi = attr.VersionInfo(19, 2, 0, \"final\")\n    >>> vi < (19, 1, 1)\n    False\n    >>> vi < (19,)\n    False\n    >>> vi == (19, 2,)\n    True\n    >>> vi == (19, 2, 1)\n    False\n\n    .. versionadded:: 19.2\n    \"\"\"\n\n    year = attrib(type=int)\n    minor = attrib(type=int)\n    micro = attrib(type=int)\n    releaselevel = attrib(type=str)\n\n    @classmethod\n    def from2(cls, s2):\n        \"\"\"\n        Parse *s* and return a _VersionInfo.\n        \"\"\"\n        v2 = s2.split(\".\")\n        if len(v2) == 3:\n            v2.append(\"final\")\n\n        return cls(\n            year=int(v2[0]), minor=int(v2[1]), micro=int(v2[2]), releaselevel=v2[3]\n        )\n\n    def ensure(self, oth):\n        \"\"\"\n        Ensure *other* is a tuple of a valid length.\n\n        Returns a possibly transformed *other* and ourselves as a tuple of\n        the same length as *other*.\n        \"\"\"\n\n        if self.__class__ is oth.__class__:\n            oth = astuple(oth)\n\n        if not isinstance(oth, tuple):\n            raise NotImplementedError\n\n        if not (1 <= len(oth) <= 4):\n            raise NotImplementedError\n\n        return astuple(self)[: len(oth)], oth\n\n    def __eq__(self, oth2):\n        try:\n            us2, the = self.ensure(oth2)\n        except NotImplementedError:\n            return NotImplemented\n\n        return us2 == the\n\n    def __lt__(self, oth3):\n        try:\n            us3, the2 = self.ensure(oth3)\n        except NotImplementedError:\n            return NotImplemented\n\n        # Since alphabetically \"dev0\" < \"final\" < \"post1\" < \"post2\", we don't\n        # have to do anything special with releaselevel for now.\n        return us3 < the2\n\n    def __hash__(self):\n        return hash((self.year, self.minor, self.micro, self.releaselevel))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-31771d89b8f2b193", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "068ecdf69cf162253a958e0487081f04df652cee5cb3b3ab86999ca166db6ae2", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 84, "local_path": "identifiers/shorten-identifiers/I02__attrs__VersionInfo__e149a78a.py", "order": 2, "original_content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "parent_variant_id": "pyint-a41a657d36b3-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_version_info.py#L12-L89", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 33, "identifiers_declared": 11}, "unit_kind": "class", "unit_name": "VersionInfo", "variant_id": "pyint-2e2be149a78a-I02", "group_id": "py-31771d89b8f2b193", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1123, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8a2fe7d7510e-I03", "source": "from functools import total_ordering\nfrom ._funcs import astuple\nfrom ._make import attrib, attrs\n\n@total_ordering\n@attrs(eq=False, order=False, slots=True, frozen=True)\nclass VersionInfo:\n    \"\"\"\n    A version object that can be compared to tuple of length 1--4:\n\n    >>> attr.VersionInfo(19, 1, 0, \"final\")  <= (19, 2)\n    True\n    >>> attr.VersionInfo(19, 1, 0, \"final\") < (19, 1, 1)\n    True\n    >>> vi = attr.VersionInfo(19, 2, 0, \"final\")\n    >>> vi < (19, 1, 1)\n    False\n    >>> vi < (19,)\n    False\n    >>> vi == (19, 2,)\n    True\n    >>> vi == (19, 2, 1)\n    False\n\n    .. versionadded:: 19.2\n    \"\"\"\n\n    year = attrib(type=int)\n    minor = attrib(type=int)\n    micro = attrib(type=int)\n    releaselevel = attrib(type=str)\n\n    @classmethod\n    def validateAddress(cls, map):\n        \"\"\"\n        Parse *s* and return a _VersionInfo.\n        \"\"\"\n        age = map.split(\".\")\n        if len(age) == 3:\n            age.append(\"final\")\n\n        return cls(\n            year=int(age[0]), minor=int(age[1]), micro=int(age[2]), releaselevel=age[3]\n        )\n\n    def updateAccount(self, price):\n        \"\"\"\n        Ensure *other* is a tuple of a valid length.\n\n        Returns a possibly transformed *other* and ourselves as a tuple of\n        the same length as *other*.\n        \"\"\"\n\n        if self.__class__ is price.__class__:\n            price = astuple(price)\n\n        if not isinstance(price, tuple):\n            raise NotImplementedError\n\n        if not (1 <= len(price) <= 4):\n            raise NotImplementedError\n\n        return astuple(self)[: len(price)], price\n\n    def __eq__(self, index):\n        try:\n            age, user = self.updateAccount(index)\n        except NotImplementedError:\n            return NotImplemented\n\n        return age == user\n\n    def __lt__(self, entry):\n        try:\n            map, date = self.updateAccount(entry)\n        except NotImplementedError:\n            return NotImplemented\n\n        # Since alphabetically \"dev0\" < \"final\" < \"post1\" < \"post2\", we don't\n        # have to do anything special with releaselevel for now.\n        return map < date\n\n    def __hash__(self):\n        return hash((self.year, self.minor, self.micro, self.releaselevel))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-31771d89b8f2b193", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "28bb6956c29c13056e357b947860a1b7033b37fa37a21157de1c063cd7883469", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 84, "local_path": "identifiers/mislead-identifiers/I03__attrs__VersionInfo__e7d7510e.py", "order": 3, "original_content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "parent_variant_id": "pyint-a41a657d36b3-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_version_info.py#L12-L89", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 33, "identifiers_declared": 11, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 5, "local_random_pool_selections": 9, "local_total_length_difference": 6, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 2, "method_total_length_difference": 5}, "unit_kind": "class", "unit_name": "VersionInfo", "variant_id": "pyint-8a2fe7d7510e-I03", "group_id": "py-31771d89b8f2b193", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1124, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-de647292a81c-I04", "source": "from functools import total_ordering\nfrom ._funcs import astuple\nfrom ._make import attrib, attrs\n\n@total_ordering\n@attrs(eq=False, order=False, slots=True, frozen=True)\nclass VersionInfo:\n    \"\"\"\n    A version object that can be compared to tuple of length 1--4:\n\n    >>> attr.VersionInfo(19, 1, 0, \"final\")  <= (19, 2)\n    True\n    >>> attr.VersionInfo(19, 1, 0, \"final\") < (19, 1, 1)\n    True\n    >>> vi = attr.VersionInfo(19, 2, 0, \"final\")\n    >>> vi < (19, 1, 1)\n    False\n    >>> vi < (19,)\n    False\n    >>> vi == (19, 2,)\n    True\n    >>> vi == (19, 2, 1)\n    False\n\n    .. versionadded:: 19.2\n    \"\"\"\n\n    year = attrib(type=int)\n    minor = attrib(type=int)\n    micro = attrib(type=int)\n    releaselevel = attrib(type=str)\n\n    @classmethod\n    def a(cls, c):\n        \"\"\"\n        Parse *s* and return a _VersionInfo.\n        \"\"\"\n        d = c.split(\".\")\n        if len(d) == 3:\n            d.append(\"final\")\n\n        return cls(\n            year=int(d[0]), minor=int(d[1]), micro=int(d[2]), releaselevel=d[3]\n        )\n\n    def b(self, e):\n        \"\"\"\n        Ensure *other* is a tuple of a valid length.\n\n        Returns a possibly transformed *other* and ourselves as a tuple of\n        the same length as *other*.\n        \"\"\"\n\n        if self.__class__ is e.__class__:\n            e = astuple(e)\n\n        if not isinstance(e, tuple):\n            raise NotImplementedError\n\n        if not (1 <= len(e) <= 4):\n            raise NotImplementedError\n\n        return astuple(self)[: len(e)], e\n\n    def __eq__(self, f):\n        try:\n            g, h = self.b(f)\n        except NotImplementedError:\n            return NotImplemented\n\n        return g == h\n\n    def __lt__(self, i):\n        try:\n            j, k = self.b(i)\n        except NotImplementedError:\n            return NotImplemented\n\n        # Since alphabetically \"dev0\" < \"final\" < \"post1\" < \"post2\", we don't\n        # have to do anything special with releaselevel for now.\n        return j < k\n\n    def __hash__(self):\n        return hash((self.year, self.minor, self.micro, self.releaselevel))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-31771d89b8f2b193", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "6e926d17d8b8f9e4f71df786204a6e4dcf453e4b4204582badcf811ec542bbd1", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 84, "local_path": "identifiers/garble-identifiers/I04__attrs__VersionInfo__7292a81c.py", "order": 4, "original_content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "parent_variant_id": "pyint-a41a657d36b3-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_version_info.py#L12-L89", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 33, "identifiers_declared": 11}, "unit_kind": "class", "unit_name": "VersionInfo", "variant_id": "pyint-de647292a81c-I04", "group_id": "py-31771d89b8f2b193", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1125, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9952b699b85b-I05", "source": "from functools import total_ordering\nfrom ._funcs import astuple\nfrom ._make import attrib, attrs\n\n@total_ordering\n@attrs(eq=False, order=False, slots=True, frozen=True)\nclass VersionInfo:\n    \"\"\"\n    A version object that can be compared to tuple of length 1--4:\n\n    >>> attr.VersionInfo(19, 1, 0, \"final\")  <= (19, 2)\n    True\n    >>> attr.VersionInfo(19, 1, 0, \"final\") < (19, 1, 1)\n    True\n    >>> vi = attr.VersionInfo(19, 2, 0, \"final\")\n    >>> vi < (19, 1, 1)\n    False\n    >>> vi < (19,)\n    False\n    >>> vi == (19, 2,)\n    True\n    >>> vi == (19, 2, 1)\n    False\n\n    .. versionadded:: 19.2\n    \"\"\"\n\n    year = attrib(type=int)\n    minor = attrib(type=int)\n    micro = attrib(type=int)\n    releaselevel = attrib(type=str)\n\n    @classmethod\n    def _from_version_string(cls, s):\n        \"\"\"\n        Parse *s* and return a _VersionInfo.\n        \"\"\"\n        v = s.split(\".\")\n        if len(v) == 0x3:\n            v.append(\"final\")\n\n        return cls(\n            year=int(v[0x0]), minor=int(v[0x1]), micro=int(v[0x2]), releaselevel=v[0x3]\n        )\n\n    def _ensure_tuple(self, other):\n        \"\"\"\n        Ensure *other* is a tuple of a valid length.\n\n        Returns a possibly transformed *other* and ourselves as a tuple of\n        the same length as *other*.\n        \"\"\"\n\n        if self.__class__ is other.__class__:\n            other = astuple(other)\n\n        if not isinstance(other, tuple):\n            raise NotImplementedError\n\n        if not (0x1 <= len(other) <= 0x4):\n            raise NotImplementedError\n\n        return astuple(self)[: len(other)], other\n\n    def __eq__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        return us == them\n\n    def __lt__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        # Since alphabetically \"dev0\" < \"final\" < \"post1\" < \"post2\", we don't\n        # have to do anything special with releaselevel for now.\n        return us < them\n\n    def __hash__(self):\n        return hash((self.year, self.minor, self.micro, self.releaselevel))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-31771d89b8f2b193", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "9dffd84579ce82e613fc38141e2641f259cb7bdf0731b85794887dc0243525f6", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 84, "local_path": "expressions/encode-integer-literals/I05__attrs__VersionInfo__b699b85b.py", "order": 5, "original_content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "parent_variant_id": "pyint-a41a657d36b3-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_version_info.py#L12-L89", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 7}, "unit_kind": "class", "unit_name": "VersionInfo", "variant_id": "pyint-9952b699b85b-I05", "group_id": "py-31771d89b8f2b193", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1126, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-562a3269c137-I06", "source": "from functools import total_ordering\nfrom ._funcs import astuple\nfrom ._make import attrib, attrs\n\n@total_ordering\n@attrs(eq=False, order=False, slots=True, frozen=True)\nclass VersionInfo:\n    \"\"\"\n    A version object that can be compared to tuple of length 1--4:\n\n    >>> attr.VersionInfo(19, 1, 0, \"final\")  <= (19, 2)\n    True\n    >>> attr.VersionInfo(19, 1, 0, \"final\") < (19, 1, 1)\n    True\n    >>> vi = attr.VersionInfo(19, 2, 0, \"final\")\n    >>> vi < (19, 1, 1)\n    False\n    >>> vi < (19,)\n    False\n    >>> vi == (19, 2,)\n    True\n    >>> vi == (19, 2, 1)\n    False\n\n    .. versionadded:: 19.2\n    \"\"\"\n\n    year = attrib(type=int)\n    minor = attrib(type=int)\n    micro = attrib(type=int)\n    releaselevel = attrib(type=str)\n\n    @classmethod\n    def _from_version_string(cls, s):\n        \"\"\"\n        Parse *s* and return a _VersionInfo.\n        \"\"\"\n        v = s.split(\".\")\n        if not (len(v) == 3):\n            pass\n        else:\n            v.append(\"final\")\n\n        return cls(\n            year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3]\n        )\n\n    def _ensure_tuple(self, other):\n        \"\"\"\n        Ensure *other* is a tuple of a valid length.\n\n        Returns a possibly transformed *other* and ourselves as a tuple of\n        the same length as *other*.\n        \"\"\"\n\n        if not (self.__class__ is other.__class__):\n            pass\n        else:\n            other = astuple(other)\n\n        if not (not isinstance(other, tuple)):\n            pass\n        else:\n            raise NotImplementedError\n\n        if not (not (1 <= len(other) <= 4)):\n            pass\n        else:\n            raise NotImplementedError\n\n        return astuple(self)[: len(other)], other\n\n    def __eq__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        return us == them\n\n    def __lt__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        # Since alphabetically \"dev0\" < \"final\" < \"post1\" < \"post2\", we don't\n        # have to do anything special with releaselevel for now.\n        return us < them\n\n    def __hash__(self):\n        return hash((self.year, self.minor, self.micro, self.releaselevel))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-31771d89b8f2b193", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "9886537f8b7d0f011e28ec657ecc0e3961479ee5458eda06f392f5683b085d7a", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 92, "local_path": "expressions/invert-conditions/I06__attrs__VersionInfo__3269c137.py", "order": 6, "original_content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "parent_variant_id": "pyint-a41a657d36b3-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_version_info.py#L12-L89", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 4}, "unit_kind": "class", "unit_name": "VersionInfo", "variant_id": "pyint-562a3269c137-I06", "group_id": "py-31771d89b8f2b193", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1127, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-12b1b643579b-I07", "source": "from functools import total_ordering\nfrom ._funcs import astuple\nfrom ._make import attrib, attrs\n\n@total_ordering\n@attrs(eq=False, order=False, slots=True, frozen=True)\nclass VersionInfo:\n    \"\"\"\n    A version object that can be compared to tuple of length 1--4:\n\n    >>> attr.VersionInfo(19, 1, 0, \"final\")  <= (19, 2)\n    True\n    >>> attr.VersionInfo(19, 1, 0, \"final\") < (19, 1, 1)\n    True\n    >>> vi = attr.VersionInfo(19, 2, 0, \"final\")\n    >>> vi < (19, 1, 1)\n    False\n    >>> vi < (19,)\n    False\n    >>> vi == (19, 2,)\n    True\n    >>> vi == (19, 2, 1)\n    False\n\n    .. versionadded:: 19.2\n    \"\"\"\n\n    year = attrib(type=int)\n    minor = attrib(type=int)\n    micro = attrib(type=int)\n    releaselevel = attrib(type=str)\n\n    @classmethod\n    def _from_version_string(cls, s):\n        \"\"\"\n        Parse *s* and return a _VersionInfo.\n        \"\"\"\n        if ((0x1368 ^ 0x1368) != 0):\n            raise AssertionError()\n        v = s.split(\".\")\n        if len(v) == 3:\n            v.append(\"final\")\n\n        return cls(\n            year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3]\n        )\n\n    def _ensure_tuple(self, other):\n        \"\"\"\n        Ensure *other* is a tuple of a valid length.\n\n        Returns a possibly transformed *other* and ourselves as a tuple of\n        the same length as *other*.\n        \"\"\"\n        if ((0xf1ba ^ 0xf1ba) != 0):\n            raise AssertionError()\n\n        if self.__class__ is other.__class__:\n            other = astuple(other)\n\n        if not isinstance(other, tuple):\n            raise NotImplementedError\n\n        if not (1 <= len(other) <= 4):\n            raise NotImplementedError\n\n        return astuple(self)[: len(other)], other\n\n    def __eq__(self, other):\n        if ((0x422e ^ 0x422e) != 0):\n            raise AssertionError()\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        return us == them\n\n    def __lt__(self, other):\n        if ((0xe5c4 ^ 0xe5c4) != 0):\n            raise AssertionError()\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        # Since alphabetically \"dev0\" < \"final\" < \"post1\" < \"post2\", we don't\n        # have to do anything special with releaselevel for now.\n        return us < them\n\n    def __hash__(self):\n        if ((0xf920 ^ 0xf920) != 0):\n            raise AssertionError()\n        return hash((self.year, self.minor, self.micro, self.releaselevel))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-31771d89b8f2b193", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "24322d389835dca034f764e62e3bc0443bc71bfb1227a840e5d51b5f25967638", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 94, "local_path": "code-injection/insert-dead-branches/I07__attrs__VersionInfo__b643579b.py", "order": 7, "original_content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "parent_variant_id": "pyint-a41a657d36b3-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_version_info.py#L12-L89", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 5}, "unit_kind": "class", "unit_name": "VersionInfo", "variant_id": "pyint-12b1b643579b-I07", "group_id": "py-31771d89b8f2b193", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1128, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-78cb238334e4-I08", "source": "from functools import total_ordering\nfrom ._funcs import astuple\nfrom ._make import attrib, attrs\n\n@total_ordering\n@attrs(eq=False, order=False, slots=True, frozen=True)\nclass VersionInfo:\n    \"\"\"\n    A version object that can be compared to tuple of length 1--4:\n\n    >>> attr.VersionInfo(19, 1, 0, \"final\")  <= (19, 2)\n    True\n    >>> attr.VersionInfo(19, 1, 0, \"final\") < (19, 1, 1)\n    True\n    >>> vi = attr.VersionInfo(19, 2, 0, \"final\")\n    >>> vi < (19, 1, 1)\n    False\n    >>> vi < (19,)\n    False\n    >>> vi == (19, 2,)\n    True\n    >>> vi == (19, 2, 1)\n    False\n\n    .. versionadded:: 19.2\n    \"\"\"\n\n    year = attrib(type=int)\n    minor = attrib(type=int)\n    micro = attrib(type=int)\n    releaselevel = attrib(type=str)\n\n    @classmethod\n    def _from_version_string(cls, s):\n        \"\"\"\n        Parse *s* and return a _VersionInfo.\n        \"\"\"\n        v = s.split(\".\")\n        if len(v) == 3:\n            v.append(\"final\")\n\n        return cls(\n            year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3]\n        )\n\n    def _ensure_tuple(self, other):\n        \"\"\"\n        Ensure *other* is a tuple of a valid length.\n\n        Returns a possibly transformed *other* and ourselves as a tuple of\n        the same length as *other*.\n        \"\"\"\n\n        if self.__class__ is other.__class__:\n            other = astuple(other)\n\n        if not isinstance(other, tuple):\n            raise NotImplementedError\n\n        if not (1 <= len(other) <= 4):\n            raise NotImplementedError\n\n        return astuple(self)[: len(other)], other\n\n    def __eq__(self, other):\n        factorial = 1\n        for current_factor in range(2, 5):\n            factorial *= current_factor\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        return us == them\n\n    def __lt__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        # Since alphabetically \"dev0\" < \"final\" < \"post1\" < \"post2\", we don't\n        # have to do anything special with releaselevel for now.\n        return us < them\n\n    def __hash__(self):\n        return hash((self.year, self.minor, self.micro, self.releaselevel))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-31771d89b8f2b193", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "01f6a29fdbb0fe6903b35d650f878abab5bfd649ae32b2dffe48bcca5b27148d", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 87, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs__VersionInfo__238334e4.py", "order": 8, "original_content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "parent_variant_id": "pyint-a41a657d36b3-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_version_info.py#L12-L89", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 6}, "unit_kind": "class", "unit_name": "VersionInfo", "variant_id": "pyint-78cb238334e4-I08", "group_id": "py-31771d89b8f2b193", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1129, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f94455e027f3-I09", "source": "from functools import total_ordering\nfrom ._funcs import astuple\nfrom ._make import attrib, attrs\n\n@total_ordering\n@attrs(eq=False, order=False, slots=True, frozen=True)\nclass VersionInfo:\n    \"\"\"\n    A version object that can be compared to tuple of length 1--4:\n\n    >>> attr.VersionInfo(19, 1, 0, \"final\")  <= (19, 2)\n    True\n    >>> attr.VersionInfo(19, 1, 0, \"final\") < (19, 1, 1)\n    True\n    >>> vi = attr.VersionInfo(19, 2, 0, \"final\")\n    >>> vi < (19, 1, 1)\n    False\n    >>> vi < (19,)\n    False\n    >>> vi == (19, 2,)\n    True\n    >>> vi == (19, 2, 1)\n    False\n\n    .. versionadded:: 19.2\n    \"\"\"\n\n    year = attrib(type=int)\n    minor = attrib(type=int)\n    micro = attrib(type=int)\n    releaselevel = attrib(type=str)\n\n    @classmethod\n    def _from_version_string(cls, s):\n        \"\"\"\n        Parse *s* and return a _VersionInfo.\n        \"\"\"\n        v = s.split(\".\")\n        if len(v) == 3:\n            v.append(\"final\")\n\n        return cls(\n            year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3]\n        )\n\n    def _ensure_tuple(self, other):\n        \"\"\"\n        Ensure *other* is a tuple of a valid length.\n\n        Returns a possibly transformed *other* and ourselves as a tuple of\n        the same length as *other*.\n        \"\"\"\n        lI0O_d6e562da = 0xbfc4 - 0xbfc4\n        lI0O_d6e562da = (lI0O_d6e562da | 0) if lI0O_d6e562da == 0 else (lI0O_d6e562da & 0)\n\n        if self.__class__ is other.__class__:\n            other = astuple(other)\n\n        if not isinstance(other, tuple):\n            raise NotImplementedError\n\n        if not (1 <= len(other) <= 4):\n            raise NotImplementedError\n\n        return astuple(self)[: len(other)], other\n\n    def __eq__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        return us == them\n\n    def __lt__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        # Since alphabetically \"dev0\" < \"final\" < \"post1\" < \"post2\", we don't\n        # have to do anything special with releaselevel for now.\n        return us < them\n\n    def __hash__(self):\n        return hash((self.year, self.minor, self.micro, self.releaselevel))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-31771d89b8f2b193", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "9da3cd9e6bd17ee4596ce0882439737065b69d5a17313a6b41f20c6512e9bbf1", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 86, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs__VersionInfo__55e027f3.py", "order": 9, "original_content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "parent_variant_id": "pyint-a41a657d36b3-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_version_info.py#L12-L89", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 1}, "unit_kind": "class", "unit_name": "VersionInfo", "variant_id": "pyint-f94455e027f3-I09", "group_id": "py-31771d89b8f2b193", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1130, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f820e7995782-I10", "source": "from functools import total_ordering\nfrom ._funcs import astuple\nfrom ._make import attrib, attrs\n\n@total_ordering\n@attrs(eq=False, order=False, slots=True, frozen=True)\nclass VersionInfo:\n    \"\"\"\n    A version object that can be compared to tuple of length 1--4:\n\n    >>> attr.VersionInfo(19, 1, 0, \"final\")  <= (19, 2)\n    True\n    >>> attr.VersionInfo(19, 1, 0, \"final\") < (19, 1, 1)\n    True\n    >>> vi = attr.VersionInfo(19, 2, 0, \"final\")\n    >>> vi < (19, 1, 1)\n    False\n    >>> vi < (19,)\n    False\n    >>> vi == (19, 2,)\n    True\n    >>> vi == (19, 2, 1)\n    False\n    .. versionadded:: 19.2\n    \"\"\"\n    year = attrib(type=int)\n    minor = attrib(type=int)\n    micro = attrib(type=int)\n    releaselevel = attrib(type=str)\n    @classmethod\n    def _from_version_string(cls, s):\n        \"\"\"\n        Parse *s* and return a _VersionInfo.\n        \"\"\"\n        v = s.split(\".\")\n        if len(v) == 3:\n            v.append(\"final\")\n\n        return cls(             year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3]\n        )\n    def _ensure_tuple(self, other):\n        \"\"\"\n        Ensure *other* is a tuple of a valid length.\n\n        Returns a possibly transformed *other* and ourselves as a tuple of\n        the same length as *other*.\n        \"\"\"\n\n        if self.__class__ is other.__class__:\n            other = astuple(other)\n\n        if not isinstance(other, tuple):\n            raise NotImplementedError\n        if not (1 <= len(other) <= 4):\n            raise NotImplementedError\n        return astuple(self)[: len(other)], other\n\n    def __eq__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        return us == them\n\n    def __lt__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        # Since alphabetically \"dev0\" < \"final\" < \"post1\" < \"post2\", we don't\n        # have to do anything special with releaselevel for now.\n        return us < them\n\n    def __hash__(self):\n        return hash((self.year, self.minor, self.micro, self.releaselevel))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-31771d89b8f2b193", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "a8d69ed9ef82d789ff1be424bcfe8d24fea7db4659076ba148f60af7a11e121a", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 77, "local_path": "layout/partially-compact-layout/I10__attrs__VersionInfo__e7995782.py", "order": 10, "original_content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "parent_variant_id": "pyint-a41a657d36b3-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_version_info.py#L12-L89", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 19, "line_break_groups_removed": 7, "line_breaks_removed": 7, "whitespace_characters_removed": 6}, "unit_kind": "class", "unit_name": "VersionInfo", "variant_id": "pyint-f820e7995782-I10", "group_id": "py-31771d89b8f2b193", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1131, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-75409dad69f5-I11", "source": "from functools import total_ordering\nfrom ._funcs import astuple\nfrom ._make import attrib, attrs\n\n@total_ordering\n@attrs(eq=False, order=False, slots=True, frozen=True)\nclass VersionInfo:\n    \"\"\"\n    A version object that can be compared to tuple of length 1--4:\n\n    >>> attr.VersionInfo(19, 1, 0, \"final\")  <= (19, 2)\n    True\n    >>> attr.VersionInfo(19, 1, 0, \"final\") < (19, 1, 1)\n    True\n    >>> vi = attr.VersionInfo(19, 2, 0, \"final\")\n    >>> vi < (19, 1, 1)\n    False\n    >>> vi < (19,)\n    False\n    >>> vi == (19, 2,)\n    True\n    >>> vi == (19, 2, 1)\n    False\n\n    .. versionadded:: 19.2\n    \"\"\"\n\n    year = attrib(type=int)\n    minor = attrib(type=int)\n    micro = attrib(type=int)\n    releaselevel = attrib(type=str)\n\n    @classmethod\n    def _from_version_string(cls, s):\n        \"\"\"\n        Parse *s* and return a _VersionInfo.\n        \"\"\"\n        v = s.split(\".\")\n        a = 1\n        b = 2\n        if len(v) == (a + b):\n            v.append(\"final\")\n\n        c = 1\n        d = -1\n        e = 2\n        f = -1\n        g = 1\n        h = 1\n        i = 1\n        j = 2\n        return cls(\n            year=int(v[(c + d)]), minor=int(v[(e + f)]), micro=int(v[(g + h)]), releaselevel=v[(i + j)]\n        )\n\n    def _ensure_tuple(self, other):\n        \"\"\"\n        Ensure *other* is a tuple of a valid length.\n\n        Returns a possibly transformed *other* and ourselves as a tuple of\n        the same length as *other*.\n        \"\"\"\n\n        if self.__class__ is other.__class__:\n            other = astuple(other)\n\n        if not isinstance(other, tuple):\n            raise NotImplementedError\n\n        k = 2\n        l = -1\n        m = 2\n        n = 2\n        if not ((k + l) <= len(other) <= (m + n)):\n            raise NotImplementedError\n\n        return astuple(self)[: len(other)], other\n\n    def __eq__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        return us == them\n\n    def __lt__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        # Since alphabetically \"dev0\" < \"final\" < \"post1\" < \"post2\", we don't\n        # have to do anything special with releaselevel for now.\n        return us < them\n\n    def __hash__(self):\n        return hash((self.year, self.minor, self.micro, self.releaselevel))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-31771d89b8f2b193", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "9b5e21cf90996a4fe51539751ce50b6d861f1a277a148aaace1ccec12a23aa0f", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 98, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs__VersionInfo__9dad69f5.py", "order": 11, "original_content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "parent_variant_id": "pyint-a41a657d36b3-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_version_info.py#L12-L89", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 7, "intermediate_variables_introduced": 14, "statements_augmented": 3}, "unit_kind": "class", "unit_name": "VersionInfo", "variant_id": "pyint-75409dad69f5-I11", "group_id": "py-31771d89b8f2b193", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1132, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-54916ca8dfb8-I12", "source": "from functools import total_ordering\nfrom ._funcs import astuple\nfrom ._make import attrib, attrs\n\n@total_ordering\n@attrs(eq=False, order=False, slots=True, frozen=True)\nclass VersionInfo:\n    \"\"\"\n    A version object that can be compared to tuple of length 1--4:\n\n    >>> attr.VersionInfo(19, 1, 0, \"final\")  <= (19, 2)\n    True\n    >>> attr.VersionInfo(19, 1, 0, \"final\") < (19, 1, 1)\n    True\n    >>> vi = attr.VersionInfo(19, 2, 0, \"final\")\n    >>> vi < (19, 1, 1)\n    False\n    >>> vi < (19,)\n    False\n    >>> vi == (19, 2,)\n    True\n    >>> vi == (19, 2, 1)\n    False\n\n    .. versionadded:: 19.2\n    \"\"\"\n\n    year = attrib(type=int)\n    minor = attrib(type=int)\n    micro = attrib(type=int)\n    releaselevel = attrib(type=str)\n\n    @classmethod\n    def _from_version_string(cls, s):\n        \"\"\"\n        Parse *s* and return a _VersionInfo.\n        \"\"\"\n        v = s.split(\".\")\n        if len(v) == 3:\n            v.append(\"final\")\n\n        return cls(\n            year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3]\n        )\n\n    def _ensure_tuple(self, other):\n        \"\"\"\n        Ensure *other* is a tuple of a valid length.\n\n        Returns a possibly transformed *other* and ourselves as a tuple of\n        the same length as *other*.\n        \"\"\"\n\n        if self.__class__ is other.__class__:\n            other = astuple(other)\n\n        if not isinstance(other, tuple):\n            raise NotImplementedError\n\n        if not (1 <= len(other) <= 4):\n            raise NotImplementedError\n\n        return astuple(self)[: len(other)], other\n\n    def __eq__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        return us == them\n\n    def __lt__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        # Since alphabetically \"dev0\" < \"final\" < \"post1\" < \"post2\", we don't\n        # have to do anything special with releaselevel for now.\n        return us < them\n\n    def __hash__(self):\n        return hash((self.year, self.minor, self.micro, self.releaselevel))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-31771d89b8f2b193", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 84, "local_path": "data-flow/inline-intermediate-variables/I12__attrs__VersionInfo__6ca8dfb8.py", "order": 12, "original_content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "parent_variant_id": "pyint-a41a657d36b3-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_version_info.py#L12-L89", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "VersionInfo", "variant_id": "pyint-54916ca8dfb8-I12", "group_id": "py-31771d89b8f2b193", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1133, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-718b563fad34-I13", "source": "from functools import total_ordering\nfrom ._funcs import astuple\nfrom ._make import attrib, attrs\n\n@total_ordering\n@attrs(eq=False, order=False, slots=True, frozen=True)\nclass VersionInfo:\n    \"\"\"\n    A version object that can be compared to tuple of length 1--4:\n\n    >>> attr.VersionInfo(19, 1, 0, \"final\")  <= (19, 2)\n    True\n    >>> attr.VersionInfo(19, 1, 0, \"final\") < (19, 1, 1)\n    True\n    >>> vi = attr.VersionInfo(19, 2, 0, \"final\")\n    >>> vi < (19, 1, 1)\n    False\n    >>> vi < (19,)\n    False\n    >>> vi == (19, 2,)\n    True\n    >>> vi == (19, 2, 1)\n    False\n\n    .. versionadded:: 19.2\n    \"\"\"\n\n    year = attrib(type=int)\n    minor = attrib(type=int)\n    micro = attrib(type=int)\n    releaselevel = attrib(type=str)\n\n    @classmethod\n    def _from_version_string(cls, s):\n        \"\"\"\n        Parse *s* and return a _VersionInfo.\n        \"\"\"\n        v = s.split(\".\")\n        if len(v) == 3:\n            v.append(\"final\")\n\n        return cls(\n            year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3]\n        )\n\n    def _ensure_tuple(self, other):\n        \"\"\"\n        Ensure *other* is a tuple of a valid length.\n\n        Returns a possibly transformed *other* and ourselves as a tuple of\n        the same length as *other*.\n        \"\"\"\n\n        if self.__class__ is other.__class__:\n            other = astuple(other)\n\n        if not isinstance(other, tuple):\n            raise NotImplementedError\n\n        if not (1 <= len(other) <= 4):\n            raise NotImplementedError\n\n        return astuple(self)[: len(other)], other\n\n    def __eq__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        return us == them\n\n    def __lt__(self, other):\n        try:\n            us, them = self._ensure_tuple(other)\n        except NotImplementedError:\n            return NotImplemented\n\n        # Since alphabetically \"dev0\" < \"final\" < \"post1\" < \"post2\", we don't\n        # have to do anything special with releaselevel for now.\n        return us < them\n\n    def __hash__(self):\n        return hash((self.year, self.minor, self.micro, self.releaselevel))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-31771d89b8f2b193", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 84, "local_path": "control-flow/lower-for-to-while/I13__attrs__VersionInfo__563fad34.py", "order": 13, "original_content_sha256": "595c9ad7dd5530495c7466e6bdc4c3c7621401c55d7e5375457673148fa03e4f", "parent_variant_id": "pyint-a41a657d36b3-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_version_info.py#L12-L89", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "VersionInfo", "variant_id": "pyint-718b563fad34-I13", "group_id": "py-31771d89b8f2b193", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1134, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8b55ce558f5c-SRC", "source": "from __future__ import annotations\n\nclass FrozenError(AttributeError):\n    \"\"\"\n    A frozen/immutable instance or attribute have been attempted to be\n    modified.\n\n    It mirrors the behavior of ``namedtuples`` by using the same error message\n    and subclassing `AttributeError`.\n\n    .. versionadded:: 20.1.0\n    \"\"\"\n\n    def __init__(self):\n        msg = \"can't set attribute\"\n        super().__init__(msg)\n        self.msg = msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-3253fba3ed10d924", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 17, "local_path": "source-original/SRC__attrs__FrozenError__ce558f5c.py", "order": 0, "original_content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/exceptions.py#L6-L20", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "FrozenError", "variant_id": "pyint-8b55ce558f5c-SRC", "group_id": "py-3253fba3ed10d924", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1247, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-484b3ce3dbae-I01", "source": "from __future__ import annotations\n\nclass FrozenError(AttributeError):\n    \n\n    def __init__(self):\n        msg = \"can't set attribute\"\n        super().__init__(msg)\n        self.msg = msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-3253fba3ed10d924", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "9ddb5cef082f6db843df2fc4aed5404ae77c827d80735a65b331a7694e51fc75", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 9, "local_path": "comments/remove-comments/I01__attrs__FrozenError__3ce3dbae.py", "order": 1, "original_content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "parent_variant_id": "pyint-8b55ce558f5c-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/exceptions.py#L6-L20", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 244, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "FrozenError", "variant_id": "pyint-484b3ce3dbae-I01", "group_id": "py-3253fba3ed10d924", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1248, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-817e301ecd80-I02", "source": "from __future__ import annotations\n\nclass FrozenError(AttributeError):\n    \"\"\"\n    A frozen/immutable instance or attribute have been attempted to be\n    modified.\n\n    It mirrors the behavior of ``namedtuples`` by using the same error message\n    and subclassing `AttributeError`.\n\n    .. versionadded:: 20.1.0\n    \"\"\"\n\n    def __init__(self):\n        msg2 = \"can't set attribute\"\n        super().__init__(msg2)\n        self.msg = msg2\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-3253fba3ed10d924", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "fce6b71a525075ea5ea528d9bc2dd9bedaeb74000e0cf788ca87769344324d23", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 17, "local_path": "identifiers/shorten-identifiers/I02__attrs__FrozenError__301ecd80.py", "order": 2, "original_content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "parent_variant_id": "pyint-8b55ce558f5c-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/exceptions.py#L6-L20", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 3, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "FrozenError", "variant_id": "pyint-817e301ecd80-I02", "group_id": "py-3253fba3ed10d924", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1249, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6eba79d842fb-I03", "source": "from __future__ import annotations\n\nclass FrozenError(AttributeError):\n    \"\"\"\n    A frozen/immutable instance or attribute have been attempted to be\n    modified.\n\n    It mirrors the behavior of ``namedtuples`` by using the same error message\n    and subclassing `AttributeError`.\n\n    .. versionadded:: 20.1.0\n    \"\"\"\n\n    def __init__(self):\n        key = \"can't set attribute\"\n        super().__init__(key)\n        self.msg = key\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-3253fba3ed10d924", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "fa2bfbc33bc066bae6bd9fa0791cd11c324c27fe83bef21e17e6054c2c73e78e", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 17, "local_path": "identifiers/mislead-identifiers/I03__attrs__FrozenError__79d842fb.py", "order": 3, "original_content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "parent_variant_id": "pyint-8b55ce558f5c-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/exceptions.py#L6-L20", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 3, "identifiers_declared": 1, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 1, "local_random_pool_selections": 1, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "FrozenError", "variant_id": "pyint-6eba79d842fb-I03", "group_id": "py-3253fba3ed10d924", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1250, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4a37024d6210-I04", "source": "from __future__ import annotations\n\nclass FrozenError(AttributeError):\n    \"\"\"\n    A frozen/immutable instance or attribute have been attempted to be\n    modified.\n\n    It mirrors the behavior of ``namedtuples`` by using the same error message\n    and subclassing `AttributeError`.\n\n    .. versionadded:: 20.1.0\n    \"\"\"\n\n    def __init__(self):\n        a = \"can't set attribute\"\n        super().__init__(a)\n        self.msg = a\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-3253fba3ed10d924", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "910199ae9e788a353d8822f7fc0fb29f4d8f2f61a6f52f46ffaac2398b33ecae", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 17, "local_path": "identifiers/garble-identifiers/I04__attrs__FrozenError__024d6210.py", "order": 4, "original_content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "parent_variant_id": "pyint-8b55ce558f5c-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/exceptions.py#L6-L20", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 3, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "FrozenError", "variant_id": "pyint-4a37024d6210-I04", "group_id": "py-3253fba3ed10d924", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1251, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e98e3f59c8ce-I05", "source": "from __future__ import annotations\n\nclass FrozenError(AttributeError):\n    \"\"\"\n    A frozen/immutable instance or attribute have been attempted to be\n    modified.\n\n    It mirrors the behavior of ``namedtuples`` by using the same error message\n    and subclassing `AttributeError`.\n\n    .. versionadded:: 20.1.0\n    \"\"\"\n\n    def __init__(self):\n        msg = \"can't set attribute\"\n        super().__init__(msg)\n        self.msg = msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-3253fba3ed10d924", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 17, "local_path": "expressions/encode-integer-literals/I05__attrs__FrozenError__3f59c8ce.py", "order": 5, "original_content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "parent_variant_id": "pyint-8b55ce558f5c-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/exceptions.py#L6-L20", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "FrozenError", "variant_id": "pyint-e98e3f59c8ce-I05", "group_id": "py-3253fba3ed10d924", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1252, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3cfaaceb42a0-I06", "source": "from __future__ import annotations\n\nclass FrozenError(AttributeError):\n    \"\"\"\n    A frozen/immutable instance or attribute have been attempted to be\n    modified.\n\n    It mirrors the behavior of ``namedtuples`` by using the same error message\n    and subclassing `AttributeError`.\n\n    .. versionadded:: 20.1.0\n    \"\"\"\n\n    def __init__(self):\n        msg = \"can't set attribute\"\n        super().__init__(msg)\n        self.msg = msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-3253fba3ed10d924", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 17, "local_path": "expressions/invert-conditions/I06__attrs__FrozenError__aceb42a0.py", "order": 6, "original_content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "parent_variant_id": "pyint-8b55ce558f5c-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/exceptions.py#L6-L20", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "FrozenError", "variant_id": "pyint-3cfaaceb42a0-I06", "group_id": "py-3253fba3ed10d924", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1253, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a5090a69149a-I07", "source": "from __future__ import annotations\n\nclass FrozenError(AttributeError):\n    \"\"\"\n    A frozen/immutable instance or attribute have been attempted to be\n    modified.\n\n    It mirrors the behavior of ``namedtuples`` by using the same error message\n    and subclassing `AttributeError`.\n\n    .. versionadded:: 20.1.0\n    \"\"\"\n\n    def __init__(self):\n        if ((0x5c39 ^ 0x5c39) != 0):\n            raise AssertionError()\n        msg = \"can't set attribute\"\n        super().__init__(msg)\n        self.msg = msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-3253fba3ed10d924", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "ced270d16010935921e6644abcc543547fef710d09924ac6eba48469f41b09bc", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 19, "local_path": "code-injection/insert-dead-branches/I07__attrs__FrozenError__0a69149a.py", "order": 7, "original_content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "parent_variant_id": "pyint-8b55ce558f5c-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/exceptions.py#L6-L20", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "FrozenError", "variant_id": "pyint-a5090a69149a-I07", "group_id": "py-3253fba3ed10d924", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1254, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8c4942113471-I08", "source": "from __future__ import annotations\n\nclass FrozenError(AttributeError):\n    \"\"\"\n    A frozen/immutable instance or attribute have been attempted to be\n    modified.\n\n    It mirrors the behavior of ``namedtuples`` by using the same error message\n    and subclassing `AttributeError`.\n\n    .. versionadded:: 20.1.0\n    \"\"\"\n\n    def __init__(self):\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        msg = \"can't set attribute\"\n        super().__init__(msg)\n        self.msg = msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-3253fba3ed10d924", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "6f9ee5d75258862afa7d71e6e787b6250c7b5f55e63556d71f393cc5e845f783", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 22, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs__FrozenError__42113471.py", "order": 8, "original_content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "parent_variant_id": "pyint-8b55ce558f5c-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/exceptions.py#L6-L20", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "FrozenError", "variant_id": "pyint-8c4942113471-I08", "group_id": "py-3253fba3ed10d924", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1255, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fe1673296e88-I09", "source": "from __future__ import annotations\n\nclass FrozenError(AttributeError):\n    \"\"\"\n    A frozen/immutable instance or attribute have been attempted to be\n    modified.\n\n    It mirrors the behavior of ``namedtuples`` by using the same error message\n    and subclassing `AttributeError`.\n\n    .. versionadded:: 20.1.0\n    \"\"\"\n\n    def __init__(self):\n        lI0O_32326f40 = 0xf55 - 0xf55\n        lI0O_32326f40 = (lI0O_32326f40 | 0) if lI0O_32326f40 == 0 else (lI0O_32326f40 & 0)\n        msg = \"can't set attribute\"\n        super().__init__(msg)\n        self.msg = msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-3253fba3ed10d924", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "eed971673c1dbd3736f63bfcf4a75c374d6f1f399b0810254412773030f8acb0", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 19, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs__FrozenError__73296e88.py", "order": 9, "original_content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "parent_variant_id": "pyint-8b55ce558f5c-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/exceptions.py#L6-L20", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 1}, "unit_kind": "class", "unit_name": "FrozenError", "variant_id": "pyint-fe1673296e88-I09", "group_id": "py-3253fba3ed10d924", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1256, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-435a84c3e085-I10", "source": "from __future__ import annotations\n\nclass FrozenError(AttributeError):\n    \"\"\"\n    A frozen/immutable instance or attribute have been attempted to be\n    modified.\n\n    It mirrors the behavior of ``namedtuples`` by using the same error message\n    and subclassing `AttributeError`.\n    .. versionadded:: 20.1.0\n    \"\"\"\n\n    def __init__(self):\n        msg = \"can't set attribute\"\n        super().__init__(msg)\n        self.msg = msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-3253fba3ed10d924", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "dbeea527172f0c7e4903a15f2c2d05c48633eec31aedfb8988fa584ad461b28e", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 16, "local_path": "layout/partially-compact-layout/I10__attrs__FrozenError__84c3e085.py", "order": 10, "original_content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "parent_variant_id": "pyint-8b55ce558f5c-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/exceptions.py#L6-L20", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 4, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "FrozenError", "variant_id": "pyint-435a84c3e085-I10", "group_id": "py-3253fba3ed10d924", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1257, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cd7bb8c7531e-I11", "source": "from __future__ import annotations\n\nclass FrozenError(AttributeError):\n    \"\"\"\n    A frozen/immutable instance or attribute have been attempted to be\n    modified.\n\n    It mirrors the behavior of ``namedtuples`` by using the same error message\n    and subclassing `AttributeError`.\n\n    .. versionadded:: 20.1.0\n    \"\"\"\n\n    def __init__(self):\n        msg = \"can't set attribute\"\n        super().__init__(msg)\n        self.msg = msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-3253fba3ed10d924", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 17, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs__FrozenError__b8c7531e.py", "order": 11, "original_content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "parent_variant_id": "pyint-8b55ce558f5c-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/exceptions.py#L6-L20", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "FrozenError", "variant_id": "pyint-cd7bb8c7531e-I11", "group_id": "py-3253fba3ed10d924", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1258, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7774e07f6af1-I12", "source": "from __future__ import annotations\n\nclass FrozenError(AttributeError):\n    \"\"\"\n    A frozen/immutable instance or attribute have been attempted to be\n    modified.\n\n    It mirrors the behavior of ``namedtuples`` by using the same error message\n    and subclassing `AttributeError`.\n\n    .. versionadded:: 20.1.0\n    \"\"\"\n\n    def __init__(self):\n        msg = \"can't set attribute\"\n        super().__init__(msg)\n        self.msg = msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-3253fba3ed10d924", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 17, "local_path": "data-flow/inline-intermediate-variables/I12__attrs__FrozenError__e07f6af1.py", "order": 12, "original_content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "parent_variant_id": "pyint-8b55ce558f5c-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/exceptions.py#L6-L20", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "FrozenError", "variant_id": "pyint-7774e07f6af1-I12", "group_id": "py-3253fba3ed10d924", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1259, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cc36a36ab088-I13", "source": "from __future__ import annotations\n\nclass FrozenError(AttributeError):\n    \"\"\"\n    A frozen/immutable instance or attribute have been attempted to be\n    modified.\n\n    It mirrors the behavior of ``namedtuples`` by using the same error message\n    and subclassing `AttributeError`.\n\n    .. versionadded:: 20.1.0\n    \"\"\"\n\n    def __init__(self):\n        msg = \"can't set attribute\"\n        super().__init__(msg)\n        self.msg = msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-3253fba3ed10d924", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 17, "local_path": "control-flow/lower-for-to-while/I13__attrs__FrozenError__a36ab088.py", "order": 13, "original_content_sha256": "ece81b74fecc64c1c1775588420d9692eb595d4dcaaaa4d2c66c7a33d91879b2", "parent_variant_id": "pyint-8b55ce558f5c-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/exceptions.py#L6-L20", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "FrozenError", "variant_id": "pyint-cc36a36ab088-I13", "group_id": "py-3253fba3ed10d924", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1260, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a83c3202e73c-SRC", "source": "from django.core.exceptions import ImproperlyConfigured\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.db.models import QuerySet\nfrom django.http import Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\nclass MultipleObjectMixin(ContextMixin):\n    \"\"\"A mixin for views manipulating multiple objects.\"\"\"\n\n    allow_empty = True\n    queryset = None\n    model = None\n    paginate_by = None\n    paginate_orphans = 0\n    context_object_name = None\n    paginator_class = Paginator\n    page_kwarg = \"page\"\n    ordering = None\n\n    def get_queryset(self):\n        \"\"\"\n        Return the list of items for this view.\n\n        The return value must be an iterable and may be an instance of\n        `QuerySet` in which case `QuerySet` specific behavior will be enabled.\n        \"\"\"\n        if self.queryset is not None:\n            queryset = self.queryset\n            if isinstance(queryset, QuerySet):\n                queryset = queryset.all()\n        elif self.model is not None:\n            queryset = self.model._default_manager.all()\n        else:\n            raise ImproperlyConfigured(\n                \"%(cls)s is missing a QuerySet. Define \"\n                \"%(cls)s.model, %(cls)s.queryset, or override \"\n                \"%(cls)s.get_queryset().\" % {\"cls\": self.__class__.__name__}\n            )\n        ordering = self.get_ordering()\n        if ordering:\n            if isinstance(ordering, str):\n                ordering = (ordering,)\n            queryset = queryset.order_by(*ordering)\n\n        return queryset\n\n    def get_ordering(self):\n        \"\"\"Return the field or fields to use for ordering the queryset.\"\"\"\n        return self.ordering\n\n    def paginate_queryset(self, queryset, page_size):\n        \"\"\"Paginate the queryset, if needed.\"\"\"\n        paginator = self.get_paginator(\n            queryset,\n            page_size,\n            orphans=self.get_paginate_orphans(),\n            allow_empty_first_page=self.get_allow_empty(),\n        )\n        page_kwarg = self.page_kwarg\n        page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1\n        try:\n            page_number = int(page)\n        except ValueError:\n            if page == \"last\":\n                page_number = paginator.num_pages\n            else:\n                raise Http404(\n                    _(\"Page is not “last”, nor can it be converted to an int.\")\n                )\n        try:\n            page = paginator.page(page_number)\n            return (paginator, page, page.object_list, page.has_other_pages())\n        except InvalidPage as e:\n            raise Http404(\n                _(\"Invalid page (%(page_number)s): %(message)s\")\n                % {\"page_number\": page_number, \"message\": str(e)}\n            )\n\n    def get_paginate_by(self, queryset):\n        \"\"\"\n        Get the number of items to paginate by, or ``None`` for no pagination.\n        \"\"\"\n        return self.paginate_by\n\n    def get_paginator(\n        self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs\n    ):\n        \"\"\"Return an instance of the paginator for this view.\"\"\"\n        return self.paginator_class(\n            queryset,\n            per_page,\n            orphans=orphans,\n            allow_empty_first_page=allow_empty_first_page,\n            **kwargs,\n        )\n\n    def get_paginate_orphans(self):\n        \"\"\"\n        Return the maximum number of orphans extend the last page by when\n        paginating.\n        \"\"\"\n        return self.paginate_orphans\n\n    def get_allow_empty(self):\n        \"\"\"\n        Return ``True`` if the view should display empty lists and ``False``\n        if a 404 should be raised instead.\n        \"\"\"\n        return self.allow_empty\n\n    def get_context_object_name(self, object_list):\n        \"\"\"Get the name of the item to be used in the context.\"\"\"\n        if self.context_object_name:\n            return self.context_object_name\n        elif hasattr(object_list, \"model\"):\n            return \"%s_list\" % object_list.model._meta.model_name\n        else:\n            return None\n\n    def get_context_data(self, *, object_list=None, **kwargs):\n        \"\"\"Get the context for this view.\"\"\"\n        queryset = object_list if object_list is not None else self.object_list\n        page_size = self.get_paginate_by(queryset)\n        context_object_name = self.get_context_object_name(queryset)\n        if page_size:\n            paginator, page, queryset, is_paginated = self.paginate_queryset(\n                queryset, page_size\n            )\n            context = {\n                \"paginator\": paginator,\n                \"page_obj\": page,\n                \"is_paginated\": is_paginated,\n                \"object_list\": queryset,\n            }\n        else:\n            context = {\n                \"paginator\": None,\n                \"page_obj\": None,\n                \"is_paginated\": False,\n                \"object_list\": queryset,\n            }\n        if context_object_name is not None:\n            context[context_object_name] = queryset\n        context.update(kwargs)\n        return super().get_context_data(**context)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-372d283847040cc3", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 146, "local_path": "source-original/SRC__django__MultipleObjectMixin__3202e73c.py", "order": 0, "original_content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/list.py#L9-L147", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "MultipleObjectMixin", "variant_id": "pyint-a83c3202e73c-SRC", "group_id": "py-372d283847040cc3", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 295, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1f723b92104c-I01", "source": "from django.core.exceptions import ImproperlyConfigured\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.db.models import QuerySet\nfrom django.http import Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\nclass MultipleObjectMixin(ContextMixin):\n    \n\n    allow_empty = True\n    queryset = None\n    model = None\n    paginate_by = None\n    paginate_orphans = 0\n    context_object_name = None\n    paginator_class = Paginator\n    page_kwarg = \"page\"\n    ordering = None\n\n    def get_queryset(self):\n        \n        if self.queryset is not None:\n            queryset = self.queryset\n            if isinstance(queryset, QuerySet):\n                queryset = queryset.all()\n        elif self.model is not None:\n            queryset = self.model._default_manager.all()\n        else:\n            raise ImproperlyConfigured(\n                \"%(cls)s is missing a QuerySet. Define \"\n                \"%(cls)s.model, %(cls)s.queryset, or override \"\n                \"%(cls)s.get_queryset().\" % {\"cls\": self.__class__.__name__}\n            )\n        ordering = self.get_ordering()\n        if ordering:\n            if isinstance(ordering, str):\n                ordering = (ordering,)\n            queryset = queryset.order_by(*ordering)\n\n        return queryset\n\n    def get_ordering(self):\n        \n        return self.ordering\n\n    def paginate_queryset(self, queryset, page_size):\n        \n        paginator = self.get_paginator(\n            queryset,\n            page_size,\n            orphans=self.get_paginate_orphans(),\n            allow_empty_first_page=self.get_allow_empty(),\n        )\n        page_kwarg = self.page_kwarg\n        page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1\n        try:\n            page_number = int(page)\n        except ValueError:\n            if page == \"last\":\n                page_number = paginator.num_pages\n            else:\n                raise Http404(\n                    _(\"Page is not “last”, nor can it be converted to an int.\")\n                )\n        try:\n            page = paginator.page(page_number)\n            return (paginator, page, page.object_list, page.has_other_pages())\n        except InvalidPage as e:\n            raise Http404(\n                _(\"Invalid page (%(page_number)s): %(message)s\")\n                % {\"page_number\": page_number, \"message\": str(e)}\n            )\n\n    def get_paginate_by(self, queryset):\n        \n        return self.paginate_by\n\n    def get_paginator(\n        self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs\n    ):\n        \n        return self.paginator_class(\n            queryset,\n            per_page,\n            orphans=orphans,\n            allow_empty_first_page=allow_empty_first_page,\n            **kwargs,\n        )\n\n    def get_paginate_orphans(self):\n        \n        return self.paginate_orphans\n\n    def get_allow_empty(self):\n        \n        return self.allow_empty\n\n    def get_context_object_name(self, object_list):\n        \n        if self.context_object_name:\n            return self.context_object_name\n        elif hasattr(object_list, \"model\"):\n            return \"%s_list\" % object_list.model._meta.model_name\n        else:\n            return None\n\n    def get_context_data(self, *, object_list=None, **kwargs):\n        \n        queryset = object_list if object_list is not None else self.object_list\n        page_size = self.get_paginate_by(queryset)\n        context_object_name = self.get_context_object_name(queryset)\n        if page_size:\n            paginator, page, queryset, is_paginated = self.paginate_queryset(\n                queryset, page_size\n            )\n            context = {\n                \"paginator\": paginator,\n                \"page_obj\": page,\n                \"is_paginated\": is_paginated,\n                \"object_list\": queryset,\n            }\n        else:\n            context = {\n                \"paginator\": None,\n                \"page_obj\": None,\n                \"is_paginated\": False,\n                \"object_list\": queryset,\n            }\n        if context_object_name is not None:\n            context[context_object_name] = queryset\n        context.update(kwargs)\n        return super().get_context_data(**context)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-372d283847040cc3", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "1e976789375e22539938278e4258bb91d9a10684fa5abe02e9e8609fa60032e7", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 133, "local_path": "comments/remove-comments/I01__django__MultipleObjectMixin__3b92104c.py", "order": 1, "original_content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "parent_variant_id": "pyint-a83c3202e73c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/list.py#L9-L147", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 860, "comments_removed": 10, "docstrings_removed": 10, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "MultipleObjectMixin", "variant_id": "pyint-1f723b92104c-I01", "group_id": "py-372d283847040cc3", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 296, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b9f7ce10cac6-I02", "source": "from django.core.exceptions import ImproperlyConfigured\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.db.models import QuerySet\nfrom django.http import Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\nclass MultipleObjectMixin(ContextMixin):\n    \"\"\"A mixin for views manipulating multiple objects.\"\"\"\n\n    allow_empty = True\n    queryset = None\n    model = None\n    paginate_by = None\n    paginate_orphans = 0\n    context_object_name = None\n    paginator_class = Paginator\n    page_kwarg = \"page\"\n    ordering = None\n\n    def get2(self):\n        \"\"\"\n        Return the list of items for this view.\n\n        The return value must be an iterable and may be an instance of\n        `QuerySet` in which case `QuerySet` specific behavior will be enabled.\n        \"\"\"\n        if self.queryset is not None:\n            que = self.queryset\n            if isinstance(que, QuerySet):\n                que = que.all()\n        elif self.model is not None:\n            que = self.model._default_manager.all()\n        else:\n            raise ImproperlyConfigured(\n                \"%(cls)s is missing a QuerySet. Define \"\n                \"%(cls)s.model, %(cls)s.queryset, or override \"\n                \"%(cls)s.get_queryset().\" % {\"cls\": self.__class__.__name__}\n            )\n        ord = self.get3()\n        if ord:\n            if isinstance(ord, str):\n                ord = (ord,)\n            que = que.order_by(*ord)\n\n        return que\n\n    def get3(self):\n        \"\"\"Return the field or fields to use for ordering the queryset.\"\"\"\n        return self.ordering\n\n    def paginate(self, que2, page2):\n        \"\"\"Paginate the queryset, if needed.\"\"\"\n        pag = self.get5(\n            que2,\n            page2,\n            orphans=self.get6(),\n            allow_empty_first_page=self.get7(),\n        )\n        page3 = self.page_kwarg\n        pag2 = self.kwargs.get(page3) or self.request.GET.get(page3) or 1\n        try:\n            page4 = int(pag2)\n        except ValueError:\n            if pag2 == \"last\":\n                page4 = pag.num_pages\n            else:\n                raise Http404(\n                    _(\"Page is not “last”, nor can it be converted to an int.\")\n                )\n        try:\n            pag2 = pag.page(page4)\n            return (pag, pag2, pag2.object_list, pag2.has_other_pages())\n        except InvalidPage as e:\n            raise Http404(\n                _(\"Invalid page (%(page_number)s): %(message)s\")\n                % {\"page_number\": page4, \"message\": str(e)}\n            )\n\n    def get4(self, que3):\n        \"\"\"\n        Get the number of items to paginate by, or ``None`` for no pagination.\n        \"\"\"\n        return self.paginate_by\n\n    def get5(\n        self, que4, per, orp=0, allow=True, **kwa\n    ):\n        \"\"\"Return an instance of the paginator for this view.\"\"\"\n        return self.paginator_class(\n            que4,\n            per,\n            orphans=orp,\n            allow_empty_first_page=allow,\n            **kwa,\n        )\n\n    def get6(self):\n        \"\"\"\n        Return the maximum number of orphans extend the last page by when\n        paginating.\n        \"\"\"\n        return self.paginate_orphans\n\n    def get7(self):\n        \"\"\"\n        Return ``True`` if the view should display empty lists and ``False``\n        if a 404 should be raised instead.\n        \"\"\"\n        return self.allow_empty\n\n    def get8(self, object):\n        \"\"\"Get the name of the item to be used in the context.\"\"\"\n        if self.context_object_name:\n            return self.context_object_name\n        elif hasattr(object, \"model\"):\n            return \"%s_list\" % object.model._meta.model_name\n        else:\n            return None\n\n    def get9(self, *, object2=None, **kwa2):\n        \"\"\"Get the context for this view.\"\"\"\n        que5 = object2 if object2 is not None else self.object_list\n        page5 = self.get4(que5)\n        context2 = self.get8(que5)\n        if page5:\n            pag3, pag4, que5, is2 = self.paginate(\n                que5, page5\n            )\n            con = {\n                \"paginator\": pag3,\n                \"page_obj\": pag4,\n                \"is_paginated\": is2,\n                \"object_list\": que5,\n            }\n        else:\n            con = {\n                \"paginator\": None,\n                \"page_obj\": None,\n                \"is_paginated\": False,\n                \"object_list\": que5,\n            }\n        if context2 is not None:\n            con[context2] = que5\n        con.update(kwa2)\n        return super().get_context_data(**con)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-372d283847040cc3", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "a1bbc2033ab1ec1a0bc71a9ef12f8005c46811260f3cb155a0ddf7b89520de2b", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 146, "local_path": "identifiers/shorten-identifiers/I02__django__MultipleObjectMixin__ce10cac6.py", "order": 2, "original_content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "parent_variant_id": "pyint-a83c3202e73c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/list.py#L9-L147", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 96, "identifiers_declared": 33}, "unit_kind": "class", "unit_name": "MultipleObjectMixin", "variant_id": "pyint-b9f7ce10cac6-I02", "group_id": "py-372d283847040cc3", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 297, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-998ae8a04559-I03", "source": "from django.core.exceptions import ImproperlyConfigured\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.db.models import QuerySet\nfrom django.http import Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\nclass MultipleObjectMixin(ContextMixin):\n    \"\"\"A mixin for views manipulating multiple objects.\"\"\"\n\n    allow_empty = True\n    queryset = None\n    model = None\n    paginate_by = None\n    paginate_orphans = 0\n    context_object_name = None\n    paginator_class = Paginator\n    page_kwarg = \"page\"\n    ordering = None\n\n    def fetchAccount(self):\n        \"\"\"\n        Return the list of items for this view.\n\n        The return value must be an iterable and may be an instance of\n        `QuerySet` in which case `QuerySet` specific behavior will be enabled.\n        \"\"\"\n        if self.queryset is not None:\n            nextUser = self.queryset\n            if isinstance(nextUser, QuerySet):\n                nextUser = nextUser.all()\n        elif self.model is not None:\n            nextUser = self.model._default_manager.all()\n        else:\n            raise ImproperlyConfigured(\n                \"%(cls)s is missing a QuerySet. Define \"\n                \"%(cls)s.model, %(cls)s.queryset, or override \"\n                \"%(cls)s.get_queryset().\" % {\"cls\": self.__class__.__name__}\n            )\n        nextData = self.fetchMessage()\n        if nextData:\n            if isinstance(nextData, str):\n                nextData = (nextData,)\n            nextUser = nextUser.order_by(*nextData)\n\n        return nextUser\n\n    def fetchMessage(self):\n        \"\"\"Return the field or fields to use for ordering the queryset.\"\"\"\n        return self.ordering\n\n    def validateMessage(self, category, finalUser):\n        \"\"\"Paginate the queryset, if needed.\"\"\"\n        nextEvent = self.validateScore(\n            category,\n            finalUser,\n            orphans=self.validateBalance(),\n            allow_empty_first_page=self.validateAddress(),\n        )\n        activeUser = self.page_kwarg\n        data = self.kwargs.get(activeUser) or self.request.GET.get(activeUser) or 1\n        try:\n            recentScore = int(data)\n        except ValueError:\n            if data == \"last\":\n                recentScore = nextEvent.num_pages\n            else:\n                raise Http404(\n                    _(\"Page is not “last”, nor can it be converted to an int.\")\n                )\n        try:\n            data = nextEvent.page(recentScore)\n            return (nextEvent, data, data.object_list, data.has_other_pages())\n        except InvalidPage as e:\n            raise Http404(\n                _(\"Invalid page (%(page_number)s): %(message)s\")\n                % {\"page_number\": recentScore, \"message\": str(e)}\n            )\n\n    def validateSession(self, discount):\n        \"\"\"\n        Get the number of items to paginate by, or ``None`` for no pagination.\n        \"\"\"\n        return self.paginate_by\n\n    def validateScore(\n        self, nextItem, document, version=0, primaryBalance=True, **result\n    ):\n        \"\"\"Return an instance of the paginator for this view.\"\"\"\n        return self.paginator_class(\n            nextItem,\n            document,\n            orphans=version,\n            allow_empty_first_page=primaryBalance,\n            **result,\n        )\n\n    def validateBalance(self):\n        \"\"\"\n        Return the maximum number of orphans extend the last page by when\n        paginating.\n        \"\"\"\n        return self.paginate_orphans\n\n    def validateAddress(self):\n        \"\"\"\n        Return ``True`` if the view should display empty lists and ``False``\n        if a 404 should be raised instead.\n        \"\"\"\n        return self.allow_empty\n\n    def validateRequest(self, currentMode):\n        \"\"\"Get the name of the item to be used in the context.\"\"\"\n        if self.context_object_name:\n            return self.context_object_name\n        elif hasattr(currentMode, \"model\"):\n            return \"%s_list\" % currentMode.model._meta.model_name\n        else:\n            return None\n\n    def validateAccount(self, *, destination=None, **result):\n        \"\"\"Get the context for this view.\"\"\"\n        nextPath = destination if destination is not None else self.object_list\n        nextIndex = self.validateSession(nextPath)\n        primaryMessage = self.validateRequest(nextPath)\n        if nextIndex:\n            nextToken, node, nextPath, activeConfig = self.validateMessage(\n                nextPath, nextIndex\n            )\n            channel = {\n                \"paginator\": nextToken,\n                \"page_obj\": node,\n                \"is_paginated\": activeConfig,\n                \"object_list\": nextPath,\n            }\n        else:\n            channel = {\n                \"paginator\": None,\n                \"page_obj\": None,\n                \"is_paginated\": False,\n                \"object_list\": nextPath,\n            }\n        if primaryMessage is not None:\n            channel[primaryMessage] = nextPath\n        channel.update(result)\n        return super().get_context_data(**channel)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-372d283847040cc3", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "7fe8be9b0f44ee087f9e590585664978de3084bf5165fa32c320b1dfb83866ef", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 146, "local_path": "identifiers/mislead-identifiers/I03__django__MultipleObjectMixin__e8a04559.py", "order": 3, "original_content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "parent_variant_id": "pyint-a83c3202e73c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/list.py#L9-L147", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 96, "identifiers_declared": 33, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 2, "local_exact_length_matches": 22, "local_random_pool_selections": 24, "local_total_length_difference": 13, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 5, "method_exact_length_matches": 5, "method_random_pool_selections": 9, "method_total_length_difference": 16}, "unit_kind": "class", "unit_name": "MultipleObjectMixin", "variant_id": "pyint-998ae8a04559-I03", "group_id": "py-372d283847040cc3", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 298, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-49bdec2e9b59-I04", "source": "from django.core.exceptions import ImproperlyConfigured\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.db.models import QuerySet\nfrom django.http import Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\nclass MultipleObjectMixin(ContextMixin):\n    \"\"\"A mixin for views manipulating multiple objects.\"\"\"\n\n    allow_empty = True\n    queryset = None\n    model = None\n    paginate_by = None\n    paginate_orphans = 0\n    context_object_name = None\n    paginator_class = Paginator\n    page_kwarg = \"page\"\n    ordering = None\n\n    def a(self):\n        \"\"\"\n        Return the list of items for this view.\n\n        The return value must be an iterable and may be an instance of\n        `QuerySet` in which case `QuerySet` specific behavior will be enabled.\n        \"\"\"\n        if self.queryset is not None:\n            k = self.queryset\n            if isinstance(k, QuerySet):\n                k = k.all()\n        elif self.model is not None:\n            k = self.model._default_manager.all()\n        else:\n            raise ImproperlyConfigured(\n                \"%(cls)s is missing a QuerySet. Define \"\n                \"%(cls)s.model, %(cls)s.queryset, or override \"\n                \"%(cls)s.get_queryset().\" % {\"cls\": self.__class__.__name__}\n            )\n        l = self.b()\n        if l:\n            if isinstance(l, str):\n                l = (l,)\n            k = k.order_by(*l)\n\n        return k\n\n    def b(self):\n        \"\"\"Return the field or fields to use for ordering the queryset.\"\"\"\n        return self.ordering\n\n    def c(self, m, n):\n        \"\"\"Paginate the queryset, if needed.\"\"\"\n        o = self.f(\n            m,\n            n,\n            orphans=self.g(),\n            allow_empty_first_page=self.h(),\n        )\n        p = self.page_kwarg\n        q = self.kwargs.get(p) or self.request.GET.get(p) or 1\n        try:\n            r = int(q)\n        except ValueError:\n            if q == \"last\":\n                r = o.num_pages\n            else:\n                raise Http404(\n                    _(\"Page is not “last”, nor can it be converted to an int.\")\n                )\n        try:\n            q = o.page(r)\n            return (o, q, q.object_list, q.has_other_pages())\n        except InvalidPage as e:\n            raise Http404(\n                _(\"Invalid page (%(page_number)s): %(message)s\")\n                % {\"page_number\": r, \"message\": str(e)}\n            )\n\n    def d(self, s):\n        \"\"\"\n        Get the number of items to paginate by, or ``None`` for no pagination.\n        \"\"\"\n        return self.paginate_by\n\n    def f(\n        self, t, u, v=0, w=True, **x\n    ):\n        \"\"\"Return an instance of the paginator for this view.\"\"\"\n        return self.paginator_class(\n            t,\n            u,\n            orphans=v,\n            allow_empty_first_page=w,\n            **x,\n        )\n\n    def g(self):\n        \"\"\"\n        Return the maximum number of orphans extend the last page by when\n        paginating.\n        \"\"\"\n        return self.paginate_orphans\n\n    def h(self):\n        \"\"\"\n        Return ``True`` if the view should display empty lists and ``False``\n        if a 404 should be raised instead.\n        \"\"\"\n        return self.allow_empty\n\n    def i(self, y):\n        \"\"\"Get the name of the item to be used in the context.\"\"\"\n        if self.context_object_name:\n            return self.context_object_name\n        elif hasattr(y, \"model\"):\n            return \"%s_list\" % y.model._meta.model_name\n        else:\n            return None\n\n    def j(self, *, z=None, **A):\n        \"\"\"Get the context for this view.\"\"\"\n        B = z if z is not None else self.object_list\n        C = self.d(B)\n        D = self.i(B)\n        if C:\n            E, F, B, G = self.c(\n                B, C\n            )\n            H = {\n                \"paginator\": E,\n                \"page_obj\": F,\n                \"is_paginated\": G,\n                \"object_list\": B,\n            }\n        else:\n            H = {\n                \"paginator\": None,\n                \"page_obj\": None,\n                \"is_paginated\": False,\n                \"object_list\": B,\n            }\n        if D is not None:\n            H[D] = B\n        H.update(A)\n        return super().get_context_data(**H)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-372d283847040cc3", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "2cbef6e12f42a0c61c1967b3d971f7af13778682a552593823b1bc0133b84d0c", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 146, "local_path": "identifiers/garble-identifiers/I04__django__MultipleObjectMixin__ec2e9b59.py", "order": 4, "original_content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "parent_variant_id": "pyint-a83c3202e73c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/list.py#L9-L147", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 96, "identifiers_declared": 33}, "unit_kind": "class", "unit_name": "MultipleObjectMixin", "variant_id": "pyint-49bdec2e9b59-I04", "group_id": "py-372d283847040cc3", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 299, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8f194d046c3a-I05", "source": "from django.core.exceptions import ImproperlyConfigured\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.db.models import QuerySet\nfrom django.http import Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\nclass MultipleObjectMixin(ContextMixin):\n    \"\"\"A mixin for views manipulating multiple objects.\"\"\"\n\n    allow_empty = True\n    queryset = None\n    model = None\n    paginate_by = None\n    paginate_orphans = 0x0\n    context_object_name = None\n    paginator_class = Paginator\n    page_kwarg = \"page\"\n    ordering = None\n\n    def get_queryset(self):\n        \"\"\"\n        Return the list of items for this view.\n\n        The return value must be an iterable and may be an instance of\n        `QuerySet` in which case `QuerySet` specific behavior will be enabled.\n        \"\"\"\n        if self.queryset is not None:\n            queryset = self.queryset\n            if isinstance(queryset, QuerySet):\n                queryset = queryset.all()\n        elif self.model is not None:\n            queryset = self.model._default_manager.all()\n        else:\n            raise ImproperlyConfigured(\n                \"%(cls)s is missing a QuerySet. Define \"\n                \"%(cls)s.model, %(cls)s.queryset, or override \"\n                \"%(cls)s.get_queryset().\" % {\"cls\": self.__class__.__name__}\n            )\n        ordering = self.get_ordering()\n        if ordering:\n            if isinstance(ordering, str):\n                ordering = (ordering,)\n            queryset = queryset.order_by(*ordering)\n\n        return queryset\n\n    def get_ordering(self):\n        \"\"\"Return the field or fields to use for ordering the queryset.\"\"\"\n        return self.ordering\n\n    def paginate_queryset(self, queryset, page_size):\n        \"\"\"Paginate the queryset, if needed.\"\"\"\n        paginator = self.get_paginator(\n            queryset,\n            page_size,\n            orphans=self.get_paginate_orphans(),\n            allow_empty_first_page=self.get_allow_empty(),\n        )\n        page_kwarg = self.page_kwarg\n        page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 0x1\n        try:\n            page_number = int(page)\n        except ValueError:\n            if page == \"last\":\n                page_number = paginator.num_pages\n            else:\n                raise Http404(\n                    _(\"Page is not “last”, nor can it be converted to an int.\")\n                )\n        try:\n            page = paginator.page(page_number)\n            return (paginator, page, page.object_list, page.has_other_pages())\n        except InvalidPage as e:\n            raise Http404(\n                _(\"Invalid page (%(page_number)s): %(message)s\")\n                % {\"page_number\": page_number, \"message\": str(e)}\n            )\n\n    def get_paginate_by(self, queryset):\n        \"\"\"\n        Get the number of items to paginate by, or ``None`` for no pagination.\n        \"\"\"\n        return self.paginate_by\n\n    def get_paginator(\n        self, queryset, per_page, orphans=0x0, allow_empty_first_page=True, **kwargs\n    ):\n        \"\"\"Return an instance of the paginator for this view.\"\"\"\n        return self.paginator_class(\n            queryset,\n            per_page,\n            orphans=orphans,\n            allow_empty_first_page=allow_empty_first_page,\n            **kwargs,\n        )\n\n    def get_paginate_orphans(self):\n        \"\"\"\n        Return the maximum number of orphans extend the last page by when\n        paginating.\n        \"\"\"\n        return self.paginate_orphans\n\n    def get_allow_empty(self):\n        \"\"\"\n        Return ``True`` if the view should display empty lists and ``False``\n        if a 404 should be raised instead.\n        \"\"\"\n        return self.allow_empty\n\n    def get_context_object_name(self, object_list):\n        \"\"\"Get the name of the item to be used in the context.\"\"\"\n        if self.context_object_name:\n            return self.context_object_name\n        elif hasattr(object_list, \"model\"):\n            return \"%s_list\" % object_list.model._meta.model_name\n        else:\n            return None\n\n    def get_context_data(self, *, object_list=None, **kwargs):\n        \"\"\"Get the context for this view.\"\"\"\n        queryset = object_list if object_list is not None else self.object_list\n        page_size = self.get_paginate_by(queryset)\n        context_object_name = self.get_context_object_name(queryset)\n        if page_size:\n            paginator, page, queryset, is_paginated = self.paginate_queryset(\n                queryset, page_size\n            )\n            context = {\n                \"paginator\": paginator,\n                \"page_obj\": page,\n                \"is_paginated\": is_paginated,\n                \"object_list\": queryset,\n            }\n        else:\n            context = {\n                \"paginator\": None,\n                \"page_obj\": None,\n                \"is_paginated\": False,\n                \"object_list\": queryset,\n            }\n        if context_object_name is not None:\n            context[context_object_name] = queryset\n        context.update(kwargs)\n        return super().get_context_data(**context)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-372d283847040cc3", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "92a8e7f846b4bbe01e2c752e20edb051d85f3f76ebf2b6d82ea4360677160e84", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 146, "local_path": "expressions/encode-integer-literals/I05__django__MultipleObjectMixin__4d046c3a.py", "order": 5, "original_content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "parent_variant_id": "pyint-a83c3202e73c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/list.py#L9-L147", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 3}, "unit_kind": "class", "unit_name": "MultipleObjectMixin", "variant_id": "pyint-8f194d046c3a-I05", "group_id": "py-372d283847040cc3", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 300, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f46b9b298fda-I06", "source": "from django.core.exceptions import ImproperlyConfigured\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.db.models import QuerySet\nfrom django.http import Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\nclass MultipleObjectMixin(ContextMixin):\n    \"\"\"A mixin for views manipulating multiple objects.\"\"\"\n\n    allow_empty = True\n    queryset = None\n    model = None\n    paginate_by = None\n    paginate_orphans = 0\n    context_object_name = None\n    paginator_class = Paginator\n    page_kwarg = \"page\"\n    ordering = None\n\n    def get_queryset(self):\n        \"\"\"\n        Return the list of items for this view.\n\n        The return value must be an iterable and may be an instance of\n        `QuerySet` in which case `QuerySet` specific behavior will be enabled.\n        \"\"\"\n        if self.queryset is not None:\n            queryset = self.queryset\n            if isinstance(queryset, QuerySet):\n                queryset = queryset.all()\n        elif self.model is not None:\n            queryset = self.model._default_manager.all()\n        else:\n            raise ImproperlyConfigured(\n                \"%(cls)s is missing a QuerySet. Define \"\n                \"%(cls)s.model, %(cls)s.queryset, or override \"\n                \"%(cls)s.get_queryset().\" % {\"cls\": self.__class__.__name__}\n            )\n        ordering = self.get_ordering()\n        if not (ordering):\n            pass\n        else:\n            if isinstance(ordering, str):\n                ordering = (ordering,)\n            queryset = queryset.order_by(*ordering)\n\n        return queryset\n\n    def get_ordering(self):\n        \"\"\"Return the field or fields to use for ordering the queryset.\"\"\"\n        return self.ordering\n\n    def paginate_queryset(self, queryset, page_size):\n        \"\"\"Paginate the queryset, if needed.\"\"\"\n        paginator = self.get_paginator(\n            queryset,\n            page_size,\n            orphans=self.get_paginate_orphans(),\n            allow_empty_first_page=self.get_allow_empty(),\n        )\n        page_kwarg = self.page_kwarg\n        page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1\n        try:\n            page_number = int(page)\n        except ValueError:\n            if not (page == \"last\"):\n                raise Http404(\n                    _(\"Page is not “last”, nor can it be converted to an int.\")\n                )\n            else:\n                page_number = paginator.num_pages\n        try:\n            page = paginator.page(page_number)\n            return (paginator, page, page.object_list, page.has_other_pages())\n        except InvalidPage as e:\n            raise Http404(\n                _(\"Invalid page (%(page_number)s): %(message)s\")\n                % {\"page_number\": page_number, \"message\": str(e)}\n            )\n\n    def get_paginate_by(self, queryset):\n        \"\"\"\n        Get the number of items to paginate by, or ``None`` for no pagination.\n        \"\"\"\n        return self.paginate_by\n\n    def get_paginator(\n        self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs\n    ):\n        \"\"\"Return an instance of the paginator for this view.\"\"\"\n        return self.paginator_class(\n            queryset,\n            per_page,\n            orphans=orphans,\n            allow_empty_first_page=allow_empty_first_page,\n            **kwargs,\n        )\n\n    def get_paginate_orphans(self):\n        \"\"\"\n        Return the maximum number of orphans extend the last page by when\n        paginating.\n        \"\"\"\n        return self.paginate_orphans\n\n    def get_allow_empty(self):\n        \"\"\"\n        Return ``True`` if the view should display empty lists and ``False``\n        if a 404 should be raised instead.\n        \"\"\"\n        return self.allow_empty\n\n    def get_context_object_name(self, object_list):\n        \"\"\"Get the name of the item to be used in the context.\"\"\"\n        if self.context_object_name:\n            return self.context_object_name\n        elif hasattr(object_list, \"model\"):\n            return \"%s_list\" % object_list.model._meta.model_name\n        else:\n            return None\n\n    def get_context_data(self, *, object_list=None, **kwargs):\n        \"\"\"Get the context for this view.\"\"\"\n        queryset = object_list if object_list is not None else self.object_list\n        page_size = self.get_paginate_by(queryset)\n        context_object_name = self.get_context_object_name(queryset)\n        if not (page_size):\n            context = {\n                \"paginator\": None,\n                \"page_obj\": None,\n                \"is_paginated\": False,\n                \"object_list\": queryset,\n            }\n        else:\n            paginator, page, queryset, is_paginated = self.paginate_queryset(\n                queryset, page_size\n            )\n            context = {\n                \"paginator\": paginator,\n                \"page_obj\": page,\n                \"is_paginated\": is_paginated,\n                \"object_list\": queryset,\n            }\n        if not (context_object_name is not None):\n            pass\n        else:\n            context[context_object_name] = queryset\n        context.update(kwargs)\n        return super().get_context_data(**context)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-372d283847040cc3", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "dc1a59a380b29595d50d5cba359fa974eadf477bcad60e21b90bd3c3b2eb766c", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 150, "local_path": "expressions/invert-conditions/I06__django__MultipleObjectMixin__9b298fda.py", "order": 6, "original_content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "parent_variant_id": "pyint-a83c3202e73c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/list.py#L9-L147", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 4}, "unit_kind": "class", "unit_name": "MultipleObjectMixin", "variant_id": "pyint-f46b9b298fda-I06", "group_id": "py-372d283847040cc3", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 301, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-677a3104753a-I07", "source": "from django.core.exceptions import ImproperlyConfigured\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.db.models import QuerySet\nfrom django.http import Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\nclass MultipleObjectMixin(ContextMixin):\n    \"\"\"A mixin for views manipulating multiple objects.\"\"\"\n\n    allow_empty = True\n    queryset = None\n    model = None\n    paginate_by = None\n    paginate_orphans = 0\n    context_object_name = None\n    paginator_class = Paginator\n    page_kwarg = \"page\"\n    ordering = None\n\n    def get_queryset(self):\n        \"\"\"\n        Return the list of items for this view.\n\n        The return value must be an iterable and may be an instance of\n        `QuerySet` in which case `QuerySet` specific behavior will be enabled.\n        \"\"\"\n        if ((0xeab ^ 0xeab) != 0):\n            raise AssertionError()\n        if self.queryset is not None:\n            queryset = self.queryset\n            if isinstance(queryset, QuerySet):\n                queryset = queryset.all()\n        elif self.model is not None:\n            queryset = self.model._default_manager.all()\n        else:\n            raise ImproperlyConfigured(\n                \"%(cls)s is missing a QuerySet. Define \"\n                \"%(cls)s.model, %(cls)s.queryset, or override \"\n                \"%(cls)s.get_queryset().\" % {\"cls\": self.__class__.__name__}\n            )\n        ordering = self.get_ordering()\n        if ordering:\n            if isinstance(ordering, str):\n                ordering = (ordering,)\n            queryset = queryset.order_by(*ordering)\n\n        return queryset\n\n    def get_ordering(self):\n        \"\"\"Return the field or fields to use for ordering the queryset.\"\"\"\n        if ((0x9fa4 ^ 0x9fa4) != 0):\n            raise AssertionError()\n        return self.ordering\n\n    def paginate_queryset(self, queryset, page_size):\n        \"\"\"Paginate the queryset, if needed.\"\"\"\n        if ((0xa398 ^ 0xa398) != 0):\n            raise AssertionError()\n        paginator = self.get_paginator(\n            queryset,\n            page_size,\n            orphans=self.get_paginate_orphans(),\n            allow_empty_first_page=self.get_allow_empty(),\n        )\n        page_kwarg = self.page_kwarg\n        page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1\n        try:\n            page_number = int(page)\n        except ValueError:\n            if page == \"last\":\n                page_number = paginator.num_pages\n            else:\n                raise Http404(\n                    _(\"Page is not “last”, nor can it be converted to an int.\")\n                )\n        try:\n            page = paginator.page(page_number)\n            return (paginator, page, page.object_list, page.has_other_pages())\n        except InvalidPage as e:\n            raise Http404(\n                _(\"Invalid page (%(page_number)s): %(message)s\")\n                % {\"page_number\": page_number, \"message\": str(e)}\n            )\n\n    def get_paginate_by(self, queryset):\n        \"\"\"\n        Get the number of items to paginate by, or ``None`` for no pagination.\n        \"\"\"\n        if ((0x38dd ^ 0x38dd) != 0):\n            raise AssertionError()\n        return self.paginate_by\n\n    def get_paginator(\n        self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs\n    ):\n        \"\"\"Return an instance of the paginator for this view.\"\"\"\n        if ((0x845 ^ 0x845) != 0):\n            raise AssertionError()\n        return self.paginator_class(\n            queryset,\n            per_page,\n            orphans=orphans,\n            allow_empty_first_page=allow_empty_first_page,\n            **kwargs,\n        )\n\n    def get_paginate_orphans(self):\n        \"\"\"\n        Return the maximum number of orphans extend the last page by when\n        paginating.\n        \"\"\"\n        if ((0x296c ^ 0x296c) != 0):\n            raise AssertionError()\n        return self.paginate_orphans\n\n    def get_allow_empty(self):\n        \"\"\"\n        Return ``True`` if the view should display empty lists and ``False``\n        if a 404 should be raised instead.\n        \"\"\"\n        if ((0x5bf3 ^ 0x5bf3) != 0):\n            raise AssertionError()\n        return self.allow_empty\n\n    def get_context_object_name(self, object_list):\n        \"\"\"Get the name of the item to be used in the context.\"\"\"\n        if ((0x1bd ^ 0x1bd) != 0):\n            raise AssertionError()\n        if self.context_object_name:\n            return self.context_object_name\n        elif hasattr(object_list, \"model\"):\n            return \"%s_list\" % object_list.model._meta.model_name\n        else:\n            return None\n\n    def get_context_data(self, *, object_list=None, **kwargs):\n        \"\"\"Get the context for this view.\"\"\"\n        if ((0xd0a6 ^ 0xd0a6) != 0):\n            raise AssertionError()\n        queryset = object_list if object_list is not None else self.object_list\n        page_size = self.get_paginate_by(queryset)\n        context_object_name = self.get_context_object_name(queryset)\n        if page_size:\n            paginator, page, queryset, is_paginated = self.paginate_queryset(\n                queryset, page_size\n            )\n            context = {\n                \"paginator\": paginator,\n                \"page_obj\": page,\n                \"is_paginated\": is_paginated,\n                \"object_list\": queryset,\n            }\n        else:\n            context = {\n                \"paginator\": None,\n                \"page_obj\": None,\n                \"is_paginated\": False,\n                \"object_list\": queryset,\n            }\n        if context_object_name is not None:\n            context[context_object_name] = queryset\n        context.update(kwargs)\n        return super().get_context_data(**context)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-372d283847040cc3", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "6a2b62c142641811d1b8f920d1ebbb4f4dcd6908b5703012ce50d78201453ce1", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 164, "local_path": "code-injection/insert-dead-branches/I07__django__MultipleObjectMixin__3104753a.py", "order": 7, "original_content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "parent_variant_id": "pyint-a83c3202e73c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/list.py#L9-L147", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 9}, "unit_kind": "class", "unit_name": "MultipleObjectMixin", "variant_id": "pyint-677a3104753a-I07", "group_id": "py-372d283847040cc3", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 302, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a8c6cc01cce5-I08", "source": "from django.core.exceptions import ImproperlyConfigured\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.db.models import QuerySet\nfrom django.http import Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\nclass MultipleObjectMixin(ContextMixin):\n    \"\"\"A mixin for views manipulating multiple objects.\"\"\"\n\n    allow_empty = True\n    queryset = None\n    model = None\n    paginate_by = None\n    paginate_orphans = 0\n    context_object_name = None\n    paginator_class = Paginator\n    page_kwarg = \"page\"\n    ordering = None\n\n    def get_queryset(self):\n        \"\"\"\n        Return the list of items for this view.\n\n        The return value must be an iterable and may be an instance of\n        `QuerySet` in which case `QuerySet` specific behavior will be enabled.\n        \"\"\"\n        even_number_count = 0\n        for candidate_number in range(6):\n            if candidate_number % 2 == 0:\n                even_number_count += 1\n        if self.queryset is not None:\n            queryset = self.queryset\n            if isinstance(queryset, QuerySet):\n                queryset = queryset.all()\n        elif self.model is not None:\n            queryset = self.model._default_manager.all()\n        else:\n            raise ImproperlyConfigured(\n                \"%(cls)s is missing a QuerySet. Define \"\n                \"%(cls)s.model, %(cls)s.queryset, or override \"\n                \"%(cls)s.get_queryset().\" % {\"cls\": self.__class__.__name__}\n            )\n        ordering = self.get_ordering()\n        if ordering:\n            if isinstance(ordering, str):\n                ordering = (ordering,)\n            queryset = queryset.order_by(*ordering)\n\n        return queryset\n\n    def get_ordering(self):\n        \"\"\"Return the field or fields to use for ordering the queryset.\"\"\"\n        return self.ordering\n\n    def paginate_queryset(self, queryset, page_size):\n        \"\"\"Paginate the queryset, if needed.\"\"\"\n        paginator = self.get_paginator(\n            queryset,\n            page_size,\n            orphans=self.get_paginate_orphans(),\n            allow_empty_first_page=self.get_allow_empty(),\n        )\n        page_kwarg = self.page_kwarg\n        page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1\n        try:\n            page_number = int(page)\n        except ValueError:\n            if page == \"last\":\n                page_number = paginator.num_pages\n            else:\n                raise Http404(\n                    _(\"Page is not “last”, nor can it be converted to an int.\")\n                )\n        try:\n            page = paginator.page(page_number)\n            return (paginator, page, page.object_list, page.has_other_pages())\n        except InvalidPage as e:\n            raise Http404(\n                _(\"Invalid page (%(page_number)s): %(message)s\")\n                % {\"page_number\": page_number, \"message\": str(e)}\n            )\n\n    def get_paginate_by(self, queryset):\n        \"\"\"\n        Get the number of items to paginate by, or ``None`` for no pagination.\n        \"\"\"\n        return self.paginate_by\n\n    def get_paginator(\n        self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs\n    ):\n        \"\"\"Return an instance of the paginator for this view.\"\"\"\n        return self.paginator_class(\n            queryset,\n            per_page,\n            orphans=orphans,\n            allow_empty_first_page=allow_empty_first_page,\n            **kwargs,\n        )\n\n    def get_paginate_orphans(self):\n        \"\"\"\n        Return the maximum number of orphans extend the last page by when\n        paginating.\n        \"\"\"\n        return self.paginate_orphans\n\n    def get_allow_empty(self):\n        \"\"\"\n        Return ``True`` if the view should display empty lists and ``False``\n        if a 404 should be raised instead.\n        \"\"\"\n        return self.allow_empty\n\n    def get_context_object_name(self, object_list):\n        \"\"\"Get the name of the item to be used in the context.\"\"\"\n        if self.context_object_name:\n            return self.context_object_name\n        elif hasattr(object_list, \"model\"):\n            return \"%s_list\" % object_list.model._meta.model_name\n        else:\n            return None\n\n    def get_context_data(self, *, object_list=None, **kwargs):\n        \"\"\"Get the context for this view.\"\"\"\n        queryset = object_list if object_list is not None else self.object_list\n        page_size = self.get_paginate_by(queryset)\n        context_object_name = self.get_context_object_name(queryset)\n        if page_size:\n            paginator, page, queryset, is_paginated = self.paginate_queryset(\n                queryset, page_size\n            )\n            context = {\n                \"paginator\": paginator,\n                \"page_obj\": page,\n                \"is_paginated\": is_paginated,\n                \"object_list\": queryset,\n            }\n        else:\n            context = {\n                \"paginator\": None,\n                \"page_obj\": None,\n                \"is_paginated\": False,\n                \"object_list\": queryset,\n            }\n        if context_object_name is not None:\n            context[context_object_name] = queryset\n        context.update(kwargs)\n        return super().get_context_data(**context)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-372d283847040cc3", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "a719a78936b9ede0fe46a98aebf80bafbeb225952a74eea844a3f9975b0787fe", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 150, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__MultipleObjectMixin__cc01cce5.py", "order": 8, "original_content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "parent_variant_id": "pyint-a83c3202e73c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/list.py#L9-L147", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 4, "readable_template_index": 2}, "unit_kind": "class", "unit_name": "MultipleObjectMixin", "variant_id": "pyint-a8c6cc01cce5-I08", "group_id": "py-372d283847040cc3", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 303, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-977cc96b24b2-I09", "source": "from django.core.exceptions import ImproperlyConfigured\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.db.models import QuerySet\nfrom django.http import Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\nclass MultipleObjectMixin(ContextMixin):\n    \"\"\"A mixin for views manipulating multiple objects.\"\"\"\n\n    allow_empty = True\n    queryset = None\n    model = None\n    paginate_by = None\n    paginate_orphans = 0\n    context_object_name = None\n    paginator_class = Paginator\n    page_kwarg = \"page\"\n    ordering = None\n\n    def get_queryset(self):\n        \"\"\"\n        Return the list of items for this view.\n\n        The return value must be an iterable and may be an instance of\n        `QuerySet` in which case `QuerySet` specific behavior will be enabled.\n        \"\"\"\n        if self.queryset is not None:\n            queryset = self.queryset\n            if isinstance(queryset, QuerySet):\n                queryset = queryset.all()\n        elif self.model is not None:\n            queryset = self.model._default_manager.all()\n        else:\n            raise ImproperlyConfigured(\n                \"%(cls)s is missing a QuerySet. Define \"\n                \"%(cls)s.model, %(cls)s.queryset, or override \"\n                \"%(cls)s.get_queryset().\" % {\"cls\": self.__class__.__name__}\n            )\n        ordering = self.get_ordering()\n        if ordering:\n            if isinstance(ordering, str):\n                ordering = (ordering,)\n            queryset = queryset.order_by(*ordering)\n\n        return queryset\n\n    def get_ordering(self):\n        \"\"\"Return the field or fields to use for ordering the queryset.\"\"\"\n        return self.ordering\n\n    def paginate_queryset(self, queryset, page_size):\n        \"\"\"Paginate the queryset, if needed.\"\"\"\n        paginator = self.get_paginator(\n            queryset,\n            page_size,\n            orphans=self.get_paginate_orphans(),\n            allow_empty_first_page=self.get_allow_empty(),\n        )\n        page_kwarg = self.page_kwarg\n        page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1\n        try:\n            page_number = int(page)\n        except ValueError:\n            if page == \"last\":\n                page_number = paginator.num_pages\n            else:\n                raise Http404(\n                    _(\"Page is not “last”, nor can it be converted to an int.\")\n                )\n        try:\n            page = paginator.page(page_number)\n            return (paginator, page, page.object_list, page.has_other_pages())\n        except InvalidPage as e:\n            raise Http404(\n                _(\"Invalid page (%(page_number)s): %(message)s\")\n                % {\"page_number\": page_number, \"message\": str(e)}\n            )\n\n    def get_paginate_by(self, queryset):\n        \"\"\"\n        Get the number of items to paginate by, or ``None`` for no pagination.\n        \"\"\"\n        return self.paginate_by\n\n    def get_paginator(\n        self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs\n    ):\n        \"\"\"Return an instance of the paginator for this view.\"\"\"\n        return self.paginator_class(\n            queryset,\n            per_page,\n            orphans=orphans,\n            allow_empty_first_page=allow_empty_first_page,\n            **kwargs,\n        )\n\n    def get_paginate_orphans(self):\n        \"\"\"\n        Return the maximum number of orphans extend the last page by when\n        paginating.\n        \"\"\"\n        return self.paginate_orphans\n\n    def get_allow_empty(self):\n        \"\"\"\n        Return ``True`` if the view should display empty lists and ``False``\n        if a 404 should be raised instead.\n        \"\"\"\n        return self.allow_empty\n\n    def get_context_object_name(self, object_list):\n        \"\"\"Get the name of the item to be used in the context.\"\"\"\n        lI0O_bf185fc7 = 0xe77a ^ 0xe77a\n        if lI0O_bf185fc7 != 0:\n            if ((lI0O_bf185fc7 | 1) & 1) == 0:\n                lI0O_bf185fc7 += 1\n            else:\n                lI0O_bf185fc7 -= 1\n        if self.context_object_name:\n            return self.context_object_name\n        elif hasattr(object_list, \"model\"):\n            return \"%s_list\" % object_list.model._meta.model_name\n        else:\n            return None\n\n    def get_context_data(self, *, object_list=None, **kwargs):\n        \"\"\"Get the context for this view.\"\"\"\n        queryset = object_list if object_list is not None else self.object_list\n        page_size = self.get_paginate_by(queryset)\n        context_object_name = self.get_context_object_name(queryset)\n        if page_size:\n            paginator, page, queryset, is_paginated = self.paginate_queryset(\n                queryset, page_size\n            )\n            context = {\n                \"paginator\": paginator,\n                \"page_obj\": page,\n                \"is_paginated\": is_paginated,\n                \"object_list\": queryset,\n            }\n        else:\n            context = {\n                \"paginator\": None,\n                \"page_obj\": None,\n                \"is_paginated\": False,\n                \"object_list\": queryset,\n            }\n        if context_object_name is not None:\n            context[context_object_name] = queryset\n        context.update(kwargs)\n        return super().get_context_data(**context)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-372d283847040cc3", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "8bef58f1b659eee5c1476b75023293d0fbbd71027d21c20b3a39210d17571d88", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 152, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__MultipleObjectMixin__c96b24b2.py", "order": 9, "original_content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "parent_variant_id": "pyint-a83c3202e73c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/list.py#L9-L147", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 5}, "unit_kind": "class", "unit_name": "MultipleObjectMixin", "variant_id": "pyint-977cc96b24b2-I09", "group_id": "py-372d283847040cc3", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 304, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d0a9b1865b27-I10", "source": "from django.core.exceptions import ImproperlyConfigured\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.db.models import QuerySet\nfrom django.http import Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\nclass MultipleObjectMixin(ContextMixin):\n    \"\"\"A mixin for views manipulating multiple objects.\"\"\"\n\n    allow_empty = True\n    queryset = None\n    model = None\n    paginate_by = None\n    paginate_orphans = 0\n    context_object_name = None\n    paginator_class = Paginator\n    page_kwarg = \"page\"\n    ordering = None\n    def get_queryset(self):\n        \"\"\"\n        Return the list of items for this view.\n        The return value must be an iterable and may be an instance of\n        `QuerySet` in which case `QuerySet` specific behavior will be enabled.\n        \"\"\"\n        if self.queryset is not None:\n            queryset = self.queryset\n            if isinstance(queryset, QuerySet):\n                queryset = queryset.all()\n        elif self.model is not None:\n            queryset = self.model._default_manager.all()\n        else:\n            raise ImproperlyConfigured(\n                \"%(cls)s is missing a QuerySet. Define \"                 \"%(cls)s.model, %(cls)s.queryset, or override \"\n                \"%(cls)s.get_queryset().\" % {\"cls\": self.__class__.__name__}\n            )\n        ordering = self.get_ordering()\n        if ordering:\n            if isinstance(ordering, str):\n                ordering = (ordering,)\n            queryset = queryset.order_by(*ordering)\n\n        return queryset\n\n    def get_ordering(self):\n        \"\"\"Return the field or fields to use for ordering the queryset.\"\"\"\n        return self.ordering\n\n    def paginate_queryset(self, queryset, page_size):\n        \"\"\"Paginate the queryset, if needed.\"\"\"\n        paginator = self.get_paginator(\n            queryset,             page_size,\n            orphans=self.get_paginate_orphans(),             allow_empty_first_page=self.get_allow_empty(),         )\n        page_kwarg = self.page_kwarg\n        page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1\n        try:\n            page_number = int(page)\n        except ValueError:\n            if page == \"last\":\n                page_number = paginator.num_pages\n            else:\n                raise Http404(                     _(\"Page is not “last”, nor can it be converted to an int.\")\n                )\n        try:\n            page = paginator.page(page_number)\n            return (paginator, page, page.object_list, page.has_other_pages())\n        except InvalidPage as e:\n            raise Http404(\n                _(\"Invalid page (%(page_number)s): %(message)s\")\n                % {\"page_number\": page_number, \"message\": str(e)}\n            )\n\n    def get_paginate_by(self, queryset):\n        \"\"\"\n        Get the number of items to paginate by, or ``None`` for no pagination.\n        \"\"\"\n        return self.paginate_by\n    def get_paginator(\n        self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs\n    ):\n        \"\"\"Return an instance of the paginator for this view.\"\"\"\n        return self.paginator_class(             queryset,             per_page,             orphans=orphans,\n            allow_empty_first_page=allow_empty_first_page,\n            **kwargs,\n        )\n    def get_paginate_orphans(self):\n        \"\"\"\n        Return the maximum number of orphans extend the last page by when\n        paginating.\n        \"\"\"\n        return self.paginate_orphans\n    def get_allow_empty(self):\n        \"\"\"\n        Return ``True`` if the view should display empty lists and ``False``\n        if a 404 should be raised instead.\n        \"\"\"\n        return self.allow_empty\n\n    def get_context_object_name(self, object_list):\n        \"\"\"Get the name of the item to be used in the context.\"\"\"\n        if self.context_object_name:\n            return self.context_object_name\n        elif hasattr(object_list, \"model\"):\n            return \"%s_list\" % object_list.model._meta.model_name\n        else:\n            return None\n    def get_context_data(self, *, object_list=None, **kwargs):\n        \"\"\"Get the context for this view.\"\"\"\n        queryset = object_list if object_list is not None else self.object_list\n        page_size = self.get_paginate_by(queryset)\n        context_object_name = self.get_context_object_name(queryset)\n        if page_size:\n            paginator, page, queryset, is_paginated = self.paginate_queryset(                 queryset, page_size             )\n            context = {\n                \"paginator\": paginator,                 \"page_obj\": page,\n                \"is_paginated\": is_paginated,\n                \"object_list\": queryset,\n            }\n        else:\n            context = {\n                \"paginator\": None,                 \"page_obj\": None,\n                \"is_paginated\": False,\n                \"object_list\": queryset,\n            }\n        if context_object_name is not None:\n            context[context_object_name] = queryset\n        context.update(kwargs)\n        return super().get_context_data(**context)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-372d283847040cc3", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "5e46e86a9fd81283e2aa8eab5fcc1f12fd77f80d3c879984d5274d0d6a7ab484", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 128, "local_path": "layout/partially-compact-layout/I10__django__MultipleObjectMixin__b1865b27.py", "order": 10, "original_content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "parent_variant_id": "pyint-a83c3202e73c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/list.py#L9-L147", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 47, "line_break_groups_removed": 18, "line_breaks_removed": 18, "whitespace_characters_removed": 6}, "unit_kind": "class", "unit_name": "MultipleObjectMixin", "variant_id": "pyint-d0a9b1865b27-I10", "group_id": "py-372d283847040cc3", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 305, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b7f42149a866-I11", "source": "from django.core.exceptions import ImproperlyConfigured\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.db.models import QuerySet\nfrom django.http import Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\nclass MultipleObjectMixin(ContextMixin):\n    \"\"\"A mixin for views manipulating multiple objects.\"\"\"\n\n    allow_empty = True\n    queryset = None\n    model = None\n    paginate_by = None\n    paginate_orphans = 0\n    context_object_name = None\n    paginator_class = Paginator\n    page_kwarg = \"page\"\n    ordering = None\n\n    def get_queryset(self):\n        \"\"\"\n        Return the list of items for this view.\n\n        The return value must be an iterable and may be an instance of\n        `QuerySet` in which case `QuerySet` specific behavior will be enabled.\n        \"\"\"\n        if self.queryset is not None:\n            queryset = self.queryset\n            if isinstance(queryset, QuerySet):\n                queryset = queryset.all()\n        elif self.model is not None:\n            queryset = self.model._default_manager.all()\n        else:\n            raise ImproperlyConfigured(\n                \"%(cls)s is missing a QuerySet. Define \"\n                \"%(cls)s.model, %(cls)s.queryset, or override \"\n                \"%(cls)s.get_queryset().\" % {\"cls\": self.__class__.__name__}\n            )\n        ordering = self.get_ordering()\n        if ordering:\n            if isinstance(ordering, str):\n                ordering = (ordering,)\n            queryset = queryset.order_by(*ordering)\n\n        return queryset\n\n    def get_ordering(self):\n        \"\"\"Return the field or fields to use for ordering the queryset.\"\"\"\n        return self.ordering\n\n    def paginate_queryset(self, queryset, page_size):\n        \"\"\"Paginate the queryset, if needed.\"\"\"\n        paginator = self.get_paginator(\n            queryset,\n            page_size,\n            orphans=self.get_paginate_orphans(),\n            allow_empty_first_page=self.get_allow_empty(),\n        )\n        page_kwarg = self.page_kwarg\n        a = 2\n        b = -1\n        page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or (a + b)\n        try:\n            page_number = int(page)\n        except ValueError:\n            if page == \"last\":\n                page_number = paginator.num_pages\n            else:\n                raise Http404(\n                    _(\"Page is not “last”, nor can it be converted to an int.\")\n                )\n        try:\n            page = paginator.page(page_number)\n            return (paginator, page, page.object_list, page.has_other_pages())\n        except InvalidPage as e:\n            raise Http404(\n                _(\"Invalid page (%(page_number)s): %(message)s\")\n                % {\"page_number\": page_number, \"message\": str(e)}\n            )\n\n    def get_paginate_by(self, queryset):\n        \"\"\"\n        Get the number of items to paginate by, or ``None`` for no pagination.\n        \"\"\"\n        return self.paginate_by\n\n    def get_paginator(\n        self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs\n    ):\n        \"\"\"Return an instance of the paginator for this view.\"\"\"\n        return self.paginator_class(\n            queryset,\n            per_page,\n            orphans=orphans,\n            allow_empty_first_page=allow_empty_first_page,\n            **kwargs,\n        )\n\n    def get_paginate_orphans(self):\n        \"\"\"\n        Return the maximum number of orphans extend the last page by when\n        paginating.\n        \"\"\"\n        return self.paginate_orphans\n\n    def get_allow_empty(self):\n        \"\"\"\n        Return ``True`` if the view should display empty lists and ``False``\n        if a 404 should be raised instead.\n        \"\"\"\n        return self.allow_empty\n\n    def get_context_object_name(self, object_list):\n        \"\"\"Get the name of the item to be used in the context.\"\"\"\n        if self.context_object_name:\n            return self.context_object_name\n        elif hasattr(object_list, \"model\"):\n            return \"%s_list\" % object_list.model._meta.model_name\n        else:\n            return None\n\n    def get_context_data(self, *, object_list=None, **kwargs):\n        \"\"\"Get the context for this view.\"\"\"\n        queryset = object_list if object_list is not None else self.object_list\n        page_size = self.get_paginate_by(queryset)\n        context_object_name = self.get_context_object_name(queryset)\n        if page_size:\n            paginator, page, queryset, is_paginated = self.paginate_queryset(\n                queryset, page_size\n            )\n            context = {\n                \"paginator\": paginator,\n                \"page_obj\": page,\n                \"is_paginated\": is_paginated,\n                \"object_list\": queryset,\n            }\n        else:\n            context = {\n                \"paginator\": None,\n                \"page_obj\": None,\n                \"is_paginated\": False,\n                \"object_list\": queryset,\n            }\n        if context_object_name is not None:\n            context[context_object_name] = queryset\n        context.update(kwargs)\n        return super().get_context_data(**context)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-372d283847040cc3", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "15934e749c383e87e350b9b1ab739f81ff8b396561cc8666cb2f785633947afd", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 148, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__MultipleObjectMixin__2149a866.py", "order": 11, "original_content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "parent_variant_id": "pyint-a83c3202e73c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/list.py#L9-L147", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 1, "intermediate_variables_introduced": 2, "statements_augmented": 1}, "unit_kind": "class", "unit_name": "MultipleObjectMixin", "variant_id": "pyint-b7f42149a866-I11", "group_id": "py-372d283847040cc3", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 306, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bea7fb27e0bf-I12", "source": "from django.core.exceptions import ImproperlyConfigured\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.db.models import QuerySet\nfrom django.http import Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\nclass MultipleObjectMixin(ContextMixin):\n    \"\"\"A mixin for views manipulating multiple objects.\"\"\"\n\n    allow_empty = True\n    queryset = None\n    model = None\n    paginate_by = None\n    paginate_orphans = 0\n    context_object_name = None\n    paginator_class = Paginator\n    page_kwarg = \"page\"\n    ordering = None\n\n    def get_queryset(self):\n        \"\"\"\n        Return the list of items for this view.\n\n        The return value must be an iterable and may be an instance of\n        `QuerySet` in which case `QuerySet` specific behavior will be enabled.\n        \"\"\"\n        if self.queryset is not None:\n            queryset = self.queryset\n            if isinstance(queryset, QuerySet):\n                queryset = queryset.all()\n        elif self.model is not None:\n            queryset = self.model._default_manager.all()\n        else:\n            raise ImproperlyConfigured(\n                \"%(cls)s is missing a QuerySet. Define \"\n                \"%(cls)s.model, %(cls)s.queryset, or override \"\n                \"%(cls)s.get_queryset().\" % {\"cls\": self.__class__.__name__}\n            )\n        ordering = self.get_ordering()\n        if ordering:\n            if isinstance(ordering, str):\n                ordering = (ordering,)\n            queryset = queryset.order_by(*ordering)\n\n        return queryset\n\n    def get_ordering(self):\n        \"\"\"Return the field or fields to use for ordering the queryset.\"\"\"\n        return self.ordering\n\n    def paginate_queryset(self, queryset, page_size):\n        \"\"\"Paginate the queryset, if needed.\"\"\"\n        paginator = self.get_paginator(\n            queryset,\n            page_size,\n            orphans=self.get_paginate_orphans(),\n            allow_empty_first_page=self.get_allow_empty(),\n        )\n        page_kwarg = self.page_kwarg\n        page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1\n        try:\n            page_number = int(page)\n        except ValueError:\n            if page == \"last\":\n                page_number = paginator.num_pages\n            else:\n                raise Http404(\n                    _(\"Page is not “last”, nor can it be converted to an int.\")\n                )\n        try:\n            page = paginator.page(page_number)\n            return (paginator, page, page.object_list, page.has_other_pages())\n        except InvalidPage as e:\n            raise Http404(\n                _(\"Invalid page (%(page_number)s): %(message)s\")\n                % {\"page_number\": page_number, \"message\": str(e)}\n            )\n\n    def get_paginate_by(self, queryset):\n        \"\"\"\n        Get the number of items to paginate by, or ``None`` for no pagination.\n        \"\"\"\n        return self.paginate_by\n\n    def get_paginator(\n        self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs\n    ):\n        \"\"\"Return an instance of the paginator for this view.\"\"\"\n        return self.paginator_class(\n            queryset,\n            per_page,\n            orphans=orphans,\n            allow_empty_first_page=allow_empty_first_page,\n            **kwargs,\n        )\n\n    def get_paginate_orphans(self):\n        \"\"\"\n        Return the maximum number of orphans extend the last page by when\n        paginating.\n        \"\"\"\n        return self.paginate_orphans\n\n    def get_allow_empty(self):\n        \"\"\"\n        Return ``True`` if the view should display empty lists and ``False``\n        if a 404 should be raised instead.\n        \"\"\"\n        return self.allow_empty\n\n    def get_context_object_name(self, object_list):\n        \"\"\"Get the name of the item to be used in the context.\"\"\"\n        if self.context_object_name:\n            return self.context_object_name\n        elif hasattr(object_list, \"model\"):\n            return \"%s_list\" % object_list.model._meta.model_name\n        else:\n            return None\n\n    def get_context_data(self, *, object_list=None, **kwargs):\n        \"\"\"Get the context for this view.\"\"\"\n        queryset = object_list if object_list is not None else self.object_list\n        page_size = self.get_paginate_by(queryset)\n        context_object_name = self.get_context_object_name(queryset)\n        if page_size:\n            paginator, page, queryset, is_paginated = self.paginate_queryset(\n                queryset, page_size\n            )\n            context = {\n                \"paginator\": paginator,\n                \"page_obj\": page,\n                \"is_paginated\": is_paginated,\n                \"object_list\": queryset,\n            }\n        else:\n            context = {\n                \"paginator\": None,\n                \"page_obj\": None,\n                \"is_paginated\": False,\n                \"object_list\": queryset,\n            }\n        if context_object_name is not None:\n            context[context_object_name] = queryset\n        context.update(kwargs)\n        return super().get_context_data(**context)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-372d283847040cc3", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 146, "local_path": "data-flow/inline-intermediate-variables/I12__django__MultipleObjectMixin__fb27e0bf.py", "order": 12, "original_content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "parent_variant_id": "pyint-a83c3202e73c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/list.py#L9-L147", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "MultipleObjectMixin", "variant_id": "pyint-bea7fb27e0bf-I12", "group_id": "py-372d283847040cc3", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 307, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1a26e61e493f-I13", "source": "from django.core.exceptions import ImproperlyConfigured\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.db.models import QuerySet\nfrom django.http import Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\nclass MultipleObjectMixin(ContextMixin):\n    \"\"\"A mixin for views manipulating multiple objects.\"\"\"\n\n    allow_empty = True\n    queryset = None\n    model = None\n    paginate_by = None\n    paginate_orphans = 0\n    context_object_name = None\n    paginator_class = Paginator\n    page_kwarg = \"page\"\n    ordering = None\n\n    def get_queryset(self):\n        \"\"\"\n        Return the list of items for this view.\n\n        The return value must be an iterable and may be an instance of\n        `QuerySet` in which case `QuerySet` specific behavior will be enabled.\n        \"\"\"\n        if self.queryset is not None:\n            queryset = self.queryset\n            if isinstance(queryset, QuerySet):\n                queryset = queryset.all()\n        elif self.model is not None:\n            queryset = self.model._default_manager.all()\n        else:\n            raise ImproperlyConfigured(\n                \"%(cls)s is missing a QuerySet. Define \"\n                \"%(cls)s.model, %(cls)s.queryset, or override \"\n                \"%(cls)s.get_queryset().\" % {\"cls\": self.__class__.__name__}\n            )\n        ordering = self.get_ordering()\n        if ordering:\n            if isinstance(ordering, str):\n                ordering = (ordering,)\n            queryset = queryset.order_by(*ordering)\n\n        return queryset\n\n    def get_ordering(self):\n        \"\"\"Return the field or fields to use for ordering the queryset.\"\"\"\n        return self.ordering\n\n    def paginate_queryset(self, queryset, page_size):\n        \"\"\"Paginate the queryset, if needed.\"\"\"\n        paginator = self.get_paginator(\n            queryset,\n            page_size,\n            orphans=self.get_paginate_orphans(),\n            allow_empty_first_page=self.get_allow_empty(),\n        )\n        page_kwarg = self.page_kwarg\n        page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1\n        try:\n            page_number = int(page)\n        except ValueError:\n            if page == \"last\":\n                page_number = paginator.num_pages\n            else:\n                raise Http404(\n                    _(\"Page is not “last”, nor can it be converted to an int.\")\n                )\n        try:\n            page = paginator.page(page_number)\n            return (paginator, page, page.object_list, page.has_other_pages())\n        except InvalidPage as e:\n            raise Http404(\n                _(\"Invalid page (%(page_number)s): %(message)s\")\n                % {\"page_number\": page_number, \"message\": str(e)}\n            )\n\n    def get_paginate_by(self, queryset):\n        \"\"\"\n        Get the number of items to paginate by, or ``None`` for no pagination.\n        \"\"\"\n        return self.paginate_by\n\n    def get_paginator(\n        self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs\n    ):\n        \"\"\"Return an instance of the paginator for this view.\"\"\"\n        return self.paginator_class(\n            queryset,\n            per_page,\n            orphans=orphans,\n            allow_empty_first_page=allow_empty_first_page,\n            **kwargs,\n        )\n\n    def get_paginate_orphans(self):\n        \"\"\"\n        Return the maximum number of orphans extend the last page by when\n        paginating.\n        \"\"\"\n        return self.paginate_orphans\n\n    def get_allow_empty(self):\n        \"\"\"\n        Return ``True`` if the view should display empty lists and ``False``\n        if a 404 should be raised instead.\n        \"\"\"\n        return self.allow_empty\n\n    def get_context_object_name(self, object_list):\n        \"\"\"Get the name of the item to be used in the context.\"\"\"\n        if self.context_object_name:\n            return self.context_object_name\n        elif hasattr(object_list, \"model\"):\n            return \"%s_list\" % object_list.model._meta.model_name\n        else:\n            return None\n\n    def get_context_data(self, *, object_list=None, **kwargs):\n        \"\"\"Get the context for this view.\"\"\"\n        queryset = object_list if object_list is not None else self.object_list\n        page_size = self.get_paginate_by(queryset)\n        context_object_name = self.get_context_object_name(queryset)\n        if page_size:\n            paginator, page, queryset, is_paginated = self.paginate_queryset(\n                queryset, page_size\n            )\n            context = {\n                \"paginator\": paginator,\n                \"page_obj\": page,\n                \"is_paginated\": is_paginated,\n                \"object_list\": queryset,\n            }\n        else:\n            context = {\n                \"paginator\": None,\n                \"page_obj\": None,\n                \"is_paginated\": False,\n                \"object_list\": queryset,\n            }\n        if context_object_name is not None:\n            context[context_object_name] = queryset\n        context.update(kwargs)\n        return super().get_context_data(**context)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-372d283847040cc3", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 146, "local_path": "control-flow/lower-for-to-while/I13__django__MultipleObjectMixin__e61e493f.py", "order": 13, "original_content_sha256": "60881950926b9f47512c2bc9d2100e94d2163d025eabb3a53d88642a91353ef1", "parent_variant_id": "pyint-a83c3202e73c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/list.py#L9-L147", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "MultipleObjectMixin", "variant_id": "pyint-1a26e61e493f-I13", "group_id": "py-372d283847040cc3", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 308, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7d520b13f7b6-SRC", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass CertParamType(click.ParamType):  # type: ignore[type-arg]\n    \"\"\"Click option type for the ``--cert`` option. Allows either an\n    existing file, the string ``'adhoc'``, or an import for a\n    :class:`~ssl.SSLContext` object.\n    \"\"\"\n\n    name = \"path\"\n\n    def __init__(self) -> None:\n        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n    def convert(\n        self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n    ) -> t.Any:\n        try:\n            import ssl\n        except ImportError:\n            raise click.BadParameter(\n                'Using \"--cert\" requires Python to be compiled with SSL support.',\n                ctx,\n                param,\n            ) from None\n\n        try:\n            return self.path_type(value, param, ctx)\n        except click.BadParameter:\n            value = click.STRING(value, param, ctx).lower()  # type: ignore[union-attr]\n\n            if value == \"adhoc\":\n                try:\n                    import cryptography  # noqa: F401\n                except ImportError:\n                    raise click.BadParameter(\n                        \"Using ad-hoc certificates requires the cryptography library.\",\n                        ctx,\n                        param,\n                    ) from None\n\n                return value\n\n            obj = import_string(value, silent=True)\n\n            if isinstance(obj, ssl.SSLContext):\n                return obj\n\n            raise\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-39025d5b32f299f1", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 69, "local_path": "source-original/SRC__flask__CertParamType__0b13f7b6.py", "order": 0, "original_content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L780-L825", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "CertParamType", "variant_id": "pyint-7d520b13f7b6-SRC", "group_id": "py-39025d5b32f299f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 435, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d8a7d8b00d5e-I01", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass CertParamType(click.ParamType):   \n    \n\n    name = \"path\"\n\n    def __init__(self) -> None:\n        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n    def convert(\n        self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n    ) -> t.Any:\n        try:\n            import ssl\n        except ImportError:\n            raise click.BadParameter(\n                'Using \"--cert\" requires Python to be compiled with SSL support.',\n                ctx,\n                param,\n            ) from None\n\n        try:\n            return self.path_type(value, param, ctx)\n        except click.BadParameter:\n            value = click.STRING(value, param, ctx).lower()   \n\n            if value == \"adhoc\":\n                try:\n                    import cryptography   \n                except ImportError:\n                    raise click.BadParameter(\n                        \"Using ad-hoc certificates requires the cryptography library.\",\n                        ctx,\n                        param,\n                    ) from None\n\n                return value\n\n            obj = import_string(value, silent=True)\n\n            if isinstance(obj, ssl.SSLContext):\n                return obj\n\n            raise\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-39025d5b32f299f1", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "502f135966e9d76d871d93d26d3a03d3c7cc5d02a78b695401f08ddd6f063675", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 66, "local_path": "comments/remove-comments/I01__flask__CertParamType__d8b00d5e.py", "order": 1, "original_content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "parent_variant_id": "pyint-7d520b13f7b6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L780-L825", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 230, "comments_removed": 4, "docstrings_removed": 1, "line_comments_removed": 3}, "unit_kind": "class", "unit_name": "CertParamType", "variant_id": "pyint-d8a7d8b00d5e-I01", "group_id": "py-39025d5b32f299f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 436, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d11e47ad8e3d-I02", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass CertParamType(click.ParamType):  # type: ignore[type-arg]\n    \"\"\"Click option type for the ``--cert`` option. Allows either an\n    existing file, the string ``'adhoc'``, or an import for a\n    :class:`~ssl.SSLContext` object.\n    \"\"\"\n\n    name = \"path\"\n\n    def __init__(self) -> None:\n        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n    def con(\n        self, val: t.Any, par: click.Parameter | None, ctx2: click.Context | None\n    ) -> t.Any:\n        try:\n            import ssl\n        except ImportError:\n            raise click.BadParameter(\n                'Using \"--cert\" requires Python to be compiled with SSL support.',\n                ctx2,\n                par,\n            ) from None\n\n        try:\n            return self.path_type(val, par, ctx2)\n        except click.BadParameter:\n            val = click.STRING(val, par, ctx2).lower()  # type: ignore[union-attr]\n\n            if val == \"adhoc\":\n                try:\n                    import cryptography  # noqa: F401\n                except ImportError:\n                    raise click.BadParameter(\n                        \"Using ad-hoc certificates requires the cryptography library.\",\n                        ctx2,\n                        par,\n                    ) from None\n\n                return val\n\n            obj2 = import_string(val, silent=True)\n\n            if isinstance(obj2, ssl.SSLContext):\n                return obj2\n\n            raise\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-39025d5b32f299f1", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "a1017eb70165f41ca45011d9a39e09caa1ef5b78cbb8600e961fa2862b9cb7d6", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 69, "local_path": "identifiers/shorten-identifiers/I02__flask__CertParamType__47ad8e3d.py", "order": 2, "original_content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "parent_variant_id": "pyint-7d520b13f7b6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L780-L825", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 21, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "CertParamType", "variant_id": "pyint-d11e47ad8e3d-I02", "group_id": "py-39025d5b32f299f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 437, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-805cca75b03e-I03", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass CertParamType(click.ParamType):  # type: ignore[type-arg]\n    \"\"\"Click option type for the ``--cert`` option. Allows either an\n    existing file, the string ``'adhoc'``, or an import for a\n    :class:`~ssl.SSLContext` object.\n    \"\"\"\n\n    name = \"path\"\n\n    def __init__(self) -> None:\n        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n    def deliver(\n        self, limit: t.Any, entry: click.Parameter | None, key: click.Context | None\n    ) -> t.Any:\n        try:\n            import ssl\n        except ImportError:\n            raise click.BadParameter(\n                'Using \"--cert\" requires Python to be compiled with SSL support.',\n                key,\n                entry,\n            ) from None\n\n        try:\n            return self.path_type(limit, entry, key)\n        except click.BadParameter:\n            limit = click.STRING(limit, entry, key).lower()  # type: ignore[union-attr]\n\n            if limit == \"adhoc\":\n                try:\n                    import cryptography  # noqa: F401\n                except ImportError:\n                    raise click.BadParameter(\n                        \"Using ad-hoc certificates requires the cryptography library.\",\n                        key,\n                        entry,\n                    ) from None\n\n                return limit\n\n            age = import_string(limit, silent=True)\n\n            if isinstance(age, ssl.SSLContext):\n                return age\n\n            raise\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-39025d5b32f299f1", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "a22630a2dac73a3660d3059ba6d89a1a2fc96af9d75dc94dcd55d0d4a15e5e39", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 69, "local_path": "identifiers/mislead-identifiers/I03__flask__CertParamType__ca75b03e.py", "order": 3, "original_content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "parent_variant_id": "pyint-7d520b13f7b6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L780-L825", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 21, "identifiers_declared": 5, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 4, "local_random_pool_selections": 4, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "CertParamType", "variant_id": "pyint-805cca75b03e-I03", "group_id": "py-39025d5b32f299f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 438, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b1be62fc2037-I04", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass CertParamType(click.ParamType):  # type: ignore[type-arg]\n    \"\"\"Click option type for the ``--cert`` option. Allows either an\n    existing file, the string ``'adhoc'``, or an import for a\n    :class:`~ssl.SSLContext` object.\n    \"\"\"\n\n    name = \"path\"\n\n    def __init__(self) -> None:\n        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n    def a(\n        self, b: t.Any, c: click.Parameter | None, d: click.Context | None\n    ) -> t.Any:\n        try:\n            import ssl\n        except ImportError:\n            raise click.BadParameter(\n                'Using \"--cert\" requires Python to be compiled with SSL support.',\n                d,\n                c,\n            ) from None\n\n        try:\n            return self.path_type(b, c, d)\n        except click.BadParameter:\n            b = click.STRING(b, c, d).lower()  # type: ignore[union-attr]\n\n            if b == \"adhoc\":\n                try:\n                    import cryptography  # noqa: F401\n                except ImportError:\n                    raise click.BadParameter(\n                        \"Using ad-hoc certificates requires the cryptography library.\",\n                        d,\n                        c,\n                    ) from None\n\n                return b\n\n            e = import_string(b, silent=True)\n\n            if isinstance(e, ssl.SSLContext):\n                return e\n\n            raise\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-39025d5b32f299f1", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "7438e1dbb7d34395e66076b4eb6b00aabc613af186f55648713376b0fe4c5d77", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 69, "local_path": "identifiers/garble-identifiers/I04__flask__CertParamType__62fc2037.py", "order": 4, "original_content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "parent_variant_id": "pyint-7d520b13f7b6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L780-L825", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 21, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "CertParamType", "variant_id": "pyint-b1be62fc2037-I04", "group_id": "py-39025d5b32f299f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 439, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9ddaff71ddf0-I05", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass CertParamType(click.ParamType):  # type: ignore[type-arg]\n    \"\"\"Click option type for the ``--cert`` option. Allows either an\n    existing file, the string ``'adhoc'``, or an import for a\n    :class:`~ssl.SSLContext` object.\n    \"\"\"\n\n    name = \"path\"\n\n    def __init__(self) -> None:\n        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n    def convert(\n        self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n    ) -> t.Any:\n        try:\n            import ssl\n        except ImportError:\n            raise click.BadParameter(\n                'Using \"--cert\" requires Python to be compiled with SSL support.',\n                ctx,\n                param,\n            ) from None\n\n        try:\n            return self.path_type(value, param, ctx)\n        except click.BadParameter:\n            value = click.STRING(value, param, ctx).lower()  # type: ignore[union-attr]\n\n            if value == \"adhoc\":\n                try:\n                    import cryptography  # noqa: F401\n                except ImportError:\n                    raise click.BadParameter(\n                        \"Using ad-hoc certificates requires the cryptography library.\",\n                        ctx,\n                        param,\n                    ) from None\n\n                return value\n\n            obj = import_string(value, silent=True)\n\n            if isinstance(obj, ssl.SSLContext):\n                return obj\n\n            raise\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-39025d5b32f299f1", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 69, "local_path": "expressions/encode-integer-literals/I05__flask__CertParamType__ff71ddf0.py", "order": 5, "original_content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "parent_variant_id": "pyint-7d520b13f7b6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L780-L825", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "CertParamType", "variant_id": "pyint-9ddaff71ddf0-I05", "group_id": "py-39025d5b32f299f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 440, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1704db9b7cd5-I06", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass CertParamType(click.ParamType):  # type: ignore[type-arg]\n    \"\"\"Click option type for the ``--cert`` option. Allows either an\n    existing file, the string ``'adhoc'``, or an import for a\n    :class:`~ssl.SSLContext` object.\n    \"\"\"\n\n    name = \"path\"\n\n    def __init__(self) -> None:\n        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n    def convert(\n        self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n    ) -> t.Any:\n        try:\n            import ssl\n        except ImportError:\n            raise click.BadParameter(\n                'Using \"--cert\" requires Python to be compiled with SSL support.',\n                ctx,\n                param,\n            ) from None\n\n        try:\n            return self.path_type(value, param, ctx)\n        except click.BadParameter:\n            value = click.STRING(value, param, ctx).lower()  # type: ignore[union-attr]\n\n            if not (value == \"adhoc\"):\n                pass\n            else:\n                try:\n                    import cryptography  # noqa: F401\n                except ImportError:\n                    raise click.BadParameter(\n                        \"Using ad-hoc certificates requires the cryptography library.\",\n                        ctx,\n                        param,\n                    ) from None\n\n                return value\n\n            obj = import_string(value, silent=True)\n\n            if not (isinstance(obj, ssl.SSLContext)):\n                pass\n            else:\n                return obj\n\n            raise\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-39025d5b32f299f1", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "1da9e5b1a89da09924cced3d00f5e5405e26c977e1f2621a1e3e2cb86b8c08b0", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 73, "local_path": "expressions/invert-conditions/I06__flask__CertParamType__db9b7cd5.py", "order": 6, "original_content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "parent_variant_id": "pyint-7d520b13f7b6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L780-L825", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 2}, "unit_kind": "class", "unit_name": "CertParamType", "variant_id": "pyint-1704db9b7cd5-I06", "group_id": "py-39025d5b32f299f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 441, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-735dadbcbe82-I07", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass CertParamType(click.ParamType):  # type: ignore[type-arg]\n    \"\"\"Click option type for the ``--cert`` option. Allows either an\n    existing file, the string ``'adhoc'``, or an import for a\n    :class:`~ssl.SSLContext` object.\n    \"\"\"\n\n    name = \"path\"\n\n    def __init__(self) -> None:\n        if ((0xe7b5 ^ 0xe7b5) != 0):\n            raise AssertionError()\n        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n    def convert(\n        self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n    ) -> t.Any:\n        if ((0xed32 ^ 0xed32) != 0):\n            raise AssertionError()\n        try:\n            import ssl\n        except ImportError:\n            raise click.BadParameter(\n                'Using \"--cert\" requires Python to be compiled with SSL support.',\n                ctx,\n                param,\n            ) from None\n\n        try:\n            return self.path_type(value, param, ctx)\n        except click.BadParameter:\n            value = click.STRING(value, param, ctx).lower()  # type: ignore[union-attr]\n\n            if value == \"adhoc\":\n                try:\n                    import cryptography  # noqa: F401\n                except ImportError:\n                    raise click.BadParameter(\n                        \"Using ad-hoc certificates requires the cryptography library.\",\n                        ctx,\n                        param,\n                    ) from None\n\n                return value\n\n            obj = import_string(value, silent=True)\n\n            if isinstance(obj, ssl.SSLContext):\n                return obj\n\n            raise\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-39025d5b32f299f1", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "8385597f1a8dc15fb93aadc31db77ea3dbccc9e4cd46fcfd7fa0402094776baa", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 73, "local_path": "code-injection/insert-dead-branches/I07__flask__CertParamType__adbcbe82.py", "order": 7, "original_content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "parent_variant_id": "pyint-7d520b13f7b6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L780-L825", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "CertParamType", "variant_id": "pyint-735dadbcbe82-I07", "group_id": "py-39025d5b32f299f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 442, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c1393b80ff8a-I08", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass CertParamType(click.ParamType):  # type: ignore[type-arg]\n    \"\"\"Click option type for the ``--cert`` option. Allows either an\n    existing file, the string ``'adhoc'``, or an import for a\n    :class:`~ssl.SSLContext` object.\n    \"\"\"\n\n    name = \"path\"\n\n    def __init__(self) -> None:\n        running_total = 0\n        for current_number in range(1, 6):\n            running_total += current_number\n        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n    def convert(\n        self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n    ) -> t.Any:\n        try:\n            import ssl\n        except ImportError:\n            raise click.BadParameter(\n                'Using \"--cert\" requires Python to be compiled with SSL support.',\n                ctx,\n                param,\n            ) from None\n\n        try:\n            return self.path_type(value, param, ctx)\n        except click.BadParameter:\n            value = click.STRING(value, param, ctx).lower()  # type: ignore[union-attr]\n\n            if value == \"adhoc\":\n                try:\n                    import cryptography  # noqa: F401\n                except ImportError:\n                    raise click.BadParameter(\n                        \"Using ad-hoc certificates requires the cryptography library.\",\n                        ctx,\n                        param,\n                    ) from None\n\n                return value\n\n            obj = import_string(value, silent=True)\n\n            if isinstance(obj, ssl.SSLContext):\n                return obj\n\n            raise\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-39025d5b32f299f1", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "f23a9763d4102a21a8f51eb5b72c032b9e483190ecb8c98f534b99aad82780f9", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 72, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__CertParamType__3b80ff8a.py", "order": 8, "original_content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "parent_variant_id": "pyint-7d520b13f7b6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L780-L825", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 0}, "unit_kind": "class", "unit_name": "CertParamType", "variant_id": "pyint-c1393b80ff8a-I08", "group_id": "py-39025d5b32f299f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 443, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9d2b4481f87c-I09", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass CertParamType(click.ParamType):  # type: ignore[type-arg]\n    \"\"\"Click option type for the ``--cert`` option. Allows either an\n    existing file, the string ``'adhoc'``, or an import for a\n    :class:`~ssl.SSLContext` object.\n    \"\"\"\n\n    name = \"path\"\n\n    def __init__(self) -> None:\n        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n    def convert(\n        self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n    ) -> t.Any:\n        lI0O_f39e4418, lI0O_7d47cae3 = 0, 0\n        while lI0O_7d47cae3 < 2:\n            lI0O_f39e4418 ^= (lI0O_7d47cae3 << 1) ^ 0x2\n            lI0O_7d47cae3 += 1\n        lI0O_f39e4418 ^= lI0O_f39e4418\n        try:\n            import ssl\n        except ImportError:\n            raise click.BadParameter(\n                'Using \"--cert\" requires Python to be compiled with SSL support.',\n                ctx,\n                param,\n            ) from None\n\n        try:\n            return self.path_type(value, param, ctx)\n        except click.BadParameter:\n            value = click.STRING(value, param, ctx).lower()  # type: ignore[union-attr]\n\n            if value == \"adhoc\":\n                try:\n                    import cryptography  # noqa: F401\n                except ImportError:\n                    raise click.BadParameter(\n                        \"Using ad-hoc certificates requires the cryptography library.\",\n                        ctx,\n                        param,\n                    ) from None\n\n                return value\n\n            obj = import_string(value, silent=True)\n\n            if isinstance(obj, ssl.SSLContext):\n                return obj\n\n            raise\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-39025d5b32f299f1", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "042f050dcb94dfb235c1995193afcba8bdbad94ee1ee63d558f52e63bf63d362", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 74, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__CertParamType__4481f87c.py", "order": 9, "original_content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "parent_variant_id": "pyint-7d520b13f7b6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L780-L825", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 2}, "unit_kind": "class", "unit_name": "CertParamType", "variant_id": "pyint-9d2b4481f87c-I09", "group_id": "py-39025d5b32f299f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 444, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2a7ed5de096e-I10", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass CertParamType(click.ParamType):  # type: ignore[type-arg]\n    \"\"\"Click option type for the ``--cert`` option. Allows either an\n    existing file, the string ``'adhoc'``, or an import for a\n    :class:`~ssl.SSLContext` object.\n    \"\"\"\n    name = \"path\"\n\n    def __init__(self) -> None:\n        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n    def convert(\n        self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n    ) -> t.Any:\n        try:\n            import ssl\n        except ImportError:\n            raise click.BadParameter(\n                'Using \"--cert\" requires Python to be compiled with SSL support.',                 ctx,\n                param,             ) from None\n\n        try:\n            return self.path_type(value, param, ctx)\n        except click.BadParameter:\n            value = click.STRING(value, param, ctx).lower()  # type: ignore[union-attr]\n\n            if value == \"adhoc\":\n                try:\n                    import cryptography  # noqa: F401\n                except ImportError:\n                    raise click.BadParameter(                         \"Using ad-hoc certificates requires the cryptography library.\",                         ctx,\n                        param,\n                    ) from None\n\n                return value\n\n            obj = import_string(value, silent=True)\n            if isinstance(obj, ssl.SSLContext):\n                return obj\n            raise\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-39025d5b32f299f1", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "14083696c2f5002e89ec17d8137cc2dc044aca46fed4c3641ad978e2f9776a87", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 61, "local_path": "layout/partially-compact-layout/I10__flask__CertParamType__d5de096e.py", "order": 10, "original_content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "parent_variant_id": "pyint-7d520b13f7b6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L780-L825", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 20, "line_break_groups_removed": 8, "line_breaks_removed": 8, "whitespace_characters_removed": 4}, "unit_kind": "class", "unit_name": "CertParamType", "variant_id": "pyint-2a7ed5de096e-I10", "group_id": "py-39025d5b32f299f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 445, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-25eb051bc84f-I11", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass CertParamType(click.ParamType):  # type: ignore[type-arg]\n    \"\"\"Click option type for the ``--cert`` option. Allows either an\n    existing file, the string ``'adhoc'``, or an import for a\n    :class:`~ssl.SSLContext` object.\n    \"\"\"\n\n    name = \"path\"\n\n    def __init__(self) -> None:\n        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n    def convert(\n        self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n    ) -> t.Any:\n        try:\n            import ssl\n        except ImportError:\n            raise click.BadParameter(\n                'Using \"--cert\" requires Python to be compiled with SSL support.',\n                ctx,\n                param,\n            ) from None\n\n        try:\n            return self.path_type(value, param, ctx)\n        except click.BadParameter:\n            value = click.STRING(value, param, ctx).lower()  # type: ignore[union-attr]\n\n            if value == \"adhoc\":\n                try:\n                    import cryptography  # noqa: F401\n                except ImportError:\n                    raise click.BadParameter(\n                        \"Using ad-hoc certificates requires the cryptography library.\",\n                        ctx,\n                        param,\n                    ) from None\n\n                return value\n\n            obj = import_string(value, silent=True)\n\n            if isinstance(obj, ssl.SSLContext):\n                return obj\n\n            raise\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-39025d5b32f299f1", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 69, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__CertParamType__051bc84f.py", "order": 11, "original_content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "parent_variant_id": "pyint-7d520b13f7b6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L780-L825", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "CertParamType", "variant_id": "pyint-25eb051bc84f-I11", "group_id": "py-39025d5b32f299f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 446, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2b6eb0ac6862-I12", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass CertParamType(click.ParamType):  # type: ignore[type-arg]\n    \"\"\"Click option type for the ``--cert`` option. Allows either an\n    existing file, the string ``'adhoc'``, or an import for a\n    :class:`~ssl.SSLContext` object.\n    \"\"\"\n\n    name = \"path\"\n\n    def __init__(self) -> None:\n        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n    def convert(\n        self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n    ) -> t.Any:\n        try:\n            import ssl\n        except ImportError:\n            raise click.BadParameter(\n                'Using \"--cert\" requires Python to be compiled with SSL support.',\n                ctx,\n                param,\n            ) from None\n\n        try:\n            return self.path_type(value, param, ctx)\n        except click.BadParameter:\n            value = click.STRING(value, param, ctx).lower()  # type: ignore[union-attr]\n\n            if value == \"adhoc\":\n                try:\n                    import cryptography  # noqa: F401\n                except ImportError:\n                    raise click.BadParameter(\n                        \"Using ad-hoc certificates requires the cryptography library.\",\n                        ctx,\n                        param,\n                    ) from None\n\n                return value\n\n            obj = import_string(value, silent=True)\n\n            if isinstance(obj, ssl.SSLContext):\n                return obj\n\n            raise\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-39025d5b32f299f1", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 69, "local_path": "data-flow/inline-intermediate-variables/I12__flask__CertParamType__b0ac6862.py", "order": 12, "original_content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "parent_variant_id": "pyint-7d520b13f7b6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L780-L825", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "CertParamType", "variant_id": "pyint-2b6eb0ac6862-I12", "group_id": "py-39025d5b32f299f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 447, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-402161046648-I13", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass CertParamType(click.ParamType):  # type: ignore[type-arg]\n    \"\"\"Click option type for the ``--cert`` option. Allows either an\n    existing file, the string ``'adhoc'``, or an import for a\n    :class:`~ssl.SSLContext` object.\n    \"\"\"\n\n    name = \"path\"\n\n    def __init__(self) -> None:\n        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n    def convert(\n        self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n    ) -> t.Any:\n        try:\n            import ssl\n        except ImportError:\n            raise click.BadParameter(\n                'Using \"--cert\" requires Python to be compiled with SSL support.',\n                ctx,\n                param,\n            ) from None\n\n        try:\n            return self.path_type(value, param, ctx)\n        except click.BadParameter:\n            value = click.STRING(value, param, ctx).lower()  # type: ignore[union-attr]\n\n            if value == \"adhoc\":\n                try:\n                    import cryptography  # noqa: F401\n                except ImportError:\n                    raise click.BadParameter(\n                        \"Using ad-hoc certificates requires the cryptography library.\",\n                        ctx,\n                        param,\n                    ) from None\n\n                return value\n\n            obj = import_string(value, silent=True)\n\n            if isinstance(obj, ssl.SSLContext):\n                return obj\n\n            raise\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-39025d5b32f299f1", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 69, "local_path": "control-flow/lower-for-to-while/I13__flask__CertParamType__61046648.py", "order": 13, "original_content_sha256": "0ba70ef9e14db2dc4b711d80d34a2e302ef8f78373d89234d07860e2fcf89b06", "parent_variant_id": "pyint-7d520b13f7b6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L780-L825", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "CertParamType", "variant_id": "pyint-402161046648-I13", "group_id": "py-39025d5b32f299f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 448, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bf7e10b68ef6-SRC", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass FlaskClient(Client):\n    \"\"\"Works like a regular Werkzeug test client, with additional behavior for\n    Flask. Can defer the cleanup of the request context until the end of a\n    ``with`` block. For general information about how to use this class refer to\n    :class:`werkzeug.test.Client`.\n\n    .. versionchanged:: 0.12\n       `app.test_client()` includes preset default environment, which can be\n       set after instantiation of the `app.test_client()` object in\n       `client.environ_base`.\n\n    Basic usage is outlined in the :doc:`/testing` chapter.\n    \"\"\"\n\n    application: Flask\n\n    def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n        super().__init__(*args, **kwargs)\n        self.preserve_context = False\n        self._new_contexts: list[t.ContextManager[t.Any]] = []\n        self._context_stack = ExitStack()\n        self.environ_base = {\n            \"REMOTE_ADDR\": \"127.0.0.1\",\n            \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n        }\n\n    @contextmanager\n    def session_transaction(\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Iterator[SessionMixin]:\n        \"\"\"When used in combination with a ``with`` statement this opens a\n        session transaction.  This can be used to modify the session that\n        the test client uses.  Once the ``with`` block is left the session is\n        stored back.\n\n        ::\n\n            with client.session_transaction() as session:\n                session['value'] = 42\n\n        Internally this is implemented by going through a temporary test\n        request context and since session handling could depend on\n        request variables this function accepts the same arguments as\n        :meth:`~flask.Flask.test_request_context` which are directly\n        passed through.\n        \"\"\"\n        if self._cookies is None:\n            raise TypeError(\n                \"Cookies are disabled. Create a client with 'use_cookies=True'.\"\n            )\n\n        app = self.application\n        ctx = app.test_request_context(*args, **kwargs)\n        self._add_cookies_to_wsgi(ctx.request.environ)\n\n        with ctx:\n            sess = app.session_interface.open_session(app, ctx.request)\n\n        if sess is None:\n            raise RuntimeError(\"Session backend did not open a session.\")\n\n        yield sess\n        resp = app.response_class()\n\n        if app.session_interface.is_null_session(sess):\n            return\n\n        with ctx:\n            app.session_interface.save_session(app, sess, resp)\n\n        self._update_cookies_from_response(\n            urlsplit(ctx.request.host_url).hostname or \"localhost\",\n            ctx.request.path,\n            resp.headers.getlist(\"Set-Cookie\"),\n        )\n\n    def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:\n        out = {**self.environ_base, **other}\n\n        if self.preserve_context:\n            out[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n\n        return out\n\n    def _request_from_builder_args(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> BaseRequest:\n        kwargs[\"environ_base\"] = self._copy_environ(kwargs.get(\"environ_base\", {}))\n        builder = EnvironBuilder(self.application, *args, **kwargs)\n\n        try:\n            return builder.get_request()\n        finally:\n            builder.close()\n\n    def open(\n        self,\n        *args: t.Any,\n        buffered: bool = False,\n        follow_redirects: bool = False,\n        **kwargs: t.Any,\n    ) -> TestResponse:\n        if args and isinstance(\n            args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n        ):\n            if isinstance(args[0], werkzeug.test.EnvironBuilder):\n                builder = copy(args[0])\n                builder.environ_base = self._copy_environ(builder.environ_base or {})  # type: ignore[arg-type]\n                request = builder.get_request()\n            elif isinstance(args[0], dict):\n                request = EnvironBuilder.from_environ(\n                    args[0], app=self.application, environ_base=self._copy_environ({})\n                ).get_request()\n            else:\n                # isinstance(args[0], BaseRequest)\n                request = copy(args[0])\n                request.environ = self._copy_environ(request.environ)\n        else:\n            # request is None\n            request = self._request_from_builder_args(args, kwargs)\n\n        # Pop any previously preserved contexts. This prevents contexts\n        # from being preserved across redirects or multiple requests\n        # within a single block.\n        self._context_stack.close()\n\n        response = super().open(\n            request,\n            buffered=buffered,\n            follow_redirects=follow_redirects,\n        )\n        response.json_module = self.application.json  # type: ignore[assignment]\n\n        # Re-push contexts that were preserved during the request.\n        for cm in self._new_contexts:\n            self._context_stack.enter_context(cm)\n\n        self._new_contexts.clear()\n        return response\n\n    def __enter__(self) -> FlaskClient:\n        if self.preserve_context:\n            raise RuntimeError(\"Cannot nest client invocations\")\n        self.preserve_context = True\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type | None,\n        exc_value: BaseException | None,\n        tb: TracebackType | None,\n    ) -> None:\n        self.preserve_context = False\n        self._context_stack.close()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-3ce2dc924679e135", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 170, "local_path": "source-original/SRC__flask__FlaskClient__10b68ef6.py", "order": 0, "original_content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L109-L262", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "FlaskClient", "variant_id": "pyint-bf7e10b68ef6-SRC", "group_id": "py-3ce2dc924679e135", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 673, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-eb9939edaa6f-I01", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass FlaskClient(Client):\n    \n\n    application: Flask\n\n    def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n        super().__init__(*args, **kwargs)\n        self.preserve_context = False\n        self._new_contexts: list[t.ContextManager[t.Any]] = []\n        self._context_stack = ExitStack()\n        self.environ_base = {\n            \"REMOTE_ADDR\": \"127.0.0.1\",\n            \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n        }\n\n    @contextmanager\n    def session_transaction(\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Iterator[SessionMixin]:\n        \n        if self._cookies is None:\n            raise TypeError(\n                \"Cookies are disabled. Create a client with 'use_cookies=True'.\"\n            )\n\n        app = self.application\n        ctx = app.test_request_context(*args, **kwargs)\n        self._add_cookies_to_wsgi(ctx.request.environ)\n\n        with ctx:\n            sess = app.session_interface.open_session(app, ctx.request)\n\n        if sess is None:\n            raise RuntimeError(\"Session backend did not open a session.\")\n\n        yield sess\n        resp = app.response_class()\n\n        if app.session_interface.is_null_session(sess):\n            return\n\n        with ctx:\n            app.session_interface.save_session(app, sess, resp)\n\n        self._update_cookies_from_response(\n            urlsplit(ctx.request.host_url).hostname or \"localhost\",\n            ctx.request.path,\n            resp.headers.getlist(\"Set-Cookie\"),\n        )\n\n    def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:\n        out = {**self.environ_base, **other}\n\n        if self.preserve_context:\n            out[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n\n        return out\n\n    def _request_from_builder_args(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> BaseRequest:\n        kwargs[\"environ_base\"] = self._copy_environ(kwargs.get(\"environ_base\", {}))\n        builder = EnvironBuilder(self.application, *args, **kwargs)\n\n        try:\n            return builder.get_request()\n        finally:\n            builder.close()\n\n    def open(\n        self,\n        *args: t.Any,\n        buffered: bool = False,\n        follow_redirects: bool = False,\n        **kwargs: t.Any,\n    ) -> TestResponse:\n        if args and isinstance(\n            args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n        ):\n            if isinstance(args[0], werkzeug.test.EnvironBuilder):\n                builder = copy(args[0])\n                builder.environ_base = self._copy_environ(builder.environ_base or {})   \n                request = builder.get_request()\n            elif isinstance(args[0], dict):\n                request = EnvironBuilder.from_environ(\n                    args[0], app=self.application, environ_base=self._copy_environ({})\n                ).get_request()\n            else:\n                 \n                request = copy(args[0])\n                request.environ = self._copy_environ(request.environ)\n        else:\n             \n            request = self._request_from_builder_args(args, kwargs)\n\n         \n         \n         \n        self._context_stack.close()\n\n        response = super().open(\n            request,\n            buffered=buffered,\n            follow_redirects=follow_redirects,\n        )\n        response.json_module = self.application.json   \n\n         \n        for cm in self._new_contexts:\n            self._context_stack.enter_context(cm)\n\n        self._new_contexts.clear()\n        return response\n\n    def __enter__(self) -> FlaskClient:\n        if self.preserve_context:\n            raise RuntimeError(\"Cannot nest client invocations\")\n        self.preserve_context = True\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type | None,\n        exc_value: BaseException | None,\n        tb: TracebackType | None,\n    ) -> None:\n        self.preserve_context = False\n        self._context_stack.close()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-3ce2dc924679e135", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "e8fa986ba35f9aed5c0468e13d572d1bee65f06bb1c6aedaca53eaf609b42a23", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 144, "local_path": "comments/remove-comments/I01__flask__FlaskClient__39edaa6f.py", "order": 1, "original_content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "parent_variant_id": "pyint-bf7e10b68ef6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L109-L262", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 1501, "comments_removed": 10, "docstrings_removed": 2, "line_comments_removed": 8}, "unit_kind": "class", "unit_name": "FlaskClient", "variant_id": "pyint-eb9939edaa6f-I01", "group_id": "py-3ce2dc924679e135", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 674, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ce8daa67b0cc-I02", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass FlaskClient(Client):\n    \"\"\"Works like a regular Werkzeug test client, with additional behavior for\n    Flask. Can defer the cleanup of the request context until the end of a\n    ``with`` block. For general information about how to use this class refer to\n    :class:`werkzeug.test.Client`.\n\n    .. versionchanged:: 0.12\n       `app.test_client()` includes preset default environment, which can be\n       set after instantiation of the `app.test_client()` object in\n       `client.environ_base`.\n\n    Basic usage is outlined in the :doc:`/testing` chapter.\n    \"\"\"\n\n    application: Flask\n\n    def __init__(self, *arg: t.Any, **kwa: t.Any) -> None:\n        super().__init__(*arg, **kwa)\n        self.preserve_context = False\n        self._new_contexts: list[t.ContextManager[t.Any]] = []\n        self._context_stack = ExitStack()\n        self.environ_base = {\n            \"REMOTE_ADDR\": \"127.0.0.1\",\n            \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n        }\n\n    @contextmanager\n    def session(\n        self, *arg2: t.Any, **kwa2: t.Any\n    ) -> t.Iterator[SessionMixin]:\n        \"\"\"When used in combination with a ``with`` statement this opens a\n        session transaction.  This can be used to modify the session that\n        the test client uses.  Once the ``with`` block is left the session is\n        stored back.\n\n        ::\n\n            with client.session_transaction() as session:\n                session['value'] = 42\n\n        Internally this is implemented by going through a temporary test\n        request context and since session handling could depend on\n        request variables this function accepts the same arguments as\n        :meth:`~flask.Flask.test_request_context` which are directly\n        passed through.\n        \"\"\"\n        if self._cookies is None:\n            raise TypeError(\n                \"Cookies are disabled. Create a client with 'use_cookies=True'.\"\n            )\n\n        app2 = self.application\n        ctx2 = app2.test_request_context(*arg2, **kwa2)\n        self._add_cookies_to_wsgi(ctx2.request.environ)\n\n        with ctx2:\n            ses = app2.session_interface.open_session(app2, ctx2.request)\n\n        if ses is None:\n            raise RuntimeError(\"Session backend did not open a session.\")\n\n        yield ses\n        res = app2.response_class()\n\n        if app2.session_interface.is_null_session(ses):\n            return\n\n        with ctx2:\n            app2.session_interface.save_session(app2, ses, res)\n\n        self._update_cookies_from_response(\n            urlsplit(ctx2.request.host_url).hostname or \"localhost\",\n            ctx2.request.path,\n            res.headers.getlist(\"Set-Cookie\"),\n        )\n\n    def copy2(self, oth: WSGIEnvironment) -> WSGIEnvironment:\n        out2 = {**self.environ_base, **oth}\n\n        if self.preserve_context:\n            out2[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n\n        return out2\n\n    def request2(\n        self, arg3: tuple[t.Any, ...], kwa3: dict[str, t.Any]\n    ) -> BaseRequest:\n        kwa3[\"environ_base\"] = self.copy2(kwa3.get(\"environ_base\", {}))\n        bui = EnvironBuilder(self.application, *arg3, **kwa3)\n\n        try:\n            return bui.get_request()\n        finally:\n            bui.close()\n\n    def ope(\n        self,\n        *arg4: t.Any,\n        buf: bool = False,\n        follow: bool = False,\n        **kwa4: t.Any,\n    ) -> TestResponse:\n        if arg4 and isinstance(\n            arg4[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n        ):\n            if isinstance(arg4[0], werkzeug.test.EnvironBuilder):\n                bui2 = copy(arg4[0])\n                bui2.environ_base = self.copy2(bui2.environ_base or {})  # type: ignore[arg-type]\n                req = bui2.get_request()\n            elif isinstance(arg4[0], dict):\n                req = EnvironBuilder.from_environ(\n                    arg4[0], app=self.application, environ_base=self.copy2({})\n                ).get_request()\n            else:\n                # isinstance(args[0], BaseRequest)\n                req = copy(arg4[0])\n                req.environ = self.copy2(req.environ)\n        else:\n            # request is None\n            req = self.request2(arg4, kwa4)\n\n        # Pop any previously preserved contexts. This prevents contexts\n        # from being preserved across redirects or multiple requests\n        # within a single block.\n        self._context_stack.close()\n\n        res2 = super().open(\n            req,\n            buffered=buf,\n            follow_redirects=follow,\n        )\n        res2.json_module = self.application.json  # type: ignore[assignment]\n\n        # Re-push contexts that were preserved during the request.\n        for cm2 in self._new_contexts:\n            self._context_stack.enter_context(cm2)\n\n        self._new_contexts.clear()\n        return res2\n\n    def __enter__(self) -> FlaskClient:\n        if self.preserve_context:\n            raise RuntimeError(\"Cannot nest client invocations\")\n        self.preserve_context = True\n        return self\n\n    def __exit__(\n        self,\n        exc: type | None,\n        exc2: BaseException | None,\n        tb: TracebackType | None,\n    ) -> None:\n        self.preserve_context = False\n        self._context_stack.close()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-3ce2dc924679e135", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "3323d486891662638f6688b4941f73696cc3da7b13ea6b71799b2ecff6788cb7", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 170, "local_path": "identifiers/shorten-identifiers/I02__flask__FlaskClient__aa67b0cc.py", "order": 2, "original_content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "parent_variant_id": "pyint-bf7e10b68ef6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L109-L262", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 88, "identifiers_declared": 28}, "unit_kind": "class", "unit_name": "FlaskClient", "variant_id": "pyint-ce8daa67b0cc-I02", "group_id": "py-3ce2dc924679e135", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 675, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-37e6e605cc34-I03", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass FlaskClient(Client):\n    \"\"\"Works like a regular Werkzeug test client, with additional behavior for\n    Flask. Can defer the cleanup of the request context until the end of a\n    ``with`` block. For general information about how to use this class refer to\n    :class:`werkzeug.test.Client`.\n\n    .. versionchanged:: 0.12\n       `app.test_client()` includes preset default environment, which can be\n       set after instantiation of the `app.test_client()` object in\n       `client.environ_base`.\n\n    Basic usage is outlined in the :doc:`/testing` chapter.\n    \"\"\"\n\n    application: Flask\n\n    def __init__(self, *mode: t.Any, **target: t.Any) -> None:\n        super().__init__(*mode, **target)\n        self.preserve_context = False\n        self._new_contexts: list[t.ContextManager[t.Any]] = []\n        self._context_stack = ExitStack()\n        self.environ_base = {\n            \"REMOTE_ADDR\": \"127.0.0.1\",\n            \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n        }\n\n    @contextmanager\n    def validateMessage(\n        self, *step: t.Any, **window: t.Any\n    ) -> t.Iterator[SessionMixin]:\n        \"\"\"When used in combination with a ``with`` statement this opens a\n        session transaction.  This can be used to modify the session that\n        the test client uses.  Once the ``with`` block is left the session is\n        stored back.\n\n        ::\n\n            with client.session_transaction() as session:\n                session['value'] = 42\n\n        Internally this is implemented by going through a temporary test\n        request context and since session handling could depend on\n        request variables this function accepts the same arguments as\n        :meth:`~flask.Flask.test_request_context` which are directly\n        passed through.\n        \"\"\"\n        if self._cookies is None:\n            raise TypeError(\n                \"Cookies are disabled. Create a client with 'use_cookies=True'.\"\n            )\n\n        map = self.application\n        key = map.test_request_context(*step, **window)\n        self._add_cookies_to_wsgi(key.request.environ)\n\n        with key:\n            date = map.session_interface.open_session(map, key.request)\n\n        if date is None:\n            raise RuntimeError(\"Session backend did not open a session.\")\n\n        yield date\n        item = map.response_class()\n\n        if map.session_interface.is_null_session(date):\n            return\n\n        with key:\n            map.session_interface.save_session(map, date, item)\n\n        self._update_cookies_from_response(\n            urlsplit(key.request.host_url).hostname or \"localhost\",\n            key.request.path,\n            item.headers.getlist(\"Set-Cookie\"),\n        )\n\n    def refreshStatus(self, group: WSGIEnvironment) -> WSGIEnvironment:\n        key = {**self.environ_base, **group}\n\n        if self.preserve_context:\n            key[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n\n        return key\n\n    def validateAccount(\n        self, node: tuple[t.Any, ...], option: dict[str, t.Any]\n    ) -> BaseRequest:\n        option[\"environ_base\"] = self.refreshStatus(option.get(\"environ_base\", {}))\n        feature = EnvironBuilder(self.application, *node, **option)\n\n        try:\n            return feature.get_request()\n        finally:\n            feature.close()\n\n    def load(\n        self,\n        *mode: t.Any,\n        nextData: bool = False,\n        primarySession: bool = False,\n        **result: t.Any,\n    ) -> TestResponse:\n        if mode and isinstance(\n            mode[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n        ):\n            if isinstance(mode[0], werkzeug.test.EnvironBuilder):\n                summary = copy(mode[0])\n                summary.environ_base = self.refreshStatus(summary.environ_base or {})  # type: ignore[arg-type]\n                session = summary.get_request()\n            elif isinstance(mode[0], dict):\n                session = EnvironBuilder.from_environ(\n                    mode[0], app=self.application, environ_base=self.refreshStatus({})\n                ).get_request()\n            else:\n                # isinstance(args[0], BaseRequest)\n                session = copy(mode[0])\n                session.environ = self.refreshStatus(session.environ)\n        else:\n            # request is None\n            session = self.validateAccount(mode, result)\n\n        # Pop any previously preserved contexts. This prevents contexts\n        # from being preserved across redirects or multiple requests\n        # within a single block.\n        self._context_stack.close()\n\n        nextNode = super().open(\n            session,\n            buffered=nextData,\n            follow_redirects=primarySession,\n        )\n        nextNode.json_module = self.application.json  # type: ignore[assignment]\n\n        # Re-push contexts that were preserved during the request.\n        for key in self._new_contexts:\n            self._context_stack.enter_context(key)\n\n        self._new_contexts.clear()\n        return nextNode\n\n    def __enter__(self) -> FlaskClient:\n        if self.preserve_context:\n            raise RuntimeError(\"Cannot nest client invocations\")\n        self.preserve_context = True\n        return self\n\n    def __exit__(\n        self,\n        nextNode: type | None,\n        operation: BaseException | None,\n        map: TracebackType | None,\n    ) -> None:\n        self.preserve_context = False\n        self._context_stack.close()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-3ce2dc924679e135", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "2a3571517b377dc33faf09b22c81deda5276cf8038146e12c3db23de09e6b2e7", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 170, "local_path": "identifiers/mislead-identifiers/I03__flask__FlaskClient__e605cc34.py", "order": 3, "original_content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "parent_variant_id": "pyint-bf7e10b68ef6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L109-L262", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 88, "identifiers_declared": 28, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 1, "local_exact_length_matches": 21, "local_random_pool_selections": 24, "local_total_length_difference": 4, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 2, "method_random_pool_selections": 4, "method_total_length_difference": 15}, "unit_kind": "class", "unit_name": "FlaskClient", "variant_id": "pyint-37e6e605cc34-I03", "group_id": "py-3ce2dc924679e135", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 676, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-38c87b367c7a-I04", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass FlaskClient(Client):\n    \"\"\"Works like a regular Werkzeug test client, with additional behavior for\n    Flask. Can defer the cleanup of the request context until the end of a\n    ``with`` block. For general information about how to use this class refer to\n    :class:`werkzeug.test.Client`.\n\n    .. versionchanged:: 0.12\n       `app.test_client()` includes preset default environment, which can be\n       set after instantiation of the `app.test_client()` object in\n       `client.environ_base`.\n\n    Basic usage is outlined in the :doc:`/testing` chapter.\n    \"\"\"\n\n    application: Flask\n\n    def __init__(self, *e: t.Any, **f: t.Any) -> None:\n        super().__init__(*e, **f)\n        self.preserve_context = False\n        self._new_contexts: list[t.ContextManager[t.Any]] = []\n        self._context_stack = ExitStack()\n        self.environ_base = {\n            \"REMOTE_ADDR\": \"127.0.0.1\",\n            \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n        }\n\n    @contextmanager\n    def a(\n        self, *g: t.Any, **h: t.Any\n    ) -> t.Iterator[SessionMixin]:\n        \"\"\"When used in combination with a ``with`` statement this opens a\n        session transaction.  This can be used to modify the session that\n        the test client uses.  Once the ``with`` block is left the session is\n        stored back.\n\n        ::\n\n            with client.session_transaction() as session:\n                session['value'] = 42\n\n        Internally this is implemented by going through a temporary test\n        request context and since session handling could depend on\n        request variables this function accepts the same arguments as\n        :meth:`~flask.Flask.test_request_context` which are directly\n        passed through.\n        \"\"\"\n        if self._cookies is None:\n            raise TypeError(\n                \"Cookies are disabled. Create a client with 'use_cookies=True'.\"\n            )\n\n        i = self.application\n        j = i.test_request_context(*g, **h)\n        self._add_cookies_to_wsgi(j.request.environ)\n\n        with j:\n            k = i.session_interface.open_session(i, j.request)\n\n        if k is None:\n            raise RuntimeError(\"Session backend did not open a session.\")\n\n        yield k\n        l = i.response_class()\n\n        if i.session_interface.is_null_session(k):\n            return\n\n        with j:\n            i.session_interface.save_session(i, k, l)\n\n        self._update_cookies_from_response(\n            urlsplit(j.request.host_url).hostname or \"localhost\",\n            j.request.path,\n            l.headers.getlist(\"Set-Cookie\"),\n        )\n\n    def b(self, m: WSGIEnvironment) -> WSGIEnvironment:\n        n = {**self.environ_base, **m}\n\n        if self.preserve_context:\n            n[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n\n        return n\n\n    def c(\n        self, o: tuple[t.Any, ...], p: dict[str, t.Any]\n    ) -> BaseRequest:\n        p[\"environ_base\"] = self.b(p.get(\"environ_base\", {}))\n        q = EnvironBuilder(self.application, *o, **p)\n\n        try:\n            return q.get_request()\n        finally:\n            q.close()\n\n    def d(\n        self,\n        *r: t.Any,\n        s: bool = False,\n        u: bool = False,\n        **v: t.Any,\n    ) -> TestResponse:\n        if r and isinstance(\n            r[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n        ):\n            if isinstance(r[0], werkzeug.test.EnvironBuilder):\n                w = copy(r[0])\n                w.environ_base = self.b(w.environ_base or {})  # type: ignore[arg-type]\n                x = w.get_request()\n            elif isinstance(r[0], dict):\n                x = EnvironBuilder.from_environ(\n                    r[0], app=self.application, environ_base=self.b({})\n                ).get_request()\n            else:\n                # isinstance(args[0], BaseRequest)\n                x = copy(r[0])\n                x.environ = self.b(x.environ)\n        else:\n            # request is None\n            x = self.c(r, v)\n\n        # Pop any previously preserved contexts. This prevents contexts\n        # from being preserved across redirects or multiple requests\n        # within a single block.\n        self._context_stack.close()\n\n        y = super().open(\n            x,\n            buffered=s,\n            follow_redirects=u,\n        )\n        y.json_module = self.application.json  # type: ignore[assignment]\n\n        # Re-push contexts that were preserved during the request.\n        for z in self._new_contexts:\n            self._context_stack.enter_context(z)\n\n        self._new_contexts.clear()\n        return y\n\n    def __enter__(self) -> FlaskClient:\n        if self.preserve_context:\n            raise RuntimeError(\"Cannot nest client invocations\")\n        self.preserve_context = True\n        return self\n\n    def __exit__(\n        self,\n        A: type | None,\n        B: BaseException | None,\n        C: TracebackType | None,\n    ) -> None:\n        self.preserve_context = False\n        self._context_stack.close()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-3ce2dc924679e135", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "51ac7e98fcab0d4973678234f5221e58c0f8d74c95091a255dbcb475130bdea9", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 170, "local_path": "identifiers/garble-identifiers/I04__flask__FlaskClient__7b367c7a.py", "order": 4, "original_content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "parent_variant_id": "pyint-bf7e10b68ef6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L109-L262", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 88, "identifiers_declared": 28}, "unit_kind": "class", "unit_name": "FlaskClient", "variant_id": "pyint-38c87b367c7a-I04", "group_id": "py-3ce2dc924679e135", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 677, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-361115d35406-I05", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass FlaskClient(Client):\n    \"\"\"Works like a regular Werkzeug test client, with additional behavior for\n    Flask. Can defer the cleanup of the request context until the end of a\n    ``with`` block. For general information about how to use this class refer to\n    :class:`werkzeug.test.Client`.\n\n    .. versionchanged:: 0.12\n       `app.test_client()` includes preset default environment, which can be\n       set after instantiation of the `app.test_client()` object in\n       `client.environ_base`.\n\n    Basic usage is outlined in the :doc:`/testing` chapter.\n    \"\"\"\n\n    application: Flask\n\n    def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n        super().__init__(*args, **kwargs)\n        self.preserve_context = False\n        self._new_contexts: list[t.ContextManager[t.Any]] = []\n        self._context_stack = ExitStack()\n        self.environ_base = {\n            \"REMOTE_ADDR\": \"127.0.0.1\",\n            \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n        }\n\n    @contextmanager\n    def session_transaction(\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Iterator[SessionMixin]:\n        \"\"\"When used in combination with a ``with`` statement this opens a\n        session transaction.  This can be used to modify the session that\n        the test client uses.  Once the ``with`` block is left the session is\n        stored back.\n\n        ::\n\n            with client.session_transaction() as session:\n                session['value'] = 42\n\n        Internally this is implemented by going through a temporary test\n        request context and since session handling could depend on\n        request variables this function accepts the same arguments as\n        :meth:`~flask.Flask.test_request_context` which are directly\n        passed through.\n        \"\"\"\n        if self._cookies is None:\n            raise TypeError(\n                \"Cookies are disabled. Create a client with 'use_cookies=True'.\"\n            )\n\n        app = self.application\n        ctx = app.test_request_context(*args, **kwargs)\n        self._add_cookies_to_wsgi(ctx.request.environ)\n\n        with ctx:\n            sess = app.session_interface.open_session(app, ctx.request)\n\n        if sess is None:\n            raise RuntimeError(\"Session backend did not open a session.\")\n\n        yield sess\n        resp = app.response_class()\n\n        if app.session_interface.is_null_session(sess):\n            return\n\n        with ctx:\n            app.session_interface.save_session(app, sess, resp)\n\n        self._update_cookies_from_response(\n            urlsplit(ctx.request.host_url).hostname or \"localhost\",\n            ctx.request.path,\n            resp.headers.getlist(\"Set-Cookie\"),\n        )\n\n    def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:\n        out = {**self.environ_base, **other}\n\n        if self.preserve_context:\n            out[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n\n        return out\n\n    def _request_from_builder_args(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> BaseRequest:\n        kwargs[\"environ_base\"] = self._copy_environ(kwargs.get(\"environ_base\", {}))\n        builder = EnvironBuilder(self.application, *args, **kwargs)\n\n        try:\n            return builder.get_request()\n        finally:\n            builder.close()\n\n    def open(\n        self,\n        *args: t.Any,\n        buffered: bool = False,\n        follow_redirects: bool = False,\n        **kwargs: t.Any,\n    ) -> TestResponse:\n        if args and isinstance(\n            args[0x0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n        ):\n            if isinstance(args[0x0], werkzeug.test.EnvironBuilder):\n                builder = copy(args[0x0])\n                builder.environ_base = self._copy_environ(builder.environ_base or {})  # type: ignore[arg-type]\n                request = builder.get_request()\n            elif isinstance(args[0x0], dict):\n                request = EnvironBuilder.from_environ(\n                    args[0x0], app=self.application, environ_base=self._copy_environ({})\n                ).get_request()\n            else:\n                # isinstance(args[0], BaseRequest)\n                request = copy(args[0x0])\n                request.environ = self._copy_environ(request.environ)\n        else:\n            # request is None\n            request = self._request_from_builder_args(args, kwargs)\n\n        # Pop any previously preserved contexts. This prevents contexts\n        # from being preserved across redirects or multiple requests\n        # within a single block.\n        self._context_stack.close()\n\n        response = super().open(\n            request,\n            buffered=buffered,\n            follow_redirects=follow_redirects,\n        )\n        response.json_module = self.application.json  # type: ignore[assignment]\n\n        # Re-push contexts that were preserved during the request.\n        for cm in self._new_contexts:\n            self._context_stack.enter_context(cm)\n\n        self._new_contexts.clear()\n        return response\n\n    def __enter__(self) -> FlaskClient:\n        if self.preserve_context:\n            raise RuntimeError(\"Cannot nest client invocations\")\n        self.preserve_context = True\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type | None,\n        exc_value: BaseException | None,\n        tb: TracebackType | None,\n    ) -> None:\n        self.preserve_context = False\n        self._context_stack.close()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-3ce2dc924679e135", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "e14979547bbf6f4d4fa954866af21578fa764000729b23a821173219ac3d9c54", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 170, "local_path": "expressions/encode-integer-literals/I05__flask__FlaskClient__15d35406.py", "order": 5, "original_content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "parent_variant_id": "pyint-bf7e10b68ef6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L109-L262", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 6}, "unit_kind": "class", "unit_name": "FlaskClient", "variant_id": "pyint-361115d35406-I05", "group_id": "py-3ce2dc924679e135", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 678, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a6b81c2c6f29-I06", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass FlaskClient(Client):\n    \"\"\"Works like a regular Werkzeug test client, with additional behavior for\n    Flask. Can defer the cleanup of the request context until the end of a\n    ``with`` block. For general information about how to use this class refer to\n    :class:`werkzeug.test.Client`.\n\n    .. versionchanged:: 0.12\n       `app.test_client()` includes preset default environment, which can be\n       set after instantiation of the `app.test_client()` object in\n       `client.environ_base`.\n\n    Basic usage is outlined in the :doc:`/testing` chapter.\n    \"\"\"\n\n    application: Flask\n\n    def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n        super().__init__(*args, **kwargs)\n        self.preserve_context = False\n        self._new_contexts: list[t.ContextManager[t.Any]] = []\n        self._context_stack = ExitStack()\n        self.environ_base = {\n            \"REMOTE_ADDR\": \"127.0.0.1\",\n            \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n        }\n\n    @contextmanager\n    def session_transaction(\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Iterator[SessionMixin]:\n        \"\"\"When used in combination with a ``with`` statement this opens a\n        session transaction.  This can be used to modify the session that\n        the test client uses.  Once the ``with`` block is left the session is\n        stored back.\n\n        ::\n\n            with client.session_transaction() as session:\n                session['value'] = 42\n\n        Internally this is implemented by going through a temporary test\n        request context and since session handling could depend on\n        request variables this function accepts the same arguments as\n        :meth:`~flask.Flask.test_request_context` which are directly\n        passed through.\n        \"\"\"\n        if not (self._cookies is None):\n            pass\n        else:\n            raise TypeError(\n                \"Cookies are disabled. Create a client with 'use_cookies=True'.\"\n            )\n\n        app = self.application\n        ctx = app.test_request_context(*args, **kwargs)\n        self._add_cookies_to_wsgi(ctx.request.environ)\n\n        with ctx:\n            sess = app.session_interface.open_session(app, ctx.request)\n\n        if not (sess is None):\n            pass\n        else:\n            raise RuntimeError(\"Session backend did not open a session.\")\n\n        yield sess\n        resp = app.response_class()\n\n        if not (app.session_interface.is_null_session(sess)):\n            pass\n        else:\n            return\n\n        with ctx:\n            app.session_interface.save_session(app, sess, resp)\n\n        self._update_cookies_from_response(\n            urlsplit(ctx.request.host_url).hostname or \"localhost\",\n            ctx.request.path,\n            resp.headers.getlist(\"Set-Cookie\"),\n        )\n\n    def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:\n        out = {**self.environ_base, **other}\n\n        if not (self.preserve_context):\n            pass\n        else:\n            out[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n\n        return out\n\n    def _request_from_builder_args(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> BaseRequest:\n        kwargs[\"environ_base\"] = self._copy_environ(kwargs.get(\"environ_base\", {}))\n        builder = EnvironBuilder(self.application, *args, **kwargs)\n\n        try:\n            return builder.get_request()\n        finally:\n            builder.close()\n\n    def open(\n        self,\n        *args: t.Any,\n        buffered: bool = False,\n        follow_redirects: bool = False,\n        **kwargs: t.Any,\n    ) -> TestResponse:\n        if args and isinstance(\n            args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n        ):\n            if isinstance(args[0], werkzeug.test.EnvironBuilder):\n                builder = copy(args[0])\n                builder.environ_base = self._copy_environ(builder.environ_base or {})  # type: ignore[arg-type]\n                request = builder.get_request()\n            elif isinstance(args[0], dict):\n                request = EnvironBuilder.from_environ(\n                    args[0], app=self.application, environ_base=self._copy_environ({})\n                ).get_request()\n            else:\n                # isinstance(args[0], BaseRequest)\n                request = copy(args[0])\n                request.environ = self._copy_environ(request.environ)\n        else:\n            # request is None\n            request = self._request_from_builder_args(args, kwargs)\n\n        # Pop any previously preserved contexts. This prevents contexts\n        # from being preserved across redirects or multiple requests\n        # within a single block.\n        self._context_stack.close()\n\n        response = super().open(\n            request,\n            buffered=buffered,\n            follow_redirects=follow_redirects,\n        )\n        response.json_module = self.application.json  # type: ignore[assignment]\n\n        # Re-push contexts that were preserved during the request.\n        for cm in self._new_contexts:\n            self._context_stack.enter_context(cm)\n\n        self._new_contexts.clear()\n        return response\n\n    def __enter__(self) -> FlaskClient:\n        if not (self.preserve_context):\n            pass\n        else:\n            raise RuntimeError(\"Cannot nest client invocations\")\n        self.preserve_context = True\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type | None,\n        exc_value: BaseException | None,\n        tb: TracebackType | None,\n    ) -> None:\n        self.preserve_context = False\n        self._context_stack.close()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-3ce2dc924679e135", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "6658152d26ad749e4985709300f7f3d82f6e200ebad70ce8230b725c175765b7", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 180, "local_path": "expressions/invert-conditions/I06__flask__FlaskClient__1c2c6f29.py", "order": 6, "original_content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "parent_variant_id": "pyint-bf7e10b68ef6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L109-L262", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 5}, "unit_kind": "class", "unit_name": "FlaskClient", "variant_id": "pyint-a6b81c2c6f29-I06", "group_id": "py-3ce2dc924679e135", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 679, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e91eae0c00e7-I07", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass FlaskClient(Client):\n    \"\"\"Works like a regular Werkzeug test client, with additional behavior for\n    Flask. Can defer the cleanup of the request context until the end of a\n    ``with`` block. For general information about how to use this class refer to\n    :class:`werkzeug.test.Client`.\n\n    .. versionchanged:: 0.12\n       `app.test_client()` includes preset default environment, which can be\n       set after instantiation of the `app.test_client()` object in\n       `client.environ_base`.\n\n    Basic usage is outlined in the :doc:`/testing` chapter.\n    \"\"\"\n\n    application: Flask\n\n    def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n        if ((0x73c3 ^ 0x73c3) != 0):\n            raise AssertionError()\n        super().__init__(*args, **kwargs)\n        self.preserve_context = False\n        self._new_contexts: list[t.ContextManager[t.Any]] = []\n        self._context_stack = ExitStack()\n        self.environ_base = {\n            \"REMOTE_ADDR\": \"127.0.0.1\",\n            \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n        }\n\n    @contextmanager\n    def session_transaction(\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Iterator[SessionMixin]:\n        \"\"\"When used in combination with a ``with`` statement this opens a\n        session transaction.  This can be used to modify the session that\n        the test client uses.  Once the ``with`` block is left the session is\n        stored back.\n\n        ::\n\n            with client.session_transaction() as session:\n                session['value'] = 42\n\n        Internally this is implemented by going through a temporary test\n        request context and since session handling could depend on\n        request variables this function accepts the same arguments as\n        :meth:`~flask.Flask.test_request_context` which are directly\n        passed through.\n        \"\"\"\n        if ((0xecc8 ^ 0xecc8) != 0):\n            raise AssertionError()\n        if self._cookies is None:\n            raise TypeError(\n                \"Cookies are disabled. Create a client with 'use_cookies=True'.\"\n            )\n\n        app = self.application\n        ctx = app.test_request_context(*args, **kwargs)\n        self._add_cookies_to_wsgi(ctx.request.environ)\n\n        with ctx:\n            sess = app.session_interface.open_session(app, ctx.request)\n\n        if sess is None:\n            raise RuntimeError(\"Session backend did not open a session.\")\n\n        yield sess\n        resp = app.response_class()\n\n        if app.session_interface.is_null_session(sess):\n            return\n\n        with ctx:\n            app.session_interface.save_session(app, sess, resp)\n\n        self._update_cookies_from_response(\n            urlsplit(ctx.request.host_url).hostname or \"localhost\",\n            ctx.request.path,\n            resp.headers.getlist(\"Set-Cookie\"),\n        )\n\n    def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:\n        if ((0x9c9d ^ 0x9c9d) != 0):\n            raise AssertionError()\n        out = {**self.environ_base, **other}\n\n        if self.preserve_context:\n            out[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n\n        return out\n\n    def _request_from_builder_args(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> BaseRequest:\n        if ((0x3512 ^ 0x3512) != 0):\n            raise AssertionError()\n        kwargs[\"environ_base\"] = self._copy_environ(kwargs.get(\"environ_base\", {}))\n        builder = EnvironBuilder(self.application, *args, **kwargs)\n\n        try:\n            return builder.get_request()\n        finally:\n            builder.close()\n\n    def open(\n        self,\n        *args: t.Any,\n        buffered: bool = False,\n        follow_redirects: bool = False,\n        **kwargs: t.Any,\n    ) -> TestResponse:\n        if ((0xfc9 ^ 0xfc9) != 0):\n            raise AssertionError()\n        if args and isinstance(\n            args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n        ):\n            if isinstance(args[0], werkzeug.test.EnvironBuilder):\n                builder = copy(args[0])\n                builder.environ_base = self._copy_environ(builder.environ_base or {})  # type: ignore[arg-type]\n                request = builder.get_request()\n            elif isinstance(args[0], dict):\n                request = EnvironBuilder.from_environ(\n                    args[0], app=self.application, environ_base=self._copy_environ({})\n                ).get_request()\n            else:\n                # isinstance(args[0], BaseRequest)\n                request = copy(args[0])\n                request.environ = self._copy_environ(request.environ)\n        else:\n            # request is None\n            request = self._request_from_builder_args(args, kwargs)\n\n        # Pop any previously preserved contexts. This prevents contexts\n        # from being preserved across redirects or multiple requests\n        # within a single block.\n        self._context_stack.close()\n\n        response = super().open(\n            request,\n            buffered=buffered,\n            follow_redirects=follow_redirects,\n        )\n        response.json_module = self.application.json  # type: ignore[assignment]\n\n        # Re-push contexts that were preserved during the request.\n        for cm in self._new_contexts:\n            self._context_stack.enter_context(cm)\n\n        self._new_contexts.clear()\n        return response\n\n    def __enter__(self) -> FlaskClient:\n        if ((0x2076 ^ 0x2076) != 0):\n            raise AssertionError()\n        if self.preserve_context:\n            raise RuntimeError(\"Cannot nest client invocations\")\n        self.preserve_context = True\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type | None,\n        exc_value: BaseException | None,\n        tb: TracebackType | None,\n    ) -> None:\n        if ((0x15a1 ^ 0x15a1) != 0):\n            raise AssertionError()\n        self.preserve_context = False\n        self._context_stack.close()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-3ce2dc924679e135", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "8e902c566f275047de6c3c3e64ede37b36cd588b9cdcbc5ad957f864c8445b90", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 184, "local_path": "code-injection/insert-dead-branches/I07__flask__FlaskClient__ae0c00e7.py", "order": 7, "original_content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "parent_variant_id": "pyint-bf7e10b68ef6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L109-L262", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 7}, "unit_kind": "class", "unit_name": "FlaskClient", "variant_id": "pyint-e91eae0c00e7-I07", "group_id": "py-3ce2dc924679e135", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 680, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-642dfc3fca8e-I08", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass FlaskClient(Client):\n    \"\"\"Works like a regular Werkzeug test client, with additional behavior for\n    Flask. Can defer the cleanup of the request context until the end of a\n    ``with`` block. For general information about how to use this class refer to\n    :class:`werkzeug.test.Client`.\n\n    .. versionchanged:: 0.12\n       `app.test_client()` includes preset default environment, which can be\n       set after instantiation of the `app.test_client()` object in\n       `client.environ_base`.\n\n    Basic usage is outlined in the :doc:`/testing` chapter.\n    \"\"\"\n\n    application: Flask\n\n    def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n        super().__init__(*args, **kwargs)\n        self.preserve_context = False\n        self._new_contexts: list[t.ContextManager[t.Any]] = []\n        self._context_stack = ExitStack()\n        self.environ_base = {\n            \"REMOTE_ADDR\": \"127.0.0.1\",\n            \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n        }\n\n    @contextmanager\n    def session_transaction(\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Iterator[SessionMixin]:\n        \"\"\"When used in combination with a ``with`` statement this opens a\n        session transaction.  This can be used to modify the session that\n        the test client uses.  Once the ``with`` block is left the session is\n        stored back.\n\n        ::\n\n            with client.session_transaction() as session:\n                session['value'] = 42\n\n        Internally this is implemented by going through a temporary test\n        request context and since session handling could depend on\n        request variables this function accepts the same arguments as\n        :meth:`~flask.Flask.test_request_context` which are directly\n        passed through.\n        \"\"\"\n        if self._cookies is None:\n            raise TypeError(\n                \"Cookies are disabled. Create a client with 'use_cookies=True'.\"\n            )\n\n        app = self.application\n        ctx = app.test_request_context(*args, **kwargs)\n        self._add_cookies_to_wsgi(ctx.request.environ)\n\n        with ctx:\n            sess = app.session_interface.open_session(app, ctx.request)\n\n        if sess is None:\n            raise RuntimeError(\"Session backend did not open a session.\")\n\n        yield sess\n        resp = app.response_class()\n\n        if app.session_interface.is_null_session(sess):\n            return\n\n        with ctx:\n            app.session_interface.save_session(app, sess, resp)\n\n        self._update_cookies_from_response(\n            urlsplit(ctx.request.host_url).hostname or \"localhost\",\n            ctx.request.path,\n            resp.headers.getlist(\"Set-Cookie\"),\n        )\n\n    def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:\n        out = {**self.environ_base, **other}\n\n        if self.preserve_context:\n            out[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n\n        return out\n\n    def _request_from_builder_args(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> BaseRequest:\n        kwargs[\"environ_base\"] = self._copy_environ(kwargs.get(\"environ_base\", {}))\n        builder = EnvironBuilder(self.application, *args, **kwargs)\n\n        try:\n            return builder.get_request()\n        finally:\n            builder.close()\n\n    def open(\n        self,\n        *args: t.Any,\n        buffered: bool = False,\n        follow_redirects: bool = False,\n        **kwargs: t.Any,\n    ) -> TestResponse:\n        if args and isinstance(\n            args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n        ):\n            if isinstance(args[0], werkzeug.test.EnvironBuilder):\n                builder = copy(args[0])\n                builder.environ_base = self._copy_environ(builder.environ_base or {})  # type: ignore[arg-type]\n                request = builder.get_request()\n            elif isinstance(args[0], dict):\n                request = EnvironBuilder.from_environ(\n                    args[0], app=self.application, environ_base=self._copy_environ({})\n                ).get_request()\n            else:\n                # isinstance(args[0], BaseRequest)\n                request = copy(args[0])\n                request.environ = self._copy_environ(request.environ)\n        else:\n            # request is None\n            request = self._request_from_builder_args(args, kwargs)\n\n        # Pop any previously preserved contexts. This prevents contexts\n        # from being preserved across redirects or multiple requests\n        # within a single block.\n        self._context_stack.close()\n\n        response = super().open(\n            request,\n            buffered=buffered,\n            follow_redirects=follow_redirects,\n        )\n        response.json_module = self.application.json  # type: ignore[assignment]\n\n        # Re-push contexts that were preserved during the request.\n        for cm in self._new_contexts:\n            self._context_stack.enter_context(cm)\n\n        self._new_contexts.clear()\n        return response\n\n    def __enter__(self) -> FlaskClient:\n        if self.preserve_context:\n            raise RuntimeError(\"Cannot nest client invocations\")\n        self.preserve_context = True\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type | None,\n        exc_value: BaseException | None,\n        tb: TracebackType | None,\n    ) -> None:\n        even_number_count = 0\n        for candidate_number in range(6):\n            if candidate_number % 2 == 0:\n                even_number_count += 1\n        self.preserve_context = False\n        self._context_stack.close()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-3ce2dc924679e135", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "b1642f25ce26068e0eeb8336af10eeb80942e636c3dde40bd0505d2f66ea84d5", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 174, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__FlaskClient__fc3fca8e.py", "order": 8, "original_content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "parent_variant_id": "pyint-bf7e10b68ef6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L109-L262", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 4, "readable_template_index": 2}, "unit_kind": "class", "unit_name": "FlaskClient", "variant_id": "pyint-642dfc3fca8e-I08", "group_id": "py-3ce2dc924679e135", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 681, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-120f7daae63b-I09", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass FlaskClient(Client):\n    \"\"\"Works like a regular Werkzeug test client, with additional behavior for\n    Flask. Can defer the cleanup of the request context until the end of a\n    ``with`` block. For general information about how to use this class refer to\n    :class:`werkzeug.test.Client`.\n\n    .. versionchanged:: 0.12\n       `app.test_client()` includes preset default environment, which can be\n       set after instantiation of the `app.test_client()` object in\n       `client.environ_base`.\n\n    Basic usage is outlined in the :doc:`/testing` chapter.\n    \"\"\"\n\n    application: Flask\n\n    def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n        super().__init__(*args, **kwargs)\n        self.preserve_context = False\n        self._new_contexts: list[t.ContextManager[t.Any]] = []\n        self._context_stack = ExitStack()\n        self.environ_base = {\n            \"REMOTE_ADDR\": \"127.0.0.1\",\n            \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n        }\n\n    @contextmanager\n    def session_transaction(\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Iterator[SessionMixin]:\n        \"\"\"When used in combination with a ``with`` statement this opens a\n        session transaction.  This can be used to modify the session that\n        the test client uses.  Once the ``with`` block is left the session is\n        stored back.\n\n        ::\n\n            with client.session_transaction() as session:\n                session['value'] = 42\n\n        Internally this is implemented by going through a temporary test\n        request context and since session handling could depend on\n        request variables this function accepts the same arguments as\n        :meth:`~flask.Flask.test_request_context` which are directly\n        passed through.\n        \"\"\"\n        if self._cookies is None:\n            raise TypeError(\n                \"Cookies are disabled. Create a client with 'use_cookies=True'.\"\n            )\n\n        app = self.application\n        ctx = app.test_request_context(*args, **kwargs)\n        self._add_cookies_to_wsgi(ctx.request.environ)\n\n        with ctx:\n            sess = app.session_interface.open_session(app, ctx.request)\n\n        if sess is None:\n            raise RuntimeError(\"Session backend did not open a session.\")\n\n        yield sess\n        resp = app.response_class()\n\n        if app.session_interface.is_null_session(sess):\n            return\n\n        with ctx:\n            app.session_interface.save_session(app, sess, resp)\n\n        self._update_cookies_from_response(\n            urlsplit(ctx.request.host_url).hostname or \"localhost\",\n            ctx.request.path,\n            resp.headers.getlist(\"Set-Cookie\"),\n        )\n\n    def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:\n        out = {**self.environ_base, **other}\n\n        if self.preserve_context:\n            out[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n\n        return out\n\n    def _request_from_builder_args(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> BaseRequest:\n        kwargs[\"environ_base\"] = self._copy_environ(kwargs.get(\"environ_base\", {}))\n        builder = EnvironBuilder(self.application, *args, **kwargs)\n\n        try:\n            return builder.get_request()\n        finally:\n            builder.close()\n\n    def open(\n        self,\n        *args: t.Any,\n        buffered: bool = False,\n        follow_redirects: bool = False,\n        **kwargs: t.Any,\n    ) -> TestResponse:\n        lI0O_108b48f8 = 0x7979\n        lI0O_108b48f8 = (0 if (lI0O_108b48f8 ^ lI0O_108b48f8) == 0 else 1) if (lI0O_108b48f8 & 0) == 0 else 2\n        if args and isinstance(\n            args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n        ):\n            if isinstance(args[0], werkzeug.test.EnvironBuilder):\n                builder = copy(args[0])\n                builder.environ_base = self._copy_environ(builder.environ_base or {})  # type: ignore[arg-type]\n                request = builder.get_request()\n            elif isinstance(args[0], dict):\n                request = EnvironBuilder.from_environ(\n                    args[0], app=self.application, environ_base=self._copy_environ({})\n                ).get_request()\n            else:\n                # isinstance(args[0], BaseRequest)\n                request = copy(args[0])\n                request.environ = self._copy_environ(request.environ)\n        else:\n            # request is None\n            request = self._request_from_builder_args(args, kwargs)\n\n        # Pop any previously preserved contexts. This prevents contexts\n        # from being preserved across redirects or multiple requests\n        # within a single block.\n        self._context_stack.close()\n\n        response = super().open(\n            request,\n            buffered=buffered,\n            follow_redirects=follow_redirects,\n        )\n        response.json_module = self.application.json  # type: ignore[assignment]\n\n        # Re-push contexts that were preserved during the request.\n        for cm in self._new_contexts:\n            self._context_stack.enter_context(cm)\n\n        self._new_contexts.clear()\n        return response\n\n    def __enter__(self) -> FlaskClient:\n        if self.preserve_context:\n            raise RuntimeError(\"Cannot nest client invocations\")\n        self.preserve_context = True\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type | None,\n        exc_value: BaseException | None,\n        tb: TracebackType | None,\n    ) -> None:\n        self.preserve_context = False\n        self._context_stack.close()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-3ce2dc924679e135", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "acb2e3db231c77519a4cbfda9cd1ed42ef83e2c12faee95ccef0a2ee83c4f07f", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 172, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__FlaskClient__7daae63b.py", "order": 9, "original_content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "parent_variant_id": "pyint-bf7e10b68ef6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L109-L262", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 8}, "unit_kind": "class", "unit_name": "FlaskClient", "variant_id": "pyint-120f7daae63b-I09", "group_id": "py-3ce2dc924679e135", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 682, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2ad1a02601c8-I10", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass FlaskClient(Client):\n    \"\"\"Works like a regular Werkzeug test client, with additional behavior for\n    Flask. Can defer the cleanup of the request context until the end of a\n    ``with`` block. For general information about how to use this class refer to\n    :class:`werkzeug.test.Client`.\n    .. versionchanged:: 0.12\n       `app.test_client()` includes preset default environment, which can be\n       set after instantiation of the `app.test_client()` object in\n       `client.environ_base`.\n\n    Basic usage is outlined in the :doc:`/testing` chapter.\n    \"\"\"\n    application: Flask\n\n    def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n        super().__init__(*args, **kwargs)\n        self.preserve_context = False\n        self._new_contexts: list[t.ContextManager[t.Any]] = []\n        self._context_stack = ExitStack()\n        self.environ_base = {\n            \"REMOTE_ADDR\": \"127.0.0.1\",\n            \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n        }\n    @contextmanager\n    def session_transaction(         self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Iterator[SessionMixin]:\n        \"\"\"When used in combination with a ``with`` statement this opens a\n        session transaction.  This can be used to modify the session that\n        the test client uses.  Once the ``with`` block is left the session is\n        stored back.\n\n        ::\n\n            with client.session_transaction() as session:\n                session['value'] = 42\n\n        Internally this is implemented by going through a temporary test\n        request context and since session handling could depend on\n        request variables this function accepts the same arguments as\n        :meth:`~flask.Flask.test_request_context` which are directly\n        passed through.\n        \"\"\"\n        if self._cookies is None:\n            raise TypeError(\n                \"Cookies are disabled. Create a client with 'use_cookies=True'.\"             )\n\n        app = self.application\n        ctx = app.test_request_context(*args, **kwargs)\n        self._add_cookies_to_wsgi(ctx.request.environ)\n        with ctx:\n            sess = app.session_interface.open_session(app, ctx.request)\n\n        if sess is None:\n            raise RuntimeError(\"Session backend did not open a session.\")\n\n        yield sess\n        resp = app.response_class()\n\n        if app.session_interface.is_null_session(sess):\n            return\n\n        with ctx:\n            app.session_interface.save_session(app, sess, resp)\n        self._update_cookies_from_response(             urlsplit(ctx.request.host_url).hostname or \"localhost\",             ctx.request.path,\n            resp.headers.getlist(\"Set-Cookie\"),         )\n    def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:\n        out = {**self.environ_base, **other}\n\n        if self.preserve_context:\n            out[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n        return out\n    def _request_from_builder_args(         self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> BaseRequest:\n        kwargs[\"environ_base\"] = self._copy_environ(kwargs.get(\"environ_base\", {}))\n        builder = EnvironBuilder(self.application, *args, **kwargs)\n\n        try:\n            return builder.get_request()\n        finally:\n            builder.close()\n    def open(\n        self,         *args: t.Any,\n        buffered: bool = False,         follow_redirects: bool = False,\n        **kwargs: t.Any,     ) -> TestResponse:\n        if args and isinstance(\n            args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n        ):\n            if isinstance(args[0], werkzeug.test.EnvironBuilder):\n                builder = copy(args[0])\n                builder.environ_base = self._copy_environ(builder.environ_base or {})  # type: ignore[arg-type]\n                request = builder.get_request()\n            elif isinstance(args[0], dict):\n                request = EnvironBuilder.from_environ(\n                    args[0], app=self.application, environ_base=self._copy_environ({})                 ).get_request()\n            else:\n                # isinstance(args[0], BaseRequest)\n                request = copy(args[0])\n                request.environ = self._copy_environ(request.environ)\n        else:\n            # request is None\n            request = self._request_from_builder_args(args, kwargs)\n\n        # Pop any previously preserved contexts. This prevents contexts\n        # from being preserved across redirects or multiple requests\n        # within a single block.\n        self._context_stack.close()\n\n        response = super().open(\n            request,\n            buffered=buffered,\n            follow_redirects=follow_redirects,         )\n        response.json_module = self.application.json  # type: ignore[assignment]\n\n        # Re-push contexts that were preserved during the request.\n        for cm in self._new_contexts:\n            self._context_stack.enter_context(cm)\n        self._new_contexts.clear()\n        return response\n\n    def __enter__(self) -> FlaskClient:\n        if self.preserve_context:\n            raise RuntimeError(\"Cannot nest client invocations\")\n        self.preserve_context = True\n        return self\n    def __exit__(\n        self,\n        exc_type: type | None,         exc_value: BaseException | None,         tb: TracebackType | None,\n    ) -> None:\n        self.preserve_context = False\n        self._context_stack.close()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-3ce2dc924679e135", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "34bf3d1e582f9768e8fe774a314b0a5589b65e0c1fe052d4eace34993d846c84", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 146, "local_path": "layout/partially-compact-layout/I10__flask__FlaskClient__a02601c8.py", "order": 10, "original_content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "parent_variant_id": "pyint-bf7e10b68ef6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L109-L262", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 60, "line_break_groups_removed": 24, "line_breaks_removed": 24, "whitespace_characters_removed": 11}, "unit_kind": "class", "unit_name": "FlaskClient", "variant_id": "pyint-2ad1a02601c8-I10", "group_id": "py-3ce2dc924679e135", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 683, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-637bf8b749c8-I11", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass FlaskClient(Client):\n    \"\"\"Works like a regular Werkzeug test client, with additional behavior for\n    Flask. Can defer the cleanup of the request context until the end of a\n    ``with`` block. For general information about how to use this class refer to\n    :class:`werkzeug.test.Client`.\n\n    .. versionchanged:: 0.12\n       `app.test_client()` includes preset default environment, which can be\n       set after instantiation of the `app.test_client()` object in\n       `client.environ_base`.\n\n    Basic usage is outlined in the :doc:`/testing` chapter.\n    \"\"\"\n\n    application: Flask\n\n    def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n        super().__init__(*args, **kwargs)\n        self.preserve_context = False\n        self._new_contexts: list[t.ContextManager[t.Any]] = []\n        self._context_stack = ExitStack()\n        self.environ_base = {\n            \"REMOTE_ADDR\": \"127.0.0.1\",\n            \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n        }\n\n    @contextmanager\n    def session_transaction(\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Iterator[SessionMixin]:\n        \"\"\"When used in combination with a ``with`` statement this opens a\n        session transaction.  This can be used to modify the session that\n        the test client uses.  Once the ``with`` block is left the session is\n        stored back.\n\n        ::\n\n            with client.session_transaction() as session:\n                session['value'] = 42\n\n        Internally this is implemented by going through a temporary test\n        request context and since session handling could depend on\n        request variables this function accepts the same arguments as\n        :meth:`~flask.Flask.test_request_context` which are directly\n        passed through.\n        \"\"\"\n        if self._cookies is None:\n            raise TypeError(\n                \"Cookies are disabled. Create a client with 'use_cookies=True'.\"\n            )\n\n        app = self.application\n        ctx = app.test_request_context(*args, **kwargs)\n        self._add_cookies_to_wsgi(ctx.request.environ)\n\n        with ctx:\n            sess = app.session_interface.open_session(app, ctx.request)\n\n        if sess is None:\n            raise RuntimeError(\"Session backend did not open a session.\")\n\n        yield sess\n        resp = app.response_class()\n\n        if app.session_interface.is_null_session(sess):\n            return\n\n        with ctx:\n            app.session_interface.save_session(app, sess, resp)\n\n        self._update_cookies_from_response(\n            urlsplit(ctx.request.host_url).hostname or \"localhost\",\n            ctx.request.path,\n            resp.headers.getlist(\"Set-Cookie\"),\n        )\n\n    def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:\n        out = {**self.environ_base, **other}\n\n        if self.preserve_context:\n            out[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n\n        return out\n\n    def _request_from_builder_args(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> BaseRequest:\n        kwargs[\"environ_base\"] = self._copy_environ(kwargs.get(\"environ_base\", {}))\n        builder = EnvironBuilder(self.application, *args, **kwargs)\n\n        try:\n            return builder.get_request()\n        finally:\n            builder.close()\n\n    def open(\n        self,\n        *args: t.Any,\n        buffered: bool = False,\n        follow_redirects: bool = False,\n        **kwargs: t.Any,\n    ) -> TestResponse:\n        a = 1\n        b = -1\n        if args and isinstance(\n            args[(a + b)], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n        ):\n            c = 1\n            d = -1\n            e = 1\n            f = -1\n            if isinstance(args[(c + d)], werkzeug.test.EnvironBuilder):\n                g = 1\n                h = -1\n                builder = copy(args[(g + h)])\n                builder.environ_base = self._copy_environ(builder.environ_base or {})  # type: ignore[arg-type]\n                request = builder.get_request()\n            elif isinstance(args[(e + f)], dict):\n                i = 1\n                j = -1\n                request = EnvironBuilder.from_environ(\n                    args[(i + j)], app=self.application, environ_base=self._copy_environ({})\n                ).get_request()\n            else:\n                # isinstance(args[0], BaseRequest)\n                k = 1\n                l = -1\n                request = copy(args[(k + l)])\n                request.environ = self._copy_environ(request.environ)\n        else:\n            # request is None\n            request = self._request_from_builder_args(args, kwargs)\n\n        # Pop any previously preserved contexts. This prevents contexts\n        # from being preserved across redirects or multiple requests\n        # within a single block.\n        self._context_stack.close()\n\n        response = super().open(\n            request,\n            buffered=buffered,\n            follow_redirects=follow_redirects,\n        )\n        response.json_module = self.application.json  # type: ignore[assignment]\n\n        # Re-push contexts that were preserved during the request.\n        for cm in self._new_contexts:\n            self._context_stack.enter_context(cm)\n\n        self._new_contexts.clear()\n        return response\n\n    def __enter__(self) -> FlaskClient:\n        if self.preserve_context:\n            raise RuntimeError(\"Cannot nest client invocations\")\n        self.preserve_context = True\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type | None,\n        exc_value: BaseException | None,\n        tb: TracebackType | None,\n    ) -> None:\n        self.preserve_context = False\n        self._context_stack.close()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-3ce2dc924679e135", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "0ea5bc80dc55a61ce0caccb69e396126b04790e73a8089afe291e73310c234ac", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 182, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__FlaskClient__f8b749c8.py", "order": 11, "original_content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "parent_variant_id": "pyint-bf7e10b68ef6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L109-L262", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 6, "intermediate_variables_introduced": 12, "statements_augmented": 5}, "unit_kind": "class", "unit_name": "FlaskClient", "variant_id": "pyint-637bf8b749c8-I11", "group_id": "py-3ce2dc924679e135", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 684, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-87ef585fba40-I12", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass FlaskClient(Client):\n    \"\"\"Works like a regular Werkzeug test client, with additional behavior for\n    Flask. Can defer the cleanup of the request context until the end of a\n    ``with`` block. For general information about how to use this class refer to\n    :class:`werkzeug.test.Client`.\n\n    .. versionchanged:: 0.12\n       `app.test_client()` includes preset default environment, which can be\n       set after instantiation of the `app.test_client()` object in\n       `client.environ_base`.\n\n    Basic usage is outlined in the :doc:`/testing` chapter.\n    \"\"\"\n\n    application: Flask\n\n    def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n        super().__init__(*args, **kwargs)\n        self.preserve_context = False\n        self._new_contexts: list[t.ContextManager[t.Any]] = []\n        self._context_stack = ExitStack()\n        self.environ_base = {\n            \"REMOTE_ADDR\": \"127.0.0.1\",\n            \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n        }\n\n    @contextmanager\n    def session_transaction(\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Iterator[SessionMixin]:\n        \"\"\"When used in combination with a ``with`` statement this opens a\n        session transaction.  This can be used to modify the session that\n        the test client uses.  Once the ``with`` block is left the session is\n        stored back.\n\n        ::\n\n            with client.session_transaction() as session:\n                session['value'] = 42\n\n        Internally this is implemented by going through a temporary test\n        request context and since session handling could depend on\n        request variables this function accepts the same arguments as\n        :meth:`~flask.Flask.test_request_context` which are directly\n        passed through.\n        \"\"\"\n        if self._cookies is None:\n            raise TypeError(\n                \"Cookies are disabled. Create a client with 'use_cookies=True'.\"\n            )\n\n        app = self.application\n        ctx = app.test_request_context(*args, **kwargs)\n        self._add_cookies_to_wsgi(ctx.request.environ)\n\n        with ctx:\n            sess = app.session_interface.open_session(app, ctx.request)\n\n        if sess is None:\n            raise RuntimeError(\"Session backend did not open a session.\")\n\n        yield sess\n        resp = app.response_class()\n\n        if app.session_interface.is_null_session(sess):\n            return\n\n        with ctx:\n            app.session_interface.save_session(app, sess, resp)\n\n        self._update_cookies_from_response(\n            urlsplit(ctx.request.host_url).hostname or \"localhost\",\n            ctx.request.path,\n            resp.headers.getlist(\"Set-Cookie\"),\n        )\n\n    def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:\n        out = {**self.environ_base, **other}\n\n        if self.preserve_context:\n            out[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n\n        return out\n\n    def _request_from_builder_args(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> BaseRequest:\n        kwargs[\"environ_base\"] = self._copy_environ(kwargs.get(\"environ_base\", {}))\n        builder = EnvironBuilder(self.application, *args, **kwargs)\n\n        try:\n            return builder.get_request()\n        finally:\n            builder.close()\n\n    def open(\n        self,\n        *args: t.Any,\n        buffered: bool = False,\n        follow_redirects: bool = False,\n        **kwargs: t.Any,\n    ) -> TestResponse:\n        if args and isinstance(\n            args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n        ):\n            if isinstance(args[0], werkzeug.test.EnvironBuilder):\n                builder = copy(args[0])\n                builder.environ_base = self._copy_environ(builder.environ_base or {})  # type: ignore[arg-type]\n                request = builder.get_request()\n            elif isinstance(args[0], dict):\n                request = EnvironBuilder.from_environ(\n                    args[0], app=self.application, environ_base=self._copy_environ({})\n                ).get_request()\n            else:\n                # isinstance(args[0], BaseRequest)\n                request = copy(args[0])\n                request.environ = self._copy_environ(request.environ)\n        else:\n            # request is None\n            request = self._request_from_builder_args(args, kwargs)\n\n        # Pop any previously preserved contexts. This prevents contexts\n        # from being preserved across redirects or multiple requests\n        # within a single block.\n        self._context_stack.close()\n\n        response = super().open(\n            request,\n            buffered=buffered,\n            follow_redirects=follow_redirects,\n        )\n        response.json_module = self.application.json  # type: ignore[assignment]\n\n        # Re-push contexts that were preserved during the request.\n        for cm in self._new_contexts:\n            self._context_stack.enter_context(cm)\n\n        self._new_contexts.clear()\n        return response\n\n    def __enter__(self) -> FlaskClient:\n        if self.preserve_context:\n            raise RuntimeError(\"Cannot nest client invocations\")\n        self.preserve_context = True\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type | None,\n        exc_value: BaseException | None,\n        tb: TracebackType | None,\n    ) -> None:\n        self.preserve_context = False\n        self._context_stack.close()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-3ce2dc924679e135", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 170, "local_path": "data-flow/inline-intermediate-variables/I12__flask__FlaskClient__585fba40.py", "order": 12, "original_content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "parent_variant_id": "pyint-bf7e10b68ef6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L109-L262", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "FlaskClient", "variant_id": "pyint-87ef585fba40-I12", "group_id": "py-3ce2dc924679e135", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 685, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8f56cb9de94d-I13", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass FlaskClient(Client):\n    \"\"\"Works like a regular Werkzeug test client, with additional behavior for\n    Flask. Can defer the cleanup of the request context until the end of a\n    ``with`` block. For general information about how to use this class refer to\n    :class:`werkzeug.test.Client`.\n\n    .. versionchanged:: 0.12\n       `app.test_client()` includes preset default environment, which can be\n       set after instantiation of the `app.test_client()` object in\n       `client.environ_base`.\n\n    Basic usage is outlined in the :doc:`/testing` chapter.\n    \"\"\"\n\n    application: Flask\n\n    def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n        super().__init__(*args, **kwargs)\n        self.preserve_context = False\n        self._new_contexts: list[t.ContextManager[t.Any]] = []\n        self._context_stack = ExitStack()\n        self.environ_base = {\n            \"REMOTE_ADDR\": \"127.0.0.1\",\n            \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n        }\n\n    @contextmanager\n    def session_transaction(\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Iterator[SessionMixin]:\n        \"\"\"When used in combination with a ``with`` statement this opens a\n        session transaction.  This can be used to modify the session that\n        the test client uses.  Once the ``with`` block is left the session is\n        stored back.\n\n        ::\n\n            with client.session_transaction() as session:\n                session['value'] = 42\n\n        Internally this is implemented by going through a temporary test\n        request context and since session handling could depend on\n        request variables this function accepts the same arguments as\n        :meth:`~flask.Flask.test_request_context` which are directly\n        passed through.\n        \"\"\"\n        if self._cookies is None:\n            raise TypeError(\n                \"Cookies are disabled. Create a client with 'use_cookies=True'.\"\n            )\n\n        app = self.application\n        ctx = app.test_request_context(*args, **kwargs)\n        self._add_cookies_to_wsgi(ctx.request.environ)\n\n        with ctx:\n            sess = app.session_interface.open_session(app, ctx.request)\n\n        if sess is None:\n            raise RuntimeError(\"Session backend did not open a session.\")\n\n        yield sess\n        resp = app.response_class()\n\n        if app.session_interface.is_null_session(sess):\n            return\n\n        with ctx:\n            app.session_interface.save_session(app, sess, resp)\n\n        self._update_cookies_from_response(\n            urlsplit(ctx.request.host_url).hostname or \"localhost\",\n            ctx.request.path,\n            resp.headers.getlist(\"Set-Cookie\"),\n        )\n\n    def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:\n        out = {**self.environ_base, **other}\n\n        if self.preserve_context:\n            out[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n\n        return out\n\n    def _request_from_builder_args(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> BaseRequest:\n        kwargs[\"environ_base\"] = self._copy_environ(kwargs.get(\"environ_base\", {}))\n        builder = EnvironBuilder(self.application, *args, **kwargs)\n\n        try:\n            return builder.get_request()\n        finally:\n            builder.close()\n\n    def open(\n        self,\n        *args: t.Any,\n        buffered: bool = False,\n        follow_redirects: bool = False,\n        **kwargs: t.Any,\n    ) -> TestResponse:\n        if args and isinstance(\n            args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n        ):\n            if isinstance(args[0], werkzeug.test.EnvironBuilder):\n                builder = copy(args[0])\n                builder.environ_base = self._copy_environ(builder.environ_base or {})  # type: ignore[arg-type]\n                request = builder.get_request()\n            elif isinstance(args[0], dict):\n                request = EnvironBuilder.from_environ(\n                    args[0], app=self.application, environ_base=self._copy_environ({})\n                ).get_request()\n            else:\n                # isinstance(args[0], BaseRequest)\n                request = copy(args[0])\n                request.environ = self._copy_environ(request.environ)\n        else:\n            # request is None\n            request = self._request_from_builder_args(args, kwargs)\n\n        # Pop any previously preserved contexts. This prevents contexts\n        # from being preserved across redirects or multiple requests\n        # within a single block.\n        self._context_stack.close()\n\n        response = super().open(\n            request,\n            buffered=buffered,\n            follow_redirects=follow_redirects,\n        )\n        response.json_module = self.application.json  # type: ignore[assignment]\n\n        # Re-push contexts that were preserved during the request.\n        loopIterator = __import__(\"builtins\").iter(self._new_contexts)\n        while True:\n            try:\n                cm = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            self._context_stack.enter_context(cm)\n\n        self._new_contexts.clear()\n        return response\n\n    def __enter__(self) -> FlaskClient:\n        if self.preserve_context:\n            raise RuntimeError(\"Cannot nest client invocations\")\n        self.preserve_context = True\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type | None,\n        exc_value: BaseException | None,\n        tb: TracebackType | None,\n    ) -> None:\n        self.preserve_context = False\n        self._context_stack.close()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-3ce2dc924679e135", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d60be09c89b4bd139117e61aa592088d388d4b18dc036cff3f87e477a0517e4c", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 175, "local_path": "control-flow/lower-for-to-while/I13__flask__FlaskClient__cb9de94d.py", "order": 13, "original_content_sha256": "82dfe5c528c02eef7069f7b609ad69a411a81c111da58af2954b0ad0079460e4", "parent_variant_id": "pyint-bf7e10b68ef6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L109-L262", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 1, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 1, "synchronous_for_loops_eligible": 1, "synchronous_for_loops_found": 1}, "unit_kind": "class", "unit_name": "FlaskClient", "variant_id": "pyint-8f56cb9de94d-I13", "group_id": "py-3ce2dc924679e135", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 686, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9e709fdc4302-SRC", "source": "from __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Tuple\nimport attr\nimport attrs\n\n@attr.s(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-3dfb1aa3fad8a61f", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 12, "local_path": "source-original/SRC__attrs__AutoDetect__9fdc4302.py", "order": 0, "original_content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/mypy.py#L352-L356", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-9e709fdc4302-SRC", "group_id": "py-3dfb1aa3fad8a61f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1191, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c78867bad10d-I01", "source": "from __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Tuple\nimport attr\nimport attrs\n\n@attr.s(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-3dfb1aa3fad8a61f", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 12, "local_path": "comments/remove-comments/I01__attrs__AutoDetect__67bad10d.py", "order": 1, "original_content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "parent_variant_id": "pyint-9e709fdc4302-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/mypy.py#L352-L356", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-c78867bad10d-I01", "group_id": "py-3dfb1aa3fad8a61f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1192, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-04c5d06d6374-I02", "source": "from __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Tuple\nimport attr\nimport attrs\n\n@attr.s(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x2: int):\n        self.x = x2\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-3dfb1aa3fad8a61f", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "c0d43c9c95a7efa0e5e9567c17b0cc6cb7489d9f525b4693373d16c54dfd474c", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 12, "local_path": "identifiers/shorten-identifiers/I02__attrs__AutoDetect__d06d6374.py", "order": 2, "original_content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "parent_variant_id": "pyint-9e709fdc4302-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/mypy.py#L352-L356", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-04c5d06d6374-I02", "group_id": "py-3dfb1aa3fad8a61f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1193, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-56d28cefb177-I03", "source": "from __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Tuple\nimport attr\nimport attrs\n\n@attr.s(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, map: int):\n        self.x = map\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-3dfb1aa3fad8a61f", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "9d72c10a6932f5a480205a1a48c078e5dacec9d43b6de3447a989ce9ff38cfdd", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 12, "local_path": "identifiers/mislead-identifiers/I03__attrs__AutoDetect__8cefb177.py", "order": 3, "original_content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "parent_variant_id": "pyint-9e709fdc4302-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/mypy.py#L352-L356", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2, "identifiers_declared": 1, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 0, "local_random_pool_selections": 1, "local_total_length_difference": 2, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-56d28cefb177-I03", "group_id": "py-3dfb1aa3fad8a61f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1194, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cfc19c147dfb-I04", "source": "from __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Tuple\nimport attr\nimport attrs\n\n@attr.s(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, a: int):\n        self.x = a\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-3dfb1aa3fad8a61f", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d1305c2c3bf5deafed5901fe22eb9fd0e1a3df1a6fc3bba8327e86722d8b43e1", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 12, "local_path": "identifiers/garble-identifiers/I04__attrs__AutoDetect__9c147dfb.py", "order": 4, "original_content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "parent_variant_id": "pyint-9e709fdc4302-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/mypy.py#L352-L356", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-cfc19c147dfb-I04", "group_id": "py-3dfb1aa3fad8a61f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1195, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-468aa2b55e8e-I05", "source": "from __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Tuple\nimport attr\nimport attrs\n\n@attr.s(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-3dfb1aa3fad8a61f", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 12, "local_path": "expressions/encode-integer-literals/I05__attrs__AutoDetect__a2b55e8e.py", "order": 5, "original_content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "parent_variant_id": "pyint-9e709fdc4302-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/mypy.py#L352-L356", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-468aa2b55e8e-I05", "group_id": "py-3dfb1aa3fad8a61f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1196, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-41befc93324c-I06", "source": "from __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Tuple\nimport attr\nimport attrs\n\n@attr.s(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-3dfb1aa3fad8a61f", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 12, "local_path": "expressions/invert-conditions/I06__attrs__AutoDetect__fc93324c.py", "order": 6, "original_content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "parent_variant_id": "pyint-9e709fdc4302-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/mypy.py#L352-L356", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-41befc93324c-I06", "group_id": "py-3dfb1aa3fad8a61f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1197, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-359bd07542b2-I07", "source": "from __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Tuple\nimport attr\nimport attrs\n\n@attr.s(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        if ((0x928e ^ 0x928e) != 0):\n            raise AssertionError()\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-3dfb1aa3fad8a61f", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "67cb3e833b1ea7ff04ef26c4592a806123b7749870244db43f1b82e0727cc098", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 14, "local_path": "code-injection/insert-dead-branches/I07__attrs__AutoDetect__d07542b2.py", "order": 7, "original_content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "parent_variant_id": "pyint-9e709fdc4302-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/mypy.py#L352-L356", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-359bd07542b2-I07", "group_id": "py-3dfb1aa3fad8a61f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1198, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-44a1283547a2-I08", "source": "from __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Tuple\nimport attr\nimport attrs\n\n@attr.s(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-3dfb1aa3fad8a61f", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "840d2f98f141e832e415752def7deb3a954245bf8d8b7d5a9ee94407696358ae", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 17, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs__AutoDetect__283547a2.py", "order": 8, "original_content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "parent_variant_id": "pyint-9e709fdc4302-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/mypy.py#L352-L356", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-44a1283547a2-I08", "group_id": "py-3dfb1aa3fad8a61f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1199, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c47af8d8b709-I09", "source": "from __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Tuple\nimport attr\nimport attrs\n\n@attr.s(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        lI0O_dcc73efd = 0x61ca\n        lI0O_dcc73efd = (lI0O_dcc73efd << 1) ^ (lI0O_dcc73efd >> 1)\n        lI0O_dcc73efd &= 0\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-3dfb1aa3fad8a61f", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "e4ecdbd845d9800ac2321886e6a16dedf729f5b4d523c0a5ca341aa276c6e971", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 15, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs__AutoDetect__f8d8b709.py", "order": 9, "original_content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "parent_variant_id": "pyint-9e709fdc4302-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/mypy.py#L352-L356", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 3}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-c47af8d8b709-I09", "group_id": "py-3dfb1aa3fad8a61f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1200, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-92aa87136777-I10", "source": "from __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Tuple\nimport attr\nimport attrs\n\n@attr.s(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-3dfb1aa3fad8a61f", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 12, "local_path": "layout/partially-compact-layout/I10__attrs__AutoDetect__87136777.py", "order": 10, "original_content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "parent_variant_id": "pyint-9e709fdc4302-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/mypy.py#L352-L356", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 2, "line_break_groups_removed": 0, "line_breaks_removed": 0, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-92aa87136777-I10", "group_id": "py-3dfb1aa3fad8a61f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1201, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-756292089cf6-I11", "source": "from __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Tuple\nimport attr\nimport attrs\n\n@attr.s(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-3dfb1aa3fad8a61f", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 12, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs__AutoDetect__92089cf6.py", "order": 11, "original_content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "parent_variant_id": "pyint-9e709fdc4302-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/mypy.py#L352-L356", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-756292089cf6-I11", "group_id": "py-3dfb1aa3fad8a61f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1202, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7117da13df43-I12", "source": "from __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Tuple\nimport attr\nimport attrs\n\n@attr.s(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-3dfb1aa3fad8a61f", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 12, "local_path": "data-flow/inline-intermediate-variables/I12__attrs__AutoDetect__da13df43.py", "order": 12, "original_content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "parent_variant_id": "pyint-9e709fdc4302-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/mypy.py#L352-L356", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-7117da13df43-I12", "group_id": "py-3dfb1aa3fad8a61f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1203, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-aa99fae2423b-I13", "source": "from __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Tuple\nimport attr\nimport attrs\n\n@attr.s(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-3dfb1aa3fad8a61f", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 12, "local_path": "control-flow/lower-for-to-while/I13__attrs__AutoDetect__fae2423b.py", "order": 13, "original_content_sha256": "c1227182775b9e8a278a9fefe09c1eed2b2ef03143a8706b25ffaec520c6c99b", "parent_variant_id": "pyint-9e709fdc4302-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/mypy.py#L352-L356", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-aa99fae2423b-I13", "group_id": "py-3dfb1aa3fad8a61f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1204, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9b38782731c3-SRC", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass Environment(BaseEnvironment):\n    \"\"\"Works like a regular Jinja environment but has some additional\n    knowledge of how Flask's blueprint works so that it can prepend the\n    name of the blueprint to referenced templates if necessary.\n    \"\"\"\n\n    def __init__(self, app: App, **options: t.Any) -> None:\n        if \"loader\" not in options:\n            options[\"loader\"] = app.create_global_jinja_loader()\n        BaseEnvironment.__init__(self, **options)\n        self.app = app\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-3ec7f88a731a7318", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 23, "local_path": "source-original/SRC__flask__Environment__782731c3.py", "order": 0, "original_content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L36-L46", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Environment", "variant_id": "pyint-9b38782731c3-SRC", "group_id": "py-3ec7f88a731a7318", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 351, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b4a92a1c7ec0-I01", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass Environment(BaseEnvironment):\n    \n\n    def __init__(self, app: App, **options: t.Any) -> None:\n        if \"loader\" not in options:\n            options[\"loader\"] = app.create_global_jinja_loader()\n        BaseEnvironment.__init__(self, **options)\n        self.app = app\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-3ec7f88a731a7318", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "d548cd9e370fb6aa40fe029aa83fedcfd61c5b70e674baa3ed3d9617f93bd2a2", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 20, "local_path": "comments/remove-comments/I01__flask__Environment__2a1c7ec0.py", "order": 1, "original_content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "parent_variant_id": "pyint-9b38782731c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L36-L46", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 209, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "Environment", "variant_id": "pyint-b4a92a1c7ec0-I01", "group_id": "py-3ec7f88a731a7318", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 352, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-10a4c1d0d08c-I02", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass Environment(BaseEnvironment):\n    \"\"\"Works like a regular Jinja environment but has some additional\n    knowledge of how Flask's blueprint works so that it can prepend the\n    name of the blueprint to referenced templates if necessary.\n    \"\"\"\n\n    def __init__(self, app2: App, **opt: t.Any) -> None:\n        if \"loader\" not in opt:\n            opt[\"loader\"] = app2.create_global_jinja_loader()\n        BaseEnvironment.__init__(self, **opt)\n        self.app = app2\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-3ec7f88a731a7318", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "cc36e96a6a5bbb230a3b29852e6da06fe0583bf0d399ef551f185340a1757e3d", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 23, "local_path": "identifiers/shorten-identifiers/I02__flask__Environment__c1d0d08c.py", "order": 2, "original_content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "parent_variant_id": "pyint-9b38782731c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L36-L46", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 7, "identifiers_declared": 2}, "unit_kind": "class", "unit_name": "Environment", "variant_id": "pyint-10a4c1d0d08c-I02", "group_id": "py-3ec7f88a731a7318", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 353, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-44c7b1f4c2cc-I03", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass Environment(BaseEnvironment):\n    \"\"\"Works like a regular Jinja environment but has some additional\n    knowledge of how Flask's blueprint works so that it can prepend the\n    name of the blueprint to referenced templates if necessary.\n    \"\"\"\n\n    def __init__(self, age: App, **message: t.Any) -> None:\n        if \"loader\" not in message:\n            message[\"loader\"] = age.create_global_jinja_loader()\n        BaseEnvironment.__init__(self, **message)\n        self.app = age\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-3ec7f88a731a7318", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "654aeeceb64871a8775f78ef8acceea3b340f659d7940ce1cbc5460456a940f4", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 23, "local_path": "identifiers/mislead-identifiers/I03__flask__Environment__b1f4c2cc.py", "order": 3, "original_content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "parent_variant_id": "pyint-9b38782731c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L36-L46", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 7, "identifiers_declared": 2, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 2, "local_random_pool_selections": 2, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "Environment", "variant_id": "pyint-44c7b1f4c2cc-I03", "group_id": "py-3ec7f88a731a7318", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 354, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ae68c3be27e6-I04", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass Environment(BaseEnvironment):\n    \"\"\"Works like a regular Jinja environment but has some additional\n    knowledge of how Flask's blueprint works so that it can prepend the\n    name of the blueprint to referenced templates if necessary.\n    \"\"\"\n\n    def __init__(self, a: App, **b: t.Any) -> None:\n        if \"loader\" not in b:\n            b[\"loader\"] = a.create_global_jinja_loader()\n        BaseEnvironment.__init__(self, **b)\n        self.app = a\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-3ec7f88a731a7318", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "0b555d394eeaeee9b8ce29e3fbae595d172ffed4f7e8812d360d83a7da4dd5b4", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 23, "local_path": "identifiers/garble-identifiers/I04__flask__Environment__c3be27e6.py", "order": 4, "original_content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "parent_variant_id": "pyint-9b38782731c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L36-L46", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 7, "identifiers_declared": 2}, "unit_kind": "class", "unit_name": "Environment", "variant_id": "pyint-ae68c3be27e6-I04", "group_id": "py-3ec7f88a731a7318", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 355, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d5c1cc7a6a54-I05", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass Environment(BaseEnvironment):\n    \"\"\"Works like a regular Jinja environment but has some additional\n    knowledge of how Flask's blueprint works so that it can prepend the\n    name of the blueprint to referenced templates if necessary.\n    \"\"\"\n\n    def __init__(self, app: App, **options: t.Any) -> None:\n        if \"loader\" not in options:\n            options[\"loader\"] = app.create_global_jinja_loader()\n        BaseEnvironment.__init__(self, **options)\n        self.app = app\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-3ec7f88a731a7318", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 23, "local_path": "expressions/encode-integer-literals/I05__flask__Environment__cc7a6a54.py", "order": 5, "original_content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "parent_variant_id": "pyint-9b38782731c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L36-L46", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "Environment", "variant_id": "pyint-d5c1cc7a6a54-I05", "group_id": "py-3ec7f88a731a7318", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 356, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-837ac0d8fb94-I06", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass Environment(BaseEnvironment):\n    \"\"\"Works like a regular Jinja environment but has some additional\n    knowledge of how Flask's blueprint works so that it can prepend the\n    name of the blueprint to referenced templates if necessary.\n    \"\"\"\n\n    def __init__(self, app: App, **options: t.Any) -> None:\n        if not (\"loader\" not in options):\n            pass\n        else:\n            options[\"loader\"] = app.create_global_jinja_loader()\n        BaseEnvironment.__init__(self, **options)\n        self.app = app\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-3ec7f88a731a7318", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "35225beae95419598715e533ff0ec19ac31cce0d6b97dd30a77d215f3b665c6b", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 25, "local_path": "expressions/invert-conditions/I06__flask__Environment__c0d8fb94.py", "order": 6, "original_content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "parent_variant_id": "pyint-9b38782731c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L36-L46", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "Environment", "variant_id": "pyint-837ac0d8fb94-I06", "group_id": "py-3ec7f88a731a7318", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 357, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1c5d91f877ae-I07", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass Environment(BaseEnvironment):\n    \"\"\"Works like a regular Jinja environment but has some additional\n    knowledge of how Flask's blueprint works so that it can prepend the\n    name of the blueprint to referenced templates if necessary.\n    \"\"\"\n\n    def __init__(self, app: App, **options: t.Any) -> None:\n        if ((0xeaa8 ^ 0xeaa8) != 0):\n            raise AssertionError()\n        if \"loader\" not in options:\n            options[\"loader\"] = app.create_global_jinja_loader()\n        BaseEnvironment.__init__(self, **options)\n        self.app = app\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-3ec7f88a731a7318", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "8cba2afbf719ce1b654467344fec93280f462e04bda0b906dfc1cf147f61a73d", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 25, "local_path": "code-injection/insert-dead-branches/I07__flask__Environment__91f877ae.py", "order": 7, "original_content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "parent_variant_id": "pyint-9b38782731c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L36-L46", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "Environment", "variant_id": "pyint-1c5d91f877ae-I07", "group_id": "py-3ec7f88a731a7318", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 358, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3111ecbb7b01-I08", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass Environment(BaseEnvironment):\n    \"\"\"Works like a regular Jinja environment but has some additional\n    knowledge of how Flask's blueprint works so that it can prepend the\n    name of the blueprint to referenced templates if necessary.\n    \"\"\"\n\n    def __init__(self, app: App, **options: t.Any) -> None:\n        remaining_steps = 3\n        while remaining_steps > 0:\n            remaining_steps -= 1\n        if \"loader\" not in options:\n            options[\"loader\"] = app.create_global_jinja_loader()\n        BaseEnvironment.__init__(self, **options)\n        self.app = app\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-3ec7f88a731a7318", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "760dd48d7264ed58ea654ed5e98efa5e9fd6547fbbe11d4cecfb269728acc121", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 26, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__Environment__ecbb7b01.py", "order": 8, "original_content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "parent_variant_id": "pyint-9b38782731c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L36-L46", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 1}, "unit_kind": "class", "unit_name": "Environment", "variant_id": "pyint-3111ecbb7b01-I08", "group_id": "py-3ec7f88a731a7318", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 359, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8dccc8e1075e-I09", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass Environment(BaseEnvironment):\n    \"\"\"Works like a regular Jinja environment but has some additional\n    knowledge of how Flask's blueprint works so that it can prepend the\n    name of the blueprint to referenced templates if necessary.\n    \"\"\"\n\n    def __init__(self, app: App, **options: t.Any) -> None:\n        lI0O_8419ee6b = 0xff3b - 0xff3b\n        lI0O_8419ee6b = (lI0O_8419ee6b | 0) if lI0O_8419ee6b == 0 else (lI0O_8419ee6b & 0)\n        if \"loader\" not in options:\n            options[\"loader\"] = app.create_global_jinja_loader()\n        BaseEnvironment.__init__(self, **options)\n        self.app = app\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-3ec7f88a731a7318", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "a09acc7865eee619f00796ce0b8adbda382fb986000d75a5e5749f4ddd291a81", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 25, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__Environment__c8e1075e.py", "order": 9, "original_content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "parent_variant_id": "pyint-9b38782731c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L36-L46", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 1}, "unit_kind": "class", "unit_name": "Environment", "variant_id": "pyint-8dccc8e1075e-I09", "group_id": "py-3ec7f88a731a7318", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 360, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1f4cd40bab80-I10", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass Environment(BaseEnvironment):\n    \"\"\"Works like a regular Jinja environment but has some additional\n    knowledge of how Flask's blueprint works so that it can prepend the\n    name of the blueprint to referenced templates if necessary.\n    \"\"\"\n\n    def __init__(self, app: App, **options: t.Any) -> None:\n        if \"loader\" not in options:\n            options[\"loader\"] = app.create_global_jinja_loader()\n        BaseEnvironment.__init__(self, **options)\n        self.app = app\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-3ec7f88a731a7318", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 23, "local_path": "layout/partially-compact-layout/I10__flask__Environment__d40bab80.py", "order": 10, "original_content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "parent_variant_id": "pyint-9b38782731c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L36-L46", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 2, "line_break_groups_removed": 0, "line_breaks_removed": 0, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "Environment", "variant_id": "pyint-1f4cd40bab80-I10", "group_id": "py-3ec7f88a731a7318", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 361, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c91020422d65-I11", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass Environment(BaseEnvironment):\n    \"\"\"Works like a regular Jinja environment but has some additional\n    knowledge of how Flask's blueprint works so that it can prepend the\n    name of the blueprint to referenced templates if necessary.\n    \"\"\"\n\n    def __init__(self, app: App, **options: t.Any) -> None:\n        if \"loader\" not in options:\n            options[\"loader\"] = app.create_global_jinja_loader()\n        BaseEnvironment.__init__(self, **options)\n        self.app = app\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-3ec7f88a731a7318", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 23, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__Environment__20422d65.py", "order": 11, "original_content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "parent_variant_id": "pyint-9b38782731c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L36-L46", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "Environment", "variant_id": "pyint-c91020422d65-I11", "group_id": "py-3ec7f88a731a7318", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 362, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ce609f6e0dcb-I12", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass Environment(BaseEnvironment):\n    \"\"\"Works like a regular Jinja environment but has some additional\n    knowledge of how Flask's blueprint works so that it can prepend the\n    name of the blueprint to referenced templates if necessary.\n    \"\"\"\n\n    def __init__(self, app: App, **options: t.Any) -> None:\n        if \"loader\" not in options:\n            options[\"loader\"] = app.create_global_jinja_loader()\n        BaseEnvironment.__init__(self, **options)\n        self.app = app\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-3ec7f88a731a7318", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 23, "local_path": "data-flow/inline-intermediate-variables/I12__flask__Environment__9f6e0dcb.py", "order": 12, "original_content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "parent_variant_id": "pyint-9b38782731c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L36-L46", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Environment", "variant_id": "pyint-ce609f6e0dcb-I12", "group_id": "py-3ec7f88a731a7318", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 363, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5b9af7a8b1c3-I13", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass Environment(BaseEnvironment):\n    \"\"\"Works like a regular Jinja environment but has some additional\n    knowledge of how Flask's blueprint works so that it can prepend the\n    name of the blueprint to referenced templates if necessary.\n    \"\"\"\n\n    def __init__(self, app: App, **options: t.Any) -> None:\n        if \"loader\" not in options:\n            options[\"loader\"] = app.create_global_jinja_loader()\n        BaseEnvironment.__init__(self, **options)\n        self.app = app\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-3ec7f88a731a7318", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 23, "local_path": "control-flow/lower-for-to-while/I13__flask__Environment__f7a8b1c3.py", "order": 13, "original_content_sha256": "a2447786a9badbe793f510a519020e228203265a684be7602955042bf6af7720", "parent_variant_id": "pyint-9b38782731c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L36-L46", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "Environment", "variant_id": "pyint-5b9af7a8b1c3-I13", "group_id": "py-3ec7f88a731a7318", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 364, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8ae23f15abf4-SRC", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass RequestsCookieJar(CookieJar, MutableMapping[str, str | None]):  # type: ignore[misc]\n    \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n\n    Unlike a regular CookieJar, this class is pickleable.\n\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n\n    _policy: CookiePolicy\n\n    def get(  # type: ignore[override]\n        self,\n        name: str,\n        default: str | None = None,\n        domain: str | None = None,\n        path: str | None = None,\n    ) -> str | None:\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        try:\n            return self._find_no_duplicates(name, domain, path)\n        except KeyError:\n            return default\n\n    def set(\n        self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any\n    ) -> Cookie | None:\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        # support client code that unsets cookies by assignment of a None value:\n        if value is None:\n            remove_cookie_by_name(\n                self, name, domain=kwargs.get(\"domain\"), path=kwargs.get(\"path\")\n            )\n            return\n\n        if isinstance(value, Morsel):\n            c = morsel_to_cookie(value)\n        else:\n            c = create_cookie(name, value, **kwargs)\n        self.set_cookie(c)\n        return c\n\n    def iterkeys(self) -> Iterator[str]:\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name\n\n    def keys(self) -> list[str]:  # type: ignore[override]\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        return list(self.iterkeys())\n\n    def itervalues(self) -> Iterator[str | None]:\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.value\n\n    def values(self) -> list[str | None]:  # type: ignore[override]\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n\n        .. seealso:: keys() and items().\n        \"\"\"\n        return list(self.itervalues())\n\n    def iteritems(self) -> Iterator[tuple[str, str | None]]:\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name, cookie.value\n\n    def items(self) -> list[tuple[str, str | None]]:  # type: ignore[override]\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n\n        .. seealso:: keys() and values().\n        \"\"\"\n        return list(self.iteritems())\n\n    def list_domains(self) -> list[str]:\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain not in domains:\n                domains.append(cookie.domain)\n        return domains\n\n    def list_paths(self) -> list[str]:\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        paths: list[str] = []\n        for cookie in iter(self):\n            if cookie.path not in paths:\n                paths.append(cookie.path)\n        return paths\n\n    def multiple_domains(self) -> bool:\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain is not None and cookie.domain in domains:  # type: ignore[reportUnnecessaryComparison]  # defensive check\n                return True\n            domains.append(cookie.domain)\n        return False  # there is only one domain in jar\n\n    def get_dict(\n        self, domain: str | None = None, path: str | None = None\n    ) -> dict[str, str | None]:\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        dictionary: dict[str, str | None] = {}\n        for cookie in iter(self):\n            if (domain is None or cookie.domain == domain) and (\n                path is None or cookie.path == path\n            ):\n                dictionary[cookie.name] = cookie.value\n        return dictionary\n\n    def __iter__(self) -> Iterator[Cookie]:  # type: ignore[override]\n        \"\"\"RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.\"\"\"\n        return super().__iter__()\n\n    def __contains__(self, name: object) -> bool:\n        try:\n            return super().__contains__(name)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, name: str) -> str | None:\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        return self._find_no_duplicates(name)\n\n    def __setitem__(\n        self, name: str, value: str | Morsel[dict[str, str]] | None\n    ) -> None:\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        self.set(name, value)\n\n    def __delitem__(self, name: str) -> None:\n        \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        remove_cookie_by_name(self, name)\n\n    def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:\n        if (\n            (value := cookie.value) is not None\n            and value.startswith('\"')\n            and value.endswith('\"')\n        ):\n            cookie.value = value.replace('\\\\\"', \"\")\n        return super().set_cookie(cookie, *args, **kwargs)\n\n    def update(  # type: ignore[override]\n        self, other: CookieJar | SupportsKeysAndGetItem[str, str]\n    ) -> None:\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if isinstance(other, cookielib.CookieJar):\n            for cookie in other:\n                self.set_cookie(copy.copy(cookie))\n        else:\n            super().update(other)\n\n    def _find(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str | None:\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        return cookie.value\n\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def _find_no_duplicates(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str:\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        toReturn = None\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        if toReturn is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {name!r}\"\n                            )\n                        # we will eventually return this as long as no cookie conflict\n                        toReturn = cookie.value\n\n        if toReturn is not None:\n            return toReturn\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def __getstate__(self) -> dict[str, Any]:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        state = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        state.pop(\"_cookies_lock\")\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        self.__dict__.update(state)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def copy(self) -> RequestsCookieJar:\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        new_cj = RequestsCookieJar()\n        new_cj.set_policy(self.get_policy())\n        new_cj.update(self)\n        return new_cj\n\n    def get_policy(self) -> CookiePolicy:\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        return self._policy\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-3fec61afc3d3278a", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 298, "local_path": "source-original/SRC__requests__RequestsCookieJar__3f15abf4.py", "order": 0, "original_content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L191-L476", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "RequestsCookieJar", "variant_id": "pyint-8ae23f15abf4-SRC", "group_id": "py-3fec61afc3d3278a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 883, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0cf995cfffd5-I01", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass RequestsCookieJar(CookieJar, MutableMapping[str, str | None]):   \n    \n\n    _policy: CookiePolicy\n\n    def get(   \n        self,\n        name: str,\n        default: str | None = None,\n        domain: str | None = None,\n        path: str | None = None,\n    ) -> str | None:\n        \n        try:\n            return self._find_no_duplicates(name, domain, path)\n        except KeyError:\n            return default\n\n    def set(\n        self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any\n    ) -> Cookie | None:\n        \n         \n        if value is None:\n            remove_cookie_by_name(\n                self, name, domain=kwargs.get(\"domain\"), path=kwargs.get(\"path\")\n            )\n            return\n\n        if isinstance(value, Morsel):\n            c = morsel_to_cookie(value)\n        else:\n            c = create_cookie(name, value, **kwargs)\n        self.set_cookie(c)\n        return c\n\n    def iterkeys(self) -> Iterator[str]:\n        \n        for cookie in iter(self):\n            yield cookie.name\n\n    def keys(self) -> list[str]:   \n        \n        return list(self.iterkeys())\n\n    def itervalues(self) -> Iterator[str | None]:\n        \n        for cookie in iter(self):\n            yield cookie.value\n\n    def values(self) -> list[str | None]:   \n        \n        return list(self.itervalues())\n\n    def iteritems(self) -> Iterator[tuple[str, str | None]]:\n        \n        for cookie in iter(self):\n            yield cookie.name, cookie.value\n\n    def items(self) -> list[tuple[str, str | None]]:   \n        \n        return list(self.iteritems())\n\n    def list_domains(self) -> list[str]:\n        \n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain not in domains:\n                domains.append(cookie.domain)\n        return domains\n\n    def list_paths(self) -> list[str]:\n        \n        paths: list[str] = []\n        for cookie in iter(self):\n            if cookie.path not in paths:\n                paths.append(cookie.path)\n        return paths\n\n    def multiple_domains(self) -> bool:\n        \n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain is not None and cookie.domain in domains:   \n                return True\n            domains.append(cookie.domain)\n        return False   \n\n    def get_dict(\n        self, domain: str | None = None, path: str | None = None\n    ) -> dict[str, str | None]:\n        \n        dictionary: dict[str, str | None] = {}\n        for cookie in iter(self):\n            if (domain is None or cookie.domain == domain) and (\n                path is None or cookie.path == path\n            ):\n                dictionary[cookie.name] = cookie.value\n        return dictionary\n\n    def __iter__(self) -> Iterator[Cookie]:   \n        \n        return super().__iter__()\n\n    def __contains__(self, name: object) -> bool:\n        try:\n            return super().__contains__(name)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, name: str) -> str | None:\n        \n        return self._find_no_duplicates(name)\n\n    def __setitem__(\n        self, name: str, value: str | Morsel[dict[str, str]] | None\n    ) -> None:\n        \n        self.set(name, value)\n\n    def __delitem__(self, name: str) -> None:\n        \n        remove_cookie_by_name(self, name)\n\n    def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:\n        if (\n            (value := cookie.value) is not None\n            and value.startswith('\"')\n            and value.endswith('\"')\n        ):\n            cookie.value = value.replace('\\\\\"', \"\")\n        return super().set_cookie(cookie, *args, **kwargs)\n\n    def update(   \n        self, other: CookieJar | SupportsKeysAndGetItem[str, str]\n    ) -> None:\n        \n        if isinstance(other, cookielib.CookieJar):\n            for cookie in other:\n                self.set_cookie(copy.copy(cookie))\n        else:\n            super().update(other)\n\n    def _find(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str | None:\n        \n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        return cookie.value\n\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def _find_no_duplicates(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str:\n        \n        toReturn = None\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        if toReturn is not None:\n                             \n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {name!r}\"\n                            )\n                         \n                        toReturn = cookie.value\n\n        if toReturn is not None:\n            return toReturn\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def __getstate__(self) -> dict[str, Any]:\n        \n        state = self.__dict__.copy()\n         \n        state.pop(\"_cookies_lock\")\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        \n        self.__dict__.update(state)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def copy(self) -> RequestsCookieJar:\n        \n        new_cj = RequestsCookieJar()\n        new_cj.set_policy(self.get_policy())\n        new_cj.update(self)\n        return new_cj\n\n    def get_policy(self) -> CookiePolicy:\n        \n        return self._policy\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-3fec61afc3d3278a", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "5acff12eb4172fe97d4a9a5af3c0b1315b9b3d1810430b2d20d5231440650256", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 211, "local_path": "comments/remove-comments/I01__requests__RequestsCookieJar__95cfffd5.py", "order": 1, "original_content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "parent_variant_id": "pyint-8ae23f15abf4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L191-L476", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 4946, "comments_removed": 37, "docstrings_removed": 24, "line_comments_removed": 13}, "unit_kind": "class", "unit_name": "RequestsCookieJar", "variant_id": "pyint-0cf995cfffd5-I01", "group_id": "py-3fec61afc3d3278a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 884, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d1680f2a3435-I02", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass RequestsCookieJar(CookieJar, MutableMapping[str, str | None]):  # type: ignore[misc]\n    \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n\n    Unlike a regular CookieJar, this class is pickleable.\n\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n\n    _policy: CookiePolicy\n\n    def get2(  # type: ignore[override]\n        self,\n        nam: str,\n        def2: str | None = None,\n        dom: str | None = None,\n        pat: str | None = None,\n    ) -> str | None:\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        try:\n            return self.find(nam, dom, pat)\n        except KeyError:\n            return def2\n\n    def set2(\n        self, nam2: str, val2: str | Morsel[dict[str, str]] | None, **kwa: Any\n    ) -> Cookie | None:\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        # support client code that unsets cookies by assignment of a None value:\n        if val2 is None:\n            remove_cookie_by_name(\n                self, nam2, domain=kwa.get(\"domain\"), path=kwa.get(\"path\")\n            )\n            return\n\n        if isinstance(val2, Morsel):\n            c2 = morsel_to_cookie(val2)\n        else:\n            c2 = create_cookie(nam2, val2, **kwa)\n        self.set3(c2)\n        return c2\n\n    def ite(self) -> Iterator[str]:\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        for coo in iter(self):\n            yield coo.name\n\n    def key(self) -> list[str]:  # type: ignore[override]\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        return list(self.ite())\n\n    def ite2(self) -> Iterator[str | None]:\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        for coo2 in iter(self):\n            yield coo2.value\n\n    def val(self) -> list[str | None]:  # type: ignore[override]\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n\n        .. seealso:: keys() and items().\n        \"\"\"\n        return list(self.ite2())\n\n    def ite3(self) -> Iterator[tuple[str, str | None]]:\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        for coo3 in iter(self):\n            yield coo3.name, coo3.value\n\n    def ite4(self) -> list[tuple[str, str | None]]:  # type: ignore[override]\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n\n        .. seealso:: keys() and values().\n        \"\"\"\n        return list(self.ite3())\n\n    def list2(self) -> list[str]:\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        dom2: list[str] = []\n        for coo4 in iter(self):\n            if coo4.domain not in dom2:\n                dom2.append(coo4.domain)\n        return dom2\n\n    def list3(self) -> list[str]:\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        pat2: list[str] = []\n        for coo5 in iter(self):\n            if coo5.path not in pat2:\n                pat2.append(coo5.path)\n        return pat2\n\n    def multiple(self) -> bool:\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        dom3: list[str] = []\n        for coo6 in iter(self):\n            if coo6.domain is not None and coo6.domain in dom3:  # type: ignore[reportUnnecessaryComparison]  # defensive check\n                return True\n            dom3.append(coo6.domain)\n        return False  # there is only one domain in jar\n\n    def get3(\n        self, dom4: str | None = None, pat3: str | None = None\n    ) -> dict[str, str | None]:\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        dic: dict[str, str | None] = {}\n        for coo7 in iter(self):\n            if (dom4 is None or coo7.domain == dom4) and (\n                pat3 is None or coo7.path == pat3\n            ):\n                dic[coo7.name] = coo7.value\n        return dic\n\n    def __iter__(self) -> Iterator[Cookie]:  # type: ignore[override]\n        \"\"\"RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.\"\"\"\n        return super().__iter__()\n\n    def __contains__(self, nam3: object) -> bool:\n        try:\n            return super().__contains__(nam3)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, nam4: str) -> str | None:\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        return self.find(nam4)\n\n    def __setitem__(\n        self, nam5: str, val3: str | Morsel[dict[str, str]] | None\n    ) -> None:\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        self.set2(nam5, val3)\n\n    def __delitem__(self, nam6: str) -> None:\n        \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        remove_cookie_by_name(self, nam6)\n\n    def set3(self, coo8: Cookie, *arg: Any, **kwa2: Any) -> None:\n        if (\n            (val4 := coo8.value) is not None\n            and val4.startswith('\"')\n            and val4.endswith('\"')\n        ):\n            coo8.value = val4.replace('\\\\\"', \"\")\n        return super().set_cookie(coo8, *arg, **kwa2)\n\n    def upd(  # type: ignore[override]\n        self, oth: CookieJar | SupportsKeysAndGetItem[str, str]\n    ) -> None:\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if isinstance(oth, cookielib.CookieJar):\n            for coo9 in oth:\n                self.set3(copy.copy(coo9))\n        else:\n            super().update(oth)\n\n    def fin(\n        self, nam7: str, dom5: str | None = None, pat4: str | None = None\n    ) -> str | None:\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        for coo10 in iter(self):\n            if coo10.name == nam7:\n                if dom5 is None or coo10.domain == dom5:\n                    if pat4 is None or coo10.path == pat4:\n                        return coo10.value\n\n        raise KeyError(f\"name={nam7!r}, domain={dom5!r}, path={pat4!r}\")\n\n    def find(\n        self, nam8: str, dom6: str | None = None, pat5: str | None = None\n    ) -> str:\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        to = None\n        for coo11 in iter(self):\n            if coo11.name == nam8:\n                if dom6 is None or coo11.domain == dom6:\n                    if pat5 is None or coo11.path == pat5:\n                        if to is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {nam8!r}\"\n                            )\n                        # we will eventually return this as long as no cookie conflict\n                        to = coo11.value\n\n        if to is not None:\n            return to\n        raise KeyError(f\"name={nam8!r}, domain={dom6!r}, path={pat5!r}\")\n\n    def __getstate__(self) -> dict[str, Any]:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        sta = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        sta.pop(\"_cookies_lock\")\n        return sta\n\n    def __setstate__(self, sta2: dict[str, Any]) -> None:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        self.__dict__.update(sta2)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def cop(self) -> RequestsCookieJar:\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        new = RequestsCookieJar()\n        new.set_policy(self.get4())\n        new.update(self)\n        return new\n\n    def get4(self) -> CookiePolicy:\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        return self._policy\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-3fec61afc3d3278a", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "485e281f1b65c03d26132af2f8ab340b52a264e266fe292d57f4880a6b062546", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 298, "local_path": "identifiers/shorten-identifiers/I02__requests__RequestsCookieJar__0f2a3435.py", "order": 2, "original_content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "parent_variant_id": "pyint-8ae23f15abf4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L191-L476", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 168, "identifiers_declared": 62}, "unit_kind": "class", "unit_name": "RequestsCookieJar", "variant_id": "pyint-d1680f2a3435-I02", "group_id": "py-3fec61afc3d3278a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 885, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-55aec3122454-I03", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass RequestsCookieJar(CookieJar, MutableMapping[str, str | None]):  # type: ignore[misc]\n    \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n\n    Unlike a regular CookieJar, this class is pickleable.\n\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n\n    _policy: CookiePolicy\n\n    def add(  # type: ignore[override]\n        self,\n        mode: str,\n        version: str | None = None,\n        client: str | None = None,\n        item: str | None = None,\n    ) -> str | None:\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        try:\n            return self.validateRequest(mode, client, item)\n        except KeyError:\n            return version\n\n    def load(\n        self, size: str, order: str | Morsel[dict[str, str]] | None, **config: Any\n    ) -> Cookie | None:\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        # support client code that unsets cookies by assignment of a None value:\n        if order is None:\n            remove_cookie_by_name(\n                self, size, domain=config.get(\"domain\"), path=config.get(\"path\")\n            )\n            return\n\n        if isinstance(order, Morsel):\n            age = morsel_to_cookie(order)\n        else:\n            age = create_cookie(size, order, **config)\n        self.parseCount(age)\n        return age\n\n    def dispatch(self) -> Iterator[str]:\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        for client in iter(self):\n            yield client.name\n\n    def save(self) -> list[str]:  # type: ignore[override]\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        return list(self.dispatch())\n\n    def findResult(self) -> Iterator[str | None]:\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        for option in iter(self):\n            yield option.value\n\n    def filter(self) -> list[str | None]:  # type: ignore[override]\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n\n        .. seealso:: keys() and items().\n        \"\"\"\n        return list(self.findResult())\n\n    def configure(self) -> Iterator[tuple[str, str | None]]:\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        for window in iter(self):\n            yield window.name, window.value\n\n    def parse(self) -> list[tuple[str, str | None]]:  # type: ignore[override]\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n\n        .. seealso:: keys() and values().\n        \"\"\"\n        return list(self.configure())\n\n    def removeRecord(self) -> list[str]:\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        context: list[str] = []\n        for region in iter(self):\n            if region.domain not in context:\n                context.append(region.domain)\n        return context\n\n    def updateNode(self) -> list[str]:\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        event: list[str] = []\n        for region in iter(self):\n            if region.path not in event:\n                event.append(region.path)\n        return event\n\n    def validateSession(self) -> bool:\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        session: list[str] = []\n        for window in iter(self):\n            if window.domain is not None and window.domain in session:  # type: ignore[reportUnnecessaryComparison]  # defensive check\n                return True\n            session.append(window.domain)\n        return False  # there is only one domain in jar\n\n    def loadItem(\n        self, offset: str | None = None, flag: str | None = None\n    ) -> dict[str, str | None]:\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        activeData: dict[str, str | None] = {}\n        for option in iter(self):\n            if (offset is None or option.domain == offset) and (\n                flag is None or option.path == flag\n            ):\n                activeData[option.name] = option.value\n        return activeData\n\n    def __iter__(self) -> Iterator[Cookie]:  # type: ignore[override]\n        \"\"\"RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.\"\"\"\n        return super().__iter__()\n\n    def __contains__(self, date: object) -> bool:\n        try:\n            return super().__contains__(date)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, flag: str) -> str | None:\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        return self.validateRequest(flag)\n\n    def __setitem__(\n        self, path: str, order: str | Morsel[dict[str, str]] | None\n    ) -> None:\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        self.load(path, order)\n\n    def __delitem__(self, size: str) -> None:\n        \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        remove_cookie_by_name(self, size)\n\n    def parseCount(self, amount: Cookie, *date: Any, **buffer: Any) -> None:\n        if (\n            (entry := amount.value) is not None\n            and entry.startswith('\"')\n            and entry.endswith('\"')\n        ):\n            amount.value = entry.replace('\\\\\"', \"\")\n        return super().set_cookie(amount, *date, **buffer)\n\n    def detect(  # type: ignore[override]\n        self, entry: CookieJar | SupportsKeysAndGetItem[str, str]\n    ) -> None:\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if isinstance(entry, cookielib.CookieJar):\n            for region in entry:\n                self.parseCount(copy.copy(region))\n        else:\n            super().update(entry)\n\n    def route(\n        self, mode: str, result: str | None = None, data: str | None = None\n    ) -> str | None:\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        for config in iter(self):\n            if config.name == mode:\n                if result is None or config.domain == result:\n                    if data is None or config.path == data:\n                        return config.value\n\n        raise KeyError(f\"name={mode!r}, domain={result!r}, path={data!r}\")\n\n    def validateRequest(\n        self, size: str, source: str | None = None, step: str | None = None\n    ) -> str:\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        document = None\n        for buffer in iter(self):\n            if buffer.name == size:\n                if source is None or buffer.domain == source:\n                    if step is None or buffer.path == step:\n                        if document is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {size!r}\"\n                            )\n                        # we will eventually return this as long as no cookie conflict\n                        document = buffer.value\n\n        if document is not None:\n            return document\n        raise KeyError(f\"name={size!r}, domain={source!r}, path={step!r}\")\n\n    def __getstate__(self) -> dict[str, Any]:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        limit = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        limit.pop(\"_cookies_lock\")\n        return limit\n\n    def __setstate__(self, token: dict[str, Any]) -> None:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        self.__dict__.update(token)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def read(self) -> RequestsCookieJar:\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        config = RequestsCookieJar()\n        config.set_policy(self.loadWindow())\n        config.update(self)\n        return config\n\n    def loadWindow(self) -> CookiePolicy:\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        return self._policy\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-3fec61afc3d3278a", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "93200da89c376f291fa417f0c90f79f4841d2789ec2ae18cf1d8b3c8d54ef9a7", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 298, "local_path": "identifiers/mislead-identifiers/I03__requests__RequestsCookieJar__c3122454.py", "order": 3, "original_content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "parent_variant_id": "pyint-8ae23f15abf4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L191-L476", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 168, "identifiers_declared": 62, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 1, "local_exact_length_matches": 43, "local_random_pool_selections": 44, "local_total_length_difference": 2, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 3, "method_exact_length_matches": 15, "method_random_pool_selections": 18, "method_total_length_difference": 6}, "unit_kind": "class", "unit_name": "RequestsCookieJar", "variant_id": "pyint-55aec3122454-I03", "group_id": "py-3fec61afc3d3278a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 886, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f07c5c591d9c-I04", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass RequestsCookieJar(CookieJar, MutableMapping[str, str | None]):  # type: ignore[misc]\n    \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n\n    Unlike a regular CookieJar, this class is pickleable.\n\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n\n    _policy: CookiePolicy\n\n    def a(  # type: ignore[override]\n        self,\n        t: str,\n        u: str | None = None,\n        v: str | None = None,\n        w: str | None = None,\n    ) -> str | None:\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        try:\n            return self.q(t, v, w)\n        except KeyError:\n            return u\n\n    def b(\n        self, x: str, y: str | Morsel[dict[str, str]] | None, **z: Any\n    ) -> Cookie | None:\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        # support client code that unsets cookies by assignment of a None value:\n        if y is None:\n            remove_cookie_by_name(\n                self, x, domain=z.get(\"domain\"), path=z.get(\"path\")\n            )\n            return\n\n        if isinstance(y, Morsel):\n            A = morsel_to_cookie(y)\n        else:\n            A = create_cookie(x, y, **z)\n        self.n(A)\n        return A\n\n    def d(self) -> Iterator[str]:\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        for B in iter(self):\n            yield B.name\n\n    def e(self) -> list[str]:  # type: ignore[override]\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        return list(self.d())\n\n    def f(self) -> Iterator[str | None]:\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        for C in iter(self):\n            yield C.value\n\n    def g(self) -> list[str | None]:  # type: ignore[override]\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n\n        .. seealso:: keys() and items().\n        \"\"\"\n        return list(self.f())\n\n    def h(self) -> Iterator[tuple[str, str | None]]:\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        for D in iter(self):\n            yield D.name, D.value\n\n    def i(self) -> list[tuple[str, str | None]]:  # type: ignore[override]\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n\n        .. seealso:: keys() and values().\n        \"\"\"\n        return list(self.h())\n\n    def j(self) -> list[str]:\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        E: list[str] = []\n        for F in iter(self):\n            if F.domain not in E:\n                E.append(F.domain)\n        return E\n\n    def k(self) -> list[str]:\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        G: list[str] = []\n        for H in iter(self):\n            if H.path not in G:\n                G.append(H.path)\n        return G\n\n    def l(self) -> bool:\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        I: list[str] = []\n        for J in iter(self):\n            if J.domain is not None and J.domain in I:  # type: ignore[reportUnnecessaryComparison]  # defensive check\n                return True\n            I.append(J.domain)\n        return False  # there is only one domain in jar\n\n    def m(\n        self, K: str | None = None, L: str | None = None\n    ) -> dict[str, str | None]:\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        M: dict[str, str | None] = {}\n        for N in iter(self):\n            if (K is None or N.domain == K) and (\n                L is None or N.path == L\n            ):\n                M[N.name] = N.value\n        return M\n\n    def __iter__(self) -> Iterator[Cookie]:  # type: ignore[override]\n        \"\"\"RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.\"\"\"\n        return super().__iter__()\n\n    def __contains__(self, O: object) -> bool:\n        try:\n            return super().__contains__(O)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, P: str) -> str | None:\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        return self.q(P)\n\n    def __setitem__(\n        self, Q: str, R: str | Morsel[dict[str, str]] | None\n    ) -> None:\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        self.b(Q, R)\n\n    def __delitem__(self, S: str) -> None:\n        \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        remove_cookie_by_name(self, S)\n\n    def n(self, T: Cookie, *U: Any, **V: Any) -> None:\n        if (\n            (W := T.value) is not None\n            and W.startswith('\"')\n            and W.endswith('\"')\n        ):\n            T.value = W.replace('\\\\\"', \"\")\n        return super().set_cookie(T, *U, **V)\n\n    def o(  # type: ignore[override]\n        self, X: CookieJar | SupportsKeysAndGetItem[str, str]\n    ) -> None:\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if isinstance(X, cookielib.CookieJar):\n            for Y in X:\n                self.n(copy.copy(Y))\n        else:\n            super().update(X)\n\n    def p(\n        self, Z: str, aa: str | None = None, ab: str | None = None\n    ) -> str | None:\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        for ac in iter(self):\n            if ac.name == Z:\n                if aa is None or ac.domain == aa:\n                    if ab is None or ac.path == ab:\n                        return ac.value\n\n        raise KeyError(f\"name={Z!r}, domain={aa!r}, path={ab!r}\")\n\n    def q(\n        self, ad: str, ae: str | None = None, af: str | None = None\n    ) -> str:\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        ag = None\n        for ah in iter(self):\n            if ah.name == ad:\n                if ae is None or ah.domain == ae:\n                    if af is None or ah.path == af:\n                        if ag is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {ad!r}\"\n                            )\n                        # we will eventually return this as long as no cookie conflict\n                        ag = ah.value\n\n        if ag is not None:\n            return ag\n        raise KeyError(f\"name={ad!r}, domain={ae!r}, path={af!r}\")\n\n    def __getstate__(self) -> dict[str, Any]:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        ai = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        ai.pop(\"_cookies_lock\")\n        return ai\n\n    def __setstate__(self, aj: dict[str, Any]) -> None:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        self.__dict__.update(aj)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def r(self) -> RequestsCookieJar:\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        ak = RequestsCookieJar()\n        ak.set_policy(self.s())\n        ak.update(self)\n        return ak\n\n    def s(self) -> CookiePolicy:\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        return self._policy\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-3fec61afc3d3278a", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "8a79c97abfb344100ea80b39a3af098f1cbce5904e0c76ef6dc86dcf7279a0d5", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 298, "local_path": "identifiers/garble-identifiers/I04__requests__RequestsCookieJar__5c591d9c.py", "order": 4, "original_content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "parent_variant_id": "pyint-8ae23f15abf4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L191-L476", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 168, "identifiers_declared": 62}, "unit_kind": "class", "unit_name": "RequestsCookieJar", "variant_id": "pyint-f07c5c591d9c-I04", "group_id": "py-3fec61afc3d3278a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 887, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2e262ecfa857-I05", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass RequestsCookieJar(CookieJar, MutableMapping[str, str | None]):  # type: ignore[misc]\n    \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n\n    Unlike a regular CookieJar, this class is pickleable.\n\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n\n    _policy: CookiePolicy\n\n    def get(  # type: ignore[override]\n        self,\n        name: str,\n        default: str | None = None,\n        domain: str | None = None,\n        path: str | None = None,\n    ) -> str | None:\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        try:\n            return self._find_no_duplicates(name, domain, path)\n        except KeyError:\n            return default\n\n    def set(\n        self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any\n    ) -> Cookie | None:\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        # support client code that unsets cookies by assignment of a None value:\n        if value is None:\n            remove_cookie_by_name(\n                self, name, domain=kwargs.get(\"domain\"), path=kwargs.get(\"path\")\n            )\n            return\n\n        if isinstance(value, Morsel):\n            c = morsel_to_cookie(value)\n        else:\n            c = create_cookie(name, value, **kwargs)\n        self.set_cookie(c)\n        return c\n\n    def iterkeys(self) -> Iterator[str]:\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name\n\n    def keys(self) -> list[str]:  # type: ignore[override]\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        return list(self.iterkeys())\n\n    def itervalues(self) -> Iterator[str | None]:\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.value\n\n    def values(self) -> list[str | None]:  # type: ignore[override]\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n\n        .. seealso:: keys() and items().\n        \"\"\"\n        return list(self.itervalues())\n\n    def iteritems(self) -> Iterator[tuple[str, str | None]]:\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name, cookie.value\n\n    def items(self) -> list[tuple[str, str | None]]:  # type: ignore[override]\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n\n        .. seealso:: keys() and values().\n        \"\"\"\n        return list(self.iteritems())\n\n    def list_domains(self) -> list[str]:\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain not in domains:\n                domains.append(cookie.domain)\n        return domains\n\n    def list_paths(self) -> list[str]:\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        paths: list[str] = []\n        for cookie in iter(self):\n            if cookie.path not in paths:\n                paths.append(cookie.path)\n        return paths\n\n    def multiple_domains(self) -> bool:\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain is not None and cookie.domain in domains:  # type: ignore[reportUnnecessaryComparison]  # defensive check\n                return True\n            domains.append(cookie.domain)\n        return False  # there is only one domain in jar\n\n    def get_dict(\n        self, domain: str | None = None, path: str | None = None\n    ) -> dict[str, str | None]:\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        dictionary: dict[str, str | None] = {}\n        for cookie in iter(self):\n            if (domain is None or cookie.domain == domain) and (\n                path is None or cookie.path == path\n            ):\n                dictionary[cookie.name] = cookie.value\n        return dictionary\n\n    def __iter__(self) -> Iterator[Cookie]:  # type: ignore[override]\n        \"\"\"RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.\"\"\"\n        return super().__iter__()\n\n    def __contains__(self, name: object) -> bool:\n        try:\n            return super().__contains__(name)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, name: str) -> str | None:\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        return self._find_no_duplicates(name)\n\n    def __setitem__(\n        self, name: str, value: str | Morsel[dict[str, str]] | None\n    ) -> None:\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        self.set(name, value)\n\n    def __delitem__(self, name: str) -> None:\n        \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        remove_cookie_by_name(self, name)\n\n    def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:\n        if (\n            (value := cookie.value) is not None\n            and value.startswith('\"')\n            and value.endswith('\"')\n        ):\n            cookie.value = value.replace('\\\\\"', \"\")\n        return super().set_cookie(cookie, *args, **kwargs)\n\n    def update(  # type: ignore[override]\n        self, other: CookieJar | SupportsKeysAndGetItem[str, str]\n    ) -> None:\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if isinstance(other, cookielib.CookieJar):\n            for cookie in other:\n                self.set_cookie(copy.copy(cookie))\n        else:\n            super().update(other)\n\n    def _find(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str | None:\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        return cookie.value\n\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def _find_no_duplicates(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str:\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        toReturn = None\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        if toReturn is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {name!r}\"\n                            )\n                        # we will eventually return this as long as no cookie conflict\n                        toReturn = cookie.value\n\n        if toReturn is not None:\n            return toReturn\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def __getstate__(self) -> dict[str, Any]:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        state = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        state.pop(\"_cookies_lock\")\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        self.__dict__.update(state)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def copy(self) -> RequestsCookieJar:\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        new_cj = RequestsCookieJar()\n        new_cj.set_policy(self.get_policy())\n        new_cj.update(self)\n        return new_cj\n\n    def get_policy(self) -> CookiePolicy:\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        return self._policy\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-3fec61afc3d3278a", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 298, "local_path": "expressions/encode-integer-literals/I05__requests__RequestsCookieJar__2ecfa857.py", "order": 5, "original_content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "parent_variant_id": "pyint-8ae23f15abf4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L191-L476", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "RequestsCookieJar", "variant_id": "pyint-2e262ecfa857-I05", "group_id": "py-3fec61afc3d3278a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 888, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-15e77a98ba05-I06", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass RequestsCookieJar(CookieJar, MutableMapping[str, str | None]):  # type: ignore[misc]\n    \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n\n    Unlike a regular CookieJar, this class is pickleable.\n\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n\n    _policy: CookiePolicy\n\n    def get(  # type: ignore[override]\n        self,\n        name: str,\n        default: str | None = None,\n        domain: str | None = None,\n        path: str | None = None,\n    ) -> str | None:\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        try:\n            return self._find_no_duplicates(name, domain, path)\n        except KeyError:\n            return default\n\n    def set(\n        self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any\n    ) -> Cookie | None:\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        # support client code that unsets cookies by assignment of a None value:\n        if not (value is None):\n            pass\n        else:\n            remove_cookie_by_name(\n                self, name, domain=kwargs.get(\"domain\"), path=kwargs.get(\"path\")\n            )\n            return\n\n        if not (isinstance(value, Morsel)):\n            c = create_cookie(name, value, **kwargs)\n        else:\n            c = morsel_to_cookie(value)\n        self.set_cookie(c)\n        return c\n\n    def iterkeys(self) -> Iterator[str]:\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name\n\n    def keys(self) -> list[str]:  # type: ignore[override]\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        return list(self.iterkeys())\n\n    def itervalues(self) -> Iterator[str | None]:\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.value\n\n    def values(self) -> list[str | None]:  # type: ignore[override]\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n\n        .. seealso:: keys() and items().\n        \"\"\"\n        return list(self.itervalues())\n\n    def iteritems(self) -> Iterator[tuple[str, str | None]]:\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name, cookie.value\n\n    def items(self) -> list[tuple[str, str | None]]:  # type: ignore[override]\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n\n        .. seealso:: keys() and values().\n        \"\"\"\n        return list(self.iteritems())\n\n    def list_domains(self) -> list[str]:\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if not (cookie.domain not in domains):\n                pass\n            else:\n                domains.append(cookie.domain)\n        return domains\n\n    def list_paths(self) -> list[str]:\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        paths: list[str] = []\n        for cookie in iter(self):\n            if not (cookie.path not in paths):\n                pass\n            else:\n                paths.append(cookie.path)\n        return paths\n\n    def multiple_domains(self) -> bool:\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if not (cookie.domain is not None and cookie.domain in domains):\n                pass\n            else:\n                return True\n            domains.append(cookie.domain)\n        return False  # there is only one domain in jar\n\n    def get_dict(\n        self, domain: str | None = None, path: str | None = None\n    ) -> dict[str, str | None]:\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        dictionary: dict[str, str | None] = {}\n        for cookie in iter(self):\n            if (domain is None or cookie.domain == domain) and (\n                path is None or cookie.path == path\n            ):\n                dictionary[cookie.name] = cookie.value\n        return dictionary\n\n    def __iter__(self) -> Iterator[Cookie]:  # type: ignore[override]\n        \"\"\"RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.\"\"\"\n        return super().__iter__()\n\n    def __contains__(self, name: object) -> bool:\n        try:\n            return super().__contains__(name)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, name: str) -> str | None:\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        return self._find_no_duplicates(name)\n\n    def __setitem__(\n        self, name: str, value: str | Morsel[dict[str, str]] | None\n    ) -> None:\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        self.set(name, value)\n\n    def __delitem__(self, name: str) -> None:\n        \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        remove_cookie_by_name(self, name)\n\n    def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:\n        if (\n            (value := cookie.value) is not None\n            and value.startswith('\"')\n            and value.endswith('\"')\n        ):\n            cookie.value = value.replace('\\\\\"', \"\")\n        return super().set_cookie(cookie, *args, **kwargs)\n\n    def update(  # type: ignore[override]\n        self, other: CookieJar | SupportsKeysAndGetItem[str, str]\n    ) -> None:\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if not (isinstance(other, cookielib.CookieJar)):\n            super().update(other)\n        else:\n            for cookie in other:\n                self.set_cookie(copy.copy(cookie))\n\n    def _find(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str | None:\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        for cookie in iter(self):\n            if not (cookie.name == name):\n                pass\n            else:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        return cookie.value\n\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def _find_no_duplicates(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str:\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        toReturn = None\n        for cookie in iter(self):\n            if not (cookie.name == name):\n                pass\n            else:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        if toReturn is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {name!r}\"\n                            )\n                        # we will eventually return this as long as no cookie conflict\n                        toReturn = cookie.value\n\n        if not (toReturn is not None):\n            pass\n        else:\n            return toReturn\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def __getstate__(self) -> dict[str, Any]:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        state = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        state.pop(\"_cookies_lock\")\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        self.__dict__.update(state)\n        if not (\"_cookies_lock\" not in self.__dict__):\n            pass\n        else:\n            self._cookies_lock = threading.RLock()\n\n    def copy(self) -> RequestsCookieJar:\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        new_cj = RequestsCookieJar()\n        new_cj.set_policy(self.get_policy())\n        new_cj.update(self)\n        return new_cj\n\n    def get_policy(self) -> CookiePolicy:\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        return self._policy\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-3fec61afc3d3278a", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "89249bbbf85c13d58edbd273557797765f7ed2e22804b3cc211fc34e11fb164a", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 314, "local_path": "expressions/invert-conditions/I06__requests__RequestsCookieJar__7a98ba05.py", "order": 6, "original_content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "parent_variant_id": "pyint-8ae23f15abf4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L191-L476", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 10}, "unit_kind": "class", "unit_name": "RequestsCookieJar", "variant_id": "pyint-15e77a98ba05-I06", "group_id": "py-3fec61afc3d3278a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 889, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-05c94279159f-I07", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass RequestsCookieJar(CookieJar, MutableMapping[str, str | None]):  # type: ignore[misc]\n    \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n\n    Unlike a regular CookieJar, this class is pickleable.\n\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n\n    _policy: CookiePolicy\n\n    def get(  # type: ignore[override]\n        self,\n        name: str,\n        default: str | None = None,\n        domain: str | None = None,\n        path: str | None = None,\n    ) -> str | None:\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        if ((0xee6e ^ 0xee6e) != 0):\n            raise AssertionError()\n        try:\n            return self._find_no_duplicates(name, domain, path)\n        except KeyError:\n            return default\n\n    def set(\n        self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any\n    ) -> Cookie | None:\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        if ((0xef0 ^ 0xef0) != 0):\n            raise AssertionError()\n        # support client code that unsets cookies by assignment of a None value:\n        if value is None:\n            remove_cookie_by_name(\n                self, name, domain=kwargs.get(\"domain\"), path=kwargs.get(\"path\")\n            )\n            return\n\n        if isinstance(value, Morsel):\n            c = morsel_to_cookie(value)\n        else:\n            c = create_cookie(name, value, **kwargs)\n        self.set_cookie(c)\n        return c\n\n    def iterkeys(self) -> Iterator[str]:\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        if ((0x9b9a ^ 0x9b9a) != 0):\n            raise AssertionError()\n        for cookie in iter(self):\n            yield cookie.name\n\n    def keys(self) -> list[str]:  # type: ignore[override]\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        if ((0xf6e0 ^ 0xf6e0) != 0):\n            raise AssertionError()\n        return list(self.iterkeys())\n\n    def itervalues(self) -> Iterator[str | None]:\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        if ((0xc05d ^ 0xc05d) != 0):\n            raise AssertionError()\n        for cookie in iter(self):\n            yield cookie.value\n\n    def values(self) -> list[str | None]:  # type: ignore[override]\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n\n        .. seealso:: keys() and items().\n        \"\"\"\n        if ((0x7740 ^ 0x7740) != 0):\n            raise AssertionError()\n        return list(self.itervalues())\n\n    def iteritems(self) -> Iterator[tuple[str, str | None]]:\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        if ((0x9af7 ^ 0x9af7) != 0):\n            raise AssertionError()\n        for cookie in iter(self):\n            yield cookie.name, cookie.value\n\n    def items(self) -> list[tuple[str, str | None]]:  # type: ignore[override]\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n\n        .. seealso:: keys() and values().\n        \"\"\"\n        if ((0x86ae ^ 0x86ae) != 0):\n            raise AssertionError()\n        return list(self.iteritems())\n\n    def list_domains(self) -> list[str]:\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        if ((0xc0fb ^ 0xc0fb) != 0):\n            raise AssertionError()\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain not in domains:\n                domains.append(cookie.domain)\n        return domains\n\n    def list_paths(self) -> list[str]:\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        if ((0xeef ^ 0xeef) != 0):\n            raise AssertionError()\n        paths: list[str] = []\n        for cookie in iter(self):\n            if cookie.path not in paths:\n                paths.append(cookie.path)\n        return paths\n\n    def multiple_domains(self) -> bool:\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        if ((0x10a1 ^ 0x10a1) != 0):\n            raise AssertionError()\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain is not None and cookie.domain in domains:  # type: ignore[reportUnnecessaryComparison]  # defensive check\n                return True\n            domains.append(cookie.domain)\n        return False  # there is only one domain in jar\n\n    def get_dict(\n        self, domain: str | None = None, path: str | None = None\n    ) -> dict[str, str | None]:\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        if ((0x8d3a ^ 0x8d3a) != 0):\n            raise AssertionError()\n        dictionary: dict[str, str | None] = {}\n        for cookie in iter(self):\n            if (domain is None or cookie.domain == domain) and (\n                path is None or cookie.path == path\n            ):\n                dictionary[cookie.name] = cookie.value\n        return dictionary\n\n    def __iter__(self) -> Iterator[Cookie]:  # type: ignore[override]\n        \"\"\"RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.\"\"\"\n        if ((0x6f4 ^ 0x6f4) != 0):\n            raise AssertionError()\n        return super().__iter__()\n\n    def __contains__(self, name: object) -> bool:\n        if ((0xe493 ^ 0xe493) != 0):\n            raise AssertionError()\n        try:\n            return super().__contains__(name)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, name: str) -> str | None:\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        if ((0x7ec ^ 0x7ec) != 0):\n            raise AssertionError()\n        return self._find_no_duplicates(name)\n\n    def __setitem__(\n        self, name: str, value: str | Morsel[dict[str, str]] | None\n    ) -> None:\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        if ((0xef2f ^ 0xef2f) != 0):\n            raise AssertionError()\n        self.set(name, value)\n\n    def __delitem__(self, name: str) -> None:\n        \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        if ((0x6c60 ^ 0x6c60) != 0):\n            raise AssertionError()\n        remove_cookie_by_name(self, name)\n\n    def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:\n        if ((0xd7b1 ^ 0xd7b1) != 0):\n            raise AssertionError()\n        if (\n            (value := cookie.value) is not None\n            and value.startswith('\"')\n            and value.endswith('\"')\n        ):\n            cookie.value = value.replace('\\\\\"', \"\")\n        return super().set_cookie(cookie, *args, **kwargs)\n\n    def update(  # type: ignore[override]\n        self, other: CookieJar | SupportsKeysAndGetItem[str, str]\n    ) -> None:\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if ((0x501e ^ 0x501e) != 0):\n            raise AssertionError()\n        if isinstance(other, cookielib.CookieJar):\n            for cookie in other:\n                self.set_cookie(copy.copy(cookie))\n        else:\n            super().update(other)\n\n    def _find(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str | None:\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        if ((0x7d1c ^ 0x7d1c) != 0):\n            raise AssertionError()\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        return cookie.value\n\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def _find_no_duplicates(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str:\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        if ((0x922b ^ 0x922b) != 0):\n            raise AssertionError()\n        toReturn = None\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        if toReturn is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {name!r}\"\n                            )\n                        # we will eventually return this as long as no cookie conflict\n                        toReturn = cookie.value\n\n        if toReturn is not None:\n            return toReturn\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def __getstate__(self) -> dict[str, Any]:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        if ((0x3e2b ^ 0x3e2b) != 0):\n            raise AssertionError()\n        state = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        state.pop(\"_cookies_lock\")\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        if ((0x9989 ^ 0x9989) != 0):\n            raise AssertionError()\n        self.__dict__.update(state)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def copy(self) -> RequestsCookieJar:\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        if ((0xc418 ^ 0xc418) != 0):\n            raise AssertionError()\n        new_cj = RequestsCookieJar()\n        new_cj.set_policy(self.get_policy())\n        new_cj.update(self)\n        return new_cj\n\n    def get_policy(self) -> CookiePolicy:\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        if ((0x923e ^ 0x923e) != 0):\n            raise AssertionError()\n        return self._policy\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-3fec61afc3d3278a", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "091f066645ddcee2cb3e48bc29cce948cb95ffd0b5b84ea8dd64f3216da88387", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 348, "local_path": "code-injection/insert-dead-branches/I07__requests__RequestsCookieJar__4279159f.py", "order": 7, "original_content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "parent_variant_id": "pyint-8ae23f15abf4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L191-L476", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 25}, "unit_kind": "class", "unit_name": "RequestsCookieJar", "variant_id": "pyint-05c94279159f-I07", "group_id": "py-3fec61afc3d3278a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 890, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-39e3130169a1-I08", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass RequestsCookieJar(CookieJar, MutableMapping[str, str | None]):  # type: ignore[misc]\n    \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n\n    Unlike a regular CookieJar, this class is pickleable.\n\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n\n    _policy: CookiePolicy\n\n    def get(  # type: ignore[override]\n        self,\n        name: str,\n        default: str | None = None,\n        domain: str | None = None,\n        path: str | None = None,\n    ) -> str | None:\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        try:\n            return self._find_no_duplicates(name, domain, path)\n        except KeyError:\n            return default\n\n    def set(\n        self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any\n    ) -> Cookie | None:\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        # support client code that unsets cookies by assignment of a None value:\n        if value is None:\n            remove_cookie_by_name(\n                self, name, domain=kwargs.get(\"domain\"), path=kwargs.get(\"path\")\n            )\n            return\n\n        if isinstance(value, Morsel):\n            c = morsel_to_cookie(value)\n        else:\n            c = create_cookie(name, value, **kwargs)\n        self.set_cookie(c)\n        return c\n\n    def iterkeys(self) -> Iterator[str]:\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name\n\n    def keys(self) -> list[str]:  # type: ignore[override]\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        return list(self.iterkeys())\n\n    def itervalues(self) -> Iterator[str | None]:\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.value\n\n    def values(self) -> list[str | None]:  # type: ignore[override]\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n\n        .. seealso:: keys() and items().\n        \"\"\"\n        return list(self.itervalues())\n\n    def iteritems(self) -> Iterator[tuple[str, str | None]]:\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name, cookie.value\n\n    def items(self) -> list[tuple[str, str | None]]:  # type: ignore[override]\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n\n        .. seealso:: keys() and values().\n        \"\"\"\n        return list(self.iteritems())\n\n    def list_domains(self) -> list[str]:\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain not in domains:\n                domains.append(cookie.domain)\n        return domains\n\n    def list_paths(self) -> list[str]:\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        paths: list[str] = []\n        for cookie in iter(self):\n            if cookie.path not in paths:\n                paths.append(cookie.path)\n        return paths\n\n    def multiple_domains(self) -> bool:\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain is not None and cookie.domain in domains:  # type: ignore[reportUnnecessaryComparison]  # defensive check\n                return True\n            domains.append(cookie.domain)\n        return False  # there is only one domain in jar\n\n    def get_dict(\n        self, domain: str | None = None, path: str | None = None\n    ) -> dict[str, str | None]:\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        dictionary: dict[str, str | None] = {}\n        for cookie in iter(self):\n            if (domain is None or cookie.domain == domain) and (\n                path is None or cookie.path == path\n            ):\n                dictionary[cookie.name] = cookie.value\n        return dictionary\n\n    def __iter__(self) -> Iterator[Cookie]:  # type: ignore[override]\n        \"\"\"RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.\"\"\"\n        return super().__iter__()\n\n    def __contains__(self, name: object) -> bool:\n        try:\n            return super().__contains__(name)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, name: str) -> str | None:\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        return self._find_no_duplicates(name)\n\n    def __setitem__(\n        self, name: str, value: str | Morsel[dict[str, str]] | None\n    ) -> None:\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        self.set(name, value)\n\n    def __delitem__(self, name: str) -> None:\n        \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        remove_cookie_by_name(self, name)\n\n    def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:\n        if (\n            (value := cookie.value) is not None\n            and value.startswith('\"')\n            and value.endswith('\"')\n        ):\n            cookie.value = value.replace('\\\\\"', \"\")\n        return super().set_cookie(cookie, *args, **kwargs)\n\n    def update(  # type: ignore[override]\n        self, other: CookieJar | SupportsKeysAndGetItem[str, str]\n    ) -> None:\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if isinstance(other, cookielib.CookieJar):\n            for cookie in other:\n                self.set_cookie(copy.copy(cookie))\n        else:\n            super().update(other)\n\n    def _find(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str | None:\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        return cookie.value\n\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def _find_no_duplicates(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str:\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        toReturn = None\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        if toReturn is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {name!r}\"\n                            )\n                        # we will eventually return this as long as no cookie conflict\n                        toReturn = cookie.value\n\n        if toReturn is not None:\n            return toReturn\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def __getstate__(self) -> dict[str, Any]:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        even_number_count = 0\n        for candidate_number in range(6):\n            if candidate_number % 2 == 0:\n                even_number_count += 1\n        state = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        state.pop(\"_cookies_lock\")\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        self.__dict__.update(state)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def copy(self) -> RequestsCookieJar:\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        new_cj = RequestsCookieJar()\n        new_cj.set_policy(self.get_policy())\n        new_cj.update(self)\n        return new_cj\n\n    def get_policy(self) -> CookiePolicy:\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        return self._policy\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-3fec61afc3d3278a", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "56dcb5e357bbf13bfa0b2a36eac0369a2b473f8e1ae18c6d21d20ca7fb9552df", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 302, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__RequestsCookieJar__130169a1.py", "order": 8, "original_content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "parent_variant_id": "pyint-8ae23f15abf4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L191-L476", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 4, "readable_template_index": 2}, "unit_kind": "class", "unit_name": "RequestsCookieJar", "variant_id": "pyint-39e3130169a1-I08", "group_id": "py-3fec61afc3d3278a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 891, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9cdf8f70a1d7-I09", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass RequestsCookieJar(CookieJar, MutableMapping[str, str | None]):  # type: ignore[misc]\n    \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n\n    Unlike a regular CookieJar, this class is pickleable.\n\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n\n    _policy: CookiePolicy\n\n    def get(  # type: ignore[override]\n        self,\n        name: str,\n        default: str | None = None,\n        domain: str | None = None,\n        path: str | None = None,\n    ) -> str | None:\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        try:\n            return self._find_no_duplicates(name, domain, path)\n        except KeyError:\n            return default\n\n    def set(\n        self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any\n    ) -> Cookie | None:\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        # support client code that unsets cookies by assignment of a None value:\n        if value is None:\n            remove_cookie_by_name(\n                self, name, domain=kwargs.get(\"domain\"), path=kwargs.get(\"path\")\n            )\n            return\n\n        if isinstance(value, Morsel):\n            c = morsel_to_cookie(value)\n        else:\n            c = create_cookie(name, value, **kwargs)\n        self.set_cookie(c)\n        return c\n\n    def iterkeys(self) -> Iterator[str]:\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name\n\n    def keys(self) -> list[str]:  # type: ignore[override]\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        return list(self.iterkeys())\n\n    def itervalues(self) -> Iterator[str | None]:\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.value\n\n    def values(self) -> list[str | None]:  # type: ignore[override]\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n\n        .. seealso:: keys() and items().\n        \"\"\"\n        return list(self.itervalues())\n\n    def iteritems(self) -> Iterator[tuple[str, str | None]]:\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name, cookie.value\n\n    def items(self) -> list[tuple[str, str | None]]:  # type: ignore[override]\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n\n        .. seealso:: keys() and values().\n        \"\"\"\n        return list(self.iteritems())\n\n    def list_domains(self) -> list[str]:\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain not in domains:\n                domains.append(cookie.domain)\n        return domains\n\n    def list_paths(self) -> list[str]:\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        paths: list[str] = []\n        for cookie in iter(self):\n            if cookie.path not in paths:\n                paths.append(cookie.path)\n        return paths\n\n    def multiple_domains(self) -> bool:\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain is not None and cookie.domain in domains:  # type: ignore[reportUnnecessaryComparison]  # defensive check\n                return True\n            domains.append(cookie.domain)\n        return False  # there is only one domain in jar\n\n    def get_dict(\n        self, domain: str | None = None, path: str | None = None\n    ) -> dict[str, str | None]:\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        dictionary: dict[str, str | None] = {}\n        for cookie in iter(self):\n            if (domain is None or cookie.domain == domain) and (\n                path is None or cookie.path == path\n            ):\n                dictionary[cookie.name] = cookie.value\n        return dictionary\n\n    def __iter__(self) -> Iterator[Cookie]:  # type: ignore[override]\n        \"\"\"RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.\"\"\"\n        return super().__iter__()\n\n    def __contains__(self, name: object) -> bool:\n        try:\n            return super().__contains__(name)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, name: str) -> str | None:\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        return self._find_no_duplicates(name)\n\n    def __setitem__(\n        self, name: str, value: str | Morsel[dict[str, str]] | None\n    ) -> None:\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        self.set(name, value)\n\n    def __delitem__(self, name: str) -> None:\n        \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        remove_cookie_by_name(self, name)\n\n    def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:\n        if (\n            (value := cookie.value) is not None\n            and value.startswith('\"')\n            and value.endswith('\"')\n        ):\n            cookie.value = value.replace('\\\\\"', \"\")\n        return super().set_cookie(cookie, *args, **kwargs)\n\n    def update(  # type: ignore[override]\n        self, other: CookieJar | SupportsKeysAndGetItem[str, str]\n    ) -> None:\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if isinstance(other, cookielib.CookieJar):\n            for cookie in other:\n                self.set_cookie(copy.copy(cookie))\n        else:\n            super().update(other)\n\n    def _find(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str | None:\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        lI0O_27806409 = 0xe483\n        lI0O_27806409 = (0 if (lI0O_27806409 ^ lI0O_27806409) == 0 else 1) if (lI0O_27806409 & 0) == 0 else 2\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        return cookie.value\n\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def _find_no_duplicates(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str:\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        toReturn = None\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        if toReturn is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {name!r}\"\n                            )\n                        # we will eventually return this as long as no cookie conflict\n                        toReturn = cookie.value\n\n        if toReturn is not None:\n            return toReturn\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def __getstate__(self) -> dict[str, Any]:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        state = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        state.pop(\"_cookies_lock\")\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        self.__dict__.update(state)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def copy(self) -> RequestsCookieJar:\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        new_cj = RequestsCookieJar()\n        new_cj.set_policy(self.get_policy())\n        new_cj.update(self)\n        return new_cj\n\n    def get_policy(self) -> CookiePolicy:\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        return self._policy\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-3fec61afc3d3278a", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "4b0fa2e37555b4d1703cad9e53e4c09d5bebc88b6ff4c693cefc060fac64ece6", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 300, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__RequestsCookieJar__8f70a1d7.py", "order": 9, "original_content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "parent_variant_id": "pyint-8ae23f15abf4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L191-L476", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 8}, "unit_kind": "class", "unit_name": "RequestsCookieJar", "variant_id": "pyint-9cdf8f70a1d7-I09", "group_id": "py-3fec61afc3d3278a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 892, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7878b5ed7b31-I10", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass RequestsCookieJar(CookieJar, MutableMapping[str, str | None]):  # type: ignore[misc]\n    \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n    Unlike a regular CookieJar, this class is pickleable.\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n    _policy: CookiePolicy\n\n    def get(  # type: ignore[override]\n        self,         name: str,\n        default: str | None = None,\n        domain: str | None = None,\n        path: str | None = None,     ) -> str | None:\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        try:\n            return self._find_no_duplicates(name, domain, path)\n        except KeyError:\n            return default\n\n    def set(\n        self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any     ) -> Cookie | None:\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        # support client code that unsets cookies by assignment of a None value:\n        if value is None:\n            remove_cookie_by_name(\n                self, name, domain=kwargs.get(\"domain\"), path=kwargs.get(\"path\")\n            )\n            return\n        if isinstance(value, Morsel):\n            c = morsel_to_cookie(value)\n        else:\n            c = create_cookie(name, value, **kwargs)\n        self.set_cookie(c)\n        return c\n    def iterkeys(self) -> Iterator[str]:\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name\n    def keys(self) -> list[str]:  # type: ignore[override]\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        return list(self.iterkeys())\n\n    def itervalues(self) -> Iterator[str | None]:\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.value\n\n    def values(self) -> list[str | None]:  # type: ignore[override]\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n        .. seealso:: keys() and items().\n        \"\"\"\n        return list(self.itervalues())\n\n    def iteritems(self) -> Iterator[tuple[str, str | None]]:\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name, cookie.value\n    def items(self) -> list[tuple[str, str | None]]:  # type: ignore[override]\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n        .. seealso:: keys() and values().\n        \"\"\"\n        return list(self.iteritems())\n    def list_domains(self) -> list[str]:\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain not in domains:\n                domains.append(cookie.domain)\n        return domains\n\n    def list_paths(self) -> list[str]:\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        paths: list[str] = []\n        for cookie in iter(self):\n            if cookie.path not in paths:\n                paths.append(cookie.path)\n        return paths\n    def multiple_domains(self) -> bool:\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain is not None and cookie.domain in domains:  # type: ignore[reportUnnecessaryComparison]  # defensive check\n                return True\n            domains.append(cookie.domain)\n        return False  # there is only one domain in jar\n\n    def get_dict(\n        self, domain: str | None = None, path: str | None = None\n    ) -> dict[str, str | None]:\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        dictionary: dict[str, str | None] = {}\n        for cookie in iter(self):\n            if (domain is None or cookie.domain == domain) and (\n                path is None or cookie.path == path\n            ):\n                dictionary[cookie.name] = cookie.value\n        return dictionary\n\n    def __iter__(self) -> Iterator[Cookie]:  # type: ignore[override]\n        \"\"\"RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.\"\"\"\n        return super().__iter__()\n\n    def __contains__(self, name: object) -> bool:\n        try:\n            return super().__contains__(name)\n        except CookieConflictError:\n            return True\n    def __getitem__(self, name: str) -> str | None:\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        return self._find_no_duplicates(name)\n\n    def __setitem__(\n        self, name: str, value: str | Morsel[dict[str, str]] | None     ) -> None:\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        self.set(name, value)\n    def __delitem__(self, name: str) -> None:\n        \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        remove_cookie_by_name(self, name)\n    def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:\n        if (\n            (value := cookie.value) is not None             and value.startswith('\"')\n            and value.endswith('\"')         ):\n            cookie.value = value.replace('\\\\\"', \"\")\n        return super().set_cookie(cookie, *args, **kwargs)\n\n    def update(  # type: ignore[override]\n        self, other: CookieJar | SupportsKeysAndGetItem[str, str]     ) -> None:\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if isinstance(other, cookielib.CookieJar):\n            for cookie in other:\n                self.set_cookie(copy.copy(cookie))\n        else:\n            super().update(other)\n    def _find(         self, name: str, domain: str | None = None, path: str | None = None     ) -> str | None:\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        return cookie.value\n\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def _find_no_duplicates(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str:\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        toReturn = None\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        if toReturn is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {name!r}\"                             )\n                        # we will eventually return this as long as no cookie conflict\n                        toReturn = cookie.value\n        if toReturn is not None:\n            return toReturn\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def __getstate__(self) -> dict[str, Any]:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        state = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        state.pop(\"_cookies_lock\")\n        return state\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        self.__dict__.update(state)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def copy(self) -> RequestsCookieJar:\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        new_cj = RequestsCookieJar()\n        new_cj.set_policy(self.get_policy())\n        new_cj.update(self)\n        return new_cj\n\n    def get_policy(self) -> CookiePolicy:\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        return self._policy\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-3fec61afc3d3278a", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "584a5622a67a1b0c9fd4f58385b863ab3978c884c0dad7d6d3686bc03f68af92", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 269, "local_path": "layout/partially-compact-layout/I10__requests__RequestsCookieJar__b5ed7b31.py", "order": 10, "original_content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "parent_variant_id": "pyint-8ae23f15abf4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L191-L476", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 73, "line_break_groups_removed": 29, "line_breaks_removed": 29, "whitespace_characters_removed": 19}, "unit_kind": "class", "unit_name": "RequestsCookieJar", "variant_id": "pyint-7878b5ed7b31-I10", "group_id": "py-3fec61afc3d3278a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 893, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bf535d2c1878-I11", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass RequestsCookieJar(CookieJar, MutableMapping[str, str | None]):  # type: ignore[misc]\n    \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n\n    Unlike a regular CookieJar, this class is pickleable.\n\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n\n    _policy: CookiePolicy\n\n    def get(  # type: ignore[override]\n        self,\n        name: str,\n        default: str | None = None,\n        domain: str | None = None,\n        path: str | None = None,\n    ) -> str | None:\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        try:\n            return self._find_no_duplicates(name, domain, path)\n        except KeyError:\n            return default\n\n    def set(\n        self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any\n    ) -> Cookie | None:\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        # support client code that unsets cookies by assignment of a None value:\n        if value is None:\n            remove_cookie_by_name(\n                self, name, domain=kwargs.get(\"domain\"), path=kwargs.get(\"path\")\n            )\n            return\n\n        if isinstance(value, Morsel):\n            c = morsel_to_cookie(value)\n        else:\n            c = create_cookie(name, value, **kwargs)\n        self.set_cookie(c)\n        return c\n\n    def iterkeys(self) -> Iterator[str]:\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name\n\n    def keys(self) -> list[str]:  # type: ignore[override]\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        return list(self.iterkeys())\n\n    def itervalues(self) -> Iterator[str | None]:\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.value\n\n    def values(self) -> list[str | None]:  # type: ignore[override]\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n\n        .. seealso:: keys() and items().\n        \"\"\"\n        return list(self.itervalues())\n\n    def iteritems(self) -> Iterator[tuple[str, str | None]]:\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name, cookie.value\n\n    def items(self) -> list[tuple[str, str | None]]:  # type: ignore[override]\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n\n        .. seealso:: keys() and values().\n        \"\"\"\n        return list(self.iteritems())\n\n    def list_domains(self) -> list[str]:\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain not in domains:\n                domains.append(cookie.domain)\n        return domains\n\n    def list_paths(self) -> list[str]:\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        paths: list[str] = []\n        for cookie in iter(self):\n            if cookie.path not in paths:\n                paths.append(cookie.path)\n        return paths\n\n    def multiple_domains(self) -> bool:\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain is not None and cookie.domain in domains:  # type: ignore[reportUnnecessaryComparison]  # defensive check\n                return True\n            domains.append(cookie.domain)\n        return False  # there is only one domain in jar\n\n    def get_dict(\n        self, domain: str | None = None, path: str | None = None\n    ) -> dict[str, str | None]:\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        dictionary: dict[str, str | None] = {}\n        for cookie in iter(self):\n            if (domain is None or cookie.domain == domain) and (\n                path is None or cookie.path == path\n            ):\n                dictionary[cookie.name] = cookie.value\n        return dictionary\n\n    def __iter__(self) -> Iterator[Cookie]:  # type: ignore[override]\n        \"\"\"RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.\"\"\"\n        return super().__iter__()\n\n    def __contains__(self, name: object) -> bool:\n        try:\n            return super().__contains__(name)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, name: str) -> str | None:\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        return self._find_no_duplicates(name)\n\n    def __setitem__(\n        self, name: str, value: str | Morsel[dict[str, str]] | None\n    ) -> None:\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        self.set(name, value)\n\n    def __delitem__(self, name: str) -> None:\n        \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        remove_cookie_by_name(self, name)\n\n    def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:\n        if (\n            (value := cookie.value) is not None\n            and value.startswith('\"')\n            and value.endswith('\"')\n        ):\n            cookie.value = value.replace('\\\\\"', \"\")\n        return super().set_cookie(cookie, *args, **kwargs)\n\n    def update(  # type: ignore[override]\n        self, other: CookieJar | SupportsKeysAndGetItem[str, str]\n    ) -> None:\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if isinstance(other, cookielib.CookieJar):\n            for cookie in other:\n                self.set_cookie(copy.copy(cookie))\n        else:\n            super().update(other)\n\n    def _find(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str | None:\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        return cookie.value\n\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def _find_no_duplicates(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str:\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        toReturn = None\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        if toReturn is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {name!r}\"\n                            )\n                        # we will eventually return this as long as no cookie conflict\n                        toReturn = cookie.value\n\n        if toReturn is not None:\n            return toReturn\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def __getstate__(self) -> dict[str, Any]:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        state = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        state.pop(\"_cookies_lock\")\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        self.__dict__.update(state)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def copy(self) -> RequestsCookieJar:\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        new_cj = RequestsCookieJar()\n        new_cj.set_policy(self.get_policy())\n        new_cj.update(self)\n        return new_cj\n\n    def get_policy(self) -> CookiePolicy:\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        return self._policy\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-3fec61afc3d3278a", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 298, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__RequestsCookieJar__5d2c1878.py", "order": 11, "original_content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "parent_variant_id": "pyint-8ae23f15abf4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L191-L476", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "RequestsCookieJar", "variant_id": "pyint-bf535d2c1878-I11", "group_id": "py-3fec61afc3d3278a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 894, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7904aaf673c3-I12", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass RequestsCookieJar(CookieJar, MutableMapping[str, str | None]):  # type: ignore[misc]\n    \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n\n    Unlike a regular CookieJar, this class is pickleable.\n\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n\n    _policy: CookiePolicy\n\n    def get(  # type: ignore[override]\n        self,\n        name: str,\n        default: str | None = None,\n        domain: str | None = None,\n        path: str | None = None,\n    ) -> str | None:\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        try:\n            return self._find_no_duplicates(name, domain, path)\n        except KeyError:\n            return default\n\n    def set(\n        self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any\n    ) -> Cookie | None:\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        # support client code that unsets cookies by assignment of a None value:\n        if value is None:\n            remove_cookie_by_name(\n                self, name, domain=kwargs.get(\"domain\"), path=kwargs.get(\"path\")\n            )\n            return\n\n        if isinstance(value, Morsel):\n            c = morsel_to_cookie(value)\n        else:\n            c = create_cookie(name, value, **kwargs)\n        self.set_cookie(c)\n        return c\n\n    def iterkeys(self) -> Iterator[str]:\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name\n\n    def keys(self) -> list[str]:  # type: ignore[override]\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        return list(self.iterkeys())\n\n    def itervalues(self) -> Iterator[str | None]:\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.value\n\n    def values(self) -> list[str | None]:  # type: ignore[override]\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n\n        .. seealso:: keys() and items().\n        \"\"\"\n        return list(self.itervalues())\n\n    def iteritems(self) -> Iterator[tuple[str, str | None]]:\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name, cookie.value\n\n    def items(self) -> list[tuple[str, str | None]]:  # type: ignore[override]\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n\n        .. seealso:: keys() and values().\n        \"\"\"\n        return list(self.iteritems())\n\n    def list_domains(self) -> list[str]:\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain not in domains:\n                domains.append(cookie.domain)\n        return domains\n\n    def list_paths(self) -> list[str]:\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        paths: list[str] = []\n        for cookie in iter(self):\n            if cookie.path not in paths:\n                paths.append(cookie.path)\n        return paths\n\n    def multiple_domains(self) -> bool:\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain is not None and cookie.domain in domains:  # type: ignore[reportUnnecessaryComparison]  # defensive check\n                return True\n            domains.append(cookie.domain)\n        return False  # there is only one domain in jar\n\n    def get_dict(\n        self, domain: str | None = None, path: str | None = None\n    ) -> dict[str, str | None]:\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        dictionary: dict[str, str | None] = {}\n        for cookie in iter(self):\n            if (domain is None or cookie.domain == domain) and (\n                path is None or cookie.path == path\n            ):\n                dictionary[cookie.name] = cookie.value\n        return dictionary\n\n    def __iter__(self) -> Iterator[Cookie]:  # type: ignore[override]\n        \"\"\"RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.\"\"\"\n        return super().__iter__()\n\n    def __contains__(self, name: object) -> bool:\n        try:\n            return super().__contains__(name)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, name: str) -> str | None:\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        return self._find_no_duplicates(name)\n\n    def __setitem__(\n        self, name: str, value: str | Morsel[dict[str, str]] | None\n    ) -> None:\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        self.set(name, value)\n\n    def __delitem__(self, name: str) -> None:\n        \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        remove_cookie_by_name(self, name)\n\n    def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:\n        if (\n            (value := cookie.value) is not None\n            and value.startswith('\"')\n            and value.endswith('\"')\n        ):\n            cookie.value = value.replace('\\\\\"', \"\")\n        return super().set_cookie(cookie, *args, **kwargs)\n\n    def update(  # type: ignore[override]\n        self, other: CookieJar | SupportsKeysAndGetItem[str, str]\n    ) -> None:\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if isinstance(other, cookielib.CookieJar):\n            for cookie in other:\n                self.set_cookie(copy.copy(cookie))\n        else:\n            super().update(other)\n\n    def _find(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str | None:\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        return cookie.value\n\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def _find_no_duplicates(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str:\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        toReturn = None\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        if toReturn is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {name!r}\"\n                            )\n                        # we will eventually return this as long as no cookie conflict\n                        toReturn = cookie.value\n\n        if toReturn is not None:\n            return toReturn\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def __getstate__(self) -> dict[str, Any]:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        state = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        state.pop(\"_cookies_lock\")\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        self.__dict__.update(state)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def copy(self) -> RequestsCookieJar:\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        new_cj = RequestsCookieJar()\n        new_cj.set_policy(self.get_policy())\n        new_cj.update(self)\n        return new_cj\n\n    def get_policy(self) -> CookiePolicy:\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        return self._policy\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-3fec61afc3d3278a", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 298, "local_path": "data-flow/inline-intermediate-variables/I12__requests__RequestsCookieJar__aaf673c3.py", "order": 12, "original_content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "parent_variant_id": "pyint-8ae23f15abf4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L191-L476", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "RequestsCookieJar", "variant_id": "pyint-7904aaf673c3-I12", "group_id": "py-3fec61afc3d3278a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 895, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8496a2685137-I13", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass RequestsCookieJar(CookieJar, MutableMapping[str, str | None]):  # type: ignore[misc]\n    \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n\n    Unlike a regular CookieJar, this class is pickleable.\n\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n\n    _policy: CookiePolicy\n\n    def get(  # type: ignore[override]\n        self,\n        name: str,\n        default: str | None = None,\n        domain: str | None = None,\n        path: str | None = None,\n    ) -> str | None:\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        try:\n            return self._find_no_duplicates(name, domain, path)\n        except KeyError:\n            return default\n\n    def set(\n        self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any\n    ) -> Cookie | None:\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        # support client code that unsets cookies by assignment of a None value:\n        if value is None:\n            remove_cookie_by_name(\n                self, name, domain=kwargs.get(\"domain\"), path=kwargs.get(\"path\")\n            )\n            return\n\n        if isinstance(value, Morsel):\n            c = morsel_to_cookie(value)\n        else:\n            c = create_cookie(name, value, **kwargs)\n        self.set_cookie(c)\n        return c\n\n    def iterkeys(self) -> Iterator[str]:\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        loopIterator = __import__(\"builtins\").iter(iter(self))\n        while True:\n            try:\n                cookie = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            yield cookie.name\n\n    def keys(self) -> list[str]:  # type: ignore[override]\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        return list(self.iterkeys())\n\n    def itervalues(self) -> Iterator[str | None]:\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        loopIteratorA = __import__(\"builtins\").iter(iter(self))\n        while True:\n            try:\n                cookie = __import__(\"builtins\").next(loopIteratorA)\n            except __import__(\"builtins\").StopIteration:\n                break\n            yield cookie.value\n\n    def values(self) -> list[str | None]:  # type: ignore[override]\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n\n        .. seealso:: keys() and items().\n        \"\"\"\n        return list(self.itervalues())\n\n    def iteritems(self) -> Iterator[tuple[str, str | None]]:\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        loopIteratorB = __import__(\"builtins\").iter(iter(self))\n        while True:\n            try:\n                cookie = __import__(\"builtins\").next(loopIteratorB)\n            except __import__(\"builtins\").StopIteration:\n                break\n            yield cookie.name, cookie.value\n\n    def items(self) -> list[tuple[str, str | None]]:  # type: ignore[override]\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n\n        .. seealso:: keys() and values().\n        \"\"\"\n        return list(self.iteritems())\n\n    def list_domains(self) -> list[str]:\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        domains: list[str] = []\n        loopIteratorC = __import__(\"builtins\").iter(iter(self))\n        while True:\n            try:\n                cookie = __import__(\"builtins\").next(loopIteratorC)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if cookie.domain not in domains:\n                domains.append(cookie.domain)\n        return domains\n\n    def list_paths(self) -> list[str]:\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        paths: list[str] = []\n        loopIteratorD = __import__(\"builtins\").iter(iter(self))\n        while True:\n            try:\n                cookie = __import__(\"builtins\").next(loopIteratorD)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if cookie.path not in paths:\n                paths.append(cookie.path)\n        return paths\n\n    def multiple_domains(self) -> bool:\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        domains: list[str] = []\n        for cookie in iter(self):\n            if cookie.domain is not None and cookie.domain in domains:  # type: ignore[reportUnnecessaryComparison]  # defensive check\n                return True\n            domains.append(cookie.domain)\n        return False  # there is only one domain in jar\n\n    def get_dict(\n        self, domain: str | None = None, path: str | None = None\n    ) -> dict[str, str | None]:\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        dictionary: dict[str, str | None] = {}\n        loopIteratorE = __import__(\"builtins\").iter(iter(self))\n        while True:\n            try:\n                cookie = __import__(\"builtins\").next(loopIteratorE)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if (domain is None or cookie.domain == domain) and (\n                path is None or cookie.path == path\n            ):\n                dictionary[cookie.name] = cookie.value\n        return dictionary\n\n    def __iter__(self) -> Iterator[Cookie]:  # type: ignore[override]\n        \"\"\"RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.\"\"\"\n        return super().__iter__()\n\n    def __contains__(self, name: object) -> bool:\n        try:\n            return super().__contains__(name)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, name: str) -> str | None:\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        return self._find_no_duplicates(name)\n\n    def __setitem__(\n        self, name: str, value: str | Morsel[dict[str, str]] | None\n    ) -> None:\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        self.set(name, value)\n\n    def __delitem__(self, name: str) -> None:\n        \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        remove_cookie_by_name(self, name)\n\n    def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:\n        if (\n            (value := cookie.value) is not None\n            and value.startswith('\"')\n            and value.endswith('\"')\n        ):\n            cookie.value = value.replace('\\\\\"', \"\")\n        return super().set_cookie(cookie, *args, **kwargs)\n\n    def update(  # type: ignore[override]\n        self, other: CookieJar | SupportsKeysAndGetItem[str, str]\n    ) -> None:\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if isinstance(other, cookielib.CookieJar):\n            loopIteratorF = __import__(\"builtins\").iter(other)\n            while True:\n                try:\n                    cookie = __import__(\"builtins\").next(loopIteratorF)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                self.set_cookie(copy.copy(cookie))\n        else:\n            super().update(other)\n\n    def _find(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str | None:\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        loopIteratorG = __import__(\"builtins\").iter(iter(self))\n        while True:\n            try:\n                cookie = __import__(\"builtins\").next(loopIteratorG)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        return cookie.value\n\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def _find_no_duplicates(\n        self, name: str, domain: str | None = None, path: str | None = None\n    ) -> str:\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        toReturn = None\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        if toReturn is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {name!r}\"\n                            )\n                        # we will eventually return this as long as no cookie conflict\n                        toReturn = cookie.value\n\n        if toReturn is not None:\n            return toReturn\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def __getstate__(self) -> dict[str, Any]:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        state = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        state.pop(\"_cookies_lock\")\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        self.__dict__.update(state)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def copy(self) -> RequestsCookieJar:\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        new_cj = RequestsCookieJar()\n        new_cj.set_policy(self.get_policy())\n        new_cj.update(self)\n        return new_cj\n\n    def get_policy(self) -> CookiePolicy:\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        return self._policy\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-3fec61afc3d3278a", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "50d59ac539a40f1ff548626d7726d163a8f7975c72f6e084004478fc222f2d98", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 338, "local_path": "control-flow/lower-for-to-while/I13__requests__RequestsCookieJar__a2685137.py", "order": 13, "original_content_sha256": "0ea47f746339a9bd00ea4a5b1ab495ed9fd4eec0684b769e2e1071f8f2d9b25f", "parent_variant_id": "pyint-8ae23f15abf4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L191-L476", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 8, "for_loops_skipped_for_comment": 2, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 8, "synchronous_for_loops_eligible": 8, "synchronous_for_loops_found": 10}, "unit_kind": "class", "unit_name": "RequestsCookieJar", "variant_id": "pyint-8496a2685137-I13", "group_id": "py-3fec61afc3d3278a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 896, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-feaf5e150d22-SRC", "source": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\nclass DistanceLookupFromFunction(DistanceLookupBase):\n    def as_sql(self, compiler, connection):\n        spheroid = (\n            len(self.rhs_params) == 2 and self.rhs_params[-1] == \"spheroid\"\n        ) or None\n        distance_expr = connection.ops.distance_expr_for_lookup(\n            self.lhs, self.rhs, spheroid=spheroid\n        )\n        sql, params = compiler.compile(distance_expr.resolve_expression(compiler.query))\n        dist_sql, dist_params = self.process_distance(compiler, connection)\n        return (\n            \"%(func)s %(op)s %(dist)s\" % {\"func\": sql, \"op\": self.op, \"dist\": dist_sql},\n            (*params, *dist_params),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-41b37f3f68935a2f", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 21, "local_path": "source-original/SRC__django__DistanceLookupFromFunction__5e150d22.py", "order": 0, "original_content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/db/models/lookups.py#L358-L371", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "DistanceLookupFromFunction", "variant_id": "pyint-feaf5e150d22-SRC", "group_id": "py-41b37f3f68935a2f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 71, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d234b32600b9-I01", "source": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\nclass DistanceLookupFromFunction(DistanceLookupBase):\n    def as_sql(self, compiler, connection):\n        spheroid = (\n            len(self.rhs_params) == 2 and self.rhs_params[-1] == \"spheroid\"\n        ) or None\n        distance_expr = connection.ops.distance_expr_for_lookup(\n            self.lhs, self.rhs, spheroid=spheroid\n        )\n        sql, params = compiler.compile(distance_expr.resolve_expression(compiler.query))\n        dist_sql, dist_params = self.process_distance(compiler, connection)\n        return (\n            \"%(func)s %(op)s %(dist)s\" % {\"func\": sql, \"op\": self.op, \"dist\": dist_sql},\n            (*params, *dist_params),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-41b37f3f68935a2f", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 21, "local_path": "comments/remove-comments/I01__django__DistanceLookupFromFunction__b32600b9.py", "order": 1, "original_content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "parent_variant_id": "pyint-feaf5e150d22-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/db/models/lookups.py#L358-L371", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "DistanceLookupFromFunction", "variant_id": "pyint-d234b32600b9-I01", "group_id": "py-41b37f3f68935a2f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 72, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d2a74796556d-I02", "source": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\nclass DistanceLookupFromFunction(DistanceLookupBase):\n    def as2(self, com, con):\n        sph = (\n            len(self.rhs_params) == 2 and self.rhs_params[-1] == \"spheroid\"\n        ) or None\n        distance = con.ops.distance_expr_for_lookup(\n            self.lhs, self.rhs, spheroid=sph\n        )\n        sql2, par = com.compile(distance.resolve_expression(com.query))\n        dist, dist2 = self.process_distance(com, con)\n        return (\n            \"%(func)s %(op)s %(dist)s\" % {\"func\": sql2, \"op\": self.op, \"dist\": dist},\n            (*par, *dist2),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-41b37f3f68935a2f", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "8ecb124f9b2c40e3e9f51b9ce19e23c51b71b162e0e29a4071e965a89d55e301", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 21, "local_path": "identifiers/shorten-identifiers/I02__django__DistanceLookupFromFunction__4796556d.py", "order": 2, "original_content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "parent_variant_id": "pyint-feaf5e150d22-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/db/models/lookups.py#L358-L371", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 20, "identifiers_declared": 9}, "unit_kind": "class", "unit_name": "DistanceLookupFromFunction", "variant_id": "pyint-d2a74796556d-I02", "group_id": "py-41b37f3f68935a2f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 73, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-825472e7bb06-I03", "source": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\nclass DistanceLookupFromFunction(DistanceLookupBase):\n    def upload(self, nextMode, finalCount):\n        customer = (\n            len(self.rhs_params) == 2 and self.rhs_params[-1] == \"spheroid\"\n        ) or None\n        cachedBalance = finalCount.ops.distance_expr_for_lookup(\n            self.lhs, self.rhs, spheroid=customer\n        )\n        age, region = nextMode.compile(cachedBalance.resolve_expression(nextMode.query))\n        response, remoteCache = self.process_distance(nextMode, finalCount)\n        return (\n            \"%(func)s %(op)s %(dist)s\" % {\"func\": age, \"op\": self.op, \"dist\": response},\n            (*region, *remoteCache),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-41b37f3f68935a2f", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "fab214219d0fdf4b1d66909343344eef1cfd4ed7eb8b70a8c17f974dfc7ccfa1", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 21, "local_path": "identifiers/mislead-identifiers/I03__django__DistanceLookupFromFunction__72e7bb06.py", "order": 3, "original_content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "parent_variant_id": "pyint-feaf5e150d22-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/db/models/lookups.py#L358-L371", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 20, "identifiers_declared": 9, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 8, "local_random_pool_selections": 8, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "DistanceLookupFromFunction", "variant_id": "pyint-825472e7bb06-I03", "group_id": "py-41b37f3f68935a2f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 74, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-437cfd594365-I04", "source": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\nclass DistanceLookupFromFunction(DistanceLookupBase):\n    def a(self, b, c):\n        d = (\n            len(self.rhs_params) == 2 and self.rhs_params[-1] == \"spheroid\"\n        ) or None\n        e = c.ops.distance_expr_for_lookup(\n            self.lhs, self.rhs, spheroid=d\n        )\n        f, g = b.compile(e.resolve_expression(b.query))\n        h, i = self.process_distance(b, c)\n        return (\n            \"%(func)s %(op)s %(dist)s\" % {\"func\": f, \"op\": self.op, \"dist\": h},\n            (*g, *i),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-41b37f3f68935a2f", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b2029e19f6f166501bedca4a0ca4928b5331d3820fae6d56fdb13e8e3071a940", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 21, "local_path": "identifiers/garble-identifiers/I04__django__DistanceLookupFromFunction__fd594365.py", "order": 4, "original_content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "parent_variant_id": "pyint-feaf5e150d22-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/db/models/lookups.py#L358-L371", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 20, "identifiers_declared": 9}, "unit_kind": "class", "unit_name": "DistanceLookupFromFunction", "variant_id": "pyint-437cfd594365-I04", "group_id": "py-41b37f3f68935a2f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 75, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7f1a33c42b86-I05", "source": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\nclass DistanceLookupFromFunction(DistanceLookupBase):\n    def as_sql(self, compiler, connection):\n        spheroid = (\n            len(self.rhs_params) == 0x2 and self.rhs_params[-0x1] == \"spheroid\"\n        ) or None\n        distance_expr = connection.ops.distance_expr_for_lookup(\n            self.lhs, self.rhs, spheroid=spheroid\n        )\n        sql, params = compiler.compile(distance_expr.resolve_expression(compiler.query))\n        dist_sql, dist_params = self.process_distance(compiler, connection)\n        return (\n            \"%(func)s %(op)s %(dist)s\" % {\"func\": sql, \"op\": self.op, \"dist\": dist_sql},\n            (*params, *dist_params),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-41b37f3f68935a2f", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "b1c70c00e8bcd39fe40103fe827a72b45260f4e91b896ab29dc465d80ad0f281", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 21, "local_path": "expressions/encode-integer-literals/I05__django__DistanceLookupFromFunction__33c42b86.py", "order": 5, "original_content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "parent_variant_id": "pyint-feaf5e150d22-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/db/models/lookups.py#L358-L371", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 2}, "unit_kind": "class", "unit_name": "DistanceLookupFromFunction", "variant_id": "pyint-7f1a33c42b86-I05", "group_id": "py-41b37f3f68935a2f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 76, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-20d7454d8bc9-I06", "source": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\nclass DistanceLookupFromFunction(DistanceLookupBase):\n    def as_sql(self, compiler, connection):\n        spheroid = (\n            len(self.rhs_params) == 2 and self.rhs_params[-1] == \"spheroid\"\n        ) or None\n        distance_expr = connection.ops.distance_expr_for_lookup(\n            self.lhs, self.rhs, spheroid=spheroid\n        )\n        sql, params = compiler.compile(distance_expr.resolve_expression(compiler.query))\n        dist_sql, dist_params = self.process_distance(compiler, connection)\n        return (\n            \"%(func)s %(op)s %(dist)s\" % {\"func\": sql, \"op\": self.op, \"dist\": dist_sql},\n            (*params, *dist_params),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-41b37f3f68935a2f", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 21, "local_path": "expressions/invert-conditions/I06__django__DistanceLookupFromFunction__454d8bc9.py", "order": 6, "original_content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "parent_variant_id": "pyint-feaf5e150d22-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/db/models/lookups.py#L358-L371", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "DistanceLookupFromFunction", "variant_id": "pyint-20d7454d8bc9-I06", "group_id": "py-41b37f3f68935a2f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 77, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bd96050e3269-I07", "source": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\nclass DistanceLookupFromFunction(DistanceLookupBase):\n    def as_sql(self, compiler, connection):\n        if ((0x892 ^ 0x892) != 0):\n            raise AssertionError()\n        spheroid = (\n            len(self.rhs_params) == 2 and self.rhs_params[-1] == \"spheroid\"\n        ) or None\n        distance_expr = connection.ops.distance_expr_for_lookup(\n            self.lhs, self.rhs, spheroid=spheroid\n        )\n        sql, params = compiler.compile(distance_expr.resolve_expression(compiler.query))\n        dist_sql, dist_params = self.process_distance(compiler, connection)\n        return (\n            \"%(func)s %(op)s %(dist)s\" % {\"func\": sql, \"op\": self.op, \"dist\": dist_sql},\n            (*params, *dist_params),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-41b37f3f68935a2f", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "3ea194980ba0b3825eb338c5c2fffbaeeed0a689bfb448fc707b55c1e7c2d116", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 23, "local_path": "code-injection/insert-dead-branches/I07__django__DistanceLookupFromFunction__050e3269.py", "order": 7, "original_content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "parent_variant_id": "pyint-feaf5e150d22-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/db/models/lookups.py#L358-L371", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "DistanceLookupFromFunction", "variant_id": "pyint-bd96050e3269-I07", "group_id": "py-41b37f3f68935a2f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 78, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f806c2a2d855-I08", "source": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\nclass DistanceLookupFromFunction(DistanceLookupBase):\n    def as_sql(self, compiler, connection):\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        spheroid = (\n            len(self.rhs_params) == 2 and self.rhs_params[-1] == \"spheroid\"\n        ) or None\n        distance_expr = connection.ops.distance_expr_for_lookup(\n            self.lhs, self.rhs, spheroid=spheroid\n        )\n        sql, params = compiler.compile(distance_expr.resolve_expression(compiler.query))\n        dist_sql, dist_params = self.process_distance(compiler, connection)\n        return (\n            \"%(func)s %(op)s %(dist)s\" % {\"func\": sql, \"op\": self.op, \"dist\": dist_sql},\n            (*params, *dist_params),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-41b37f3f68935a2f", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "8f1b91e72b9e40fc875e195ca3d0ad1511d71393502935c7194a7cdb00b5a939", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 26, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__DistanceLookupFromFunction__c2a2d855.py", "order": 8, "original_content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "parent_variant_id": "pyint-feaf5e150d22-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/db/models/lookups.py#L358-L371", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "DistanceLookupFromFunction", "variant_id": "pyint-f806c2a2d855-I08", "group_id": "py-41b37f3f68935a2f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 79, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0aa933b55769-I09", "source": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\nclass DistanceLookupFromFunction(DistanceLookupBase):\n    def as_sql(self, compiler, connection):\n        lI0O_4886f00d, lI0O_a8df735e = 0, 0\n        while lI0O_a8df735e < 2:\n            lI0O_4886f00d ^= (lI0O_a8df735e << 1) ^ 0x5\n            lI0O_a8df735e += 1\n        lI0O_4886f00d ^= lI0O_4886f00d\n        spheroid = (\n            len(self.rhs_params) == 2 and self.rhs_params[-1] == \"spheroid\"\n        ) or None\n        distance_expr = connection.ops.distance_expr_for_lookup(\n            self.lhs, self.rhs, spheroid=spheroid\n        )\n        sql, params = compiler.compile(distance_expr.resolve_expression(compiler.query))\n        dist_sql, dist_params = self.process_distance(compiler, connection)\n        return (\n            \"%(func)s %(op)s %(dist)s\" % {\"func\": sql, \"op\": self.op, \"dist\": dist_sql},\n            (*params, *dist_params),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-41b37f3f68935a2f", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "5e4f12a59cc1d1938989f16b1238522a6ae9ed0b68676bbac5e6df8c94017a16", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 26, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__DistanceLookupFromFunction__33b55769.py", "order": 9, "original_content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "parent_variant_id": "pyint-feaf5e150d22-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/db/models/lookups.py#L358-L371", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 2}, "unit_kind": "class", "unit_name": "DistanceLookupFromFunction", "variant_id": "pyint-0aa933b55769-I09", "group_id": "py-41b37f3f68935a2f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 80, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a92ceff1d2eb-I10", "source": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\nclass DistanceLookupFromFunction(DistanceLookupBase):\n    def as_sql(self, compiler, connection):\n        spheroid = (             len(self.rhs_params) == 2 and self.rhs_params[-1] == \"spheroid\"         ) or None\n        distance_expr = connection.ops.distance_expr_for_lookup(\n            self.lhs, self.rhs, spheroid=spheroid         )\n        sql, params = compiler.compile(distance_expr.resolve_expression(compiler.query))\n        dist_sql, dist_params = self.process_distance(compiler, connection)\n        return (\n            \"%(func)s %(op)s %(dist)s\" % {\"func\": sql, \"op\": self.op, \"dist\": dist_sql},\n            (*params, *dist_params),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-41b37f3f68935a2f", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "3d66e05b43b24cfb24b73a68f84d9217ca9d3a677dfc03500c33ff958f5b2098", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 18, "local_path": "layout/partially-compact-layout/I10__django__DistanceLookupFromFunction__eff1d2eb.py", "order": 10, "original_content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "parent_variant_id": "pyint-feaf5e150d22-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/db/models/lookups.py#L358-L371", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 8, "line_break_groups_removed": 3, "line_breaks_removed": 3, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "DistanceLookupFromFunction", "variant_id": "pyint-a92ceff1d2eb-I10", "group_id": "py-41b37f3f68935a2f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 81, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-821a89e515be-I11", "source": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\nclass DistanceLookupFromFunction(DistanceLookupBase):\n    def as_sql(self, compiler, connection):\n        a = 1\n        b = 1\n        c = 2\n        d = -1\n        spheroid = (\n            len(self.rhs_params) == (a + b) and self.rhs_params[-(c + d)] == \"spheroid\"\n        ) or None\n        distance_expr = connection.ops.distance_expr_for_lookup(\n            self.lhs, self.rhs, spheroid=spheroid\n        )\n        sql, params = compiler.compile(distance_expr.resolve_expression(compiler.query))\n        dist_sql, dist_params = self.process_distance(compiler, connection)\n        return (\n            \"%(func)s %(op)s %(dist)s\" % {\"func\": sql, \"op\": self.op, \"dist\": dist_sql},\n            (*params, *dist_params),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-41b37f3f68935a2f", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "cd1b6c032d9fee3727b4e282a4a18b2b34db582a7f87ca68c5c9b803cff8e54d", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 25, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__DistanceLookupFromFunction__89e515be.py", "order": 11, "original_content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "parent_variant_id": "pyint-feaf5e150d22-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/db/models/lookups.py#L358-L371", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 2, "intermediate_variables_introduced": 4, "statements_augmented": 1}, "unit_kind": "class", "unit_name": "DistanceLookupFromFunction", "variant_id": "pyint-821a89e515be-I11", "group_id": "py-41b37f3f68935a2f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 82, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bbeb82f65ed0-I12", "source": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\nclass DistanceLookupFromFunction(DistanceLookupBase):\n    def as_sql(self, compiler, connection):\n        spheroid = (\n            len(self.rhs_params) == 2 and self.rhs_params[-1] == \"spheroid\"\n        ) or None\n        distance_expr = connection.ops.distance_expr_for_lookup(\n            self.lhs, self.rhs, spheroid=spheroid\n        )\n        sql, params = compiler.compile(distance_expr.resolve_expression(compiler.query))\n        dist_sql, dist_params = self.process_distance(compiler, connection)\n        return (\n            \"%(func)s %(op)s %(dist)s\" % {\"func\": sql, \"op\": self.op, \"dist\": dist_sql},\n            (*params, *dist_params),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-41b37f3f68935a2f", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 21, "local_path": "data-flow/inline-intermediate-variables/I12__django__DistanceLookupFromFunction__82f65ed0.py", "order": 12, "original_content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "parent_variant_id": "pyint-feaf5e150d22-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/db/models/lookups.py#L358-L371", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "DistanceLookupFromFunction", "variant_id": "pyint-bbeb82f65ed0-I12", "group_id": "py-41b37f3f68935a2f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 83, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-383da6ce2d1e-I13", "source": "from django.contrib.gis.db.models.fields import BaseSpatialField\nfrom django.contrib.gis.measure import Distance\nfrom django.db import NotSupportedError\nfrom django.db.models import Expression, Lookup, Transform\nfrom django.db.models.sql.query import Query\nfrom django.utils.regex_helper import _lazy_re_compile\n\nclass DistanceLookupFromFunction(DistanceLookupBase):\n    def as_sql(self, compiler, connection):\n        spheroid = (\n            len(self.rhs_params) == 2 and self.rhs_params[-1] == \"spheroid\"\n        ) or None\n        distance_expr = connection.ops.distance_expr_for_lookup(\n            self.lhs, self.rhs, spheroid=spheroid\n        )\n        sql, params = compiler.compile(distance_expr.resolve_expression(compiler.query))\n        dist_sql, dist_params = self.process_distance(compiler, connection)\n        return (\n            \"%(func)s %(op)s %(dist)s\" % {\"func\": sql, \"op\": self.op, \"dist\": dist_sql},\n            (*params, *dist_params),\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-41b37f3f68935a2f", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 21, "local_path": "control-flow/lower-for-to-while/I13__django__DistanceLookupFromFunction__a6ce2d1e.py", "order": 13, "original_content_sha256": "fc2a4f44e693e32a260c47ee6a8935aa635c9072b173cb8f4d263fa8f189f7b3", "parent_variant_id": "pyint-feaf5e150d22-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/db/models/lookups.py#L358-L371", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "DistanceLookupFromFunction", "variant_id": "pyint-383da6ce2d1e-I13", "group_id": "py-41b37f3f68935a2f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 84, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1e82ee0019f6-SRC", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2.loaders import BaseLoader\nfrom werkzeug.routing import RequestRedirect\nfrom .blueprints import Blueprint\nfrom .globals import _cv_app\nfrom .sansio.app import App\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n    \"\"\"Raised from request.files during debugging.  The idea is that it can\n    provide a better error message than just a generic KeyError/BadRequest.\n    \"\"\"\n\n    def __init__(self, request: Request, key: str) -> None:\n        form_matches = request.form.getlist(key)\n        buf = [\n            f\"You tried to access the file {key!r} in the request.files\"\n            \" dictionary but it does not exist. The mimetype for the\"\n            f\" request is {request.mimetype!r} instead of\"\n            \" 'multipart/form-data' which means that no file contents\"\n            \" were transmitted. To fix this error you should provide\"\n            ' enctype=\"multipart/form-data\" in your form.'\n        ]\n        if form_matches:\n            names = \", \".join(repr(x) for x in form_matches)\n            buf.append(\n                \"\\n\\nThe browser instead transmitted some file names. \"\n                f\"This was submitted: {names}\"\n            )\n        self.msg = \"\".join(buf)\n\n    def __str__(self) -> str:\n        return self.msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-43102cfb49c2d997", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 33, "local_path": "source-original/SRC__flask__DebugFilesKeyError__ee0019f6.py", "order": 0, "original_content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/debughelpers.py#L23-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "DebugFilesKeyError", "variant_id": "pyint-1e82ee0019f6-SRC", "group_id": "py-43102cfb49c2d997", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 477, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-400e8bd3620f-I01", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2.loaders import BaseLoader\nfrom werkzeug.routing import RequestRedirect\nfrom .blueprints import Blueprint\nfrom .globals import _cv_app\nfrom .sansio.app import App\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n    \n\n    def __init__(self, request: Request, key: str) -> None:\n        form_matches = request.form.getlist(key)\n        buf = [\n            f\"You tried to access the file {key!r} in the request.files\"\n            \" dictionary but it does not exist. The mimetype for the\"\n            f\" request is {request.mimetype!r} instead of\"\n            \" 'multipart/form-data' which means that no file contents\"\n            \" were transmitted. To fix this error you should provide\"\n            ' enctype=\"multipart/form-data\" in your form.'\n        ]\n        if form_matches:\n            names = \", \".join(repr(x) for x in form_matches)\n            buf.append(\n                \"\\n\\nThe browser instead transmitted some file names. \"\n                f\"This was submitted: {names}\"\n            )\n        self.msg = \"\".join(buf)\n\n    def __str__(self) -> str:\n        return self.msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-43102cfb49c2d997", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "0cf406f9b8461bd08d6797308e48177cbdff00fcef07d8308e736590e0bfbe07", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 31, "local_path": "comments/remove-comments/I01__flask__DebugFilesKeyError__8bd3620f.py", "order": 1, "original_content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "parent_variant_id": "pyint-1e82ee0019f6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/debughelpers.py#L23-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 155, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "DebugFilesKeyError", "variant_id": "pyint-400e8bd3620f-I01", "group_id": "py-43102cfb49c2d997", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 478, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9176e32f493e-I02", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2.loaders import BaseLoader\nfrom werkzeug.routing import RequestRedirect\nfrom .blueprints import Blueprint\nfrom .globals import _cv_app\nfrom .sansio.app import App\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n    \"\"\"Raised from request.files during debugging.  The idea is that it can\n    provide a better error message than just a generic KeyError/BadRequest.\n    \"\"\"\n\n    def __init__(self, req: Request, key2: str) -> None:\n        form2 = req.form.getlist(key2)\n        buf2 = [\n            f\"You tried to access the file {key2!r} in the request.files\"\n            \" dictionary but it does not exist. The mimetype for the\"\n            f\" request is {req.mimetype!r} instead of\"\n            \" 'multipart/form-data' which means that no file contents\"\n            \" were transmitted. To fix this error you should provide\"\n            ' enctype=\"multipart/form-data\" in your form.'\n        ]\n        if form2:\n            nam = \", \".join(repr(x2) for x2 in form2)\n            buf2.append(\n                \"\\n\\nThe browser instead transmitted some file names. \"\n                f\"This was submitted: {nam}\"\n            )\n        self.msg = \"\".join(buf2)\n\n    def __str__(self) -> str:\n        return self.msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-43102cfb49c2d997", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "0882616894f60bc20b91c3ab1b089051713d65efddb44be380708da2c625c1d8", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 33, "local_path": "identifiers/shorten-identifiers/I02__flask__DebugFilesKeyError__e32f493e.py", "order": 2, "original_content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "parent_variant_id": "pyint-1e82ee0019f6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/debughelpers.py#L23-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 16, "identifiers_declared": 6}, "unit_kind": "class", "unit_name": "DebugFilesKeyError", "variant_id": "pyint-9176e32f493e-I02", "group_id": "py-43102cfb49c2d997", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 479, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-91965a98f193-I03", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2.loaders import BaseLoader\nfrom werkzeug.routing import RequestRedirect\nfrom .blueprints import Blueprint\nfrom .globals import _cv_app\nfrom .sansio.app import App\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n    \"\"\"Raised from request.files during debugging.  The idea is that it can\n    provide a better error message than just a generic KeyError/BadRequest.\n    \"\"\"\n\n    def __init__(self, version: Request, map: str) -> None:\n        sharedResult = version.form.getlist(map)\n        age = [\n            f\"You tried to access the file {map!r} in the request.files\"\n            \" dictionary but it does not exist. The mimetype for the\"\n            f\" request is {version.mimetype!r} instead of\"\n            \" 'multipart/form-data' which means that no file contents\"\n            \" were transmitted. To fix this error you should provide\"\n            ' enctype=\"multipart/form-data\" in your form.'\n        ]\n        if sharedResult:\n            price = \", \".join(repr(node) for node in sharedResult)\n            age.append(\n                \"\\n\\nThe browser instead transmitted some file names. \"\n                f\"This was submitted: {price}\"\n            )\n        self.msg = \"\".join(age)\n\n    def __str__(self) -> str:\n        return self.msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-43102cfb49c2d997", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "c19c095b6a24ed33bc2f2ab021553e0be59e784d17ee1d9440fee2c576e8ee01", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 33, "local_path": "identifiers/mislead-identifiers/I03__flask__DebugFilesKeyError__5a98f193.py", "order": 3, "original_content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "parent_variant_id": "pyint-1e82ee0019f6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/debughelpers.py#L23-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 16, "identifiers_declared": 6, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 3, "local_exact_length_matches": 5, "local_random_pool_selections": 6, "local_total_length_difference": 3, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "DebugFilesKeyError", "variant_id": "pyint-91965a98f193-I03", "group_id": "py-43102cfb49c2d997", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 480, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3e9944ce72f5-I04", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2.loaders import BaseLoader\nfrom werkzeug.routing import RequestRedirect\nfrom .blueprints import Blueprint\nfrom .globals import _cv_app\nfrom .sansio.app import App\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n    \"\"\"Raised from request.files during debugging.  The idea is that it can\n    provide a better error message than just a generic KeyError/BadRequest.\n    \"\"\"\n\n    def __init__(self, a: Request, b: str) -> None:\n        c = a.form.getlist(b)\n        d = [\n            f\"You tried to access the file {b!r} in the request.files\"\n            \" dictionary but it does not exist. The mimetype for the\"\n            f\" request is {a.mimetype!r} instead of\"\n            \" 'multipart/form-data' which means that no file contents\"\n            \" were transmitted. To fix this error you should provide\"\n            ' enctype=\"multipart/form-data\" in your form.'\n        ]\n        if c:\n            e = \", \".join(repr(f) for f in c)\n            d.append(\n                \"\\n\\nThe browser instead transmitted some file names. \"\n                f\"This was submitted: {e}\"\n            )\n        self.msg = \"\".join(d)\n\n    def __str__(self) -> str:\n        return self.msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-43102cfb49c2d997", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b06852cc74cc9708df1e2b0e88e76b136e7d6304055584b364138ce9b947e9ab", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 33, "local_path": "identifiers/garble-identifiers/I04__flask__DebugFilesKeyError__44ce72f5.py", "order": 4, "original_content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "parent_variant_id": "pyint-1e82ee0019f6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/debughelpers.py#L23-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 16, "identifiers_declared": 6}, "unit_kind": "class", "unit_name": "DebugFilesKeyError", "variant_id": "pyint-3e9944ce72f5-I04", "group_id": "py-43102cfb49c2d997", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 481, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bfcdf163c3cc-I05", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2.loaders import BaseLoader\nfrom werkzeug.routing import RequestRedirect\nfrom .blueprints import Blueprint\nfrom .globals import _cv_app\nfrom .sansio.app import App\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n    \"\"\"Raised from request.files during debugging.  The idea is that it can\n    provide a better error message than just a generic KeyError/BadRequest.\n    \"\"\"\n\n    def __init__(self, request: Request, key: str) -> None:\n        form_matches = request.form.getlist(key)\n        buf = [\n            f\"You tried to access the file {key!r} in the request.files\"\n            \" dictionary but it does not exist. The mimetype for the\"\n            f\" request is {request.mimetype!r} instead of\"\n            \" 'multipart/form-data' which means that no file contents\"\n            \" were transmitted. To fix this error you should provide\"\n            ' enctype=\"multipart/form-data\" in your form.'\n        ]\n        if form_matches:\n            names = \", \".join(repr(x) for x in form_matches)\n            buf.append(\n                \"\\n\\nThe browser instead transmitted some file names. \"\n                f\"This was submitted: {names}\"\n            )\n        self.msg = \"\".join(buf)\n\n    def __str__(self) -> str:\n        return self.msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-43102cfb49c2d997", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 33, "local_path": "expressions/encode-integer-literals/I05__flask__DebugFilesKeyError__f163c3cc.py", "order": 5, "original_content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "parent_variant_id": "pyint-1e82ee0019f6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/debughelpers.py#L23-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "DebugFilesKeyError", "variant_id": "pyint-bfcdf163c3cc-I05", "group_id": "py-43102cfb49c2d997", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 482, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f1a8bc187542-I06", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2.loaders import BaseLoader\nfrom werkzeug.routing import RequestRedirect\nfrom .blueprints import Blueprint\nfrom .globals import _cv_app\nfrom .sansio.app import App\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n    \"\"\"Raised from request.files during debugging.  The idea is that it can\n    provide a better error message than just a generic KeyError/BadRequest.\n    \"\"\"\n\n    def __init__(self, request: Request, key: str) -> None:\n        form_matches = request.form.getlist(key)\n        buf = [\n            f\"You tried to access the file {key!r} in the request.files\"\n            \" dictionary but it does not exist. The mimetype for the\"\n            f\" request is {request.mimetype!r} instead of\"\n            \" 'multipart/form-data' which means that no file contents\"\n            \" were transmitted. To fix this error you should provide\"\n            ' enctype=\"multipart/form-data\" in your form.'\n        ]\n        if not (form_matches):\n            pass\n        else:\n            names = \", \".join(repr(x) for x in form_matches)\n            buf.append(\n                \"\\n\\nThe browser instead transmitted some file names. \"\n                f\"This was submitted: {names}\"\n            )\n        self.msg = \"\".join(buf)\n\n    def __str__(self) -> str:\n        return self.msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-43102cfb49c2d997", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "963bc48d7b991dfc817e7778f1287d10dad6452e69d6ee0d7d24c357884280f8", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 35, "local_path": "expressions/invert-conditions/I06__flask__DebugFilesKeyError__bc187542.py", "order": 6, "original_content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "parent_variant_id": "pyint-1e82ee0019f6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/debughelpers.py#L23-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "DebugFilesKeyError", "variant_id": "pyint-f1a8bc187542-I06", "group_id": "py-43102cfb49c2d997", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 483, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8280ee2c175b-I07", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2.loaders import BaseLoader\nfrom werkzeug.routing import RequestRedirect\nfrom .blueprints import Blueprint\nfrom .globals import _cv_app\nfrom .sansio.app import App\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n    \"\"\"Raised from request.files during debugging.  The idea is that it can\n    provide a better error message than just a generic KeyError/BadRequest.\n    \"\"\"\n\n    def __init__(self, request: Request, key: str) -> None:\n        if ((0xf943 ^ 0xf943) != 0):\n            raise AssertionError()\n        form_matches = request.form.getlist(key)\n        buf = [\n            f\"You tried to access the file {key!r} in the request.files\"\n            \" dictionary but it does not exist. The mimetype for the\"\n            f\" request is {request.mimetype!r} instead of\"\n            \" 'multipart/form-data' which means that no file contents\"\n            \" were transmitted. To fix this error you should provide\"\n            ' enctype=\"multipart/form-data\" in your form.'\n        ]\n        if form_matches:\n            names = \", \".join(repr(x) for x in form_matches)\n            buf.append(\n                \"\\n\\nThe browser instead transmitted some file names. \"\n                f\"This was submitted: {names}\"\n            )\n        self.msg = \"\".join(buf)\n\n    def __str__(self) -> str:\n        if ((0x9a4c ^ 0x9a4c) != 0):\n            raise AssertionError()\n        return self.msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-43102cfb49c2d997", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "7ac7924369065d39074e61d51360c304c472c3ed3af9892b9693e51f0b3ac470", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 37, "local_path": "code-injection/insert-dead-branches/I07__flask__DebugFilesKeyError__ee2c175b.py", "order": 7, "original_content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "parent_variant_id": "pyint-1e82ee0019f6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/debughelpers.py#L23-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "DebugFilesKeyError", "variant_id": "pyint-8280ee2c175b-I07", "group_id": "py-43102cfb49c2d997", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 484, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-459e498cd5b4-I08", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2.loaders import BaseLoader\nfrom werkzeug.routing import RequestRedirect\nfrom .blueprints import Blueprint\nfrom .globals import _cv_app\nfrom .sansio.app import App\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n    \"\"\"Raised from request.files during debugging.  The idea is that it can\n    provide a better error message than just a generic KeyError/BadRequest.\n    \"\"\"\n\n    def __init__(self, request: Request, key: str) -> None:\n        form_matches = request.form.getlist(key)\n        buf = [\n            f\"You tried to access the file {key!r} in the request.files\"\n            \" dictionary but it does not exist. The mimetype for the\"\n            f\" request is {request.mimetype!r} instead of\"\n            \" 'multipart/form-data' which means that no file contents\"\n            \" were transmitted. To fix this error you should provide\"\n            ' enctype=\"multipart/form-data\" in your form.'\n        ]\n        if form_matches:\n            names = \", \".join(repr(x) for x in form_matches)\n            buf.append(\n                \"\\n\\nThe browser instead transmitted some file names. \"\n                f\"This was submitted: {names}\"\n            )\n        self.msg = \"\".join(buf)\n\n    def __str__(self) -> str:\n        feature_enabled = False\n        for toggle_count in range(3):\n            feature_enabled = not feature_enabled\n        return self.msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-43102cfb49c2d997", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d34c095259165d62c922bd7535c4ce3a80898795abfbea0de053be1659848377", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 36, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__DebugFilesKeyError__498cd5b4.py", "order": 8, "original_content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "parent_variant_id": "pyint-1e82ee0019f6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/debughelpers.py#L23-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 7}, "unit_kind": "class", "unit_name": "DebugFilesKeyError", "variant_id": "pyint-459e498cd5b4-I08", "group_id": "py-43102cfb49c2d997", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 485, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f639a1b318bf-I09", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2.loaders import BaseLoader\nfrom werkzeug.routing import RequestRedirect\nfrom .blueprints import Blueprint\nfrom .globals import _cv_app\nfrom .sansio.app import App\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n    \"\"\"Raised from request.files during debugging.  The idea is that it can\n    provide a better error message than just a generic KeyError/BadRequest.\n    \"\"\"\n\n    def __init__(self, request: Request, key: str) -> None:\n        form_matches = request.form.getlist(key)\n        buf = [\n            f\"You tried to access the file {key!r} in the request.files\"\n            \" dictionary but it does not exist. The mimetype for the\"\n            f\" request is {request.mimetype!r} instead of\"\n            \" 'multipart/form-data' which means that no file contents\"\n            \" were transmitted. To fix this error you should provide\"\n            ' enctype=\"multipart/form-data\" in your form.'\n        ]\n        if form_matches:\n            names = \", \".join(repr(x) for x in form_matches)\n            buf.append(\n                \"\\n\\nThe browser instead transmitted some file names. \"\n                f\"This was submitted: {names}\"\n            )\n        self.msg = \"\".join(buf)\n\n    def __str__(self) -> str:\n        lI0O_b747243e, lI0O_89a60444 = 0x6a66, True\n        while lI0O_89a60444:\n            lI0O_b747243e ^= 0x6a66\n            lI0O_89a60444 = False\n        return self.msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-43102cfb49c2d997", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "c0b0e25a0915c01a50e3e236bad72bb744fea0af27df85b6286096c3ea0bed27", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 37, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__DebugFilesKeyError__a1b318bf.py", "order": 9, "original_content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "parent_variant_id": "pyint-1e82ee0019f6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/debughelpers.py#L23-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 7}, "unit_kind": "class", "unit_name": "DebugFilesKeyError", "variant_id": "pyint-f639a1b318bf-I09", "group_id": "py-43102cfb49c2d997", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 486, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-94e35b92ed03-I10", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2.loaders import BaseLoader\nfrom werkzeug.routing import RequestRedirect\nfrom .blueprints import Blueprint\nfrom .globals import _cv_app\nfrom .sansio.app import App\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n    \"\"\"Raised from request.files during debugging.  The idea is that it can\n    provide a better error message than just a generic KeyError/BadRequest.\n    \"\"\"\n\n    def __init__(self, request: Request, key: str) -> None:\n        form_matches = request.form.getlist(key)\n        buf = [\n            f\"You tried to access the file {key!r} in the request.files\"             \" dictionary but it does not exist. The mimetype for the\"\n            f\" request is {request.mimetype!r} instead of\"             \" 'multipart/form-data' which means that no file contents\"\n            \" were transmitted. To fix this error you should provide\"\n            ' enctype=\"multipart/form-data\" in your form.'\n        ]\n        if form_matches:\n            names = \", \".join(repr(x) for x in form_matches)\n            buf.append(                 \"\\n\\nThe browser instead transmitted some file names. \"                 f\"This was submitted: {names}\"             )\n        self.msg = \"\".join(buf)\n\n    def __str__(self) -> str:\n        return self.msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-43102cfb49c2d997", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "831e83022c93ed7801eef6435cfa0802320112eacaf07afb57e65850524572ff", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 28, "local_path": "layout/partially-compact-layout/I10__flask__DebugFilesKeyError__5b92ed03.py", "order": 10, "original_content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "parent_variant_id": "pyint-1e82ee0019f6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/debughelpers.py#L23-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 13, "line_break_groups_removed": 5, "line_breaks_removed": 5, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "DebugFilesKeyError", "variant_id": "pyint-94e35b92ed03-I10", "group_id": "py-43102cfb49c2d997", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 487, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a9be4792115d-I11", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2.loaders import BaseLoader\nfrom werkzeug.routing import RequestRedirect\nfrom .blueprints import Blueprint\nfrom .globals import _cv_app\nfrom .sansio.app import App\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n    \"\"\"Raised from request.files during debugging.  The idea is that it can\n    provide a better error message than just a generic KeyError/BadRequest.\n    \"\"\"\n\n    def __init__(self, request: Request, key: str) -> None:\n        form_matches = request.form.getlist(key)\n        buf = [\n            f\"You tried to access the file {key!r} in the request.files\"\n            \" dictionary but it does not exist. The mimetype for the\"\n            f\" request is {request.mimetype!r} instead of\"\n            \" 'multipart/form-data' which means that no file contents\"\n            \" were transmitted. To fix this error you should provide\"\n            ' enctype=\"multipart/form-data\" in your form.'\n        ]\n        if form_matches:\n            names = \", \".join(repr(x) for x in form_matches)\n            buf.append(\n                \"\\n\\nThe browser instead transmitted some file names. \"\n                f\"This was submitted: {names}\"\n            )\n        self.msg = \"\".join(buf)\n\n    def __str__(self) -> str:\n        return self.msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-43102cfb49c2d997", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 33, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__DebugFilesKeyError__4792115d.py", "order": 11, "original_content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "parent_variant_id": "pyint-1e82ee0019f6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/debughelpers.py#L23-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "DebugFilesKeyError", "variant_id": "pyint-a9be4792115d-I11", "group_id": "py-43102cfb49c2d997", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 488, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e54029042b94-I12", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2.loaders import BaseLoader\nfrom werkzeug.routing import RequestRedirect\nfrom .blueprints import Blueprint\nfrom .globals import _cv_app\nfrom .sansio.app import App\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n    \"\"\"Raised from request.files during debugging.  The idea is that it can\n    provide a better error message than just a generic KeyError/BadRequest.\n    \"\"\"\n\n    def __init__(self, request: Request, key: str) -> None:\n        form_matches = request.form.getlist(key)\n        buf = [\n            f\"You tried to access the file {key!r} in the request.files\"\n            \" dictionary but it does not exist. The mimetype for the\"\n            f\" request is {request.mimetype!r} instead of\"\n            \" 'multipart/form-data' which means that no file contents\"\n            \" were transmitted. To fix this error you should provide\"\n            ' enctype=\"multipart/form-data\" in your form.'\n        ]\n        if form_matches:\n            names = \", \".join(repr(x) for x in form_matches)\n            buf.append(\n                \"\\n\\nThe browser instead transmitted some file names. \"\n                f\"This was submitted: {names}\"\n            )\n        self.msg = \"\".join(buf)\n\n    def __str__(self) -> str:\n        return self.msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-43102cfb49c2d997", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 33, "local_path": "data-flow/inline-intermediate-variables/I12__flask__DebugFilesKeyError__29042b94.py", "order": 12, "original_content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "parent_variant_id": "pyint-1e82ee0019f6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/debughelpers.py#L23-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "DebugFilesKeyError", "variant_id": "pyint-e54029042b94-I12", "group_id": "py-43102cfb49c2d997", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 489, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8862cf36a291-I13", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2.loaders import BaseLoader\nfrom werkzeug.routing import RequestRedirect\nfrom .blueprints import Blueprint\nfrom .globals import _cv_app\nfrom .sansio.app import App\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n    \"\"\"Raised from request.files during debugging.  The idea is that it can\n    provide a better error message than just a generic KeyError/BadRequest.\n    \"\"\"\n\n    def __init__(self, request: Request, key: str) -> None:\n        form_matches = request.form.getlist(key)\n        buf = [\n            f\"You tried to access the file {key!r} in the request.files\"\n            \" dictionary but it does not exist. The mimetype for the\"\n            f\" request is {request.mimetype!r} instead of\"\n            \" 'multipart/form-data' which means that no file contents\"\n            \" were transmitted. To fix this error you should provide\"\n            ' enctype=\"multipart/form-data\" in your form.'\n        ]\n        if form_matches:\n            names = \", \".join(repr(x) for x in form_matches)\n            buf.append(\n                \"\\n\\nThe browser instead transmitted some file names. \"\n                f\"This was submitted: {names}\"\n            )\n        self.msg = \"\".join(buf)\n\n    def __str__(self) -> str:\n        return self.msg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-43102cfb49c2d997", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 33, "local_path": "control-flow/lower-for-to-while/I13__flask__DebugFilesKeyError__cf36a291.py", "order": 13, "original_content_sha256": "b0ce3876e6f8fd5737233f77747eca688e4c908ceb4b54e3da90d3a55c7a2feb", "parent_variant_id": "pyint-1e82ee0019f6-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/debughelpers.py#L23-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "DebugFilesKeyError", "variant_id": "pyint-8862cf36a291-I13", "group_id": "py-43102cfb49c2d997", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 490, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bedbeb4d5970-SRC", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-4b5f37cac24402cd", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 10, "local_path": "source-original/SRC__requests__ConnectTimeout__eb4d5970.py", "order": 0, "original_content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L91-L95", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "ConnectTimeout", "variant_id": "pyint-bedbeb4d5970-SRC", "group_id": "py-4b5f37cac24402cd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1009, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-18f000153ee8-I01", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-4b5f37cac24402cd", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "2f61278bc3175566dc2bf4c52c7b1de0782560c597a14af94c6fdb8b7ebd3ea6", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 7, "local_path": "comments/remove-comments/I01__requests__ConnectTimeout__00153ee8.py", "order": 1, "original_content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "parent_variant_id": "pyint-bedbeb4d5970-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L91-L95", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 132, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "ConnectTimeout", "variant_id": "pyint-18f000153ee8-I01", "group_id": "py-4b5f37cac24402cd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1010, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-04dc9b78b9d6-I02", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-4b5f37cac24402cd", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 10, "local_path": "identifiers/shorten-identifiers/I02__requests__ConnectTimeout__9b78b9d6.py", "order": 2, "original_content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "parent_variant_id": "pyint-bedbeb4d5970-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L91-L95", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 0, "identifiers_declared": 0}, "unit_kind": "class", "unit_name": "ConnectTimeout", "variant_id": "pyint-04dc9b78b9d6-I02", "group_id": "py-4b5f37cac24402cd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1011, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-59427968d4b8-I03", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-4b5f37cac24402cd", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 10, "local_path": "identifiers/mislead-identifiers/I03__requests__ConnectTimeout__7968d4b8.py", "order": 3, "original_content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "parent_variant_id": "pyint-bedbeb4d5970-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L91-L95", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 0, "identifiers_declared": 0, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 0, "local_random_pool_selections": 0, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "ConnectTimeout", "variant_id": "pyint-59427968d4b8-I03", "group_id": "py-4b5f37cac24402cd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1012, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-db93c6560a63-I04", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-4b5f37cac24402cd", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 10, "local_path": "identifiers/garble-identifiers/I04__requests__ConnectTimeout__c6560a63.py", "order": 4, "original_content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "parent_variant_id": "pyint-bedbeb4d5970-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L91-L95", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 0, "identifiers_declared": 0}, "unit_kind": "class", "unit_name": "ConnectTimeout", "variant_id": "pyint-db93c6560a63-I04", "group_id": "py-4b5f37cac24402cd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1013, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c0f6cf2dbd69-I05", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-4b5f37cac24402cd", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 10, "local_path": "expressions/encode-integer-literals/I05__requests__ConnectTimeout__cf2dbd69.py", "order": 5, "original_content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "parent_variant_id": "pyint-bedbeb4d5970-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L91-L95", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "ConnectTimeout", "variant_id": "pyint-c0f6cf2dbd69-I05", "group_id": "py-4b5f37cac24402cd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1014, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b7b217e3dc2d-I06", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-4b5f37cac24402cd", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 10, "local_path": "expressions/invert-conditions/I06__requests__ConnectTimeout__17e3dc2d.py", "order": 6, "original_content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "parent_variant_id": "pyint-bedbeb4d5970-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L91-L95", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "ConnectTimeout", "variant_id": "pyint-b7b217e3dc2d-I06", "group_id": "py-4b5f37cac24402cd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1015, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ce70c88c3edb-I07", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-4b5f37cac24402cd", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 10, "local_path": "code-injection/insert-dead-branches/I07__requests__ConnectTimeout__c88c3edb.py", "order": 7, "original_content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "parent_variant_id": "pyint-bedbeb4d5970-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L91-L95", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 0}, "unit_kind": "class", "unit_name": "ConnectTimeout", "variant_id": "pyint-ce70c88c3edb-I07", "group_id": "py-4b5f37cac24402cd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1016, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0df73684105d-I08", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-4b5f37cac24402cd", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 10, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__ConnectTimeout__3684105d.py", "order": 8, "original_content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "parent_variant_id": "pyint-bedbeb4d5970-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L91-L95", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 0, "readable_lines_injected": 0, "readable_template_index": -1}, "unit_kind": "class", "unit_name": "ConnectTimeout", "variant_id": "pyint-0df73684105d-I08", "group_id": "py-4b5f37cac24402cd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1017, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cb46e2424dd7-I09", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-4b5f37cac24402cd", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 10, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__ConnectTimeout__e2424dd7.py", "order": 9, "original_content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "parent_variant_id": "pyint-bedbeb4d5970-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L91-L95", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 0, "low_readability_template_index": -1}, "unit_kind": "class", "unit_name": "ConnectTimeout", "variant_id": "pyint-cb46e2424dd7-I09", "group_id": "py-4b5f37cac24402cd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1018, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7bb951a3dc2f-I10", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-4b5f37cac24402cd", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 10, "local_path": "layout/partially-compact-layout/I10__requests__ConnectTimeout__51a3dc2f.py", "order": 10, "original_content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "parent_variant_id": "pyint-bedbeb4d5970-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L91-L95", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 2, "line_break_groups_removed": 0, "line_breaks_removed": 0, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "ConnectTimeout", "variant_id": "pyint-7bb951a3dc2f-I10", "group_id": "py-4b5f37cac24402cd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1019, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dbfa20772fc7-I11", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-4b5f37cac24402cd", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 10, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__ConnectTimeout__20772fc7.py", "order": 11, "original_content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "parent_variant_id": "pyint-bedbeb4d5970-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L91-L95", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "ConnectTimeout", "variant_id": "pyint-dbfa20772fc7-I11", "group_id": "py-4b5f37cac24402cd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1020, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a9fc213a95e4-I12", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-4b5f37cac24402cd", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 10, "local_path": "data-flow/inline-intermediate-variables/I12__requests__ConnectTimeout__213a95e4.py", "order": 12, "original_content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "parent_variant_id": "pyint-bedbeb4d5970-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L91-L95", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "ConnectTimeout", "variant_id": "pyint-a9fc213a95e4-I12", "group_id": "py-4b5f37cac24402cd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1021, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-663ee6babdaa-I13", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-4b5f37cac24402cd", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 10, "local_path": "control-flow/lower-for-to-while/I13__requests__ConnectTimeout__e6babdaa.py", "order": 13, "original_content_sha256": "ffb71211dd20c3efcdb40f50dc8230b2d5f3831373e9b4ab20573bb4296a452f", "parent_variant_id": "pyint-bedbeb4d5970-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L91-L95", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "ConnectTimeout", "variant_id": "pyint-663ee6babdaa-I13", "group_id": "py-4b5f37cac24402cd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1022, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e8ea6259daac-SRC", "source": "from itertools import chain\nfrom django.core.exceptions import (\n    NON_FIELD_ERRORS,\n    FieldError,\n    ImproperlyConfigured,\n    ValidationError,\n)\nfrom django.core.validators import ProhibitNullCharactersValidator\nfrom django.db.models.utils import AltersData, get_blank_choice_label\nfrom django.forms.fields import ChoiceField, Field\nfrom django.forms.forms import BaseForm, DeclarativeFieldsMetaclass\nfrom django.forms.formsets import BaseFormSet, formset_factory\nfrom django.forms.utils import ErrorList\nfrom django.forms.widgets import (\n    HiddenInput,\n    MultipleHiddenInput,\n    RadioSelect,\n    SelectMultiple,\n)\nfrom django.utils.choices import BaseChoiceIterator\nfrom django.utils.hashable import make_hashable\nfrom django.utils.text import capfirst, get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nclass InlineForeignKeyField(Field):\n    \"\"\"\n    A basic integer field that deals with validating the given value to a\n    given parent instance in an inline.\n    \"\"\"\n\n    widget = HiddenInput\n    default_error_messages = {\n        \"invalid_choice\": _(\"The inline value did not match the parent instance.\"),\n    }\n\n    def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs):\n        self.parent_instance = parent_instance\n        self.pk_field = pk_field\n        self.to_field = to_field\n        if self.parent_instance is not None:\n            if self.to_field:\n                kwargs[\"initial\"] = getattr(self.parent_instance, self.to_field)\n            else:\n                kwargs[\"initial\"] = self.parent_instance.pk\n        kwargs[\"required\"] = False\n        super().__init__(*args, **kwargs)\n\n    def clean(self, value):\n        if value in self.empty_values:\n            if self.pk_field:\n                return None\n            # if there is no value act as we did before.\n            return self.parent_instance\n        # ensure we compare the values as equal types.\n        if self.to_field:\n            orig = getattr(self.parent_instance, self.to_field)\n        else:\n            orig = self.parent_instance.pk\n        if str(value) != str(orig):\n            raise ValidationError(\n                self.error_messages[\"invalid_choice\"], code=\"invalid_choice\"\n            )\n        return self.parent_instance\n\n    def has_changed(self, initial, data):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-4f1adc9e150f5390", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 67, "local_path": "source-original/SRC__django__InlineForeignKeyField__6259daac.py", "order": 0, "original_content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/forms/models.py#L1376-L1417", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "InlineForeignKeyField", "variant_id": "pyint-e8ea6259daac-SRC", "group_id": "py-4f1adc9e150f5390", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 113, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-050fc5fdfe2d-I01", "source": "from itertools import chain\nfrom django.core.exceptions import (\n    NON_FIELD_ERRORS,\n    FieldError,\n    ImproperlyConfigured,\n    ValidationError,\n)\nfrom django.core.validators import ProhibitNullCharactersValidator\nfrom django.db.models.utils import AltersData, get_blank_choice_label\nfrom django.forms.fields import ChoiceField, Field\nfrom django.forms.forms import BaseForm, DeclarativeFieldsMetaclass\nfrom django.forms.formsets import BaseFormSet, formset_factory\nfrom django.forms.utils import ErrorList\nfrom django.forms.widgets import (\n    HiddenInput,\n    MultipleHiddenInput,\n    RadioSelect,\n    SelectMultiple,\n)\nfrom django.utils.choices import BaseChoiceIterator\nfrom django.utils.hashable import make_hashable\nfrom django.utils.text import capfirst, get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nclass InlineForeignKeyField(Field):\n    \n\n    widget = HiddenInput\n    default_error_messages = {\n        \"invalid_choice\": _(\"The inline value did not match the parent instance.\"),\n    }\n\n    def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs):\n        self.parent_instance = parent_instance\n        self.pk_field = pk_field\n        self.to_field = to_field\n        if self.parent_instance is not None:\n            if self.to_field:\n                kwargs[\"initial\"] = getattr(self.parent_instance, self.to_field)\n            else:\n                kwargs[\"initial\"] = self.parent_instance.pk\n        kwargs[\"required\"] = False\n        super().__init__(*args, **kwargs)\n\n    def clean(self, value):\n        if value in self.empty_values:\n            if self.pk_field:\n                return None\n             \n            return self.parent_instance\n         \n        if self.to_field:\n            orig = getattr(self.parent_instance, self.to_field)\n        else:\n            orig = self.parent_instance.pk\n        if str(value) != str(orig):\n            raise ValidationError(\n                self.error_messages[\"invalid_choice\"], code=\"invalid_choice\"\n            )\n        return self.parent_instance\n\n    def has_changed(self, initial, data):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-4f1adc9e150f5390", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "fb6e6a8f25609ec7e932abf6d9ceca4df44aaf4a663af31858d15a42bbf49a75", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 64, "local_path": "comments/remove-comments/I01__django__InlineForeignKeyField__c5fdfe2d.py", "order": 1, "original_content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "parent_variant_id": "pyint-e8ea6259daac-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/forms/models.py#L1376-L1417", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 213, "comments_removed": 3, "docstrings_removed": 1, "line_comments_removed": 2}, "unit_kind": "class", "unit_name": "InlineForeignKeyField", "variant_id": "pyint-050fc5fdfe2d-I01", "group_id": "py-4f1adc9e150f5390", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 114, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-24fafcbfc18b-I02", "source": "from itertools import chain\nfrom django.core.exceptions import (\n    NON_FIELD_ERRORS,\n    FieldError,\n    ImproperlyConfigured,\n    ValidationError,\n)\nfrom django.core.validators import ProhibitNullCharactersValidator\nfrom django.db.models.utils import AltersData, get_blank_choice_label\nfrom django.forms.fields import ChoiceField, Field\nfrom django.forms.forms import BaseForm, DeclarativeFieldsMetaclass\nfrom django.forms.formsets import BaseFormSet, formset_factory\nfrom django.forms.utils import ErrorList\nfrom django.forms.widgets import (\n    HiddenInput,\n    MultipleHiddenInput,\n    RadioSelect,\n    SelectMultiple,\n)\nfrom django.utils.choices import BaseChoiceIterator\nfrom django.utils.hashable import make_hashable\nfrom django.utils.text import capfirst, get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nclass InlineForeignKeyField(Field):\n    \"\"\"\n    A basic integer field that deals with validating the given value to a\n    given parent instance in an inline.\n    \"\"\"\n\n    widget = HiddenInput\n    default_error_messages = {\n        \"invalid_choice\": _(\"The inline value did not match the parent instance.\"),\n    }\n\n    def __init__(self, parent, *arg, pk2=False, to=None, **kwa):\n        self.parent_instance = parent\n        self.pk_field = pk2\n        self.to_field = to\n        if self.parent_instance is not None:\n            if self.to_field:\n                kwa[\"initial\"] = getattr(self.parent_instance, self.to_field)\n            else:\n                kwa[\"initial\"] = self.parent_instance.pk\n        kwa[\"required\"] = False\n        super().__init__(*arg, **kwa)\n\n    def cle(self, val):\n        if val in self.empty_values:\n            if self.pk_field:\n                return None\n            # if there is no value act as we did before.\n            return self.parent_instance\n        # ensure we compare the values as equal types.\n        if self.to_field:\n            ori = getattr(self.parent_instance, self.to_field)\n        else:\n            ori = self.parent_instance.pk\n        if str(val) != str(ori):\n            raise ValidationError(\n                self.error_messages[\"invalid_choice\"], code=\"invalid_choice\"\n            )\n        return self.parent_instance\n\n    def has(self, ini, dat):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-4f1adc9e150f5390", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "c7ed13b42e7241c46680e8adef6ffbfb105da51ec9d92010b6bff9c110a0caf8", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 67, "local_path": "identifiers/shorten-identifiers/I02__django__InlineForeignKeyField__fcbfc18b.py", "order": 2, "original_content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "parent_variant_id": "pyint-e8ea6259daac-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/forms/models.py#L1376-L1417", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 23, "identifiers_declared": 11}, "unit_kind": "class", "unit_name": "InlineForeignKeyField", "variant_id": "pyint-24fafcbfc18b-I02", "group_id": "py-4f1adc9e150f5390", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 115, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8f0b5e24d60c-I03", "source": "from itertools import chain\nfrom django.core.exceptions import (\n    NON_FIELD_ERRORS,\n    FieldError,\n    ImproperlyConfigured,\n    ValidationError,\n)\nfrom django.core.validators import ProhibitNullCharactersValidator\nfrom django.db.models.utils import AltersData, get_blank_choice_label\nfrom django.forms.fields import ChoiceField, Field\nfrom django.forms.forms import BaseForm, DeclarativeFieldsMetaclass\nfrom django.forms.formsets import BaseFormSet, formset_factory\nfrom django.forms.utils import ErrorList\nfrom django.forms.widgets import (\n    HiddenInput,\n    MultipleHiddenInput,\n    RadioSelect,\n    SelectMultiple,\n)\nfrom django.utils.choices import BaseChoiceIterator\nfrom django.utils.hashable import make_hashable\nfrom django.utils.text import capfirst, get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nclass InlineForeignKeyField(Field):\n    \"\"\"\n    A basic integer field that deals with validating the given value to a\n    given parent instance in an inline.\n    \"\"\"\n\n    widget = HiddenInput\n    default_error_messages = {\n        \"invalid_choice\": _(\"The inline value did not match the parent instance.\"),\n    }\n\n    def __init__(self, pendingAccount, *data, nextItem=False, location=None, **target):\n        self.parent_instance = pendingAccount\n        self.pk_field = nextItem\n        self.to_field = location\n        if self.parent_instance is not None:\n            if self.to_field:\n                target[\"initial\"] = getattr(self.parent_instance, self.to_field)\n            else:\n                target[\"initial\"] = self.parent_instance.pk\n        target[\"required\"] = False\n        super().__init__(*data, **target)\n\n    def check(self, group):\n        if group in self.empty_values:\n            if self.pk_field:\n                return None\n            # if there is no value act as we did before.\n            return self.parent_instance\n        # ensure we compare the values as equal types.\n        if self.to_field:\n            step = getattr(self.parent_instance, self.to_field)\n        else:\n            step = self.parent_instance.pk\n        if str(group) != str(step):\n            raise ValidationError(\n                self.error_messages[\"invalid_choice\"], code=\"invalid_choice\"\n            )\n        return self.parent_instance\n\n    def parseBuffer(self, version, size):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-4f1adc9e150f5390", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "faf1d4491d76a3b7e822de5344ae25d0f0519378856317bc800aa0ef794c9520", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 67, "local_path": "identifiers/mislead-identifiers/I03__django__InlineForeignKeyField__5e24d60c.py", "order": 3, "original_content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "parent_variant_id": "pyint-e8ea6259daac-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/forms/models.py#L1376-L1417", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 23, "identifiers_declared": 11, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 8, "local_random_pool_selections": 9, "local_total_length_difference": 1, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 2, "method_random_pool_selections": 2, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "InlineForeignKeyField", "variant_id": "pyint-8f0b5e24d60c-I03", "group_id": "py-4f1adc9e150f5390", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 116, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-560120bd996f-I04", "source": "from itertools import chain\nfrom django.core.exceptions import (\n    NON_FIELD_ERRORS,\n    FieldError,\n    ImproperlyConfigured,\n    ValidationError,\n)\nfrom django.core.validators import ProhibitNullCharactersValidator\nfrom django.db.models.utils import AltersData, get_blank_choice_label\nfrom django.forms.fields import ChoiceField, Field\nfrom django.forms.forms import BaseForm, DeclarativeFieldsMetaclass\nfrom django.forms.formsets import BaseFormSet, formset_factory\nfrom django.forms.utils import ErrorList\nfrom django.forms.widgets import (\n    HiddenInput,\n    MultipleHiddenInput,\n    RadioSelect,\n    SelectMultiple,\n)\nfrom django.utils.choices import BaseChoiceIterator\nfrom django.utils.hashable import make_hashable\nfrom django.utils.text import capfirst, get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nclass InlineForeignKeyField(Field):\n    \"\"\"\n    A basic integer field that deals with validating the given value to a\n    given parent instance in an inline.\n    \"\"\"\n\n    widget = HiddenInput\n    default_error_messages = {\n        \"invalid_choice\": _(\"The inline value did not match the parent instance.\"),\n    }\n\n    def __init__(self, c, *d, e=False, f=None, **g):\n        self.parent_instance = c\n        self.pk_field = e\n        self.to_field = f\n        if self.parent_instance is not None:\n            if self.to_field:\n                g[\"initial\"] = getattr(self.parent_instance, self.to_field)\n            else:\n                g[\"initial\"] = self.parent_instance.pk\n        g[\"required\"] = False\n        super().__init__(*d, **g)\n\n    def a(self, h):\n        if h in self.empty_values:\n            if self.pk_field:\n                return None\n            # if there is no value act as we did before.\n            return self.parent_instance\n        # ensure we compare the values as equal types.\n        if self.to_field:\n            i = getattr(self.parent_instance, self.to_field)\n        else:\n            i = self.parent_instance.pk\n        if str(h) != str(i):\n            raise ValidationError(\n                self.error_messages[\"invalid_choice\"], code=\"invalid_choice\"\n            )\n        return self.parent_instance\n\n    def b(self, j, k):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-4f1adc9e150f5390", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d692e40c56af9314480d674033ea786780f14d9ff479e17f79263f61677ac7b6", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 67, "local_path": "identifiers/garble-identifiers/I04__django__InlineForeignKeyField__20bd996f.py", "order": 4, "original_content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "parent_variant_id": "pyint-e8ea6259daac-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/forms/models.py#L1376-L1417", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 23, "identifiers_declared": 11}, "unit_kind": "class", "unit_name": "InlineForeignKeyField", "variant_id": "pyint-560120bd996f-I04", "group_id": "py-4f1adc9e150f5390", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 117, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-285ea0b567b8-I05", "source": "from itertools import chain\nfrom django.core.exceptions import (\n    NON_FIELD_ERRORS,\n    FieldError,\n    ImproperlyConfigured,\n    ValidationError,\n)\nfrom django.core.validators import ProhibitNullCharactersValidator\nfrom django.db.models.utils import AltersData, get_blank_choice_label\nfrom django.forms.fields import ChoiceField, Field\nfrom django.forms.forms import BaseForm, DeclarativeFieldsMetaclass\nfrom django.forms.formsets import BaseFormSet, formset_factory\nfrom django.forms.utils import ErrorList\nfrom django.forms.widgets import (\n    HiddenInput,\n    MultipleHiddenInput,\n    RadioSelect,\n    SelectMultiple,\n)\nfrom django.utils.choices import BaseChoiceIterator\nfrom django.utils.hashable import make_hashable\nfrom django.utils.text import capfirst, get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nclass InlineForeignKeyField(Field):\n    \"\"\"\n    A basic integer field that deals with validating the given value to a\n    given parent instance in an inline.\n    \"\"\"\n\n    widget = HiddenInput\n    default_error_messages = {\n        \"invalid_choice\": _(\"The inline value did not match the parent instance.\"),\n    }\n\n    def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs):\n        self.parent_instance = parent_instance\n        self.pk_field = pk_field\n        self.to_field = to_field\n        if self.parent_instance is not None:\n            if self.to_field:\n                kwargs[\"initial\"] = getattr(self.parent_instance, self.to_field)\n            else:\n                kwargs[\"initial\"] = self.parent_instance.pk\n        kwargs[\"required\"] = False\n        super().__init__(*args, **kwargs)\n\n    def clean(self, value):\n        if value in self.empty_values:\n            if self.pk_field:\n                return None\n            # if there is no value act as we did before.\n            return self.parent_instance\n        # ensure we compare the values as equal types.\n        if self.to_field:\n            orig = getattr(self.parent_instance, self.to_field)\n        else:\n            orig = self.parent_instance.pk\n        if str(value) != str(orig):\n            raise ValidationError(\n                self.error_messages[\"invalid_choice\"], code=\"invalid_choice\"\n            )\n        return self.parent_instance\n\n    def has_changed(self, initial, data):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-4f1adc9e150f5390", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 67, "local_path": "expressions/encode-integer-literals/I05__django__InlineForeignKeyField__a0b567b8.py", "order": 5, "original_content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "parent_variant_id": "pyint-e8ea6259daac-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/forms/models.py#L1376-L1417", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "InlineForeignKeyField", "variant_id": "pyint-285ea0b567b8-I05", "group_id": "py-4f1adc9e150f5390", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 118, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-644834ccab3c-I06", "source": "from itertools import chain\nfrom django.core.exceptions import (\n    NON_FIELD_ERRORS,\n    FieldError,\n    ImproperlyConfigured,\n    ValidationError,\n)\nfrom django.core.validators import ProhibitNullCharactersValidator\nfrom django.db.models.utils import AltersData, get_blank_choice_label\nfrom django.forms.fields import ChoiceField, Field\nfrom django.forms.forms import BaseForm, DeclarativeFieldsMetaclass\nfrom django.forms.formsets import BaseFormSet, formset_factory\nfrom django.forms.utils import ErrorList\nfrom django.forms.widgets import (\n    HiddenInput,\n    MultipleHiddenInput,\n    RadioSelect,\n    SelectMultiple,\n)\nfrom django.utils.choices import BaseChoiceIterator\nfrom django.utils.hashable import make_hashable\nfrom django.utils.text import capfirst, get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nclass InlineForeignKeyField(Field):\n    \"\"\"\n    A basic integer field that deals with validating the given value to a\n    given parent instance in an inline.\n    \"\"\"\n\n    widget = HiddenInput\n    default_error_messages = {\n        \"invalid_choice\": _(\"The inline value did not match the parent instance.\"),\n    }\n\n    def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs):\n        self.parent_instance = parent_instance\n        self.pk_field = pk_field\n        self.to_field = to_field\n        if not (self.parent_instance is not None):\n            pass\n        else:\n            if self.to_field:\n                kwargs[\"initial\"] = getattr(self.parent_instance, self.to_field)\n            else:\n                kwargs[\"initial\"] = self.parent_instance.pk\n        kwargs[\"required\"] = False\n        super().__init__(*args, **kwargs)\n\n    def clean(self, value):\n        if not (value in self.empty_values):\n            pass\n        else:\n            if self.pk_field:\n                return None\n            # if there is no value act as we did before.\n            return self.parent_instance\n        # ensure we compare the values as equal types.\n        if not (self.to_field):\n            orig = self.parent_instance.pk\n        else:\n            orig = getattr(self.parent_instance, self.to_field)\n        if not (str(value) != str(orig)):\n            pass\n        else:\n            raise ValidationError(\n                self.error_messages[\"invalid_choice\"], code=\"invalid_choice\"\n            )\n        return self.parent_instance\n\n    def has_changed(self, initial, data):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-4f1adc9e150f5390", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "d096a322d7505e5c8ada49d385ca2fbabe6d0642af15d661e8e1e80463e88a4f", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 73, "local_path": "expressions/invert-conditions/I06__django__InlineForeignKeyField__34ccab3c.py", "order": 6, "original_content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "parent_variant_id": "pyint-e8ea6259daac-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/forms/models.py#L1376-L1417", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 4}, "unit_kind": "class", "unit_name": "InlineForeignKeyField", "variant_id": "pyint-644834ccab3c-I06", "group_id": "py-4f1adc9e150f5390", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 119, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-acd81d65310c-I07", "source": "from itertools import chain\nfrom django.core.exceptions import (\n    NON_FIELD_ERRORS,\n    FieldError,\n    ImproperlyConfigured,\n    ValidationError,\n)\nfrom django.core.validators import ProhibitNullCharactersValidator\nfrom django.db.models.utils import AltersData, get_blank_choice_label\nfrom django.forms.fields import ChoiceField, Field\nfrom django.forms.forms import BaseForm, DeclarativeFieldsMetaclass\nfrom django.forms.formsets import BaseFormSet, formset_factory\nfrom django.forms.utils import ErrorList\nfrom django.forms.widgets import (\n    HiddenInput,\n    MultipleHiddenInput,\n    RadioSelect,\n    SelectMultiple,\n)\nfrom django.utils.choices import BaseChoiceIterator\nfrom django.utils.hashable import make_hashable\nfrom django.utils.text import capfirst, get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nclass InlineForeignKeyField(Field):\n    \"\"\"\n    A basic integer field that deals with validating the given value to a\n    given parent instance in an inline.\n    \"\"\"\n\n    widget = HiddenInput\n    default_error_messages = {\n        \"invalid_choice\": _(\"The inline value did not match the parent instance.\"),\n    }\n\n    def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs):\n        if ((0x83dd ^ 0x83dd) != 0):\n            raise AssertionError()\n        self.parent_instance = parent_instance\n        self.pk_field = pk_field\n        self.to_field = to_field\n        if self.parent_instance is not None:\n            if self.to_field:\n                kwargs[\"initial\"] = getattr(self.parent_instance, self.to_field)\n            else:\n                kwargs[\"initial\"] = self.parent_instance.pk\n        kwargs[\"required\"] = False\n        super().__init__(*args, **kwargs)\n\n    def clean(self, value):\n        if ((0xcfb9 ^ 0xcfb9) != 0):\n            raise AssertionError()\n        if value in self.empty_values:\n            if self.pk_field:\n                return None\n            # if there is no value act as we did before.\n            return self.parent_instance\n        # ensure we compare the values as equal types.\n        if self.to_field:\n            orig = getattr(self.parent_instance, self.to_field)\n        else:\n            orig = self.parent_instance.pk\n        if str(value) != str(orig):\n            raise ValidationError(\n                self.error_messages[\"invalid_choice\"], code=\"invalid_choice\"\n            )\n        return self.parent_instance\n\n    def has_changed(self, initial, data):\n        if ((0x3a81 ^ 0x3a81) != 0):\n            raise AssertionError()\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-4f1adc9e150f5390", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "1f582583b5516e95f234ec753d37e37dc763e543722a1eb04d44cf66e0027fae", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 73, "local_path": "code-injection/insert-dead-branches/I07__django__InlineForeignKeyField__1d65310c.py", "order": 7, "original_content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "parent_variant_id": "pyint-e8ea6259daac-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/forms/models.py#L1376-L1417", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 3}, "unit_kind": "class", "unit_name": "InlineForeignKeyField", "variant_id": "pyint-acd81d65310c-I07", "group_id": "py-4f1adc9e150f5390", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 120, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8d4493ced1ff-I08", "source": "from itertools import chain\nfrom django.core.exceptions import (\n    NON_FIELD_ERRORS,\n    FieldError,\n    ImproperlyConfigured,\n    ValidationError,\n)\nfrom django.core.validators import ProhibitNullCharactersValidator\nfrom django.db.models.utils import AltersData, get_blank_choice_label\nfrom django.forms.fields import ChoiceField, Field\nfrom django.forms.forms import BaseForm, DeclarativeFieldsMetaclass\nfrom django.forms.formsets import BaseFormSet, formset_factory\nfrom django.forms.utils import ErrorList\nfrom django.forms.widgets import (\n    HiddenInput,\n    MultipleHiddenInput,\n    RadioSelect,\n    SelectMultiple,\n)\nfrom django.utils.choices import BaseChoiceIterator\nfrom django.utils.hashable import make_hashable\nfrom django.utils.text import capfirst, get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nclass InlineForeignKeyField(Field):\n    \"\"\"\n    A basic integer field that deals with validating the given value to a\n    given parent instance in an inline.\n    \"\"\"\n\n    widget = HiddenInput\n    default_error_messages = {\n        \"invalid_choice\": _(\"The inline value did not match the parent instance.\"),\n    }\n\n    def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs):\n        self.parent_instance = parent_instance\n        self.pk_field = pk_field\n        self.to_field = to_field\n        if self.parent_instance is not None:\n            if self.to_field:\n                kwargs[\"initial\"] = getattr(self.parent_instance, self.to_field)\n            else:\n                kwargs[\"initial\"] = self.parent_instance.pk\n        kwargs[\"required\"] = False\n        super().__init__(*args, **kwargs)\n\n    def clean(self, value):\n        feature_enabled = False\n        for toggle_count in range(3):\n            feature_enabled = not feature_enabled\n        if value in self.empty_values:\n            if self.pk_field:\n                return None\n            # if there is no value act as we did before.\n            return self.parent_instance\n        # ensure we compare the values as equal types.\n        if self.to_field:\n            orig = getattr(self.parent_instance, self.to_field)\n        else:\n            orig = self.parent_instance.pk\n        if str(value) != str(orig):\n            raise ValidationError(\n                self.error_messages[\"invalid_choice\"], code=\"invalid_choice\"\n            )\n        return self.parent_instance\n\n    def has_changed(self, initial, data):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-4f1adc9e150f5390", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "2c8f0ccb3a2d1fc4760f0acd41a5d995603043ee0878d911db41d9d13e8358cd", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 70, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__InlineForeignKeyField__93ced1ff.py", "order": 8, "original_content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "parent_variant_id": "pyint-e8ea6259daac-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/forms/models.py#L1376-L1417", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 7}, "unit_kind": "class", "unit_name": "InlineForeignKeyField", "variant_id": "pyint-8d4493ced1ff-I08", "group_id": "py-4f1adc9e150f5390", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 121, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6d4470261d83-I09", "source": "from itertools import chain\nfrom django.core.exceptions import (\n    NON_FIELD_ERRORS,\n    FieldError,\n    ImproperlyConfigured,\n    ValidationError,\n)\nfrom django.core.validators import ProhibitNullCharactersValidator\nfrom django.db.models.utils import AltersData, get_blank_choice_label\nfrom django.forms.fields import ChoiceField, Field\nfrom django.forms.forms import BaseForm, DeclarativeFieldsMetaclass\nfrom django.forms.formsets import BaseFormSet, formset_factory\nfrom django.forms.utils import ErrorList\nfrom django.forms.widgets import (\n    HiddenInput,\n    MultipleHiddenInput,\n    RadioSelect,\n    SelectMultiple,\n)\nfrom django.utils.choices import BaseChoiceIterator\nfrom django.utils.hashable import make_hashable\nfrom django.utils.text import capfirst, get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nclass InlineForeignKeyField(Field):\n    \"\"\"\n    A basic integer field that deals with validating the given value to a\n    given parent instance in an inline.\n    \"\"\"\n\n    widget = HiddenInput\n    default_error_messages = {\n        \"invalid_choice\": _(\"The inline value did not match the parent instance.\"),\n    }\n\n    def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs):\n        self.parent_instance = parent_instance\n        self.pk_field = pk_field\n        self.to_field = to_field\n        if self.parent_instance is not None:\n            if self.to_field:\n                kwargs[\"initial\"] = getattr(self.parent_instance, self.to_field)\n            else:\n                kwargs[\"initial\"] = self.parent_instance.pk\n        kwargs[\"required\"] = False\n        super().__init__(*args, **kwargs)\n\n    def clean(self, value):\n        lI0O_b9382977 = 0x3a91 ^ 0x3a91\n        if lI0O_b9382977 != 0:\n            if ((lI0O_b9382977 | 1) & 1) == 0:\n                lI0O_b9382977 += 1\n            else:\n                lI0O_b9382977 -= 1\n        if value in self.empty_values:\n            if self.pk_field:\n                return None\n            # if there is no value act as we did before.\n            return self.parent_instance\n        # ensure we compare the values as equal types.\n        if self.to_field:\n            orig = getattr(self.parent_instance, self.to_field)\n        else:\n            orig = self.parent_instance.pk\n        if str(value) != str(orig):\n            raise ValidationError(\n                self.error_messages[\"invalid_choice\"], code=\"invalid_choice\"\n            )\n        return self.parent_instance\n\n    def has_changed(self, initial, data):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-4f1adc9e150f5390", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "f6422595cf879cb6cde2c42fe8b9ea88a29960e8838dc226e039efab9eccf50b", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 73, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__InlineForeignKeyField__70261d83.py", "order": 9, "original_content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "parent_variant_id": "pyint-e8ea6259daac-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/forms/models.py#L1376-L1417", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 5}, "unit_kind": "class", "unit_name": "InlineForeignKeyField", "variant_id": "pyint-6d4470261d83-I09", "group_id": "py-4f1adc9e150f5390", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 122, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-453c0b086217-I10", "source": "from itertools import chain\nfrom django.core.exceptions import (     NON_FIELD_ERRORS,\n    FieldError,\n    ImproperlyConfigured,     ValidationError,\n)\nfrom django.core.validators import ProhibitNullCharactersValidator\nfrom django.db.models.utils import AltersData, get_blank_choice_label\nfrom django.forms.fields import ChoiceField, Field\nfrom django.forms.forms import BaseForm, DeclarativeFieldsMetaclass\nfrom django.forms.formsets import BaseFormSet, formset_factory\nfrom django.forms.utils import ErrorList\nfrom django.forms.widgets import (     HiddenInput,\n    MultipleHiddenInput,\n    RadioSelect,     SelectMultiple,\n)\nfrom django.utils.choices import BaseChoiceIterator\nfrom django.utils.hashable import make_hashable\nfrom django.utils.text import capfirst, get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nclass InlineForeignKeyField(Field):\n    \"\"\"\n    A basic integer field that deals with validating the given value to a\n    given parent instance in an inline.\n    \"\"\"\n\n    widget = HiddenInput\n    default_error_messages = {         \"invalid_choice\": _(\"The inline value did not match the parent instance.\"),\n    }\n\n    def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs):\n        self.parent_instance = parent_instance\n        self.pk_field = pk_field\n        self.to_field = to_field\n        if self.parent_instance is not None:\n            if self.to_field:\n                kwargs[\"initial\"] = getattr(self.parent_instance, self.to_field)\n            else:\n                kwargs[\"initial\"] = self.parent_instance.pk\n        kwargs[\"required\"] = False\n        super().__init__(*args, **kwargs)\n\n    def clean(self, value):\n        if value in self.empty_values:\n            if self.pk_field:\n                return None\n            # if there is no value act as we did before.\n            return self.parent_instance\n        # ensure we compare the values as equal types.\n        if self.to_field:\n            orig = getattr(self.parent_instance, self.to_field)\n        else:\n            orig = self.parent_instance.pk\n        if str(value) != str(orig):\n            raise ValidationError(                 self.error_messages[\"invalid_choice\"], code=\"invalid_choice\"             )\n        return self.parent_instance\n\n    def has_changed(self, initial, data):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-4f1adc9e150f5390", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "823bf95bcaade797f7d688ad389e667b7f14311a468d1bc594e98269cc9ce09b", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 60, "local_path": "layout/partially-compact-layout/I10__django__InlineForeignKeyField__0b086217.py", "order": 10, "original_content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "parent_variant_id": "pyint-e8ea6259daac-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/forms/models.py#L1376-L1417", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 19, "line_break_groups_removed": 7, "line_breaks_removed": 7, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "InlineForeignKeyField", "variant_id": "pyint-453c0b086217-I10", "group_id": "py-4f1adc9e150f5390", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 123, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ef54db7554e2-I11", "source": "from itertools import chain\nfrom django.core.exceptions import (\n    NON_FIELD_ERRORS,\n    FieldError,\n    ImproperlyConfigured,\n    ValidationError,\n)\nfrom django.core.validators import ProhibitNullCharactersValidator\nfrom django.db.models.utils import AltersData, get_blank_choice_label\nfrom django.forms.fields import ChoiceField, Field\nfrom django.forms.forms import BaseForm, DeclarativeFieldsMetaclass\nfrom django.forms.formsets import BaseFormSet, formset_factory\nfrom django.forms.utils import ErrorList\nfrom django.forms.widgets import (\n    HiddenInput,\n    MultipleHiddenInput,\n    RadioSelect,\n    SelectMultiple,\n)\nfrom django.utils.choices import BaseChoiceIterator\nfrom django.utils.hashable import make_hashable\nfrom django.utils.text import capfirst, get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nclass InlineForeignKeyField(Field):\n    \"\"\"\n    A basic integer field that deals with validating the given value to a\n    given parent instance in an inline.\n    \"\"\"\n\n    widget = HiddenInput\n    default_error_messages = {\n        \"invalid_choice\": _(\"The inline value did not match the parent instance.\"),\n    }\n\n    def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs):\n        self.parent_instance = parent_instance\n        self.pk_field = pk_field\n        self.to_field = to_field\n        if self.parent_instance is not None:\n            if self.to_field:\n                kwargs[\"initial\"] = getattr(self.parent_instance, self.to_field)\n            else:\n                kwargs[\"initial\"] = self.parent_instance.pk\n        kwargs[\"required\"] = False\n        super().__init__(*args, **kwargs)\n\n    def clean(self, value):\n        if value in self.empty_values:\n            if self.pk_field:\n                return None\n            # if there is no value act as we did before.\n            return self.parent_instance\n        # ensure we compare the values as equal types.\n        if self.to_field:\n            orig = getattr(self.parent_instance, self.to_field)\n        else:\n            orig = self.parent_instance.pk\n        if str(value) != str(orig):\n            raise ValidationError(\n                self.error_messages[\"invalid_choice\"], code=\"invalid_choice\"\n            )\n        return self.parent_instance\n\n    def has_changed(self, initial, data):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-4f1adc9e150f5390", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 67, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__InlineForeignKeyField__db7554e2.py", "order": 11, "original_content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "parent_variant_id": "pyint-e8ea6259daac-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/forms/models.py#L1376-L1417", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "InlineForeignKeyField", "variant_id": "pyint-ef54db7554e2-I11", "group_id": "py-4f1adc9e150f5390", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 124, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-75e0d005c1b1-I12", "source": "from itertools import chain\nfrom django.core.exceptions import (\n    NON_FIELD_ERRORS,\n    FieldError,\n    ImproperlyConfigured,\n    ValidationError,\n)\nfrom django.core.validators import ProhibitNullCharactersValidator\nfrom django.db.models.utils import AltersData, get_blank_choice_label\nfrom django.forms.fields import ChoiceField, Field\nfrom django.forms.forms import BaseForm, DeclarativeFieldsMetaclass\nfrom django.forms.formsets import BaseFormSet, formset_factory\nfrom django.forms.utils import ErrorList\nfrom django.forms.widgets import (\n    HiddenInput,\n    MultipleHiddenInput,\n    RadioSelect,\n    SelectMultiple,\n)\nfrom django.utils.choices import BaseChoiceIterator\nfrom django.utils.hashable import make_hashable\nfrom django.utils.text import capfirst, get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nclass InlineForeignKeyField(Field):\n    \"\"\"\n    A basic integer field that deals with validating the given value to a\n    given parent instance in an inline.\n    \"\"\"\n\n    widget = HiddenInput\n    default_error_messages = {\n        \"invalid_choice\": _(\"The inline value did not match the parent instance.\"),\n    }\n\n    def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs):\n        self.parent_instance = parent_instance\n        self.pk_field = pk_field\n        self.to_field = to_field\n        if self.parent_instance is not None:\n            if self.to_field:\n                kwargs[\"initial\"] = getattr(self.parent_instance, self.to_field)\n            else:\n                kwargs[\"initial\"] = self.parent_instance.pk\n        kwargs[\"required\"] = False\n        super().__init__(*args, **kwargs)\n\n    def clean(self, value):\n        if value in self.empty_values:\n            if self.pk_field:\n                return None\n            # if there is no value act as we did before.\n            return self.parent_instance\n        # ensure we compare the values as equal types.\n        if self.to_field:\n            orig = getattr(self.parent_instance, self.to_field)\n        else:\n            orig = self.parent_instance.pk\n        if str(value) != str(orig):\n            raise ValidationError(\n                self.error_messages[\"invalid_choice\"], code=\"invalid_choice\"\n            )\n        return self.parent_instance\n\n    def has_changed(self, initial, data):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-4f1adc9e150f5390", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 67, "local_path": "data-flow/inline-intermediate-variables/I12__django__InlineForeignKeyField__d005c1b1.py", "order": 12, "original_content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "parent_variant_id": "pyint-e8ea6259daac-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/forms/models.py#L1376-L1417", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "InlineForeignKeyField", "variant_id": "pyint-75e0d005c1b1-I12", "group_id": "py-4f1adc9e150f5390", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 125, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-26c291142439-I13", "source": "from itertools import chain\nfrom django.core.exceptions import (\n    NON_FIELD_ERRORS,\n    FieldError,\n    ImproperlyConfigured,\n    ValidationError,\n)\nfrom django.core.validators import ProhibitNullCharactersValidator\nfrom django.db.models.utils import AltersData, get_blank_choice_label\nfrom django.forms.fields import ChoiceField, Field\nfrom django.forms.forms import BaseForm, DeclarativeFieldsMetaclass\nfrom django.forms.formsets import BaseFormSet, formset_factory\nfrom django.forms.utils import ErrorList\nfrom django.forms.widgets import (\n    HiddenInput,\n    MultipleHiddenInput,\n    RadioSelect,\n    SelectMultiple,\n)\nfrom django.utils.choices import BaseChoiceIterator\nfrom django.utils.hashable import make_hashable\nfrom django.utils.text import capfirst, get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nclass InlineForeignKeyField(Field):\n    \"\"\"\n    A basic integer field that deals with validating the given value to a\n    given parent instance in an inline.\n    \"\"\"\n\n    widget = HiddenInput\n    default_error_messages = {\n        \"invalid_choice\": _(\"The inline value did not match the parent instance.\"),\n    }\n\n    def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs):\n        self.parent_instance = parent_instance\n        self.pk_field = pk_field\n        self.to_field = to_field\n        if self.parent_instance is not None:\n            if self.to_field:\n                kwargs[\"initial\"] = getattr(self.parent_instance, self.to_field)\n            else:\n                kwargs[\"initial\"] = self.parent_instance.pk\n        kwargs[\"required\"] = False\n        super().__init__(*args, **kwargs)\n\n    def clean(self, value):\n        if value in self.empty_values:\n            if self.pk_field:\n                return None\n            # if there is no value act as we did before.\n            return self.parent_instance\n        # ensure we compare the values as equal types.\n        if self.to_field:\n            orig = getattr(self.parent_instance, self.to_field)\n        else:\n            orig = self.parent_instance.pk\n        if str(value) != str(orig):\n            raise ValidationError(\n                self.error_messages[\"invalid_choice\"], code=\"invalid_choice\"\n            )\n        return self.parent_instance\n\n    def has_changed(self, initial, data):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-4f1adc9e150f5390", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 67, "local_path": "control-flow/lower-for-to-while/I13__django__InlineForeignKeyField__91142439.py", "order": 13, "original_content_sha256": "d2edbac25c738b67be87b80d7cb04d01410b8715801dce4be73e75891fbad7e5", "parent_variant_id": "pyint-e8ea6259daac-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/forms/models.py#L1376-L1417", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "InlineForeignKeyField", "variant_id": "pyint-26c291142439-I13", "group_id": "py-4f1adc9e150f5390", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 126, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-63c43928c958-SRC", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n    _thread_local: threading.local\n    last_nonce: str\n    nonce_count: int\n    chal: dict[str, str]\n    pos: int | None\n    num_401_calls: int | None\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n\n    def init_per_thread_state(self) -> None:\n        # Ensure state is initialized just once per-thread\n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def build_digest_header(self, method: str, url: str) -> str | None:\n        \"\"\"\n        :rtype: str\n        \"\"\"\n\n        realm = self._thread_local.chal[\"realm\"]\n        nonce = self._thread_local.chal[\"nonce\"]\n        qop = self._thread_local.chal.get(\"qop\")\n        algorithm = self._thread_local.chal.get(\"algorithm\")\n        opaque = self._thread_local.chal.get(\"opaque\")\n        hash_utf8 = None\n\n        if algorithm is None:\n            _algorithm = \"MD5\"\n        else:\n            _algorithm = algorithm.upper()\n        # lambdas assume digest modules are imported at the top level\n        if _algorithm == \"MD5\" or _algorithm == \"MD5-SESS\":\n\n            def md5_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.md5(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = md5_utf8\n        elif _algorithm == \"SHA\":\n\n            def sha_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha1(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha_utf8\n        elif _algorithm == \"SHA-256\":\n\n            def sha256_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha256(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha256_utf8\n        elif _algorithm == \"SHA-512\":\n\n            def sha512_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha512(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha512_utf8\n\n        if hash_utf8 is None:\n            return None\n\n        def KD(s: str, d: str) -> str:\n            return hash_utf8(f\"{s}:{d}\")\n\n        # XXX not implemented yet\n        entdig = None\n        p_parsed = urlparse(url)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        path = p_parsed.path or \"/\"\n        if p_parsed.query:\n            path += f\"?{p_parsed.query}\"\n\n        A1 = f\"{self.username}:{realm}:{self.password}\"\n        A2 = f\"{method}:{path}\"\n\n        HA1 = hash_utf8(A1)\n        HA2 = hash_utf8(A2)\n\n        if nonce == self._thread_local.last_nonce:\n            self._thread_local.nonce_count += 1\n        else:\n            self._thread_local.nonce_count = 1\n        ncvalue = f\"{self._thread_local.nonce_count:08x}\"\n        s = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        s += nonce.encode(\"utf-8\")\n        s += time.ctime().encode(\"utf-8\")\n        s += os.urandom(8)\n\n        cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:16]\n        if _algorithm == \"MD5-SESS\":\n            HA1 = hash_utf8(f\"{HA1}:{nonce}:{cnonce}\")  # type: ignore[reportConstantRedefinition]  # RFC 2617 terminology\n\n        if not qop:\n            respdig = KD(HA1, f\"{nonce}:{HA2}\")\n        elif qop == \"auth\" or \"auth\" in qop.split(\",\"):\n            noncebit = f\"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}\"\n            respdig = KD(HA1, noncebit)\n        else:\n            # XXX handle auth-int.\n            return None\n\n        self._thread_local.last_nonce = nonce\n\n        # XXX should the partial digests be encoded too?\n        base = (\n            f'username=\"{self.username}\", realm=\"{realm}\", nonce=\"{nonce}\", '\n            f'uri=\"{path}\", response=\"{respdig}\"'\n        )\n        if opaque:\n            base += f', opaque=\"{opaque}\"'\n        if algorithm:\n            base += f', algorithm=\"{algorithm}\"'\n        if entdig:\n            base += f', digest=\"{entdig}\"'\n        if qop:\n            base += f', qop=\"auth\", nc={ncvalue}, cnonce=\"{cnonce}\"'\n\n        return f\"Digest {base}\"\n\n    def handle_redirect(self, r: Response, **kwargs: Any) -> None:\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        if r.is_redirect:\n            self._thread_local.num_401_calls = 1\n\n    def handle_401(self, r: Response, **kwargs: Any) -> Response:\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n\n        :rtype: requests.Response\n        \"\"\"\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        if not 400 <= r.status_code < 500:\n            self._thread_local.num_401_calls = 1\n            return r\n\n        if self._thread_local.pos is not None:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            if (seek := getattr(r.request.body, \"seek\", None)) is not None:\n                seek(self._thread_local.pos)\n        s_auth = r.headers.get(\"www-authenticate\", \"\")\n\n        if \"digest\" in s_auth.lower() and self._thread_local.num_401_calls < 2:\n            self._thread_local.num_401_calls += 1\n            pat = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(pat.sub(\"\", s_auth, count=1))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            r.content\n            r.close()\n            prep = r.request.copy()\n            cookie_jar = cast(\"CookieJar\", prep._cookies)\n            extract_cookies_to_jar(cookie_jar, r.request, r.raw)\n            prep.prepare_cookies(cookie_jar)\n\n            _digest_auth = self.build_digest_header(\n                cast(str, prep.method), cast(str, prep.url)\n            )\n            if _digest_auth:\n                prep.headers[\"Authorization\"] = _digest_auth\n            _r = r.connection.send(prep, **kwargs)\n            _r.history.append(r)\n            _r.request = prep\n\n            return _r\n\n        self._thread_local.num_401_calls = 1\n        return r\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        # Initialize per-thread state, if needed\n        self.init_per_thread_state()\n        # If we have a saved nonce, skip the 401\n        if self._thread_local.last_nonce:\n            _digest_auth = self.build_digest_header(\n                cast(str, r.method), cast(str, r.url)\n            )\n            if _digest_auth:\n                r.headers[\"Authorization\"] = _digest_auth\n        if (tell := getattr(r.body, \"tell\", None)) is not None:\n            self._thread_local.pos = tell()\n        else:\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        r.register_hook(\"response\", self.handle_401)\n        r.register_hook(\"response\", self.handle_redirect)\n        self._thread_local.num_401_calls = 1\n\n        return r\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-505ae146e7f68698", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 245, "local_path": "source-original/SRC__requests__HTTPDigestAuth__3928c958.py", "order": 0, "original_content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L124-L354", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "HTTPDigestAuth", "variant_id": "pyint-63c43928c958-SRC", "group_id": "py-505ae146e7f68698", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 855, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bef4632bde49-I01", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPDigestAuth(AuthBase):\n    \n\n    username: bytes | str\n    password: bytes | str\n    _thread_local: threading.local\n    last_nonce: str\n    nonce_count: int\n    chal: dict[str, str]\n    pos: int | None\n    num_401_calls: int | None\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n         \n        self._thread_local = threading.local()\n\n    def init_per_thread_state(self) -> None:\n         \n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def build_digest_header(self, method: str, url: str) -> str | None:\n        \n\n        realm = self._thread_local.chal[\"realm\"]\n        nonce = self._thread_local.chal[\"nonce\"]\n        qop = self._thread_local.chal.get(\"qop\")\n        algorithm = self._thread_local.chal.get(\"algorithm\")\n        opaque = self._thread_local.chal.get(\"opaque\")\n        hash_utf8 = None\n\n        if algorithm is None:\n            _algorithm = \"MD5\"\n        else:\n            _algorithm = algorithm.upper()\n         \n        if _algorithm == \"MD5\" or _algorithm == \"MD5-SESS\":\n\n            def md5_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.md5(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = md5_utf8\n        elif _algorithm == \"SHA\":\n\n            def sha_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha1(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha_utf8\n        elif _algorithm == \"SHA-256\":\n\n            def sha256_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha256(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha256_utf8\n        elif _algorithm == \"SHA-512\":\n\n            def sha512_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha512(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha512_utf8\n\n        if hash_utf8 is None:\n            return None\n\n        def KD(s: str, d: str) -> str:\n            return hash_utf8(f\"{s}:{d}\")\n\n         \n        entdig = None\n        p_parsed = urlparse(url)\n         \n        path = p_parsed.path or \"/\"\n        if p_parsed.query:\n            path += f\"?{p_parsed.query}\"\n\n        A1 = f\"{self.username}:{realm}:{self.password}\"\n        A2 = f\"{method}:{path}\"\n\n        HA1 = hash_utf8(A1)\n        HA2 = hash_utf8(A2)\n\n        if nonce == self._thread_local.last_nonce:\n            self._thread_local.nonce_count += 1\n        else:\n            self._thread_local.nonce_count = 1\n        ncvalue = f\"{self._thread_local.nonce_count:08x}\"\n        s = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        s += nonce.encode(\"utf-8\")\n        s += time.ctime().encode(\"utf-8\")\n        s += os.urandom(8)\n\n        cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:16]\n        if _algorithm == \"MD5-SESS\":\n            HA1 = hash_utf8(f\"{HA1}:{nonce}:{cnonce}\")   \n\n        if not qop:\n            respdig = KD(HA1, f\"{nonce}:{HA2}\")\n        elif qop == \"auth\" or \"auth\" in qop.split(\",\"):\n            noncebit = f\"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}\"\n            respdig = KD(HA1, noncebit)\n        else:\n             \n            return None\n\n        self._thread_local.last_nonce = nonce\n\n         \n        base = (\n            f'username=\"{self.username}\", realm=\"{realm}\", nonce=\"{nonce}\", '\n            f'uri=\"{path}\", response=\"{respdig}\"'\n        )\n        if opaque:\n            base += f', opaque=\"{opaque}\"'\n        if algorithm:\n            base += f', algorithm=\"{algorithm}\"'\n        if entdig:\n            base += f', digest=\"{entdig}\"'\n        if qop:\n            base += f', qop=\"auth\", nc={ncvalue}, cnonce=\"{cnonce}\"'\n\n        return f\"Digest {base}\"\n\n    def handle_redirect(self, r: Response, **kwargs: Any) -> None:\n        \n        if r.is_redirect:\n            self._thread_local.num_401_calls = 1\n\n    def handle_401(self, r: Response, **kwargs: Any) -> Response:\n        \n\n         \n         \n        if not 400 <= r.status_code < 500:\n            self._thread_local.num_401_calls = 1\n            return r\n\n        if self._thread_local.pos is not None:\n             \n             \n            if (seek := getattr(r.request.body, \"seek\", None)) is not None:\n                seek(self._thread_local.pos)\n        s_auth = r.headers.get(\"www-authenticate\", \"\")\n\n        if \"digest\" in s_auth.lower() and self._thread_local.num_401_calls < 2:\n            self._thread_local.num_401_calls += 1\n            pat = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(pat.sub(\"\", s_auth, count=1))\n\n             \n             \n            r.content\n            r.close()\n            prep = r.request.copy()\n            cookie_jar = cast(\"CookieJar\", prep._cookies)\n            extract_cookies_to_jar(cookie_jar, r.request, r.raw)\n            prep.prepare_cookies(cookie_jar)\n\n            _digest_auth = self.build_digest_header(\n                cast(str, prep.method), cast(str, prep.url)\n            )\n            if _digest_auth:\n                prep.headers[\"Authorization\"] = _digest_auth\n            _r = r.connection.send(prep, **kwargs)\n            _r.history.append(r)\n            _r.request = prep\n\n            return _r\n\n        self._thread_local.num_401_calls = 1\n        return r\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n         \n        self.init_per_thread_state()\n         \n        if self._thread_local.last_nonce:\n            _digest_auth = self.build_digest_header(\n                cast(str, r.method), cast(str, r.url)\n            )\n            if _digest_auth:\n                r.headers[\"Authorization\"] = _digest_auth\n        if (tell := getattr(r.body, \"tell\", None)) is not None:\n            self._thread_local.pos = tell()\n        else:\n             \n             \n             \n             \n            self._thread_local.pos = None\n        r.register_hook(\"response\", self.handle_401)\n        r.register_hook(\"response\", self.handle_redirect)\n        self._thread_local.num_401_calls = 1\n\n        return r\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-505ae146e7f68698", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "c90a758c8a2febe3638f7a8b5d0ab6194ed4d036d1df60c253076ef28ce11049", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 239, "local_path": "comments/remove-comments/I01__requests__HTTPDigestAuth__632bde49.py", "order": 1, "original_content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "parent_variant_id": "pyint-63c43928c958-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L124-L354", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 1166, "comments_removed": 24, "docstrings_removed": 4, "line_comments_removed": 20}, "unit_kind": "class", "unit_name": "HTTPDigestAuth", "variant_id": "pyint-bef4632bde49-I01", "group_id": "py-505ae146e7f68698", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 856, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0ce36c22a695-I02", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n    _thread_local: threading.local\n    last_nonce: str\n    nonce_count: int\n    chal: dict[str, str]\n    pos: int | None\n    num_401_calls: int | None\n\n    @overload\n    def __init__(self, use: str, pas: str) -> None: ...\n    @overload\n    def __init__(self, use2: bytes, pas2: bytes) -> None: ...\n\n    def __init__(self, use3: bytes | str, pas3: bytes | str) -> None:\n        self.username = use3\n        self.password = pas3\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n\n    def init2(self) -> None:\n        # Ensure state is initialized just once per-thread\n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def build(self, met: str, url2: str) -> str | None:\n        \"\"\"\n        :rtype: str\n        \"\"\"\n\n        rea = self._thread_local.chal[\"realm\"]\n        non = self._thread_local.chal[\"nonce\"]\n        qop2 = self._thread_local.chal.get(\"qop\")\n        alg = self._thread_local.chal.get(\"algorithm\")\n        opa = self._thread_local.chal.get(\"opaque\")\n        hash = None\n\n        if alg is None:\n            alg2 = \"MD5\"\n        else:\n            alg2 = alg.upper()\n        # lambdas assume digest modules are imported at the top level\n        if alg2 == \"MD5\" or alg2 == \"MD5-SESS\":\n\n            def md5_utf8(x2: str | bytes) -> str:\n                if isinstance(x2, str):\n                    x2 = x2.encode(\"utf-8\")\n                return hashlib.md5(x2, usedforsecurity=False).hexdigest()\n\n            hash = md5_utf8\n        elif alg2 == \"SHA\":\n\n            def sha_utf8(x3: str | bytes) -> str:\n                if isinstance(x3, str):\n                    x3 = x3.encode(\"utf-8\")\n                return hashlib.sha1(x3, usedforsecurity=False).hexdigest()\n\n            hash = sha_utf8\n        elif alg2 == \"SHA-256\":\n\n            def sha256_utf8(x4: str | bytes) -> str:\n                if isinstance(x4, str):\n                    x4 = x4.encode(\"utf-8\")\n                return hashlib.sha256(x4, usedforsecurity=False).hexdigest()\n\n            hash = sha256_utf8\n        elif alg2 == \"SHA-512\":\n\n            def sha512_utf8(x5: str | bytes) -> str:\n                if isinstance(x5, str):\n                    x5 = x5.encode(\"utf-8\")\n                return hashlib.sha512(x5, usedforsecurity=False).hexdigest()\n\n            hash = sha512_utf8\n\n        if hash is None:\n            return None\n\n        def KD(s3: str, d2: str) -> str:\n            return hash_utf8(f\"{s3}:{d2}\")\n\n        # XXX not implemented yet\n        ent = None\n        p = urlparse(url2)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        pat2 = p.path or \"/\"\n        if p.query:\n            pat2 += f\"?{p.query}\"\n\n        a1 = f\"{self.username}:{rea}:{self.password}\"\n        a2 = f\"{met}:{pat2}\"\n\n        hA1 = hash(a1)\n        hA2 = hash(a2)\n\n        if non == self._thread_local.last_nonce:\n            self._thread_local.nonce_count += 1\n        else:\n            self._thread_local.nonce_count = 1\n        ncv = f\"{self._thread_local.nonce_count:08x}\"\n        s2 = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        s2 += non.encode(\"utf-8\")\n        s2 += time.ctime().encode(\"utf-8\")\n        s2 += os.urandom(8)\n\n        cno = hashlib.sha1(s2, usedforsecurity=False).hexdigest()[:16]\n        if alg2 == \"MD5-SESS\":\n            hA1 = hash(f\"{hA1}:{non}:{cno}\")  # type: ignore[reportConstantRedefinition]  # RFC 2617 terminology\n\n        if not qop2:\n            res = KD(hA1, f\"{non}:{hA2}\")\n        elif qop2 == \"auth\" or \"auth\" in qop2.split(\",\"):\n            non2 = f\"{non}:{ncv}:{cno}:auth:{hA2}\"\n            res = KD(hA1, non2)\n        else:\n            # XXX handle auth-int.\n            return None\n\n        self._thread_local.last_nonce = non\n\n        # XXX should the partial digests be encoded too?\n        bas = (\n            f'username=\"{self.username}\", realm=\"{rea}\", nonce=\"{non}\", '\n            f'uri=\"{pat2}\", response=\"{res}\"'\n        )\n        if opa:\n            bas += f', opaque=\"{opa}\"'\n        if alg:\n            bas += f', algorithm=\"{alg}\"'\n        if ent:\n            bas += f', digest=\"{ent}\"'\n        if qop2:\n            bas += f', qop=\"auth\", nc={ncv}, cnonce=\"{cno}\"'\n\n        return f\"Digest {bas}\"\n\n    def handle(self, r2: Response, **kwa: Any) -> None:\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        if r2.is_redirect:\n            self._thread_local.num_401_calls = 1\n\n    def handle2(self, r3: Response, **kwa2: Any) -> Response:\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n\n        :rtype: requests.Response\n        \"\"\"\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        if not 400 <= r3.status_code < 500:\n            self._thread_local.num_401_calls = 1\n            return r3\n\n        if self._thread_local.pos is not None:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            if (see := getattr(r3.request.body, \"seek\", None)) is not None:\n                see(self._thread_local.pos)\n        s4 = r3.headers.get(\"www-authenticate\", \"\")\n\n        if \"digest\" in s4.lower() and self._thread_local.num_401_calls < 2:\n            self._thread_local.num_401_calls += 1\n            pat3 = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(pat3.sub(\"\", s4, count=1))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            r3.content\n            r3.close()\n            pre = r3.request.copy()\n            cookie = cast(\"CookieJar\", pre._cookies)\n            extract_cookies_to_jar(cookie, r3.request, r3.raw)\n            pre.prepare_cookies(cookie)\n\n            digest = self.build(\n                cast(str, pre.method), cast(str, pre.url)\n            )\n            if digest:\n                pre.headers[\"Authorization\"] = digest\n            r4 = r3.connection.send(pre, **kwa2)\n            r4.history.append(r3)\n            r4.request = pre\n\n            return r4\n\n        self._thread_local.num_401_calls = 1\n        return r3\n\n    def __call__(self, r5: PreparedRequest) -> PreparedRequest:\n        # Initialize per-thread state, if needed\n        self.init2()\n        # If we have a saved nonce, skip the 401\n        if self._thread_local.last_nonce:\n            digest2 = self.build(\n                cast(str, r5.method), cast(str, r5.url)\n            )\n            if digest2:\n                r5.headers[\"Authorization\"] = digest2\n        if (tel := getattr(r5.body, \"tell\", None)) is not None:\n            self._thread_local.pos = tel()\n        else:\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        r5.register_hook(\"response\", self.handle2)\n        r5.register_hook(\"response\", self.handle)\n        self._thread_local.num_401_calls = 1\n\n        return r5\n\n    def __eq__(self, oth: object) -> bool:\n        return all(\n            [\n                self.username == getattr(oth, \"username\", None),\n                self.password == getattr(oth, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, oth2: Any) -> bool:\n        return not self == oth2\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-505ae146e7f68698", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "7a4b2e2ffa18bfc8cfc9727c97568ecb1fd2139a9eb9ca6dd17aeb85c058eee4", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 245, "local_path": "identifiers/shorten-identifiers/I02__requests__HTTPDigestAuth__6c22a695.py", "order": 2, "original_content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "parent_variant_id": "pyint-63c43928c958-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L124-L354", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 193, "identifiers_declared": 54}, "unit_kind": "class", "unit_name": "HTTPDigestAuth", "variant_id": "pyint-0ce36c22a695-I02", "group_id": "py-505ae146e7f68698", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 857, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-69739d0d1f74-I03", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n    _thread_local: threading.local\n    last_nonce: str\n    nonce_count: int\n    chal: dict[str, str]\n    pos: int | None\n    num_401_calls: int | None\n\n    @overload\n    def __init__(self, schedule: str, localKey: str) -> None: ...\n    @overload\n    def __init__(self, category: bytes, customer: bytes) -> None: ...\n\n    def __init__(self, schedule: bytes | str, localKey: bytes | str) -> None:\n        self.username = schedule\n        self.password = localKey\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n\n    def validateMessage(self) -> None:\n        # Ensure state is initialized just once per-thread\n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def validateAccount(self, client: str, age: str) -> str | None:\n        \"\"\"\n        :rtype: str\n        \"\"\"\n\n        batch = self._thread_local.chal[\"realm\"]\n        count = self._thread_local.chal[\"nonce\"]\n        key = self._thread_local.chal.get(\"qop\")\n        backupKey = self._thread_local.chal.get(\"algorithm\")\n        source = self._thread_local.chal.get(\"opaque\")\n        recentKey = None\n\n        if backupKey is None:\n            sharedData = \"MD5\"\n        else:\n            sharedData = backupKey.upper()\n        # lambdas assume digest modules are imported at the top level\n        if sharedData == \"MD5\" or sharedData == \"MD5-SESS\":\n\n            def md5_utf8(key: str | bytes) -> str:\n                if isinstance(key, str):\n                    key = key.encode(\"utf-8\")\n                return hashlib.md5(key, usedforsecurity=False).hexdigest()\n\n            recentKey = md5_utf8\n        elif sharedData == \"SHA\":\n\n            def sha_utf8(age: str | bytes) -> str:\n                if isinstance(age, str):\n                    age = age.encode(\"utf-8\")\n                return hashlib.sha1(age, usedforsecurity=False).hexdigest()\n\n            recentKey = sha_utf8\n        elif sharedData == \"SHA-256\":\n\n            def sha256_utf8(map: str | bytes) -> str:\n                if isinstance(map, str):\n                    map = map.encode(\"utf-8\")\n                return hashlib.sha256(map, usedforsecurity=False).hexdigest()\n\n            recentKey = sha256_utf8\n        elif sharedData == \"SHA-512\":\n\n            def sha512_utf8(key: str | bytes) -> str:\n                if isinstance(key, str):\n                    key = key.encode(\"utf-8\")\n                return hashlib.sha512(key, usedforsecurity=False).hexdigest()\n\n            recentKey = sha512_utf8\n\n        if recentKey is None:\n            return None\n\n        def KD(age: str, key: str) -> str:\n            return hash_utf8(f\"{age}:{key}\")\n\n        # XXX not implemented yet\n        target = None\n        finalKey = urlparse(age)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        flag = finalKey.path or \"/\"\n        if finalKey.query:\n            flag += f\"?{finalKey.query}\"\n\n        map = f\"{self.username}:{batch}:{self.password}\"\n        date = f\"{client}:{flag}\"\n\n        item = recentKey(map)\n        node = recentKey(date)\n\n        if count == self._thread_local.last_nonce:\n            self._thread_local.nonce_count += 1\n        else:\n            self._thread_local.nonce_count = 1\n        session = f\"{self._thread_local.nonce_count:08x}\"\n        step = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        step += count.encode(\"utf-8\")\n        step += time.ctime().encode(\"utf-8\")\n        step += os.urandom(8)\n\n        option = hashlib.sha1(step, usedforsecurity=False).hexdigest()[:16]\n        if sharedData == \"MD5-SESS\":\n            item = recentKey(f\"{item}:{count}:{option}\")  # type: ignore[reportConstantRedefinition]  # RFC 2617 terminology\n\n        if not key:\n            nextKey = KD(item, f\"{count}:{node}\")\n        elif key == \"auth\" or \"auth\" in key.split(\",\"):\n            nextPath = f\"{count}:{session}:{option}:auth:{node}\"\n            nextKey = KD(item, nextPath)\n        else:\n            # XXX handle auth-int.\n            return None\n\n        self._thread_local.last_nonce = count\n\n        # XXX should the partial digests be encoded too?\n        user = (\n            f'username=\"{self.username}\", realm=\"{batch}\", nonce=\"{count}\", '\n            f'uri=\"{flag}\", response=\"{nextKey}\"'\n        )\n        if source:\n            user += f', opaque=\"{source}\"'\n        if backupKey:\n            user += f', algorithm=\"{backupKey}\"'\n        if target:\n            user += f', digest=\"{target}\"'\n        if key:\n            user += f', qop=\"auth\", nc={session}, cnonce=\"{option}\"'\n\n        return f\"Digest {user}\"\n\n    def validateBalance(self, age: Response, **status: Any) -> None:\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        if age.is_redirect:\n            self._thread_local.num_401_calls = 1\n\n    def findBuffer(self, map: Response, **result: Any) -> Response:\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n\n        :rtype: requests.Response\n        \"\"\"\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        if not 400 <= map.status_code < 500:\n            self._thread_local.num_401_calls = 1\n            return map\n\n        if self._thread_local.pos is not None:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            if (node := getattr(map.request.body, \"seek\", None)) is not None:\n                node(self._thread_local.pos)\n        source = map.headers.get(\"www-authenticate\", \"\")\n\n        if \"digest\" in source.lower() and self._thread_local.num_401_calls < 2:\n            self._thread_local.num_401_calls += 1\n            age = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(age.sub(\"\", source, count=1))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            map.content\n            map.close()\n            data = map.request.copy()\n            finalScore = cast(\"CookieJar\", data._cookies)\n            extract_cookies_to_jar(finalScore, map.request, map.raw)\n            data.prepare_cookies(finalScore)\n\n            defaultEvent = self.validateAccount(\n                cast(str, data.method), cast(str, data.url)\n            )\n            if defaultEvent:\n                data.headers[\"Authorization\"] = defaultEvent\n            key = map.connection.send(data, **result)\n            key.history.append(map)\n            key.request = data\n\n            return key\n\n        self._thread_local.num_401_calls = 1\n        return map\n\n    def __call__(self, key: PreparedRequest) -> PreparedRequest:\n        # Initialize per-thread state, if needed\n        self.validateMessage()\n        # If we have a saved nonce, skip the 401\n        if self._thread_local.last_nonce:\n            backupClient = self.validateAccount(\n                cast(str, key.method), cast(str, key.url)\n            )\n            if backupClient:\n                key.headers[\"Authorization\"] = backupClient\n        if (path := getattr(key.body, \"tell\", None)) is not None:\n            self._thread_local.pos = path()\n        else:\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        key.register_hook(\"response\", self.findBuffer)\n        key.register_hook(\"response\", self.validateBalance)\n        self._thread_local.num_401_calls = 1\n\n        return key\n\n    def __eq__(self, entry: object) -> bool:\n        return all(\n            [\n                self.username == getattr(entry, \"username\", None),\n                self.password == getattr(entry, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, count: Any) -> bool:\n        return not self == count\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-505ae146e7f68698", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "22a92d71f7368461e9f3f955a7b2532e1c115d176ac59167db2fc693c5a29fea", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 245, "local_path": "identifiers/mislead-identifiers/I03__requests__HTTPDigestAuth__9d0d1f74.py", "order": 3, "original_content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "parent_variant_id": "pyint-63c43928c958-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L124-L354", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 193, "identifiers_declared": 54, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 19, "local_exact_length_matches": 35, "local_random_pool_selections": 50, "local_total_length_difference": 27, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 2, "method_random_pool_selections": 4, "method_total_length_difference": 10}, "unit_kind": "class", "unit_name": "HTTPDigestAuth", "variant_id": "pyint-69739d0d1f74-I03", "group_id": "py-505ae146e7f68698", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 858, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-76e701e8aab4-I04", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n    _thread_local: threading.local\n    last_nonce: str\n    nonce_count: int\n    chal: dict[str, str]\n    pos: int | None\n    num_401_calls: int | None\n\n    @overload\n    def __init__(self, f: str, g: str) -> None: ...\n    @overload\n    def __init__(self, h: bytes, i: bytes) -> None: ...\n\n    def __init__(self, j: bytes | str, k: bytes | str) -> None:\n        self.username = j\n        self.password = k\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n\n    def a(self) -> None:\n        # Ensure state is initialized just once per-thread\n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def b(self, l: str, m: str) -> str | None:\n        \"\"\"\n        :rtype: str\n        \"\"\"\n\n        n = self._thread_local.chal[\"realm\"]\n        o = self._thread_local.chal[\"nonce\"]\n        p = self._thread_local.chal.get(\"qop\")\n        q = self._thread_local.chal.get(\"algorithm\")\n        t = self._thread_local.chal.get(\"opaque\")\n        u = None\n\n        if q is None:\n            v = \"MD5\"\n        else:\n            v = q.upper()\n        # lambdas assume digest modules are imported at the top level\n        if v == \"MD5\" or v == \"MD5-SESS\":\n\n            def md5_utf8(K: str | bytes) -> str:\n                if isinstance(K, str):\n                    K = K.encode(\"utf-8\")\n                return hashlib.md5(K, usedforsecurity=False).hexdigest()\n\n            u = md5_utf8\n        elif v == \"SHA\":\n\n            def sha_utf8(L: str | bytes) -> str:\n                if isinstance(L, str):\n                    L = L.encode(\"utf-8\")\n                return hashlib.sha1(L, usedforsecurity=False).hexdigest()\n\n            u = sha_utf8\n        elif v == \"SHA-256\":\n\n            def sha256_utf8(M: str | bytes) -> str:\n                if isinstance(M, str):\n                    M = M.encode(\"utf-8\")\n                return hashlib.sha256(M, usedforsecurity=False).hexdigest()\n\n            u = sha256_utf8\n        elif v == \"SHA-512\":\n\n            def sha512_utf8(N: str | bytes) -> str:\n                if isinstance(N, str):\n                    N = N.encode(\"utf-8\")\n                return hashlib.sha512(N, usedforsecurity=False).hexdigest()\n\n            u = sha512_utf8\n\n        if u is None:\n            return None\n\n        def KD(O: str, P: str) -> str:\n            return hash_utf8(f\"{O}:{P}\")\n\n        # XXX not implemented yet\n        w = None\n        y = urlparse(m)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        z = y.path or \"/\"\n        if y.query:\n            z += f\"?{y.query}\"\n\n        A = f\"{self.username}:{n}:{self.password}\"\n        B = f\"{l}:{z}\"\n\n        C = u(A)\n        D = u(B)\n\n        if o == self._thread_local.last_nonce:\n            self._thread_local.nonce_count += 1\n        else:\n            self._thread_local.nonce_count = 1\n        E = f\"{self._thread_local.nonce_count:08x}\"\n        F = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        F += o.encode(\"utf-8\")\n        F += time.ctime().encode(\"utf-8\")\n        F += os.urandom(8)\n\n        G = hashlib.sha1(F, usedforsecurity=False).hexdigest()[:16]\n        if v == \"MD5-SESS\":\n            C = u(f\"{C}:{o}:{G}\")  # type: ignore[reportConstantRedefinition]  # RFC 2617 terminology\n\n        if not p:\n            H = KD(C, f\"{o}:{D}\")\n        elif p == \"auth\" or \"auth\" in p.split(\",\"):\n            I = f\"{o}:{E}:{G}:auth:{D}\"\n            H = KD(C, I)\n        else:\n            # XXX handle auth-int.\n            return None\n\n        self._thread_local.last_nonce = o\n\n        # XXX should the partial digests be encoded too?\n        J = (\n            f'username=\"{self.username}\", realm=\"{n}\", nonce=\"{o}\", '\n            f'uri=\"{z}\", response=\"{H}\"'\n        )\n        if t:\n            J += f', opaque=\"{t}\"'\n        if q:\n            J += f', algorithm=\"{q}\"'\n        if w:\n            J += f', digest=\"{w}\"'\n        if p:\n            J += f', qop=\"auth\", nc={E}, cnonce=\"{G}\"'\n\n        return f\"Digest {J}\"\n\n    def c(self, Q: Response, **R: Any) -> None:\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        if Q.is_redirect:\n            self._thread_local.num_401_calls = 1\n\n    def e(self, S: Response, **T: Any) -> Response:\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n\n        :rtype: requests.Response\n        \"\"\"\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        if not 400 <= S.status_code < 500:\n            self._thread_local.num_401_calls = 1\n            return S\n\n        if self._thread_local.pos is not None:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            if (U := getattr(S.request.body, \"seek\", None)) is not None:\n                U(self._thread_local.pos)\n        V = S.headers.get(\"www-authenticate\", \"\")\n\n        if \"digest\" in V.lower() and self._thread_local.num_401_calls < 2:\n            self._thread_local.num_401_calls += 1\n            W = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(W.sub(\"\", V, count=1))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            S.content\n            S.close()\n            X = S.request.copy()\n            Y = cast(\"CookieJar\", X._cookies)\n            extract_cookies_to_jar(Y, S.request, S.raw)\n            X.prepare_cookies(Y)\n\n            Z = self.b(\n                cast(str, X.method), cast(str, X.url)\n            )\n            if Z:\n                X.headers[\"Authorization\"] = Z\n            aa = S.connection.send(X, **T)\n            aa.history.append(S)\n            aa.request = X\n\n            return aa\n\n        self._thread_local.num_401_calls = 1\n        return S\n\n    def __call__(self, ab: PreparedRequest) -> PreparedRequest:\n        # Initialize per-thread state, if needed\n        self.a()\n        # If we have a saved nonce, skip the 401\n        if self._thread_local.last_nonce:\n            ac = self.b(\n                cast(str, ab.method), cast(str, ab.url)\n            )\n            if ac:\n                ab.headers[\"Authorization\"] = ac\n        if (ad := getattr(ab.body, \"tell\", None)) is not None:\n            self._thread_local.pos = ad()\n        else:\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        ab.register_hook(\"response\", self.e)\n        ab.register_hook(\"response\", self.c)\n        self._thread_local.num_401_calls = 1\n\n        return ab\n\n    def __eq__(self, ae: object) -> bool:\n        return all(\n            [\n                self.username == getattr(ae, \"username\", None),\n                self.password == getattr(ae, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, af: Any) -> bool:\n        return not self == af\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-505ae146e7f68698", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "37991e260ae8e9badd904f934208abb2fb380b17783fc3e90a81f3fca26b450d", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 245, "local_path": "identifiers/garble-identifiers/I04__requests__HTTPDigestAuth__01e8aab4.py", "order": 4, "original_content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "parent_variant_id": "pyint-63c43928c958-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L124-L354", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 193, "identifiers_declared": 54}, "unit_kind": "class", "unit_name": "HTTPDigestAuth", "variant_id": "pyint-76e701e8aab4-I04", "group_id": "py-505ae146e7f68698", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 859, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0fdda1a48b80-I05", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n    _thread_local: threading.local\n    last_nonce: str\n    nonce_count: int\n    chal: dict[str, str]\n    pos: int | None\n    num_401_calls: int | None\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n\n    def init_per_thread_state(self) -> None:\n        # Ensure state is initialized just once per-thread\n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0x0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def build_digest_header(self, method: str, url: str) -> str | None:\n        \"\"\"\n        :rtype: str\n        \"\"\"\n\n        realm = self._thread_local.chal[\"realm\"]\n        nonce = self._thread_local.chal[\"nonce\"]\n        qop = self._thread_local.chal.get(\"qop\")\n        algorithm = self._thread_local.chal.get(\"algorithm\")\n        opaque = self._thread_local.chal.get(\"opaque\")\n        hash_utf8 = None\n\n        if algorithm is None:\n            _algorithm = \"MD5\"\n        else:\n            _algorithm = algorithm.upper()\n        # lambdas assume digest modules are imported at the top level\n        if _algorithm == \"MD5\" or _algorithm == \"MD5-SESS\":\n\n            def md5_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.md5(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = md5_utf8\n        elif _algorithm == \"SHA\":\n\n            def sha_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha1(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha_utf8\n        elif _algorithm == \"SHA-256\":\n\n            def sha256_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha256(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha256_utf8\n        elif _algorithm == \"SHA-512\":\n\n            def sha512_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha512(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha512_utf8\n\n        if hash_utf8 is None:\n            return None\n\n        def KD(s: str, d: str) -> str:\n            return hash_utf8(f\"{s}:{d}\")\n\n        # XXX not implemented yet\n        entdig = None\n        p_parsed = urlparse(url)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        path = p_parsed.path or \"/\"\n        if p_parsed.query:\n            path += f\"?{p_parsed.query}\"\n\n        A1 = f\"{self.username}:{realm}:{self.password}\"\n        A2 = f\"{method}:{path}\"\n\n        HA1 = hash_utf8(A1)\n        HA2 = hash_utf8(A2)\n\n        if nonce == self._thread_local.last_nonce:\n            self._thread_local.nonce_count += 0x1\n        else:\n            self._thread_local.nonce_count = 0x1\n        ncvalue = f\"{self._thread_local.nonce_count:08x}\"\n        s = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        s += nonce.encode(\"utf-8\")\n        s += time.ctime().encode(\"utf-8\")\n        s += os.urandom(0x8)\n\n        cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:0x10]\n        if _algorithm == \"MD5-SESS\":\n            HA1 = hash_utf8(f\"{HA1}:{nonce}:{cnonce}\")  # type: ignore[reportConstantRedefinition]  # RFC 2617 terminology\n\n        if not qop:\n            respdig = KD(HA1, f\"{nonce}:{HA2}\")\n        elif qop == \"auth\" or \"auth\" in qop.split(\",\"):\n            noncebit = f\"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}\"\n            respdig = KD(HA1, noncebit)\n        else:\n            # XXX handle auth-int.\n            return None\n\n        self._thread_local.last_nonce = nonce\n\n        # XXX should the partial digests be encoded too?\n        base = (\n            f'username=\"{self.username}\", realm=\"{realm}\", nonce=\"{nonce}\", '\n            f'uri=\"{path}\", response=\"{respdig}\"'\n        )\n        if opaque:\n            base += f', opaque=\"{opaque}\"'\n        if algorithm:\n            base += f', algorithm=\"{algorithm}\"'\n        if entdig:\n            base += f', digest=\"{entdig}\"'\n        if qop:\n            base += f', qop=\"auth\", nc={ncvalue}, cnonce=\"{cnonce}\"'\n\n        return f\"Digest {base}\"\n\n    def handle_redirect(self, r: Response, **kwargs: Any) -> None:\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        if r.is_redirect:\n            self._thread_local.num_401_calls = 0x1\n\n    def handle_401(self, r: Response, **kwargs: Any) -> Response:\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n\n        :rtype: requests.Response\n        \"\"\"\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        if not 0x190 <= r.status_code < 0x1f4:\n            self._thread_local.num_401_calls = 0x1\n            return r\n\n        if self._thread_local.pos is not None:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            if (seek := getattr(r.request.body, \"seek\", None)) is not None:\n                seek(self._thread_local.pos)\n        s_auth = r.headers.get(\"www-authenticate\", \"\")\n\n        if \"digest\" in s_auth.lower() and self._thread_local.num_401_calls < 0x2:\n            self._thread_local.num_401_calls += 0x1\n            pat = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(pat.sub(\"\", s_auth, count=0x1))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            r.content\n            r.close()\n            prep = r.request.copy()\n            cookie_jar = cast(\"CookieJar\", prep._cookies)\n            extract_cookies_to_jar(cookie_jar, r.request, r.raw)\n            prep.prepare_cookies(cookie_jar)\n\n            _digest_auth = self.build_digest_header(\n                cast(str, prep.method), cast(str, prep.url)\n            )\n            if _digest_auth:\n                prep.headers[\"Authorization\"] = _digest_auth\n            _r = r.connection.send(prep, **kwargs)\n            _r.history.append(r)\n            _r.request = prep\n\n            return _r\n\n        self._thread_local.num_401_calls = 0x1\n        return r\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        # Initialize per-thread state, if needed\n        self.init_per_thread_state()\n        # If we have a saved nonce, skip the 401\n        if self._thread_local.last_nonce:\n            _digest_auth = self.build_digest_header(\n                cast(str, r.method), cast(str, r.url)\n            )\n            if _digest_auth:\n                r.headers[\"Authorization\"] = _digest_auth\n        if (tell := getattr(r.body, \"tell\", None)) is not None:\n            self._thread_local.pos = tell()\n        else:\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        r.register_hook(\"response\", self.handle_401)\n        r.register_hook(\"response\", self.handle_redirect)\n        self._thread_local.num_401_calls = 0x1\n\n        return r\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-505ae146e7f68698", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "b1140291b49850e06b5c6f79f381b4afec83a2fc7fedc1d350f6a6670e185cf8", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 245, "local_path": "expressions/encode-integer-literals/I05__requests__HTTPDigestAuth__a1a48b80.py", "order": 5, "original_content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "parent_variant_id": "pyint-63c43928c958-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L124-L354", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 14}, "unit_kind": "class", "unit_name": "HTTPDigestAuth", "variant_id": "pyint-0fdda1a48b80-I05", "group_id": "py-505ae146e7f68698", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 860, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f229e6146ebc-I06", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n    _thread_local: threading.local\n    last_nonce: str\n    nonce_count: int\n    chal: dict[str, str]\n    pos: int | None\n    num_401_calls: int | None\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n\n    def init_per_thread_state(self) -> None:\n        # Ensure state is initialized just once per-thread\n        if not (not hasattr(self._thread_local, \"init\")):\n            pass\n        else:\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def build_digest_header(self, method: str, url: str) -> str | None:\n        \"\"\"\n        :rtype: str\n        \"\"\"\n\n        realm = self._thread_local.chal[\"realm\"]\n        nonce = self._thread_local.chal[\"nonce\"]\n        qop = self._thread_local.chal.get(\"qop\")\n        algorithm = self._thread_local.chal.get(\"algorithm\")\n        opaque = self._thread_local.chal.get(\"opaque\")\n        hash_utf8 = None\n\n        if not (algorithm is None):\n            _algorithm = algorithm.upper()\n        else:\n            _algorithm = \"MD5\"\n        # lambdas assume digest modules are imported at the top level\n        if _algorithm == \"MD5\" or _algorithm == \"MD5-SESS\":\n\n            def md5_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.md5(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = md5_utf8\n        elif _algorithm == \"SHA\":\n\n            def sha_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha1(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha_utf8\n        elif _algorithm == \"SHA-256\":\n\n            def sha256_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha256(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha256_utf8\n        elif _algorithm == \"SHA-512\":\n\n            def sha512_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha512(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha512_utf8\n\n        if not (hash_utf8 is None):\n            pass\n        else:\n            return None\n\n        def KD(s: str, d: str) -> str:\n            return hash_utf8(f\"{s}:{d}\")\n\n        # XXX not implemented yet\n        entdig = None\n        p_parsed = urlparse(url)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        path = p_parsed.path or \"/\"\n        if not (p_parsed.query):\n            pass\n        else:\n            path += f\"?{p_parsed.query}\"\n\n        A1 = f\"{self.username}:{realm}:{self.password}\"\n        A2 = f\"{method}:{path}\"\n\n        HA1 = hash_utf8(A1)\n        HA2 = hash_utf8(A2)\n\n        if not (nonce == self._thread_local.last_nonce):\n            self._thread_local.nonce_count = 1\n        else:\n            self._thread_local.nonce_count += 1\n        ncvalue = f\"{self._thread_local.nonce_count:08x}\"\n        s = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        s += nonce.encode(\"utf-8\")\n        s += time.ctime().encode(\"utf-8\")\n        s += os.urandom(8)\n\n        cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:16]\n        if not (_algorithm == \"MD5-SESS\"):\n            pass\n        else:\n            HA1 = hash_utf8(f\"{HA1}:{nonce}:{cnonce}\")  # type: ignore[reportConstantRedefinition]  # RFC 2617 terminology  # type: ignore[reportConstantRedefinition]  # RFC 2617 terminology\n\n        if not qop:\n            respdig = KD(HA1, f\"{nonce}:{HA2}\")\n        elif qop == \"auth\" or \"auth\" in qop.split(\",\"):\n            noncebit = f\"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}\"\n            respdig = KD(HA1, noncebit)\n        else:\n            # XXX handle auth-int.\n            return None\n\n        self._thread_local.last_nonce = nonce\n\n        # XXX should the partial digests be encoded too?\n        base = (\n            f'username=\"{self.username}\", realm=\"{realm}\", nonce=\"{nonce}\", '\n            f'uri=\"{path}\", response=\"{respdig}\"'\n        )\n        if not (opaque):\n            pass\n        else:\n            base += f', opaque=\"{opaque}\"'\n        if not (algorithm):\n            pass\n        else:\n            base += f', algorithm=\"{algorithm}\"'\n        if not (entdig):\n            pass\n        else:\n            base += f', digest=\"{entdig}\"'\n        if not (qop):\n            pass\n        else:\n            base += f', qop=\"auth\", nc={ncvalue}, cnonce=\"{cnonce}\"'\n\n        return f\"Digest {base}\"\n\n    def handle_redirect(self, r: Response, **kwargs: Any) -> None:\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        if not (r.is_redirect):\n            pass\n        else:\n            self._thread_local.num_401_calls = 1\n\n    def handle_401(self, r: Response, **kwargs: Any) -> Response:\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n\n        :rtype: requests.Response\n        \"\"\"\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        if not (not 400 <= r.status_code < 500):\n            pass\n        else:\n            self._thread_local.num_401_calls = 1\n            return r\n\n        if not (self._thread_local.pos is not None):\n            pass\n        else:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            if (seek := getattr(r.request.body, \"seek\", None)) is not None:\n                seek(self._thread_local.pos)\n        s_auth = r.headers.get(\"www-authenticate\", \"\")\n\n        if not (\"digest\" in s_auth.lower() and self._thread_local.num_401_calls < 2):\n            pass\n        else:\n            self._thread_local.num_401_calls += 1\n            pat = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(pat.sub(\"\", s_auth, count=1))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            r.content\n            r.close()\n            prep = r.request.copy()\n            cookie_jar = cast(\"CookieJar\", prep._cookies)\n            extract_cookies_to_jar(cookie_jar, r.request, r.raw)\n            prep.prepare_cookies(cookie_jar)\n\n            _digest_auth = self.build_digest_header(\n                cast(str, prep.method), cast(str, prep.url)\n            )\n            if _digest_auth:\n                prep.headers[\"Authorization\"] = _digest_auth\n            _r = r.connection.send(prep, **kwargs)\n            _r.history.append(r)\n            _r.request = prep\n\n            return _r\n\n        self._thread_local.num_401_calls = 1\n        return r\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        # Initialize per-thread state, if needed\n        self.init_per_thread_state()\n        # If we have a saved nonce, skip the 401\n        if not (self._thread_local.last_nonce):\n            pass\n        else:\n            _digest_auth = self.build_digest_header(\n                cast(str, r.method), cast(str, r.url)\n            )\n            if _digest_auth:\n                r.headers[\"Authorization\"] = _digest_auth\n        if not ((tell := getattr(r.body, \"tell\", None)) is not None):\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        else:\n            self._thread_local.pos = tell()\n        r.register_hook(\"response\", self.handle_401)\n        r.register_hook(\"response\", self.handle_redirect)\n        self._thread_local.num_401_calls = 1\n\n        return r\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-505ae146e7f68698", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "adbb420625ab98e9492e764626d3031dfc4ca6885572fc0e77d78042ad849d0a", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 271, "local_path": "expressions/invert-conditions/I06__requests__HTTPDigestAuth__e6146ebc.py", "order": 6, "original_content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "parent_variant_id": "pyint-63c43928c958-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L124-L354", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 16}, "unit_kind": "class", "unit_name": "HTTPDigestAuth", "variant_id": "pyint-f229e6146ebc-I06", "group_id": "py-505ae146e7f68698", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 861, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d1c8b9b00f33-I07", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n    _thread_local: threading.local\n    last_nonce: str\n    nonce_count: int\n    chal: dict[str, str]\n    pos: int | None\n    num_401_calls: int | None\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        if ((0x1014 ^ 0x1014) != 0):\n            raise AssertionError()\n        self.username = username\n        self.password = password\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n\n    def init_per_thread_state(self) -> None:\n        # Ensure state is initialized just once per-thread\n        if ((0x865b ^ 0x865b) != 0):\n            raise AssertionError()\n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def build_digest_header(self, method: str, url: str) -> str | None:\n        \"\"\"\n        :rtype: str\n        \"\"\"\n        if ((0x3455 ^ 0x3455) != 0):\n            raise AssertionError()\n\n        realm = self._thread_local.chal[\"realm\"]\n        nonce = self._thread_local.chal[\"nonce\"]\n        qop = self._thread_local.chal.get(\"qop\")\n        algorithm = self._thread_local.chal.get(\"algorithm\")\n        opaque = self._thread_local.chal.get(\"opaque\")\n        hash_utf8 = None\n\n        if algorithm is None:\n            _algorithm = \"MD5\"\n        else:\n            _algorithm = algorithm.upper()\n        # lambdas assume digest modules are imported at the top level\n        if _algorithm == \"MD5\" or _algorithm == \"MD5-SESS\":\n\n            def md5_utf8(x: str | bytes) -> str:\n                if ((0xb345 ^ 0xb345) != 0):\n                    raise AssertionError()\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.md5(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = md5_utf8\n        elif _algorithm == \"SHA\":\n\n            def sha_utf8(x: str | bytes) -> str:\n                if ((0x7b4e ^ 0x7b4e) != 0):\n                    raise AssertionError()\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha1(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha_utf8\n        elif _algorithm == \"SHA-256\":\n\n            def sha256_utf8(x: str | bytes) -> str:\n                if ((0x6804 ^ 0x6804) != 0):\n                    raise AssertionError()\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha256(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha256_utf8\n        elif _algorithm == \"SHA-512\":\n\n            def sha512_utf8(x: str | bytes) -> str:\n                if ((0x294d ^ 0x294d) != 0):\n                    raise AssertionError()\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha512(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha512_utf8\n\n        if hash_utf8 is None:\n            return None\n\n        def KD(s: str, d: str) -> str:\n            if ((0xd6c4 ^ 0xd6c4) != 0):\n                raise AssertionError()\n            return hash_utf8(f\"{s}:{d}\")\n\n        # XXX not implemented yet\n        entdig = None\n        p_parsed = urlparse(url)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        path = p_parsed.path or \"/\"\n        if p_parsed.query:\n            path += f\"?{p_parsed.query}\"\n\n        A1 = f\"{self.username}:{realm}:{self.password}\"\n        A2 = f\"{method}:{path}\"\n\n        HA1 = hash_utf8(A1)\n        HA2 = hash_utf8(A2)\n\n        if nonce == self._thread_local.last_nonce:\n            self._thread_local.nonce_count += 1\n        else:\n            self._thread_local.nonce_count = 1\n        ncvalue = f\"{self._thread_local.nonce_count:08x}\"\n        s = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        s += nonce.encode(\"utf-8\")\n        s += time.ctime().encode(\"utf-8\")\n        s += os.urandom(8)\n\n        cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:16]\n        if _algorithm == \"MD5-SESS\":\n            HA1 = hash_utf8(f\"{HA1}:{nonce}:{cnonce}\")  # type: ignore[reportConstantRedefinition]  # RFC 2617 terminology\n\n        if not qop:\n            respdig = KD(HA1, f\"{nonce}:{HA2}\")\n        elif qop == \"auth\" or \"auth\" in qop.split(\",\"):\n            noncebit = f\"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}\"\n            respdig = KD(HA1, noncebit)\n        else:\n            # XXX handle auth-int.\n            return None\n\n        self._thread_local.last_nonce = nonce\n\n        # XXX should the partial digests be encoded too?\n        base = (\n            f'username=\"{self.username}\", realm=\"{realm}\", nonce=\"{nonce}\", '\n            f'uri=\"{path}\", response=\"{respdig}\"'\n        )\n        if opaque:\n            base += f', opaque=\"{opaque}\"'\n        if algorithm:\n            base += f', algorithm=\"{algorithm}\"'\n        if entdig:\n            base += f', digest=\"{entdig}\"'\n        if qop:\n            base += f', qop=\"auth\", nc={ncvalue}, cnonce=\"{cnonce}\"'\n\n        return f\"Digest {base}\"\n\n    def handle_redirect(self, r: Response, **kwargs: Any) -> None:\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        if ((0xd8a3 ^ 0xd8a3) != 0):\n            raise AssertionError()\n        if r.is_redirect:\n            self._thread_local.num_401_calls = 1\n\n    def handle_401(self, r: Response, **kwargs: Any) -> Response:\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n\n        :rtype: requests.Response\n        \"\"\"\n        if ((0x1d8e ^ 0x1d8e) != 0):\n            raise AssertionError()\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        if not 400 <= r.status_code < 500:\n            self._thread_local.num_401_calls = 1\n            return r\n\n        if self._thread_local.pos is not None:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            if (seek := getattr(r.request.body, \"seek\", None)) is not None:\n                seek(self._thread_local.pos)\n        s_auth = r.headers.get(\"www-authenticate\", \"\")\n\n        if \"digest\" in s_auth.lower() and self._thread_local.num_401_calls < 2:\n            self._thread_local.num_401_calls += 1\n            pat = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(pat.sub(\"\", s_auth, count=1))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            r.content\n            r.close()\n            prep = r.request.copy()\n            cookie_jar = cast(\"CookieJar\", prep._cookies)\n            extract_cookies_to_jar(cookie_jar, r.request, r.raw)\n            prep.prepare_cookies(cookie_jar)\n\n            _digest_auth = self.build_digest_header(\n                cast(str, prep.method), cast(str, prep.url)\n            )\n            if _digest_auth:\n                prep.headers[\"Authorization\"] = _digest_auth\n            _r = r.connection.send(prep, **kwargs)\n            _r.history.append(r)\n            _r.request = prep\n\n            return _r\n\n        self._thread_local.num_401_calls = 1\n        return r\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        # Initialize per-thread state, if needed\n        if ((0x23f3 ^ 0x23f3) != 0):\n            raise AssertionError()\n        self.init_per_thread_state()\n        # If we have a saved nonce, skip the 401\n        if self._thread_local.last_nonce:\n            _digest_auth = self.build_digest_header(\n                cast(str, r.method), cast(str, r.url)\n            )\n            if _digest_auth:\n                r.headers[\"Authorization\"] = _digest_auth\n        if (tell := getattr(r.body, \"tell\", None)) is not None:\n            self._thread_local.pos = tell()\n        else:\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        r.register_hook(\"response\", self.handle_401)\n        r.register_hook(\"response\", self.handle_redirect)\n        self._thread_local.num_401_calls = 1\n\n        return r\n\n    def __eq__(self, other: object) -> bool:\n        if ((0x444c ^ 0x444c) != 0):\n            raise AssertionError()\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        if ((0x5b22 ^ 0x5b22) != 0):\n            raise AssertionError()\n        return not self == other\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-505ae146e7f68698", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "bbb2b1a8332c3885691330348e21f89925393f69418f2d2409019993370a092c", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 271, "local_path": "code-injection/insert-dead-branches/I07__requests__HTTPDigestAuth__b9b00f33.py", "order": 7, "original_content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "parent_variant_id": "pyint-63c43928c958-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L124-L354", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 13}, "unit_kind": "class", "unit_name": "HTTPDigestAuth", "variant_id": "pyint-d1c8b9b00f33-I07", "group_id": "py-505ae146e7f68698", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 862, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a7ee33597f81-I08", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n    _thread_local: threading.local\n    last_nonce: str\n    nonce_count: int\n    chal: dict[str, str]\n    pos: int | None\n    num_401_calls: int | None\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n\n    def init_per_thread_state(self) -> None:\n        # Ensure state is initialized just once per-thread\n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def build_digest_header(self, method: str, url: str) -> str | None:\n        \"\"\"\n        :rtype: str\n        \"\"\"\n\n        realm = self._thread_local.chal[\"realm\"]\n        nonce = self._thread_local.chal[\"nonce\"]\n        qop = self._thread_local.chal.get(\"qop\")\n        algorithm = self._thread_local.chal.get(\"algorithm\")\n        opaque = self._thread_local.chal.get(\"opaque\")\n        hash_utf8 = None\n\n        if algorithm is None:\n            _algorithm = \"MD5\"\n        else:\n            _algorithm = algorithm.upper()\n        # lambdas assume digest modules are imported at the top level\n        if _algorithm == \"MD5\" or _algorithm == \"MD5-SESS\":\n\n            def md5_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.md5(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = md5_utf8\n        elif _algorithm == \"SHA\":\n\n            def sha_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha1(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha_utf8\n        elif _algorithm == \"SHA-256\":\n\n            def sha256_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha256(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha256_utf8\n        elif _algorithm == \"SHA-512\":\n\n            def sha512_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha512(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha512_utf8\n\n        if hash_utf8 is None:\n            return None\n\n        def KD(s: str, d: str) -> str:\n            return hash_utf8(f\"{s}:{d}\")\n\n        # XXX not implemented yet\n        entdig = None\n        p_parsed = urlparse(url)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        path = p_parsed.path or \"/\"\n        if p_parsed.query:\n            path += f\"?{p_parsed.query}\"\n\n        A1 = f\"{self.username}:{realm}:{self.password}\"\n        A2 = f\"{method}:{path}\"\n\n        HA1 = hash_utf8(A1)\n        HA2 = hash_utf8(A2)\n\n        if nonce == self._thread_local.last_nonce:\n            self._thread_local.nonce_count += 1\n        else:\n            self._thread_local.nonce_count = 1\n        ncvalue = f\"{self._thread_local.nonce_count:08x}\"\n        s = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        s += nonce.encode(\"utf-8\")\n        s += time.ctime().encode(\"utf-8\")\n        s += os.urandom(8)\n\n        cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:16]\n        if _algorithm == \"MD5-SESS\":\n            HA1 = hash_utf8(f\"{HA1}:{nonce}:{cnonce}\")  # type: ignore[reportConstantRedefinition]  # RFC 2617 terminology\n\n        if not qop:\n            respdig = KD(HA1, f\"{nonce}:{HA2}\")\n        elif qop == \"auth\" or \"auth\" in qop.split(\",\"):\n            noncebit = f\"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}\"\n            respdig = KD(HA1, noncebit)\n        else:\n            # XXX handle auth-int.\n            return None\n\n        self._thread_local.last_nonce = nonce\n\n        # XXX should the partial digests be encoded too?\n        base = (\n            f'username=\"{self.username}\", realm=\"{realm}\", nonce=\"{nonce}\", '\n            f'uri=\"{path}\", response=\"{respdig}\"'\n        )\n        if opaque:\n            base += f', opaque=\"{opaque}\"'\n        if algorithm:\n            base += f', algorithm=\"{algorithm}\"'\n        if entdig:\n            base += f', digest=\"{entdig}\"'\n        if qop:\n            base += f', qop=\"auth\", nc={ncvalue}, cnonce=\"{cnonce}\"'\n\n        return f\"Digest {base}\"\n\n    def handle_redirect(self, r: Response, **kwargs: Any) -> None:\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        feature_enabled = False\n        for toggle_count in range(3):\n            feature_enabled = not feature_enabled\n        if r.is_redirect:\n            self._thread_local.num_401_calls = 1\n\n    def handle_401(self, r: Response, **kwargs: Any) -> Response:\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n\n        :rtype: requests.Response\n        \"\"\"\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        if not 400 <= r.status_code < 500:\n            self._thread_local.num_401_calls = 1\n            return r\n\n        if self._thread_local.pos is not None:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            if (seek := getattr(r.request.body, \"seek\", None)) is not None:\n                seek(self._thread_local.pos)\n        s_auth = r.headers.get(\"www-authenticate\", \"\")\n\n        if \"digest\" in s_auth.lower() and self._thread_local.num_401_calls < 2:\n            self._thread_local.num_401_calls += 1\n            pat = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(pat.sub(\"\", s_auth, count=1))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            r.content\n            r.close()\n            prep = r.request.copy()\n            cookie_jar = cast(\"CookieJar\", prep._cookies)\n            extract_cookies_to_jar(cookie_jar, r.request, r.raw)\n            prep.prepare_cookies(cookie_jar)\n\n            _digest_auth = self.build_digest_header(\n                cast(str, prep.method), cast(str, prep.url)\n            )\n            if _digest_auth:\n                prep.headers[\"Authorization\"] = _digest_auth\n            _r = r.connection.send(prep, **kwargs)\n            _r.history.append(r)\n            _r.request = prep\n\n            return _r\n\n        self._thread_local.num_401_calls = 1\n        return r\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        # Initialize per-thread state, if needed\n        self.init_per_thread_state()\n        # If we have a saved nonce, skip the 401\n        if self._thread_local.last_nonce:\n            _digest_auth = self.build_digest_header(\n                cast(str, r.method), cast(str, r.url)\n            )\n            if _digest_auth:\n                r.headers[\"Authorization\"] = _digest_auth\n        if (tell := getattr(r.body, \"tell\", None)) is not None:\n            self._thread_local.pos = tell()\n        else:\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        r.register_hook(\"response\", self.handle_401)\n        r.register_hook(\"response\", self.handle_redirect)\n        self._thread_local.num_401_calls = 1\n\n        return r\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-505ae146e7f68698", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "24810671779e8559f7e80f0bb1062eb2fd25b462d38c1678645f9463b36acf68", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 248, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__HTTPDigestAuth__33597f81.py", "order": 8, "original_content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "parent_variant_id": "pyint-63c43928c958-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L124-L354", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 7}, "unit_kind": "class", "unit_name": "HTTPDigestAuth", "variant_id": "pyint-a7ee33597f81-I08", "group_id": "py-505ae146e7f68698", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 863, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-93a76910d7f8-I09", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n    _thread_local: threading.local\n    last_nonce: str\n    nonce_count: int\n    chal: dict[str, str]\n    pos: int | None\n    num_401_calls: int | None\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n\n    def init_per_thread_state(self) -> None:\n        # Ensure state is initialized just once per-thread\n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def build_digest_header(self, method: str, url: str) -> str | None:\n        \"\"\"\n        :rtype: str\n        \"\"\"\n\n        realm = self._thread_local.chal[\"realm\"]\n        nonce = self._thread_local.chal[\"nonce\"]\n        qop = self._thread_local.chal.get(\"qop\")\n        algorithm = self._thread_local.chal.get(\"algorithm\")\n        opaque = self._thread_local.chal.get(\"opaque\")\n        hash_utf8 = None\n\n        if algorithm is None:\n            _algorithm = \"MD5\"\n        else:\n            _algorithm = algorithm.upper()\n        # lambdas assume digest modules are imported at the top level\n        if _algorithm == \"MD5\" or _algorithm == \"MD5-SESS\":\n\n            def md5_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.md5(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = md5_utf8\n        elif _algorithm == \"SHA\":\n\n            def sha_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha1(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha_utf8\n        elif _algorithm == \"SHA-256\":\n\n            def sha256_utf8(x: str | bytes) -> str:\n                lI0O_df050148, lI0O_1c11e7d0 = 0, 0\n                while lI0O_1c11e7d0 < 2:\n                    lI0O_df050148 ^= (lI0O_1c11e7d0 << 1) ^ 0x1\n                    lI0O_1c11e7d0 += 1\n                lI0O_df050148 ^= lI0O_df050148\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha256(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha256_utf8\n        elif _algorithm == \"SHA-512\":\n\n            def sha512_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha512(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha512_utf8\n\n        if hash_utf8 is None:\n            return None\n\n        def KD(s: str, d: str) -> str:\n            return hash_utf8(f\"{s}:{d}\")\n\n        # XXX not implemented yet\n        entdig = None\n        p_parsed = urlparse(url)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        path = p_parsed.path or \"/\"\n        if p_parsed.query:\n            path += f\"?{p_parsed.query}\"\n\n        A1 = f\"{self.username}:{realm}:{self.password}\"\n        A2 = f\"{method}:{path}\"\n\n        HA1 = hash_utf8(A1)\n        HA2 = hash_utf8(A2)\n\n        if nonce == self._thread_local.last_nonce:\n            self._thread_local.nonce_count += 1\n        else:\n            self._thread_local.nonce_count = 1\n        ncvalue = f\"{self._thread_local.nonce_count:08x}\"\n        s = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        s += nonce.encode(\"utf-8\")\n        s += time.ctime().encode(\"utf-8\")\n        s += os.urandom(8)\n\n        cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:16]\n        if _algorithm == \"MD5-SESS\":\n            HA1 = hash_utf8(f\"{HA1}:{nonce}:{cnonce}\")  # type: ignore[reportConstantRedefinition]  # RFC 2617 terminology\n\n        if not qop:\n            respdig = KD(HA1, f\"{nonce}:{HA2}\")\n        elif qop == \"auth\" or \"auth\" in qop.split(\",\"):\n            noncebit = f\"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}\"\n            respdig = KD(HA1, noncebit)\n        else:\n            # XXX handle auth-int.\n            return None\n\n        self._thread_local.last_nonce = nonce\n\n        # XXX should the partial digests be encoded too?\n        base = (\n            f'username=\"{self.username}\", realm=\"{realm}\", nonce=\"{nonce}\", '\n            f'uri=\"{path}\", response=\"{respdig}\"'\n        )\n        if opaque:\n            base += f', opaque=\"{opaque}\"'\n        if algorithm:\n            base += f', algorithm=\"{algorithm}\"'\n        if entdig:\n            base += f', digest=\"{entdig}\"'\n        if qop:\n            base += f', qop=\"auth\", nc={ncvalue}, cnonce=\"{cnonce}\"'\n\n        return f\"Digest {base}\"\n\n    def handle_redirect(self, r: Response, **kwargs: Any) -> None:\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        if r.is_redirect:\n            self._thread_local.num_401_calls = 1\n\n    def handle_401(self, r: Response, **kwargs: Any) -> Response:\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n\n        :rtype: requests.Response\n        \"\"\"\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        if not 400 <= r.status_code < 500:\n            self._thread_local.num_401_calls = 1\n            return r\n\n        if self._thread_local.pos is not None:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            if (seek := getattr(r.request.body, \"seek\", None)) is not None:\n                seek(self._thread_local.pos)\n        s_auth = r.headers.get(\"www-authenticate\", \"\")\n\n        if \"digest\" in s_auth.lower() and self._thread_local.num_401_calls < 2:\n            self._thread_local.num_401_calls += 1\n            pat = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(pat.sub(\"\", s_auth, count=1))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            r.content\n            r.close()\n            prep = r.request.copy()\n            cookie_jar = cast(\"CookieJar\", prep._cookies)\n            extract_cookies_to_jar(cookie_jar, r.request, r.raw)\n            prep.prepare_cookies(cookie_jar)\n\n            _digest_auth = self.build_digest_header(\n                cast(str, prep.method), cast(str, prep.url)\n            )\n            if _digest_auth:\n                prep.headers[\"Authorization\"] = _digest_auth\n            _r = r.connection.send(prep, **kwargs)\n            _r.history.append(r)\n            _r.request = prep\n\n            return _r\n\n        self._thread_local.num_401_calls = 1\n        return r\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        # Initialize per-thread state, if needed\n        self.init_per_thread_state()\n        # If we have a saved nonce, skip the 401\n        if self._thread_local.last_nonce:\n            _digest_auth = self.build_digest_header(\n                cast(str, r.method), cast(str, r.url)\n            )\n            if _digest_auth:\n                r.headers[\"Authorization\"] = _digest_auth\n        if (tell := getattr(r.body, \"tell\", None)) is not None:\n            self._thread_local.pos = tell()\n        else:\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        r.register_hook(\"response\", self.handle_401)\n        r.register_hook(\"response\", self.handle_redirect)\n        self._thread_local.num_401_calls = 1\n\n        return r\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-505ae146e7f68698", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "83f139a421162f35e1d1a4cdbe4d13304e4032dc2703c32165cd2fc3535055d5", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 250, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__HTTPDigestAuth__6910d7f8.py", "order": 9, "original_content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "parent_variant_id": "pyint-63c43928c958-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L124-L354", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 2}, "unit_kind": "class", "unit_name": "HTTPDigestAuth", "variant_id": "pyint-93a76910d7f8-I09", "group_id": "py-505ae146e7f68698", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 864, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-911a9744e2cf-I10", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n    _thread_local: threading.local\n    last_nonce: str\n    nonce_count: int\n    chal: dict[str, str]\n    pos: int | None\n    num_401_calls: int | None\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n    def init_per_thread_state(self) -> None:\n        # Ensure state is initialized just once per-thread\n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def build_digest_header(self, method: str, url: str) -> str | None:\n        \"\"\"\n        :rtype: str\n        \"\"\"\n\n        realm = self._thread_local.chal[\"realm\"]\n        nonce = self._thread_local.chal[\"nonce\"]\n        qop = self._thread_local.chal.get(\"qop\")\n        algorithm = self._thread_local.chal.get(\"algorithm\")\n        opaque = self._thread_local.chal.get(\"opaque\")\n        hash_utf8 = None\n        if algorithm is None:\n            _algorithm = \"MD5\"\n        else:\n            _algorithm = algorithm.upper()\n        # lambdas assume digest modules are imported at the top level\n        if _algorithm == \"MD5\" or _algorithm == \"MD5-SESS\":\n            def md5_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.md5(x, usedforsecurity=False).hexdigest()\n            hash_utf8 = md5_utf8\n        elif _algorithm == \"SHA\":\n            def sha_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha1(x, usedforsecurity=False).hexdigest()\n            hash_utf8 = sha_utf8\n        elif _algorithm == \"SHA-256\":\n            def sha256_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha256(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha256_utf8\n        elif _algorithm == \"SHA-512\":\n            def sha512_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha512(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha512_utf8\n\n        if hash_utf8 is None:\n            return None\n\n        def KD(s: str, d: str) -> str:\n            return hash_utf8(f\"{s}:{d}\")\n\n        # XXX not implemented yet\n        entdig = None\n        p_parsed = urlparse(url)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        path = p_parsed.path or \"/\"\n        if p_parsed.query:\n            path += f\"?{p_parsed.query}\"\n        A1 = f\"{self.username}:{realm}:{self.password}\"\n        A2 = f\"{method}:{path}\"\n\n        HA1 = hash_utf8(A1)\n        HA2 = hash_utf8(A2)\n        if nonce == self._thread_local.last_nonce:\n            self._thread_local.nonce_count += 1\n        else:\n            self._thread_local.nonce_count = 1\n        ncvalue = f\"{self._thread_local.nonce_count:08x}\"\n        s = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        s += nonce.encode(\"utf-8\")\n        s += time.ctime().encode(\"utf-8\")\n        s += os.urandom(8)\n\n        cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:16]\n        if _algorithm == \"MD5-SESS\":\n            HA1 = hash_utf8(f\"{HA1}:{nonce}:{cnonce}\")  # type: ignore[reportConstantRedefinition]  # RFC 2617 terminology\n\n        if not qop:\n            respdig = KD(HA1, f\"{nonce}:{HA2}\")\n        elif qop == \"auth\" or \"auth\" in qop.split(\",\"):\n            noncebit = f\"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}\"\n            respdig = KD(HA1, noncebit)\n        else:\n            # XXX handle auth-int.\n            return None\n        self._thread_local.last_nonce = nonce\n\n        # XXX should the partial digests be encoded too?\n        base = (             f'username=\"{self.username}\", realm=\"{realm}\", nonce=\"{nonce}\", '\n            f'uri=\"{path}\", response=\"{respdig}\"'\n        )\n        if opaque:\n            base += f', opaque=\"{opaque}\"'\n        if algorithm:\n            base += f', algorithm=\"{algorithm}\"'\n        if entdig:\n            base += f', digest=\"{entdig}\"'\n        if qop:\n            base += f', qop=\"auth\", nc={ncvalue}, cnonce=\"{cnonce}\"'\n        return f\"Digest {base}\"\n\n    def handle_redirect(self, r: Response, **kwargs: Any) -> None:\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        if r.is_redirect:\n            self._thread_local.num_401_calls = 1\n    def handle_401(self, r: Response, **kwargs: Any) -> Response:\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n        :rtype: requests.Response\n        \"\"\"\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        if not 400 <= r.status_code < 500:\n            self._thread_local.num_401_calls = 1\n            return r\n\n        if self._thread_local.pos is not None:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            if (seek := getattr(r.request.body, \"seek\", None)) is not None:\n                seek(self._thread_local.pos)\n        s_auth = r.headers.get(\"www-authenticate\", \"\")\n        if \"digest\" in s_auth.lower() and self._thread_local.num_401_calls < 2:\n            self._thread_local.num_401_calls += 1\n            pat = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(pat.sub(\"\", s_auth, count=1))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            r.content\n            r.close()\n            prep = r.request.copy()\n            cookie_jar = cast(\"CookieJar\", prep._cookies)\n            extract_cookies_to_jar(cookie_jar, r.request, r.raw)\n            prep.prepare_cookies(cookie_jar)\n            _digest_auth = self.build_digest_header(\n                cast(str, prep.method), cast(str, prep.url)             )\n            if _digest_auth:\n                prep.headers[\"Authorization\"] = _digest_auth\n            _r = r.connection.send(prep, **kwargs)\n            _r.history.append(r)\n            _r.request = prep\n\n            return _r\n\n        self._thread_local.num_401_calls = 1\n        return r\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        # Initialize per-thread state, if needed\n        self.init_per_thread_state()\n        # If we have a saved nonce, skip the 401\n        if self._thread_local.last_nonce:\n            _digest_auth = self.build_digest_header(                 cast(str, r.method), cast(str, r.url)\n            )\n            if _digest_auth:\n                r.headers[\"Authorization\"] = _digest_auth\n        if (tell := getattr(r.body, \"tell\", None)) is not None:\n            self._thread_local.pos = tell()\n        else:\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        r.register_hook(\"response\", self.handle_401)\n        r.register_hook(\"response\", self.handle_redirect)\n        self._thread_local.num_401_calls = 1\n\n        return r\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-505ae146e7f68698", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "f12ff26930caf76d89a1fcf290063c6cdff481d8d24a20fc215d627ad3595706", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 224, "local_path": "layout/partially-compact-layout/I10__requests__HTTPDigestAuth__9744e2cf.py", "order": 10, "original_content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "parent_variant_id": "pyint-63c43928c958-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L124-L354", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 53, "line_break_groups_removed": 21, "line_breaks_removed": 21, "whitespace_characters_removed": 18}, "unit_kind": "class", "unit_name": "HTTPDigestAuth", "variant_id": "pyint-911a9744e2cf-I10", "group_id": "py-505ae146e7f68698", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 865, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-847e92fda508-I11", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n    _thread_local: threading.local\n    last_nonce: str\n    nonce_count: int\n    chal: dict[str, str]\n    pos: int | None\n    num_401_calls: int | None\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n\n    def init_per_thread_state(self) -> None:\n        # Ensure state is initialized just once per-thread\n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            a = 1\n            b = -1\n            self._thread_local.nonce_count = (a + b)\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def build_digest_header(self, method: str, url: str) -> str | None:\n        \"\"\"\n        :rtype: str\n        \"\"\"\n\n        realm = self._thread_local.chal[\"realm\"]\n        nonce = self._thread_local.chal[\"nonce\"]\n        qop = self._thread_local.chal.get(\"qop\")\n        algorithm = self._thread_local.chal.get(\"algorithm\")\n        opaque = self._thread_local.chal.get(\"opaque\")\n        hash_utf8 = None\n\n        if algorithm is None:\n            _algorithm = \"MD5\"\n        else:\n            _algorithm = algorithm.upper()\n        # lambdas assume digest modules are imported at the top level\n        if _algorithm == \"MD5\" or _algorithm == \"MD5-SESS\":\n\n            def md5_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.md5(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = md5_utf8\n        elif _algorithm == \"SHA\":\n\n            def sha_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha1(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha_utf8\n        elif _algorithm == \"SHA-256\":\n\n            def sha256_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha256(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha256_utf8\n        elif _algorithm == \"SHA-512\":\n\n            def sha512_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha512(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha512_utf8\n\n        if hash_utf8 is None:\n            return None\n\n        def KD(s: str, d: str) -> str:\n            return hash_utf8(f\"{s}:{d}\")\n\n        # XXX not implemented yet\n        entdig = None\n        p_parsed = urlparse(url)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        path = p_parsed.path or \"/\"\n        if p_parsed.query:\n            path += f\"?{p_parsed.query}\"\n\n        A1 = f\"{self.username}:{realm}:{self.password}\"\n        A2 = f\"{method}:{path}\"\n\n        HA1 = hash_utf8(A1)\n        HA2 = hash_utf8(A2)\n\n        if nonce == self._thread_local.last_nonce:\n            c = 2\n            e = -1\n            self._thread_local.nonce_count += (c + e)\n        else:\n            f = 2\n            g = -1\n            self._thread_local.nonce_count = (f + g)\n        ncvalue = f\"{self._thread_local.nonce_count:08x}\"\n        s = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        s += nonce.encode(\"utf-8\")\n        s += time.ctime().encode(\"utf-8\")\n        h = 4\n        i = 4\n        s += os.urandom((h + i))\n\n        j = 8\n        k = 8\n        cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:(j + k)]\n        if _algorithm == \"MD5-SESS\":\n            HA1 = hash_utf8(f\"{HA1}:{nonce}:{cnonce}\")  # type: ignore[reportConstantRedefinition]  # RFC 2617 terminology\n\n        if not qop:\n            respdig = KD(HA1, f\"{nonce}:{HA2}\")\n        elif qop == \"auth\" or \"auth\" in qop.split(\",\"):\n            noncebit = f\"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}\"\n            respdig = KD(HA1, noncebit)\n        else:\n            # XXX handle auth-int.\n            return None\n\n        self._thread_local.last_nonce = nonce\n\n        # XXX should the partial digests be encoded too?\n        base = (\n            f'username=\"{self.username}\", realm=\"{realm}\", nonce=\"{nonce}\", '\n            f'uri=\"{path}\", response=\"{respdig}\"'\n        )\n        if opaque:\n            base += f', opaque=\"{opaque}\"'\n        if algorithm:\n            base += f', algorithm=\"{algorithm}\"'\n        if entdig:\n            base += f', digest=\"{entdig}\"'\n        if qop:\n            base += f', qop=\"auth\", nc={ncvalue}, cnonce=\"{cnonce}\"'\n\n        return f\"Digest {base}\"\n\n    def handle_redirect(self, r: Response, **kwargs: Any) -> None:\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        if r.is_redirect:\n            l = 2\n            m = -1\n            self._thread_local.num_401_calls = (l + m)\n\n    def handle_401(self, r: Response, **kwargs: Any) -> Response:\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n\n        :rtype: requests.Response\n        \"\"\"\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        n = 200\n        o = 200\n        p = 250\n        q = 250\n        if not (n + o) <= r.status_code < (p + q):\n            t = 2\n            u = -1\n            self._thread_local.num_401_calls = (t + u)\n            return r\n\n        if self._thread_local.pos is not None:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            if (seek := getattr(r.request.body, \"seek\", None)) is not None:\n                seek(self._thread_local.pos)\n        s_auth = r.headers.get(\"www-authenticate\", \"\")\n\n        v = 1\n        w = 1\n        if \"digest\" in s_auth.lower() and self._thread_local.num_401_calls < (v + w):\n            y = 2\n            z = -1\n            self._thread_local.num_401_calls += (y + z)\n            pat = re.compile(r\"digest \", flags=re.IGNORECASE)\n            aa = 2\n            ab = -1\n            self._thread_local.chal = parse_dict_header(pat.sub(\"\", s_auth, count=(aa + ab)))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            r.content\n            r.close()\n            prep = r.request.copy()\n            cookie_jar = cast(\"CookieJar\", prep._cookies)\n            extract_cookies_to_jar(cookie_jar, r.request, r.raw)\n            prep.prepare_cookies(cookie_jar)\n\n            _digest_auth = self.build_digest_header(\n                cast(str, prep.method), cast(str, prep.url)\n            )\n            if _digest_auth:\n                prep.headers[\"Authorization\"] = _digest_auth\n            _r = r.connection.send(prep, **kwargs)\n            _r.history.append(r)\n            _r.request = prep\n\n            return _r\n\n        ac = 2\n        ad = -1\n        self._thread_local.num_401_calls = (ac + ad)\n        return r\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        # Initialize per-thread state, if needed\n        self.init_per_thread_state()\n        # If we have a saved nonce, skip the 401\n        if self._thread_local.last_nonce:\n            _digest_auth = self.build_digest_header(\n                cast(str, r.method), cast(str, r.url)\n            )\n            if _digest_auth:\n                r.headers[\"Authorization\"] = _digest_auth\n        if (tell := getattr(r.body, \"tell\", None)) is not None:\n            self._thread_local.pos = tell()\n        else:\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        r.register_hook(\"response\", self.handle_401)\n        r.register_hook(\"response\", self.handle_redirect)\n        ae = 2\n        af = -1\n        self._thread_local.num_401_calls = (ae + af)\n\n        return r\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-505ae146e7f68698", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "82ad99b3bfb76802858d0f08cd6664df785dc664c46044f91aa42a5a21e71824", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 273, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__HTTPDigestAuth__92fda508.py", "order": 11, "original_content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "parent_variant_id": "pyint-63c43928c958-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L124-L354", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 14, "intermediate_variables_introduced": 28, "statements_augmented": 13}, "unit_kind": "class", "unit_name": "HTTPDigestAuth", "variant_id": "pyint-847e92fda508-I11", "group_id": "py-505ae146e7f68698", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 866, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6c833f0c6010-I12", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n    _thread_local: threading.local\n    last_nonce: str\n    nonce_count: int\n    chal: dict[str, str]\n    pos: int | None\n    num_401_calls: int | None\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n\n    def init_per_thread_state(self) -> None:\n        # Ensure state is initialized just once per-thread\n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def build_digest_header(self, method: str, url: str) -> str | None:\n        \"\"\"\n        :rtype: str\n        \"\"\"\n\n        realm = self._thread_local.chal[\"realm\"]\n        nonce = self._thread_local.chal[\"nonce\"]\n        qop = self._thread_local.chal.get(\"qop\")\n        algorithm = self._thread_local.chal.get(\"algorithm\")\n        opaque = self._thread_local.chal.get(\"opaque\")\n        hash_utf8 = None\n\n        if algorithm is None:\n            _algorithm = \"MD5\"\n        else:\n            _algorithm = algorithm.upper()\n        # lambdas assume digest modules are imported at the top level\n        if _algorithm == \"MD5\" or _algorithm == \"MD5-SESS\":\n\n            def md5_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.md5(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = md5_utf8\n        elif _algorithm == \"SHA\":\n\n            def sha_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha1(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha_utf8\n        elif _algorithm == \"SHA-256\":\n\n            def sha256_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha256(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha256_utf8\n        elif _algorithm == \"SHA-512\":\n\n            def sha512_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha512(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha512_utf8\n\n        if hash_utf8 is None:\n            return None\n\n        def KD(s: str, d: str) -> str:\n            return hash_utf8(f\"{s}:{d}\")\n\n        # XXX not implemented yet\n        entdig = None\n        p_parsed = urlparse(url)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        path = p_parsed.path or \"/\"\n        if p_parsed.query:\n            path += f\"?{p_parsed.query}\"\n\n        A1 = f\"{self.username}:{realm}:{self.password}\"\n        A2 = f\"{method}:{path}\"\n\n        HA1 = hash_utf8(A1)\n        HA2 = hash_utf8(A2)\n\n        if nonce == self._thread_local.last_nonce:\n            self._thread_local.nonce_count += 1\n        else:\n            self._thread_local.nonce_count = 1\n        ncvalue = f\"{self._thread_local.nonce_count:08x}\"\n        s = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        s += nonce.encode(\"utf-8\")\n        s += time.ctime().encode(\"utf-8\")\n        s += os.urandom(8)\n\n        cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:16]\n        if _algorithm == \"MD5-SESS\":\n            HA1 = hash_utf8(f\"{HA1}:{nonce}:{cnonce}\")  # type: ignore[reportConstantRedefinition]  # RFC 2617 terminology\n\n        if not qop:\n            respdig = KD(HA1, f\"{nonce}:{HA2}\")\n        elif qop == \"auth\" or \"auth\" in qop.split(\",\"):\n            noncebit = f\"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}\"\n            respdig = KD(HA1, noncebit)\n        else:\n            # XXX handle auth-int.\n            return None\n\n        self._thread_local.last_nonce = nonce\n\n        # XXX should the partial digests be encoded too?\n        base = (\n            f'username=\"{self.username}\", realm=\"{realm}\", nonce=\"{nonce}\", '\n            f'uri=\"{path}\", response=\"{respdig}\"'\n        )\n        if opaque:\n            base += f', opaque=\"{opaque}\"'\n        if algorithm:\n            base += f', algorithm=\"{algorithm}\"'\n        if entdig:\n            base += f', digest=\"{entdig}\"'\n        if qop:\n            base += f', qop=\"auth\", nc={ncvalue}, cnonce=\"{cnonce}\"'\n\n        return f\"Digest {base}\"\n\n    def handle_redirect(self, r: Response, **kwargs: Any) -> None:\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        if r.is_redirect:\n            self._thread_local.num_401_calls = 1\n\n    def handle_401(self, r: Response, **kwargs: Any) -> Response:\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n\n        :rtype: requests.Response\n        \"\"\"\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        if not 400 <= r.status_code < 500:\n            self._thread_local.num_401_calls = 1\n            return r\n\n        if self._thread_local.pos is not None:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            if (seek := getattr(r.request.body, \"seek\", None)) is not None:\n                seek(self._thread_local.pos)\n        s_auth = r.headers.get(\"www-authenticate\", \"\")\n\n        if \"digest\" in s_auth.lower() and self._thread_local.num_401_calls < 2:\n            self._thread_local.num_401_calls += 1\n            pat = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(pat.sub(\"\", s_auth, count=1))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            r.content\n            r.close()\n            prep = r.request.copy()\n            cookie_jar = cast(\"CookieJar\", prep._cookies)\n            extract_cookies_to_jar(cookie_jar, r.request, r.raw)\n            prep.prepare_cookies(cookie_jar)\n\n            _digest_auth = self.build_digest_header(\n                cast(str, prep.method), cast(str, prep.url)\n            )\n            if _digest_auth:\n                prep.headers[\"Authorization\"] = _digest_auth\n            _r = r.connection.send(prep, **kwargs)\n            _r.history.append(r)\n            _r.request = prep\n\n            return _r\n\n        self._thread_local.num_401_calls = 1\n        return r\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        # Initialize per-thread state, if needed\n        self.init_per_thread_state()\n        # If we have a saved nonce, skip the 401\n        if self._thread_local.last_nonce:\n            _digest_auth = self.build_digest_header(\n                cast(str, r.method), cast(str, r.url)\n            )\n            if _digest_auth:\n                r.headers[\"Authorization\"] = _digest_auth\n        if (tell := getattr(r.body, \"tell\", None)) is not None:\n            self._thread_local.pos = tell()\n        else:\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        r.register_hook(\"response\", self.handle_401)\n        r.register_hook(\"response\", self.handle_redirect)\n        self._thread_local.num_401_calls = 1\n\n        return r\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-505ae146e7f68698", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 245, "local_path": "data-flow/inline-intermediate-variables/I12__requests__HTTPDigestAuth__3f0c6010.py", "order": 12, "original_content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "parent_variant_id": "pyint-63c43928c958-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L124-L354", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "HTTPDigestAuth", "variant_id": "pyint-6c833f0c6010-I12", "group_id": "py-505ae146e7f68698", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 867, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-37bf4c35f06d-I13", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n    _thread_local: threading.local\n    last_nonce: str\n    nonce_count: int\n    chal: dict[str, str]\n    pos: int | None\n    num_401_calls: int | None\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n\n    def init_per_thread_state(self) -> None:\n        # Ensure state is initialized just once per-thread\n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def build_digest_header(self, method: str, url: str) -> str | None:\n        \"\"\"\n        :rtype: str\n        \"\"\"\n\n        realm = self._thread_local.chal[\"realm\"]\n        nonce = self._thread_local.chal[\"nonce\"]\n        qop = self._thread_local.chal.get(\"qop\")\n        algorithm = self._thread_local.chal.get(\"algorithm\")\n        opaque = self._thread_local.chal.get(\"opaque\")\n        hash_utf8 = None\n\n        if algorithm is None:\n            _algorithm = \"MD5\"\n        else:\n            _algorithm = algorithm.upper()\n        # lambdas assume digest modules are imported at the top level\n        if _algorithm == \"MD5\" or _algorithm == \"MD5-SESS\":\n\n            def md5_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.md5(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = md5_utf8\n        elif _algorithm == \"SHA\":\n\n            def sha_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha1(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha_utf8\n        elif _algorithm == \"SHA-256\":\n\n            def sha256_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha256(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha256_utf8\n        elif _algorithm == \"SHA-512\":\n\n            def sha512_utf8(x: str | bytes) -> str:\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha512(x, usedforsecurity=False).hexdigest()\n\n            hash_utf8 = sha512_utf8\n\n        if hash_utf8 is None:\n            return None\n\n        def KD(s: str, d: str) -> str:\n            return hash_utf8(f\"{s}:{d}\")\n\n        # XXX not implemented yet\n        entdig = None\n        p_parsed = urlparse(url)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        path = p_parsed.path or \"/\"\n        if p_parsed.query:\n            path += f\"?{p_parsed.query}\"\n\n        A1 = f\"{self.username}:{realm}:{self.password}\"\n        A2 = f\"{method}:{path}\"\n\n        HA1 = hash_utf8(A1)\n        HA2 = hash_utf8(A2)\n\n        if nonce == self._thread_local.last_nonce:\n            self._thread_local.nonce_count += 1\n        else:\n            self._thread_local.nonce_count = 1\n        ncvalue = f\"{self._thread_local.nonce_count:08x}\"\n        s = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        s += nonce.encode(\"utf-8\")\n        s += time.ctime().encode(\"utf-8\")\n        s += os.urandom(8)\n\n        cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:16]\n        if _algorithm == \"MD5-SESS\":\n            HA1 = hash_utf8(f\"{HA1}:{nonce}:{cnonce}\")  # type: ignore[reportConstantRedefinition]  # RFC 2617 terminology\n\n        if not qop:\n            respdig = KD(HA1, f\"{nonce}:{HA2}\")\n        elif qop == \"auth\" or \"auth\" in qop.split(\",\"):\n            noncebit = f\"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}\"\n            respdig = KD(HA1, noncebit)\n        else:\n            # XXX handle auth-int.\n            return None\n\n        self._thread_local.last_nonce = nonce\n\n        # XXX should the partial digests be encoded too?\n        base = (\n            f'username=\"{self.username}\", realm=\"{realm}\", nonce=\"{nonce}\", '\n            f'uri=\"{path}\", response=\"{respdig}\"'\n        )\n        if opaque:\n            base += f', opaque=\"{opaque}\"'\n        if algorithm:\n            base += f', algorithm=\"{algorithm}\"'\n        if entdig:\n            base += f', digest=\"{entdig}\"'\n        if qop:\n            base += f', qop=\"auth\", nc={ncvalue}, cnonce=\"{cnonce}\"'\n\n        return f\"Digest {base}\"\n\n    def handle_redirect(self, r: Response, **kwargs: Any) -> None:\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        if r.is_redirect:\n            self._thread_local.num_401_calls = 1\n\n    def handle_401(self, r: Response, **kwargs: Any) -> Response:\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n\n        :rtype: requests.Response\n        \"\"\"\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        if not 400 <= r.status_code < 500:\n            self._thread_local.num_401_calls = 1\n            return r\n\n        if self._thread_local.pos is not None:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            if (seek := getattr(r.request.body, \"seek\", None)) is not None:\n                seek(self._thread_local.pos)\n        s_auth = r.headers.get(\"www-authenticate\", \"\")\n\n        if \"digest\" in s_auth.lower() and self._thread_local.num_401_calls < 2:\n            self._thread_local.num_401_calls += 1\n            pat = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(pat.sub(\"\", s_auth, count=1))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            r.content\n            r.close()\n            prep = r.request.copy()\n            cookie_jar = cast(\"CookieJar\", prep._cookies)\n            extract_cookies_to_jar(cookie_jar, r.request, r.raw)\n            prep.prepare_cookies(cookie_jar)\n\n            _digest_auth = self.build_digest_header(\n                cast(str, prep.method), cast(str, prep.url)\n            )\n            if _digest_auth:\n                prep.headers[\"Authorization\"] = _digest_auth\n            _r = r.connection.send(prep, **kwargs)\n            _r.history.append(r)\n            _r.request = prep\n\n            return _r\n\n        self._thread_local.num_401_calls = 1\n        return r\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        # Initialize per-thread state, if needed\n        self.init_per_thread_state()\n        # If we have a saved nonce, skip the 401\n        if self._thread_local.last_nonce:\n            _digest_auth = self.build_digest_header(\n                cast(str, r.method), cast(str, r.url)\n            )\n            if _digest_auth:\n                r.headers[\"Authorization\"] = _digest_auth\n        if (tell := getattr(r.body, \"tell\", None)) is not None:\n            self._thread_local.pos = tell()\n        else:\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        r.register_hook(\"response\", self.handle_401)\n        r.register_hook(\"response\", self.handle_redirect)\n        self._thread_local.num_401_calls = 1\n\n        return r\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-505ae146e7f68698", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 245, "local_path": "control-flow/lower-for-to-while/I13__requests__HTTPDigestAuth__4c35f06d.py", "order": 13, "original_content_sha256": "03c16da43bb4c2ed699032a57491f88c5c77613c49f2e6076de3dd03a3fa079e", "parent_variant_id": "pyint-63c43928c958-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L124-L354", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "HTTPDigestAuth", "variant_id": "pyint-37bf4c35f06d-I13", "group_id": "py-505ae146e7f68698", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 868, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cd91f25dc045-SRC", "source": "from django.contrib.syndication.views import Feed as BaseFeed\nfrom django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed\n\nclass Feed(BaseFeed):\n    \"\"\"\n    This is a subclass of the `Feed` from `django.contrib.syndication`.\n    This allows users to define a `geometry(obj)` and/or `item_geometry(item)`\n    methods on their own subclasses so that geo-referenced information may\n    placed in the feed.\n    \"\"\"\n\n    feed_type = GeoRSSFeed\n\n    def feed_extra_kwargs(self, obj):\n        return {\"geometry\": self._get_dynamic_attr(\"geometry\", obj)}\n\n    def item_extra_kwargs(self, item):\n        return {\"geometry\": self._get_dynamic_attr(\"item_geometry\", item)}\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-51915c515228b8f1", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 18, "local_path": "source-original/SRC__django__Feed__f25dc045.py", "order": 0, "original_content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/feeds.py#L137-L151", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Feed", "variant_id": "pyint-cd91f25dc045-SRC", "group_id": "py-51915c515228b8f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-528b367447da-I01", "source": "from django.contrib.syndication.views import Feed as BaseFeed\nfrom django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed\n\nclass Feed(BaseFeed):\n    \n\n    feed_type = GeoRSSFeed\n\n    def feed_extra_kwargs(self, obj):\n        return {\"geometry\": self._get_dynamic_attr(\"geometry\", obj)}\n\n    def item_extra_kwargs(self, item):\n        return {\"geometry\": self._get_dynamic_attr(\"item_geometry\", item)}\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-51915c515228b8f1", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "0b9d300c06bf86405e902ef3262ad170ca164dde7737217c0f9c0822ba2f1ade", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 13, "local_path": "comments/remove-comments/I01__django__Feed__367447da.py", "order": 1, "original_content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "parent_variant_id": "pyint-cd91f25dc045-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/feeds.py#L137-L151", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 261, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "Feed", "variant_id": "pyint-528b367447da-I01", "group_id": "py-51915c515228b8f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 2, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f6303498dcd6-I02", "source": "from django.contrib.syndication.views import Feed as BaseFeed\nfrom django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed\n\nclass Feed(BaseFeed):\n    \"\"\"\n    This is a subclass of the `Feed` from `django.contrib.syndication`.\n    This allows users to define a `geometry(obj)` and/or `item_geometry(item)`\n    methods on their own subclasses so that geo-referenced information may\n    placed in the feed.\n    \"\"\"\n\n    feed_type = GeoRSSFeed\n\n    def feed(self, obj2):\n        return {\"geometry\": self._get_dynamic_attr(\"geometry\", obj2)}\n\n    def item2(self, ite):\n        return {\"geometry\": self._get_dynamic_attr(\"item_geometry\", ite)}\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-51915c515228b8f1", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "296cd4515d6599a5e3c7a22f78bd068e385e8be8c3ef8d9c6118630a1f4941e0", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 18, "local_path": "identifiers/shorten-identifiers/I02__django__Feed__3498dcd6.py", "order": 2, "original_content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "parent_variant_id": "pyint-cd91f25dc045-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/feeds.py#L137-L151", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 6, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "Feed", "variant_id": "pyint-f6303498dcd6-I02", "group_id": "py-51915c515228b8f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 3, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dc6a7d313abe-I03", "source": "from django.contrib.syndication.views import Feed as BaseFeed\nfrom django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed\n\nclass Feed(BaseFeed):\n    \"\"\"\n    This is a subclass of the `Feed` from `django.contrib.syndication`.\n    This allows users to define a `geometry(obj)` and/or `item_geometry(item)`\n    methods on their own subclasses so that geo-referenced information may\n    placed in the feed.\n    \"\"\"\n\n    feed_type = GeoRSSFeed\n\n    def validateBalance(self, key):\n        return {\"geometry\": self._get_dynamic_attr(\"geometry\", key)}\n\n    def validateMessage(self, flag):\n        return {\"geometry\": self._get_dynamic_attr(\"item_geometry\", flag)}\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-51915c515228b8f1", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "a45253ec9da29527e2dff5e81dee68369eecae4f424c2ac4dd1ed33683bf4a67", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 18, "local_path": "identifiers/mislead-identifiers/I03__django__Feed__7d313abe.py", "order": 3, "original_content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "parent_variant_id": "pyint-cd91f25dc045-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/feeds.py#L137-L151", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 6, "identifiers_declared": 4, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 2, "local_random_pool_selections": 2, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 2, "method_total_length_difference": 4}, "unit_kind": "class", "unit_name": "Feed", "variant_id": "pyint-dc6a7d313abe-I03", "group_id": "py-51915c515228b8f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 4, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2f2ec24b0716-I04", "source": "from django.contrib.syndication.views import Feed as BaseFeed\nfrom django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed\n\nclass Feed(BaseFeed):\n    \"\"\"\n    This is a subclass of the `Feed` from `django.contrib.syndication`.\n    This allows users to define a `geometry(obj)` and/or `item_geometry(item)`\n    methods on their own subclasses so that geo-referenced information may\n    placed in the feed.\n    \"\"\"\n\n    feed_type = GeoRSSFeed\n\n    def a(self, c):\n        return {\"geometry\": self._get_dynamic_attr(\"geometry\", c)}\n\n    def b(self, d):\n        return {\"geometry\": self._get_dynamic_attr(\"item_geometry\", d)}\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-51915c515228b8f1", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "2be7214d14ce8d4b35c5e8342d05810f56748c7a63eaf27d3f43431eb1c43823", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 18, "local_path": "identifiers/garble-identifiers/I04__django__Feed__c24b0716.py", "order": 4, "original_content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "parent_variant_id": "pyint-cd91f25dc045-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/feeds.py#L137-L151", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 6, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "Feed", "variant_id": "pyint-2f2ec24b0716-I04", "group_id": "py-51915c515228b8f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 5, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ad005ff98304-I05", "source": "from django.contrib.syndication.views import Feed as BaseFeed\nfrom django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed\n\nclass Feed(BaseFeed):\n    \"\"\"\n    This is a subclass of the `Feed` from `django.contrib.syndication`.\n    This allows users to define a `geometry(obj)` and/or `item_geometry(item)`\n    methods on their own subclasses so that geo-referenced information may\n    placed in the feed.\n    \"\"\"\n\n    feed_type = GeoRSSFeed\n\n    def feed_extra_kwargs(self, obj):\n        return {\"geometry\": self._get_dynamic_attr(\"geometry\", obj)}\n\n    def item_extra_kwargs(self, item):\n        return {\"geometry\": self._get_dynamic_attr(\"item_geometry\", item)}\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-51915c515228b8f1", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 18, "local_path": "expressions/encode-integer-literals/I05__django__Feed__5ff98304.py", "order": 5, "original_content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "parent_variant_id": "pyint-cd91f25dc045-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/feeds.py#L137-L151", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "Feed", "variant_id": "pyint-ad005ff98304-I05", "group_id": "py-51915c515228b8f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 6, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ce3966227224-I06", "source": "from django.contrib.syndication.views import Feed as BaseFeed\nfrom django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed\n\nclass Feed(BaseFeed):\n    \"\"\"\n    This is a subclass of the `Feed` from `django.contrib.syndication`.\n    This allows users to define a `geometry(obj)` and/or `item_geometry(item)`\n    methods on their own subclasses so that geo-referenced information may\n    placed in the feed.\n    \"\"\"\n\n    feed_type = GeoRSSFeed\n\n    def feed_extra_kwargs(self, obj):\n        return {\"geometry\": self._get_dynamic_attr(\"geometry\", obj)}\n\n    def item_extra_kwargs(self, item):\n        return {\"geometry\": self._get_dynamic_attr(\"item_geometry\", item)}\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-51915c515228b8f1", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 18, "local_path": "expressions/invert-conditions/I06__django__Feed__66227224.py", "order": 6, "original_content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "parent_variant_id": "pyint-cd91f25dc045-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/feeds.py#L137-L151", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "Feed", "variant_id": "pyint-ce3966227224-I06", "group_id": "py-51915c515228b8f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 7, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a0847441a2df-I07", "source": "from django.contrib.syndication.views import Feed as BaseFeed\nfrom django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed\n\nclass Feed(BaseFeed):\n    \"\"\"\n    This is a subclass of the `Feed` from `django.contrib.syndication`.\n    This allows users to define a `geometry(obj)` and/or `item_geometry(item)`\n    methods on their own subclasses so that geo-referenced information may\n    placed in the feed.\n    \"\"\"\n\n    feed_type = GeoRSSFeed\n\n    def feed_extra_kwargs(self, obj):\n        if ((0xdd42 ^ 0xdd42) != 0):\n            raise AssertionError()\n        return {\"geometry\": self._get_dynamic_attr(\"geometry\", obj)}\n\n    def item_extra_kwargs(self, item):\n        if ((0x8e20 ^ 0x8e20) != 0):\n            raise AssertionError()\n        return {\"geometry\": self._get_dynamic_attr(\"item_geometry\", item)}\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-51915c515228b8f1", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "cd7dc2c8b32c9112875eddeda569fe13b366ed5f18434725c05447fb72ad1e7a", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 22, "local_path": "code-injection/insert-dead-branches/I07__django__Feed__7441a2df.py", "order": 7, "original_content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "parent_variant_id": "pyint-cd91f25dc045-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/feeds.py#L137-L151", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "Feed", "variant_id": "pyint-a0847441a2df-I07", "group_id": "py-51915c515228b8f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 8, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-03c24fb10d8a-I08", "source": "from django.contrib.syndication.views import Feed as BaseFeed\nfrom django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed\n\nclass Feed(BaseFeed):\n    \"\"\"\n    This is a subclass of the `Feed` from `django.contrib.syndication`.\n    This allows users to define a `geometry(obj)` and/or `item_geometry(item)`\n    methods on their own subclasses so that geo-referenced information may\n    placed in the feed.\n    \"\"\"\n\n    feed_type = GeoRSSFeed\n\n    def feed_extra_kwargs(self, obj):\n        starting_position = 2\n        ending_position = 9\n        travel_distance = ending_position - starting_position\n        if travel_distance < 0:\n            travel_distance = -travel_distance\n        return {\"geometry\": self._get_dynamic_attr(\"geometry\", obj)}\n\n    def item_extra_kwargs(self, item):\n        return {\"geometry\": self._get_dynamic_attr(\"item_geometry\", item)}\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-51915c515228b8f1", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "947ba405229c6f1b3f95aed0ae7eeb6c06bc4b59474350e212581d6909e24247", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 23, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__Feed__4fb10d8a.py", "order": 8, "original_content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "parent_variant_id": "pyint-cd91f25dc045-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/feeds.py#L137-L151", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 9}, "unit_kind": "class", "unit_name": "Feed", "variant_id": "pyint-03c24fb10d8a-I08", "group_id": "py-51915c515228b8f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 9, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c45e992ce126-I09", "source": "from django.contrib.syndication.views import Feed as BaseFeed\nfrom django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed\n\nclass Feed(BaseFeed):\n    \"\"\"\n    This is a subclass of the `Feed` from `django.contrib.syndication`.\n    This allows users to define a `geometry(obj)` and/or `item_geometry(item)`\n    methods on their own subclasses so that geo-referenced information may\n    placed in the feed.\n    \"\"\"\n\n    feed_type = GeoRSSFeed\n\n    def feed_extra_kwargs(self, obj):\n        return {\"geometry\": self._get_dynamic_attr(\"geometry\", obj)}\n\n    def item_extra_kwargs(self, item):\n        lI0O_0eadf9d1 = 0xd8d8\n        lI0O_0eadf9d1 = ((lI0O_0eadf9d1 ^ 0xd8d8) | 0) & -1\n        if (lI0O_0eadf9d1 & 1) == 1:\n            lI0O_0eadf9d1 ^= lI0O_0eadf9d1\n        return {\"geometry\": self._get_dynamic_attr(\"item_geometry\", item)}\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-51915c515228b8f1", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "3e7192d02184cb421edfe63264d2c8e6fe0dfc21b0b5e49aaf77f9e79f8983fe", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 22, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__Feed__992ce126.py", "order": 9, "original_content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "parent_variant_id": "pyint-cd91f25dc045-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/feeds.py#L137-L151", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 0}, "unit_kind": "class", "unit_name": "Feed", "variant_id": "pyint-c45e992ce126-I09", "group_id": "py-51915c515228b8f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 10, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ffc235d6710f-I10", "source": "from django.contrib.syndication.views import Feed as BaseFeed\nfrom django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed\n\nclass Feed(BaseFeed):\n    \"\"\"\n    This is a subclass of the `Feed` from `django.contrib.syndication`.\n    This allows users to define a `geometry(obj)` and/or `item_geometry(item)`\n    methods on their own subclasses so that geo-referenced information may\n    placed in the feed.\n    \"\"\"\n    feed_type = GeoRSSFeed\n\n    def feed_extra_kwargs(self, obj):\n        return {\"geometry\": self._get_dynamic_attr(\"geometry\", obj)}\n\n    def item_extra_kwargs(self, item):\n        return {\"geometry\": self._get_dynamic_attr(\"item_geometry\", item)}\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-51915c515228b8f1", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "f03b956245704764687fcf8517517ab263dd5a7ebe0fc77eca4e2d3ab4d67a4e", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 17, "local_path": "layout/partially-compact-layout/I10__django__Feed__35d6710f.py", "order": 10, "original_content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "parent_variant_id": "pyint-cd91f25dc045-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/feeds.py#L137-L151", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 4, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "Feed", "variant_id": "pyint-ffc235d6710f-I10", "group_id": "py-51915c515228b8f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 11, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b86cd72c0dbb-I11", "source": "from django.contrib.syndication.views import Feed as BaseFeed\nfrom django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed\n\nclass Feed(BaseFeed):\n    \"\"\"\n    This is a subclass of the `Feed` from `django.contrib.syndication`.\n    This allows users to define a `geometry(obj)` and/or `item_geometry(item)`\n    methods on their own subclasses so that geo-referenced information may\n    placed in the feed.\n    \"\"\"\n\n    feed_type = GeoRSSFeed\n\n    def feed_extra_kwargs(self, obj):\n        return {\"geometry\": self._get_dynamic_attr(\"geometry\", obj)}\n\n    def item_extra_kwargs(self, item):\n        return {\"geometry\": self._get_dynamic_attr(\"item_geometry\", item)}\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-51915c515228b8f1", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 18, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__Feed__d72c0dbb.py", "order": 11, "original_content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "parent_variant_id": "pyint-cd91f25dc045-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/feeds.py#L137-L151", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "Feed", "variant_id": "pyint-b86cd72c0dbb-I11", "group_id": "py-51915c515228b8f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 12, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-635d59e3cc16-I12", "source": "from django.contrib.syndication.views import Feed as BaseFeed\nfrom django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed\n\nclass Feed(BaseFeed):\n    \"\"\"\n    This is a subclass of the `Feed` from `django.contrib.syndication`.\n    This allows users to define a `geometry(obj)` and/or `item_geometry(item)`\n    methods on their own subclasses so that geo-referenced information may\n    placed in the feed.\n    \"\"\"\n\n    feed_type = GeoRSSFeed\n\n    def feed_extra_kwargs(self, obj):\n        return {\"geometry\": self._get_dynamic_attr(\"geometry\", obj)}\n\n    def item_extra_kwargs(self, item):\n        return {\"geometry\": self._get_dynamic_attr(\"item_geometry\", item)}\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-51915c515228b8f1", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 18, "local_path": "data-flow/inline-intermediate-variables/I12__django__Feed__59e3cc16.py", "order": 12, "original_content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "parent_variant_id": "pyint-cd91f25dc045-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/feeds.py#L137-L151", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Feed", "variant_id": "pyint-635d59e3cc16-I12", "group_id": "py-51915c515228b8f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 13, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-80a1d7e7312f-I13", "source": "from django.contrib.syndication.views import Feed as BaseFeed\nfrom django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed\n\nclass Feed(BaseFeed):\n    \"\"\"\n    This is a subclass of the `Feed` from `django.contrib.syndication`.\n    This allows users to define a `geometry(obj)` and/or `item_geometry(item)`\n    methods on their own subclasses so that geo-referenced information may\n    placed in the feed.\n    \"\"\"\n\n    feed_type = GeoRSSFeed\n\n    def feed_extra_kwargs(self, obj):\n        return {\"geometry\": self._get_dynamic_attr(\"geometry\", obj)}\n\n    def item_extra_kwargs(self, item):\n        return {\"geometry\": self._get_dynamic_attr(\"item_geometry\", item)}\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-51915c515228b8f1", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 18, "local_path": "control-flow/lower-for-to-while/I13__django__Feed__d7e7312f.py", "order": 13, "original_content_sha256": "839a4678ce1670885fc438254339e494fc483d9cde61d059ad14bc2fcdc07089", "parent_variant_id": "pyint-cd91f25dc045-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/feeds.py#L137-L151", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "Feed", "variant_id": "pyint-80a1d7e7312f-I13", "group_id": "py-51915c515228b8f1", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 14, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-552616694637-SRC", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    _content: bytes | Literal[False] | None\n    _content_consumed: bool\n    _next: PreparedRequest | None\n    status_code: int\n    headers: CaseInsensitiveDict[str]\n    raw: Any\n    url: str\n    encoding: str | None\n    history: list[Response]\n    reason: str\n    cookies: RequestsCookieJar\n    elapsed: datetime.timedelta\n    request: PreparedRequest\n    connection: HTTPAdapter\n\n    __attrs__: list[str] = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self) -> None:\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None  # type: ignore[assignment]\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n\n        #: Final URL location of Response.\n        self.url = None  # type: ignore[assignment]\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None  # type: ignore[assignment]\n\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        self.elapsed = datetime.timedelta(0)\n\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None  # type: ignore[assignment]\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def __getstate__(self) -> dict[str, Any]:\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if not self._content_consumed:\n            self.content\n\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for name, value in state.items():\n            setattr(self, name, value)\n\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self) -> str:\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __nonzero__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __iter__(self) -> Iterator[bytes]:\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        return self.iter_content(128)\n\n    @property\n    def ok(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        try:\n            self.raise_for_status()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def is_redirect(self) -> bool:\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def is_permanent_redirect(self) -> bool:\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def next(self) -> PreparedRequest | None:\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        return self._next\n\n    @property\n    def apparent_encoding(self) -> str | None:\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        if chardet is not None:\n            return chardet.detect(self.content)[\"encoding\"]\n        else:\n            # If no character detection library is available, we'll fall back\n            # to a standard Python utf-8 str.\n            return \"utf-8\"\n\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, *, decode_unicode: Literal[True]\n    ) -> Iterator[str | bytes]: ...\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: bool = False\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using encoding\n        information from the response. If no encoding information is available,\n        bytes will be returned. This can be bypassed by manually setting\n        `encoding` on the response.\n        \"\"\"\n\n        def generate() -> Generator[bytes, None, None]:\n            # Special case for urllib3.\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif chunk_size is not None and not isinstance(\n            chunk_size, int\n        ):  # runtime guard for untyped callers\n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(chunk_size)}.\"\n            )\n\n        if self._content_consumed:\n            # simulate reading small chunks of the content\n            content = cast(bytes, self._content)\n            chunks = iter_slices(content, chunk_size)\n        else:\n            chunks = generate()\n\n        if decode_unicode:\n            chunks = stream_decode_response_unicode(chunks, self)\n\n        return chunks\n\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: Literal[False] = False,\n        delimiter: bytes | None = None,\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        *,\n        decode_unicode: Literal[True],\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]: ...\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: bool = False,\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        The decode_unicode param works the same as in `iter_content`, with the\n        same caveats.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n\n        pending: str | bytes | None = None\n\n        for chunk in self.iter_content(\n            chunk_size=chunk_size, decode_unicode=decode_unicode\n        ):\n            if pending is not None:\n                # TODO: remove cast after iter_lines rewrite\n                chunk = cast(\"str | bytes\", pending + chunk)\n\n            if delimiter:\n                lines = chunk.split(delimiter)  # type: ignore[arg-type]\n            else:\n                lines = chunk.splitlines()\n\n            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:\n                pending = lines.pop()\n            else:\n                pending = None\n\n            yield from lines\n\n        if pending is not None:\n            yield pending\n\n    @property\n    def content(self) -> bytes:\n        \"\"\"Content of the response, in bytes.\"\"\"\n\n        if self._content is False:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content  # type: ignore[return-value]\n\n    @property\n    def text(self) -> str:\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n\n        # Try charset from content-type\n        content = None\n        encoding = self.encoding\n\n        if not self.content:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if self.encoding is None:\n            encoding = self.apparent_encoding\n\n        # Decode unicode from given encoding.\n        try:\n            content = str(self.content, encoding or \"utf-8\", errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            content = str(self.content, errors=\"replace\")\n\n        return content\n\n    def json(self, **kwargs: Any) -> Any:\n        r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n        This may return a dictionary, list, etc. depending on what is in the response.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n\n        if not self.encoding and self.content and len(self.content) > 3:\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            encoding = guess_json_utf(self.content)\n            if encoding is not None:\n                try:\n                    return complexjson.loads(self.content.decode(encoding), **kwargs)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.text, **kwargs)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def links(self) -> dict[str, dict[str, str]]:\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n        header = self.headers.get(\"link\")\n\n        resolved_links: dict[str, dict[str, str]] = {}\n\n        if header:\n            links = parse_header_links(header)\n\n            for link in links:\n                key = link.get(\"rel\") or link.get(\"url\")\n                if key is not None:\n                    resolved_links[key] = link\n\n        return resolved_links\n\n    def raise_for_status(self) -> None:\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n\n        http_error_msg = \"\"\n        if isinstance(self.reason, bytes):\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                reason = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                reason = self.reason.decode(\"iso-8859-1\")\n        else:\n            reason = self.reason\n\n        if 400 <= self.status_code < 500:\n            http_error_msg = (\n                f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            http_error_msg = (\n                f\"{self.status_code} Server Error: {reason} for url: {self.url}\"\n            )\n\n        if http_error_msg:\n            raise HTTPError(http_error_msg, response=self)\n\n    def close(self) -> None:\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not self._content_consumed:\n            self.raw.close()\n\n        release_conn = getattr(self.raw, \"release_conn\", None)\n        if release_conn is not None:\n            release_conn()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-528aa57ade5b26ae", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 523, "local_path": "source-original/SRC__requests__Response__16694637.py", "order": 0, "original_content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L732-L1184", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-552616694637-SRC", "group_id": "py-528aa57ade5b26ae", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 701, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-803f7c9f1613-I01", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna   \nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Response:\n    \n\n    _content: bytes | Literal[False] | None\n    _content_consumed: bool\n    _next: PreparedRequest | None\n    status_code: int\n    headers: CaseInsensitiveDict[str]\n    raw: Any\n    url: str\n    encoding: str | None\n    history: list[Response]\n    reason: str\n    cookies: RequestsCookieJar\n    elapsed: datetime.timedelta\n    request: PreparedRequest\n    connection: HTTPAdapter\n\n    __attrs__: list[str] = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self) -> None:\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n         \n        self.status_code = None   \n\n         \n         \n         \n        self.headers = CaseInsensitiveDict()\n\n         \n         \n         \n        self.raw = None\n\n         \n        self.url = None   \n\n         \n        self.encoding = None\n\n         \n         \n         \n        self.history = []\n\n         \n        self.reason = None   \n\n         \n        self.cookies = cookiejar_from_dict({})\n\n         \n         \n         \n         \n         \n         \n        self.elapsed = datetime.timedelta(0)\n\n         \n         \n        self.request = None   \n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def __getstate__(self) -> dict[str, Any]:\n         \n         \n        if not self._content_consumed:\n            self.content\n\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for name, value in state.items():\n            setattr(self, name, value)\n\n         \n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self) -> str:\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self) -> bool:\n        \n        return self.ok\n\n    def __nonzero__(self) -> bool:\n        \n        return self.ok\n\n    def __iter__(self) -> Iterator[bytes]:\n        \n        return self.iter_content(128)\n\n    @property\n    def ok(self) -> bool:\n        \n        try:\n            self.raise_for_status()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def is_redirect(self) -> bool:\n        \n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def is_permanent_redirect(self) -> bool:\n        \n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def next(self) -> PreparedRequest | None:\n        \n        return self._next\n\n    @property\n    def apparent_encoding(self) -> str | None:\n        \n        if chardet is not None:\n            return chardet.detect(self.content)[\"encoding\"]\n        else:\n             \n             \n            return \"utf-8\"\n\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, *, decode_unicode: Literal[True]\n    ) -> Iterator[str | bytes]: ...\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: bool = False\n    ) -> Iterator[str | bytes]:\n        \n\n        def generate() -> Generator[bytes, None, None]:\n             \n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                 \n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif chunk_size is not None and not isinstance(\n            chunk_size, int\n        ):   \n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(chunk_size)}.\"\n            )\n\n        if self._content_consumed:\n             \n            content = cast(bytes, self._content)\n            chunks = iter_slices(content, chunk_size)\n        else:\n            chunks = generate()\n\n        if decode_unicode:\n            chunks = stream_decode_response_unicode(chunks, self)\n\n        return chunks\n\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: Literal[False] = False,\n        delimiter: bytes | None = None,\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        *,\n        decode_unicode: Literal[True],\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]: ...\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: bool = False,\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]:\n        \n\n        pending: str | bytes | None = None\n\n        for chunk in self.iter_content(\n            chunk_size=chunk_size, decode_unicode=decode_unicode\n        ):\n            if pending is not None:\n                 \n                chunk = cast(\"str | bytes\", pending + chunk)\n\n            if delimiter:\n                lines = chunk.split(delimiter)   \n            else:\n                lines = chunk.splitlines()\n\n            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:\n                pending = lines.pop()\n            else:\n                pending = None\n\n            yield from lines\n\n        if pending is not None:\n            yield pending\n\n    @property\n    def content(self) -> bytes:\n        \n\n        if self._content is False:\n             \n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n         \n         \n        return self._content   \n\n    @property\n    def text(self) -> str:\n        \n\n         \n        content = None\n        encoding = self.encoding\n\n        if not self.content:\n            return \"\"\n\n         \n        if self.encoding is None:\n            encoding = self.apparent_encoding\n\n         \n        try:\n            content = str(self.content, encoding or \"utf-8\", errors=\"replace\")\n        except (LookupError, TypeError):\n             \n             \n             \n             \n             \n             \n            content = str(self.content, errors=\"replace\")\n\n        return content\n\n    def json(self, **kwargs: Any) -> Any:\n        \n\n        if not self.encoding and self.content and len(self.content) > 3:\n             \n             \n             \n             \n            encoding = guess_json_utf(self.content)\n            if encoding is not None:\n                try:\n                    return complexjson.loads(self.content.decode(encoding), **kwargs)\n                except UnicodeDecodeError:\n                     \n                     \n                     \n                     \n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.text, **kwargs)\n        except JSONDecodeError as e:\n             \n             \n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def links(self) -> dict[str, dict[str, str]]:\n        \n\n        header = self.headers.get(\"link\")\n\n        resolved_links: dict[str, dict[str, str]] = {}\n\n        if header:\n            links = parse_header_links(header)\n\n            for link in links:\n                key = link.get(\"rel\") or link.get(\"url\")\n                if key is not None:\n                    resolved_links[key] = link\n\n        return resolved_links\n\n    def raise_for_status(self) -> None:\n        \n\n        http_error_msg = \"\"\n        if isinstance(self.reason, bytes):\n             \n             \n             \n             \n            try:\n                reason = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                reason = self.reason.decode(\"iso-8859-1\")\n        else:\n            reason = self.reason\n\n        if 400 <= self.status_code < 500:\n            http_error_msg = (\n                f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            http_error_msg = (\n                f\"{self.status_code} Server Error: {reason} for url: {self.url}\"\n            )\n\n        if http_error_msg:\n            raise HTTPError(http_error_msg, response=self)\n\n    def close(self) -> None:\n        \n        if not self._content_consumed:\n            self.raw.close()\n\n        release_conn = getattr(self.raw, \"release_conn\", None)\n        if release_conn is not None:\n            release_conn()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-528aa57ade5b26ae", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "ebb7931182a351db355d631cc6a36add0af21589b3094fc3bda7398321306305", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 457, "local_path": "comments/remove-comments/I01__requests__Response__7c9f1613.py", "order": 1, "original_content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "parent_variant_id": "pyint-552616694637-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L732-L1184", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 7065, "comments_removed": 82, "docstrings_removed": 17, "line_comments_removed": 65}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-803f7c9f1613-I01", "group_id": "py-528aa57ade5b26ae", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 702, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b9b90615b151-I02", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    _content: bytes | Literal[False] | None\n    _content_consumed: bool\n    _next: PreparedRequest | None\n    status_code: int\n    headers: CaseInsensitiveDict[str]\n    raw: Any\n    url: str\n    encoding: str | None\n    history: list[Response]\n    reason: str\n    cookies: RequestsCookieJar\n    elapsed: datetime.timedelta\n    request: PreparedRequest\n    connection: HTTPAdapter\n\n    __attrs__: list[str] = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self) -> None:\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None  # type: ignore[assignment]\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n\n        #: Final URL location of Response.\n        self.url = None  # type: ignore[assignment]\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None  # type: ignore[assignment]\n\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        self.elapsed = datetime.timedelta(0)\n\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None  # type: ignore[assignment]\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *arg: Any) -> None:\n        self.clo()\n\n    def __getstate__(self) -> dict[str, Any]:\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if not self._content_consumed:\n            self.con\n\n        return {att: getattr(self, att, None) for att in self.__attrs__}\n\n    def __setstate__(self, sta: dict[str, Any]) -> None:\n        for nam, val in sta.items():\n            setattr(self, nam, val)\n\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self) -> str:\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok2\n\n    def __nonzero__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok2\n\n    def __iter__(self) -> Iterator[bytes]:\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        return self.iter3(128)\n\n    @property\n    def ok2(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        try:\n            self.raise2()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def is2(self) -> bool:\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def is3(self) -> bool:\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def nex(self) -> PreparedRequest | None:\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        return self._next\n\n    @property\n    def apparent(self) -> str | None:\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        if chardet is not None:\n            return chardet.detect(self.con)[\"encoding\"]\n        else:\n            # If no character detection library is available, we'll fall back\n            # to a standard Python utf-8 str.\n            return \"utf-8\"\n\n    @overload\n    def iter3(\n        self, chunk2: int | None = 1, decode2: Literal[False] = False\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter3(\n        self, chunk3: int | None = 1, *, decode3: Literal[True]\n    ) -> Iterator[str | bytes]: ...\n    def iter3(\n        self, chunk4: int | None = 1, decode4: bool = False\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using encoding\n        information from the response. If no encoding information is available,\n        bytes will be returned. This can be bypassed by manually setting\n        `encoding` on the response.\n        \"\"\"\n\n        def generate() -> Generator[bytes, None, None]:\n            # Special case for urllib3.\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    chu2 = self.raw.read(chunk_size)\n                    if not chu2:\n                        break\n                    yield chu2\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif chunk4 is not None and not isinstance(\n            chunk4, int\n        ):  # runtime guard for untyped callers\n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(chunk4)}.\"\n            )\n\n        if self._content_consumed:\n            # simulate reading small chunks of the content\n            con2 = cast(bytes, self._content)\n            chu = iter_slices(con2, chunk4)\n        else:\n            chu = generate()\n\n        if decode4:\n            chu = stream_decode_response_unicode(chu, self)\n\n        return chu\n\n    @overload\n    def iter6(\n        self,\n        chunk5: int = ITER_CHUNK_SIZE,\n        decode5: Literal[False] = False,\n        del2: bytes | None = None,\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter6(\n        self,\n        chunk6: int = ITER_CHUNK_SIZE,\n        *,\n        decode6: Literal[True],\n        del3: str | bytes | None = None,\n    ) -> Iterator[str | bytes]: ...\n    def iter6(\n        self,\n        chunk7: int = ITER_CHUNK_SIZE,\n        decode7: bool = False,\n        del4: str | bytes | None = None,\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        The decode_unicode param works the same as in `iter_content`, with the\n        same caveats.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n\n        pen: str | bytes | None = None\n\n        for chu3 in self.iter3(\n            chunk_size=chunk7, decode_unicode=decode7\n        ):\n            if pen is not None:\n                # TODO: remove cast after iter_lines rewrite\n                chu3 = cast(\"str | bytes\", pen + chu3)\n\n            if del4:\n                lin2 = chu3.split(del4)  # type: ignore[arg-type]\n            else:\n                lin2 = chu3.splitlines()\n\n            if lin2 and lin2[-1] and chu3 and lin2[-1][-1] == chu3[-1]:\n                pen = lin2.pop()\n            else:\n                pen = None\n\n            yield from lin2\n\n        if pen is not None:\n            yield pen\n\n    @property\n    def con(self) -> bytes:\n        \"\"\"Content of the response, in bytes.\"\"\"\n\n        if self._content is False:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.iter3(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content  # type: ignore[return-value]\n\n    @property\n    def tex(self) -> str:\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n\n        # Try charset from content-type\n        con3 = None\n        enc = self.encoding\n\n        if not self.con:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if self.encoding is None:\n            enc = self.apparent\n\n        # Decode unicode from given encoding.\n        try:\n            con3 = str(self.con, enc or \"utf-8\", errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            con3 = str(self.con, errors=\"replace\")\n\n        return con3\n\n    def jso(self, **kwa: Any) -> Any:\n        r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n        This may return a dictionary, list, etc. depending on what is in the response.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n\n        if not self.encoding and self.con and len(self.con) > 3:\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            enc2 = guess_json_utf(self.con)\n            if enc2 is not None:\n                try:\n                    return complexjson.loads(self.con.decode(enc2), **kwa)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.tex, **kwa)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def lin(self) -> dict[str, dict[str, str]]:\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n        hea = self.headers.get(\"link\")\n\n        resolved: dict[str, dict[str, str]] = {}\n\n        if hea:\n            lin3 = parse_header_links(hea)\n\n            for lin4 in lin3:\n                key2 = lin4.get(\"rel\") or lin4.get(\"url\")\n                if key2 is not None:\n                    resolved[key2] = lin4\n\n        return resolved\n\n    def raise2(self) -> None:\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n\n        http = \"\"\n        if isinstance(self.reason, bytes):\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                rea = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                rea = self.reason.decode(\"iso-8859-1\")\n        else:\n            rea = self.reason\n\n        if 400 <= self.status_code < 500:\n            http = (\n                f\"{self.status_code} Client Error: {rea} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            http = (\n                f\"{self.status_code} Server Error: {rea} for url: {self.url}\"\n            )\n\n        if http:\n            raise HTTPError(http, response=self)\n\n    def clo(self) -> None:\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not self._content_consumed:\n            self.raw.close()\n\n        release = getattr(self.raw, \"release_conn\", None)\n        if release is not None:\n            release()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-528aa57ade5b26ae", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "f816dd7ac7f1315be75803aaf837d1015adca32e16ec02c1da5d3890198d81e6", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 523, "local_path": "identifiers/shorten-identifiers/I02__requests__Response__0615b151.py", "order": 2, "original_content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "parent_variant_id": "pyint-552616694637-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L732-L1184", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 141, "identifiers_declared": 55}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-b9b90615b151-I02", "group_id": "py-528aa57ade5b26ae", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 703, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9939da3fa38d-I03", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    _content: bytes | Literal[False] | None\n    _content_consumed: bool\n    _next: PreparedRequest | None\n    status_code: int\n    headers: CaseInsensitiveDict[str]\n    raw: Any\n    url: str\n    encoding: str | None\n    history: list[Response]\n    reason: str\n    cookies: RequestsCookieJar\n    elapsed: datetime.timedelta\n    request: PreparedRequest\n    connection: HTTPAdapter\n\n    __attrs__: list[str] = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self) -> None:\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None  # type: ignore[assignment]\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n\n        #: Final URL location of Response.\n        self.url = None  # type: ignore[assignment]\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None  # type: ignore[assignment]\n\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        self.elapsed = datetime.timedelta(0)\n\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None  # type: ignore[assignment]\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *node: Any) -> None:\n        self.reset()\n\n    def __getstate__(self) -> dict[str, Any]:\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if not self._content_consumed:\n            self.replace\n\n        return {flag: getattr(self, flag, None) for flag in self.__attrs__}\n\n    def __setstate__(self, limit: dict[str, Any]) -> None:\n        for step, cache in limit.items():\n            setattr(self, step, cache)\n\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self) -> str:\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.add\n\n    def __nonzero__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.add\n\n    def __iter__(self) -> Iterator[bytes]:\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        return self.fetchAccount(128)\n\n    @property\n    def add(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        try:\n            self.validateAddress()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def updateEvent(self) -> bool:\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def validateRequest(self) -> bool:\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def copy(self) -> PreparedRequest | None:\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        return self._next\n\n    @property\n    def validateAccount(self) -> str | None:\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        if chardet is not None:\n            return chardet.detect(self.replace)[\"encoding\"]\n        else:\n            # If no character detection library is available, we'll fall back\n            # to a standard Python utf-8 str.\n            return \"utf-8\"\n\n    @overload\n    def fetchAccount(\n        self, sharedNode: int | None = 1, primaryAddress: Literal[False] = False\n    ) -> Iterator[bytes]: ...\n    @overload\n    def fetchAccount(\n        self, remoteItem: int | None = 1, *, primaryAccount: Literal[True]\n    ) -> Iterator[str | bytes]: ...\n    def fetchAccount(\n        self, backupData: int | None = 1, pendingRequest: bool = False\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using encoding\n        information from the response. If no encoding information is available,\n        bytes will be returned. This can be bypassed by manually setting\n        `encoding` on the response.\n        \"\"\"\n\n        def generate() -> Generator[bytes, None, None]:\n            # Special case for urllib3.\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    count = self.raw.read(chunk_size)\n                    if not count:\n                        break\n                    yield count\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif backupData is not None and not isinstance(\n            backupData, int\n        ):  # runtime guard for untyped callers\n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(backupData)}.\"\n            )\n\n        if self._content_consumed:\n            # simulate reading small chunks of the content\n            session = cast(bytes, self._content)\n            amount = iter_slices(session, backupData)\n        else:\n            amount = generate()\n\n        if pendingRequest:\n            amount = stream_decode_response_unicode(amount, self)\n\n        return amount\n\n    @overload\n    def updateMode(\n        self,\n        localOrder: int = ITER_CHUNK_SIZE,\n        defaultSession: Literal[False] = False,\n        localNode: bytes | None = None,\n    ) -> Iterator[bytes]: ...\n    @overload\n    def updateMode(\n        self,\n        cachedData: int = ITER_CHUNK_SIZE,\n        *,\n        pendingMessage: Literal[True],\n        nextCount: str | bytes | None = None,\n    ) -> Iterator[str | bytes]: ...\n    def updateMode(\n        self,\n        recentNode: int = ITER_CHUNK_SIZE,\n        primaryMessage: bool = False,\n        nextState: str | bytes | None = None,\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        The decode_unicode param works the same as in `iter_content`, with the\n        same caveats.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n\n        context: str | bytes | None = None\n\n        for cache in self.fetchAccount(\n            chunk_size=recentNode, decode_unicode=primaryMessage\n        ):\n            if context is not None:\n                # TODO: remove cast after iter_lines rewrite\n                cache = cast(\"str | bytes\", context + cache)\n\n            if nextState:\n                price = cache.split(nextState)  # type: ignore[arg-type]\n            else:\n                price = cache.splitlines()\n\n            if price and price[-1] and cache and price[-1][-1] == cache[-1]:\n                context = price.pop()\n            else:\n                context = None\n\n            yield from price\n\n        if context is not None:\n            yield context\n\n    @property\n    def replace(self) -> bytes:\n        \"\"\"Content of the response, in bytes.\"\"\"\n\n        if self._content is False:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.fetchAccount(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content  # type: ignore[return-value]\n\n    @property\n    def save(self) -> str:\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n\n        # Try charset from content-type\n        version = None\n        response = self.encoding\n\n        if not self.replace:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if self.encoding is None:\n            response = self.validateAccount\n\n        # Decode unicode from given encoding.\n        try:\n            version = str(self.replace, response or \"utf-8\", errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            version = str(self.replace, errors=\"replace\")\n\n        return version\n\n    def send(self, **client: Any) -> Any:\n        r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n        This may return a dictionary, list, etc. depending on what is in the response.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n\n        if not self.encoding and self.replace and len(self.replace) > 3:\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            location = guess_json_utf(self.replace)\n            if location is not None:\n                try:\n                    return complexjson.loads(self.replace.decode(location), **client)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.save, **client)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def apply(self) -> dict[str, dict[str, str]]:\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n        window = self.headers.get(\"link\")\n\n        primarySession: dict[str, dict[str, str]] = {}\n\n        if window:\n            state = parse_header_links(window)\n\n            for step in state:\n                map = step.get(\"rel\") or step.get(\"url\")\n                if map is not None:\n                    primarySession[map] = step\n\n        return primarySession\n\n    def validateAddress(self) -> None:\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n\n        currentRequest = \"\"\n        if isinstance(self.reason, bytes):\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                status = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                status = self.reason.decode(\"iso-8859-1\")\n        else:\n            status = self.reason\n\n        if 400 <= self.status_code < 500:\n            currentRequest = (\n                f\"{self.status_code} Client Error: {status} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            currentRequest = (\n                f\"{self.status_code} Server Error: {status} for url: {self.url}\"\n            )\n\n        if currentRequest:\n            raise HTTPError(currentRequest, response=self)\n\n    def reset(self) -> None:\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not self._content_consumed:\n            self.raw.close()\n\n        sharedRecord = getattr(self.raw, \"release_conn\", None)\n        if sharedRecord is not None:\n            sharedRecord()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-528aa57ade5b26ae", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "ed239cd6fcece98d77210c5f93dc4a78a12c2ab1576a761e370173b0eb7591a7", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 523, "local_path": "identifiers/mislead-identifiers/I03__requests__Response__da3fa38d.py", "order": 3, "original_content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "parent_variant_id": "pyint-552616694637-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L732-L1184", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 141, "identifiers_declared": 55, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 38, "local_random_pool_selections": 38, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 2, "method_exact_length_matches": 9, "method_random_pool_selections": 17, "method_total_length_difference": 10}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-9939da3fa38d-I03", "group_id": "py-528aa57ade5b26ae", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 704, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-483aca9cdeb3-I04", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    _content: bytes | Literal[False] | None\n    _content_consumed: bool\n    _next: PreparedRequest | None\n    status_code: int\n    headers: CaseInsensitiveDict[str]\n    raw: Any\n    url: str\n    encoding: str | None\n    history: list[Response]\n    reason: str\n    cookies: RequestsCookieJar\n    elapsed: datetime.timedelta\n    request: PreparedRequest\n    connection: HTTPAdapter\n\n    __attrs__: list[str] = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self) -> None:\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None  # type: ignore[assignment]\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n\n        #: Final URL location of Response.\n        self.url = None  # type: ignore[assignment]\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None  # type: ignore[assignment]\n\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        self.elapsed = datetime.timedelta(0)\n\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None  # type: ignore[assignment]\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *s: Any) -> None:\n        self.r()\n\n    def __getstate__(self) -> dict[str, Any]:\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if not self._content_consumed:\n            self.m\n\n        return {t: getattr(self, t, None) for t in self.__attrs__}\n\n    def __setstate__(self, u: dict[str, Any]) -> None:\n        for v, w in u.items():\n            setattr(self, v, w)\n\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self) -> str:\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.a\n\n    def __nonzero__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.a\n\n    def __iter__(self) -> Iterator[bytes]:\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        return self.i(128)\n\n    @property\n    def a(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        try:\n            self.q()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def b(self) -> bool:\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def c(self) -> bool:\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def d(self) -> PreparedRequest | None:\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        return self._next\n\n    @property\n    def f(self) -> str | None:\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        if chardet is not None:\n            return chardet.detect(self.m)[\"encoding\"]\n        else:\n            # If no character detection library is available, we'll fall back\n            # to a standard Python utf-8 str.\n            return \"utf-8\"\n\n    @overload\n    def i(\n        self, x: int | None = 1, y: Literal[False] = False\n    ) -> Iterator[bytes]: ...\n    @overload\n    def i(\n        self, z: int | None = 1, *, A: Literal[True]\n    ) -> Iterator[str | bytes]: ...\n    def i(\n        self, B: int | None = 1, C: bool = False\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using encoding\n        information from the response. If no encoding information is available,\n        bytes will be returned. This can be bypassed by manually setting\n        `encoding` on the response.\n        \"\"\"\n\n        def generate() -> Generator[bytes, None, None]:\n            # Special case for urllib3.\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    F = self.raw.read(chunk_size)\n                    if not F:\n                        break\n                    yield F\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif B is not None and not isinstance(\n            B, int\n        ):  # runtime guard for untyped callers\n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(B)}.\"\n            )\n\n        if self._content_consumed:\n            # simulate reading small chunks of the content\n            D = cast(bytes, self._content)\n            E = iter_slices(D, B)\n        else:\n            E = generate()\n\n        if C:\n            E = stream_decode_response_unicode(E, self)\n\n        return E\n\n    @overload\n    def l(\n        self,\n        G: int = ITER_CHUNK_SIZE,\n        H: Literal[False] = False,\n        I: bytes | None = None,\n    ) -> Iterator[bytes]: ...\n    @overload\n    def l(\n        self,\n        J: int = ITER_CHUNK_SIZE,\n        *,\n        K: Literal[True],\n        L: str | bytes | None = None,\n    ) -> Iterator[str | bytes]: ...\n    def l(\n        self,\n        M: int = ITER_CHUNK_SIZE,\n        N: bool = False,\n        O: str | bytes | None = None,\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        The decode_unicode param works the same as in `iter_content`, with the\n        same caveats.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n\n        P: str | bytes | None = None\n\n        for Q in self.i(\n            chunk_size=M, decode_unicode=N\n        ):\n            if P is not None:\n                # TODO: remove cast after iter_lines rewrite\n                Q = cast(\"str | bytes\", P + Q)\n\n            if O:\n                R = Q.split(O)  # type: ignore[arg-type]\n            else:\n                R = Q.splitlines()\n\n            if R and R[-1] and Q and R[-1][-1] == Q[-1]:\n                P = R.pop()\n            else:\n                P = None\n\n            yield from R\n\n        if P is not None:\n            yield P\n\n    @property\n    def m(self) -> bytes:\n        \"\"\"Content of the response, in bytes.\"\"\"\n\n        if self._content is False:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.i(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content  # type: ignore[return-value]\n\n    @property\n    def n(self) -> str:\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n\n        # Try charset from content-type\n        S = None\n        T = self.encoding\n\n        if not self.m:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if self.encoding is None:\n            T = self.f\n\n        # Decode unicode from given encoding.\n        try:\n            S = str(self.m, T or \"utf-8\", errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            S = str(self.m, errors=\"replace\")\n\n        return S\n\n    def o(self, **U: Any) -> Any:\n        r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n        This may return a dictionary, list, etc. depending on what is in the response.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n\n        if not self.encoding and self.m and len(self.m) > 3:\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            V = guess_json_utf(self.m)\n            if V is not None:\n                try:\n                    return complexjson.loads(self.m.decode(V), **U)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.n, **U)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def p(self) -> dict[str, dict[str, str]]:\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n        W = self.headers.get(\"link\")\n\n        X: dict[str, dict[str, str]] = {}\n\n        if W:\n            Y = parse_header_links(W)\n\n            for Z in Y:\n                aa = Z.get(\"rel\") or Z.get(\"url\")\n                if aa is not None:\n                    X[aa] = Z\n\n        return X\n\n    def q(self) -> None:\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n\n        ab = \"\"\n        if isinstance(self.reason, bytes):\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                ac = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                ac = self.reason.decode(\"iso-8859-1\")\n        else:\n            ac = self.reason\n\n        if 400 <= self.status_code < 500:\n            ab = (\n                f\"{self.status_code} Client Error: {ac} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            ab = (\n                f\"{self.status_code} Server Error: {ac} for url: {self.url}\"\n            )\n\n        if ab:\n            raise HTTPError(ab, response=self)\n\n    def r(self) -> None:\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not self._content_consumed:\n            self.raw.close()\n\n        ad = getattr(self.raw, \"release_conn\", None)\n        if ad is not None:\n            ad()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-528aa57ade5b26ae", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "033e3698ad82952fd79bb7928cfa9b7435aec1367b47c3bd3e1bb2775b49f920", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 523, "local_path": "identifiers/garble-identifiers/I04__requests__Response__ca9cdeb3.py", "order": 4, "original_content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "parent_variant_id": "pyint-552616694637-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L732-L1184", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 141, "identifiers_declared": 55}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-483aca9cdeb3-I04", "group_id": "py-528aa57ade5b26ae", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 705, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ee0e09a8469a-I05", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    _content: bytes | Literal[False] | None\n    _content_consumed: bool\n    _next: PreparedRequest | None\n    status_code: int\n    headers: CaseInsensitiveDict[str]\n    raw: Any\n    url: str\n    encoding: str | None\n    history: list[Response]\n    reason: str\n    cookies: RequestsCookieJar\n    elapsed: datetime.timedelta\n    request: PreparedRequest\n    connection: HTTPAdapter\n\n    __attrs__: list[str] = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self) -> None:\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None  # type: ignore[assignment]\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n\n        #: Final URL location of Response.\n        self.url = None  # type: ignore[assignment]\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None  # type: ignore[assignment]\n\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        self.elapsed = datetime.timedelta(0x0)\n\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None  # type: ignore[assignment]\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def __getstate__(self) -> dict[str, Any]:\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if not self._content_consumed:\n            self.content\n\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for name, value in state.items():\n            setattr(self, name, value)\n\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self) -> str:\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __nonzero__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __iter__(self) -> Iterator[bytes]:\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        return self.iter_content(0x80)\n\n    @property\n    def ok(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        try:\n            self.raise_for_status()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def is_redirect(self) -> bool:\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def is_permanent_redirect(self) -> bool:\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def next(self) -> PreparedRequest | None:\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        return self._next\n\n    @property\n    def apparent_encoding(self) -> str | None:\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        if chardet is not None:\n            return chardet.detect(self.content)[\"encoding\"]\n        else:\n            # If no character detection library is available, we'll fall back\n            # to a standard Python utf-8 str.\n            return \"utf-8\"\n\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 0x1, decode_unicode: Literal[False] = False\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 0x1, *, decode_unicode: Literal[True]\n    ) -> Iterator[str | bytes]: ...\n    def iter_content(\n        self, chunk_size: int | None = 0x1, decode_unicode: bool = False\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using encoding\n        information from the response. If no encoding information is available,\n        bytes will be returned. This can be bypassed by manually setting\n        `encoding` on the response.\n        \"\"\"\n\n        def generate() -> Generator[bytes, None, None]:\n            # Special case for urllib3.\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif chunk_size is not None and not isinstance(\n            chunk_size, int\n        ):  # runtime guard for untyped callers\n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(chunk_size)}.\"\n            )\n\n        if self._content_consumed:\n            # simulate reading small chunks of the content\n            content = cast(bytes, self._content)\n            chunks = iter_slices(content, chunk_size)\n        else:\n            chunks = generate()\n\n        if decode_unicode:\n            chunks = stream_decode_response_unicode(chunks, self)\n\n        return chunks\n\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: Literal[False] = False,\n        delimiter: bytes | None = None,\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        *,\n        decode_unicode: Literal[True],\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]: ...\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: bool = False,\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        The decode_unicode param works the same as in `iter_content`, with the\n        same caveats.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n\n        pending: str | bytes | None = None\n\n        for chunk in self.iter_content(\n            chunk_size=chunk_size, decode_unicode=decode_unicode\n        ):\n            if pending is not None:\n                # TODO: remove cast after iter_lines rewrite\n                chunk = cast(\"str | bytes\", pending + chunk)\n\n            if delimiter:\n                lines = chunk.split(delimiter)  # type: ignore[arg-type]\n            else:\n                lines = chunk.splitlines()\n\n            if lines and lines[-0x1] and chunk and lines[-0x1][-0x1] == chunk[-0x1]:\n                pending = lines.pop()\n            else:\n                pending = None\n\n            yield from lines\n\n        if pending is not None:\n            yield pending\n\n    @property\n    def content(self) -> bytes:\n        \"\"\"Content of the response, in bytes.\"\"\"\n\n        if self._content is False:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0x0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content  # type: ignore[return-value]\n\n    @property\n    def text(self) -> str:\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n\n        # Try charset from content-type\n        content = None\n        encoding = self.encoding\n\n        if not self.content:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if self.encoding is None:\n            encoding = self.apparent_encoding\n\n        # Decode unicode from given encoding.\n        try:\n            content = str(self.content, encoding or \"utf-8\", errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            content = str(self.content, errors=\"replace\")\n\n        return content\n\n    def json(self, **kwargs: Any) -> Any:\n        r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n        This may return a dictionary, list, etc. depending on what is in the response.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n\n        if not self.encoding and self.content and len(self.content) > 0x3:\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            encoding = guess_json_utf(self.content)\n            if encoding is not None:\n                try:\n                    return complexjson.loads(self.content.decode(encoding), **kwargs)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.text, **kwargs)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def links(self) -> dict[str, dict[str, str]]:\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n        header = self.headers.get(\"link\")\n\n        resolved_links: dict[str, dict[str, str]] = {}\n\n        if header:\n            links = parse_header_links(header)\n\n            for link in links:\n                key = link.get(\"rel\") or link.get(\"url\")\n                if key is not None:\n                    resolved_links[key] = link\n\n        return resolved_links\n\n    def raise_for_status(self) -> None:\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n\n        http_error_msg = \"\"\n        if isinstance(self.reason, bytes):\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                reason = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                reason = self.reason.decode(\"iso-8859-1\")\n        else:\n            reason = self.reason\n\n        if 0x190 <= self.status_code < 0x1f4:\n            http_error_msg = (\n                f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n            )\n\n        elif 0x1f4 <= self.status_code < 0x258:\n            http_error_msg = (\n                f\"{self.status_code} Server Error: {reason} for url: {self.url}\"\n            )\n\n        if http_error_msg:\n            raise HTTPError(http_error_msg, response=self)\n\n    def close(self) -> None:\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not self._content_consumed:\n            self.raw.close()\n\n        release_conn = getattr(self.raw, \"release_conn\", None)\n        if release_conn is not None:\n            release_conn()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-528aa57ade5b26ae", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "fc338a5d83a75e15345ae123e8f5d41f1e661b5262b15e5c59a2875c698c33ec", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 523, "local_path": "expressions/encode-integer-literals/I05__requests__Response__09a8469a.py", "order": 5, "original_content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "parent_variant_id": "pyint-552616694637-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L732-L1184", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 15}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-ee0e09a8469a-I05", "group_id": "py-528aa57ade5b26ae", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 706, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-39a6a08d2866-I06", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    _content: bytes | Literal[False] | None\n    _content_consumed: bool\n    _next: PreparedRequest | None\n    status_code: int\n    headers: CaseInsensitiveDict[str]\n    raw: Any\n    url: str\n    encoding: str | None\n    history: list[Response]\n    reason: str\n    cookies: RequestsCookieJar\n    elapsed: datetime.timedelta\n    request: PreparedRequest\n    connection: HTTPAdapter\n\n    __attrs__: list[str] = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self) -> None:\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None  # type: ignore[assignment]\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n\n        #: Final URL location of Response.\n        self.url = None  # type: ignore[assignment]\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None  # type: ignore[assignment]\n\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        self.elapsed = datetime.timedelta(0)\n\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None  # type: ignore[assignment]\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def __getstate__(self) -> dict[str, Any]:\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if not (not self._content_consumed):\n            pass\n        else:\n            self.content\n\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for name, value in state.items():\n            setattr(self, name, value)\n\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self) -> str:\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __nonzero__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __iter__(self) -> Iterator[bytes]:\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        return self.iter_content(128)\n\n    @property\n    def ok(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        try:\n            self.raise_for_status()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def is_redirect(self) -> bool:\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def is_permanent_redirect(self) -> bool:\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def next(self) -> PreparedRequest | None:\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        return self._next\n\n    @property\n    def apparent_encoding(self) -> str | None:\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        if not (chardet is not None):\n            # If no character detection library is available, we'll fall back\n            # to a standard Python utf-8 str.\n            return \"utf-8\"\n        else:\n            return chardet.detect(self.content)[\"encoding\"]\n\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, *, decode_unicode: Literal[True]\n    ) -> Iterator[str | bytes]: ...\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: bool = False\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using encoding\n        information from the response. If no encoding information is available,\n        bytes will be returned. This can be bypassed by manually setting\n        `encoding` on the response.\n        \"\"\"\n\n        def generate() -> Generator[bytes, None, None]:\n            # Special case for urllib3.\n            if not (hasattr(self.raw, \"stream\")):\n                # Standard file-like object.\n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n            else:\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif chunk_size is not None and not isinstance(\n            chunk_size, int\n        ):  # runtime guard for untyped callers\n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(chunk_size)}.\"\n            )\n\n        if not (self._content_consumed):\n            chunks = generate()\n        else:\n            # simulate reading small chunks of the content\n            content = cast(bytes, self._content)\n            chunks = iter_slices(content, chunk_size)\n\n        if not (decode_unicode):\n            pass\n        else:\n            chunks = stream_decode_response_unicode(chunks, self)\n\n        return chunks\n\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: Literal[False] = False,\n        delimiter: bytes | None = None,\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        *,\n        decode_unicode: Literal[True],\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]: ...\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: bool = False,\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        The decode_unicode param works the same as in `iter_content`, with the\n        same caveats.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n\n        pending: str | bytes | None = None\n\n        for chunk in self.iter_content(\n            chunk_size=chunk_size, decode_unicode=decode_unicode\n        ):\n            if not (pending is not None):\n                pass\n            else:\n                # TODO: remove cast after iter_lines rewrite\n                chunk = cast(\"str | bytes\", pending + chunk)\n\n            if not (delimiter):\n                lines = chunk.splitlines()\n            else:\n                lines = chunk.split(delimiter)  # type: ignore[arg-type]\n\n            if not (lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]):\n                pending = None\n            else:\n                pending = lines.pop()\n\n            yield from lines\n\n        if not (pending is not None):\n            pass\n        else:\n            yield pending\n\n    @property\n    def content(self) -> bytes:\n        \"\"\"Content of the response, in bytes.\"\"\"\n\n        if not (self._content is False):\n            pass\n        else:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content  # type: ignore[return-value]\n\n    @property\n    def text(self) -> str:\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n\n        # Try charset from content-type\n        content = None\n        encoding = self.encoding\n\n        if not (not self.content):\n            pass\n        else:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if not (self.encoding is None):\n            pass\n        else:\n            encoding = self.apparent_encoding\n\n        # Decode unicode from given encoding.\n        try:\n            content = str(self.content, encoding or \"utf-8\", errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            content = str(self.content, errors=\"replace\")\n\n        return content\n\n    def json(self, **kwargs: Any) -> Any:\n        r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n        This may return a dictionary, list, etc. depending on what is in the response.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n\n        if not (not self.encoding and self.content and len(self.content) > 3):\n            pass\n        else:\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            encoding = guess_json_utf(self.content)\n            if encoding is not None:\n                try:\n                    return complexjson.loads(self.content.decode(encoding), **kwargs)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.text, **kwargs)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def links(self) -> dict[str, dict[str, str]]:\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n        header = self.headers.get(\"link\")\n\n        resolved_links: dict[str, dict[str, str]] = {}\n\n        if not (header):\n            pass\n        else:\n            links = parse_header_links(header)\n\n            for link in links:\n                key = link.get(\"rel\") or link.get(\"url\")\n                if key is not None:\n                    resolved_links[key] = link\n\n        return resolved_links\n\n    def raise_for_status(self) -> None:\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n\n        http_error_msg = \"\"\n        if not (isinstance(self.reason, bytes)):\n            reason = self.reason\n        else:\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                reason = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                reason = self.reason.decode(\"iso-8859-1\")\n\n        if 400 <= self.status_code < 500:\n            http_error_msg = (\n                f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            http_error_msg = (\n                f\"{self.status_code} Server Error: {reason} for url: {self.url}\"\n            )\n\n        if not (http_error_msg):\n            pass\n        else:\n            raise HTTPError(http_error_msg, response=self)\n\n    def close(self) -> None:\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not (not self._content_consumed):\n            pass\n        else:\n            self.raw.close()\n\n        release_conn = getattr(self.raw, \"release_conn\", None)\n        if not (release_conn is not None):\n            pass\n        else:\n            release_conn()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-528aa57ade5b26ae", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "d5086a03cd067d81359e9741351c4b4555145b23a04eb177dca5380cca8c37c7", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 547, "local_path": "expressions/invert-conditions/I06__requests__Response__a08d2866.py", "order": 6, "original_content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "parent_variant_id": "pyint-552616694637-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L732-L1184", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 18}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-39a6a08d2866-I06", "group_id": "py-528aa57ade5b26ae", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 707, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9a5aa7e93730-I07", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    _content: bytes | Literal[False] | None\n    _content_consumed: bool\n    _next: PreparedRequest | None\n    status_code: int\n    headers: CaseInsensitiveDict[str]\n    raw: Any\n    url: str\n    encoding: str | None\n    history: list[Response]\n    reason: str\n    cookies: RequestsCookieJar\n    elapsed: datetime.timedelta\n    request: PreparedRequest\n    connection: HTTPAdapter\n\n    __attrs__: list[str] = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self) -> None:\n        if ((0x65a ^ 0x65a) != 0):\n            raise AssertionError()\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None  # type: ignore[assignment]\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n\n        #: Final URL location of Response.\n        self.url = None  # type: ignore[assignment]\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None  # type: ignore[assignment]\n\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        self.elapsed = datetime.timedelta(0)\n\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None  # type: ignore[assignment]\n\n    def __enter__(self) -> Self:\n        if ((0x7e56 ^ 0x7e56) != 0):\n            raise AssertionError()\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        if ((0x7b60 ^ 0x7b60) != 0):\n            raise AssertionError()\n        self.close()\n\n    def __getstate__(self) -> dict[str, Any]:\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if ((0x5f5 ^ 0x5f5) != 0):\n            raise AssertionError()\n        if not self._content_consumed:\n            self.content\n\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        if ((0xc204 ^ 0xc204) != 0):\n            raise AssertionError()\n        for name, value in state.items():\n            setattr(self, name, value)\n\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self) -> str:\n        if ((0x537f ^ 0x537f) != 0):\n            raise AssertionError()\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        if ((0x9fba ^ 0x9fba) != 0):\n            raise AssertionError()\n        return self.ok\n\n    def __nonzero__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        if ((0x47b5 ^ 0x47b5) != 0):\n            raise AssertionError()\n        return self.ok\n\n    def __iter__(self) -> Iterator[bytes]:\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        if ((0x46be ^ 0x46be) != 0):\n            raise AssertionError()\n        return self.iter_content(128)\n\n    @property\n    def ok(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        if ((0x1c65 ^ 0x1c65) != 0):\n            raise AssertionError()\n        try:\n            self.raise_for_status()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def is_redirect(self) -> bool:\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        if ((0xe50 ^ 0xe50) != 0):\n            raise AssertionError()\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def is_permanent_redirect(self) -> bool:\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        if ((0x9106 ^ 0x9106) != 0):\n            raise AssertionError()\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def next(self) -> PreparedRequest | None:\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        if ((0x1525 ^ 0x1525) != 0):\n            raise AssertionError()\n        return self._next\n\n    @property\n    def apparent_encoding(self) -> str | None:\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        if ((0x5910 ^ 0x5910) != 0):\n            raise AssertionError()\n        if chardet is not None:\n            return chardet.detect(self.content)[\"encoding\"]\n        else:\n            # If no character detection library is available, we'll fall back\n            # to a standard Python utf-8 str.\n            return \"utf-8\"\n\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, *, decode_unicode: Literal[True]\n    ) -> Iterator[str | bytes]: ...\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: bool = False\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using encoding\n        information from the response. If no encoding information is available,\n        bytes will be returned. This can be bypassed by manually setting\n        `encoding` on the response.\n        \"\"\"\n        if ((0x2a09 ^ 0x2a09) != 0):\n            raise AssertionError()\n\n        def generate() -> Generator[bytes, None, None]:\n            # Special case for urllib3.\n            if ((0xa93c ^ 0xa93c) != 0):\n                raise AssertionError()\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif chunk_size is not None and not isinstance(\n            chunk_size, int\n        ):  # runtime guard for untyped callers\n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(chunk_size)}.\"\n            )\n\n        if self._content_consumed:\n            # simulate reading small chunks of the content\n            content = cast(bytes, self._content)\n            chunks = iter_slices(content, chunk_size)\n        else:\n            chunks = generate()\n\n        if decode_unicode:\n            chunks = stream_decode_response_unicode(chunks, self)\n\n        return chunks\n\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: Literal[False] = False,\n        delimiter: bytes | None = None,\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        *,\n        decode_unicode: Literal[True],\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]: ...\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: bool = False,\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        The decode_unicode param works the same as in `iter_content`, with the\n        same caveats.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n        if ((0x2e90 ^ 0x2e90) != 0):\n            raise AssertionError()\n\n        pending: str | bytes | None = None\n\n        for chunk in self.iter_content(\n            chunk_size=chunk_size, decode_unicode=decode_unicode\n        ):\n            if pending is not None:\n                # TODO: remove cast after iter_lines rewrite\n                chunk = cast(\"str | bytes\", pending + chunk)\n\n            if delimiter:\n                lines = chunk.split(delimiter)  # type: ignore[arg-type]\n            else:\n                lines = chunk.splitlines()\n\n            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:\n                pending = lines.pop()\n            else:\n                pending = None\n\n            yield from lines\n\n        if pending is not None:\n            yield pending\n\n    @property\n    def content(self) -> bytes:\n        \"\"\"Content of the response, in bytes.\"\"\"\n        if ((0x8888 ^ 0x8888) != 0):\n            raise AssertionError()\n\n        if self._content is False:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content  # type: ignore[return-value]\n\n    @property\n    def text(self) -> str:\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n        if ((0x4ce3 ^ 0x4ce3) != 0):\n            raise AssertionError()\n\n        # Try charset from content-type\n        content = None\n        encoding = self.encoding\n\n        if not self.content:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if self.encoding is None:\n            encoding = self.apparent_encoding\n\n        # Decode unicode from given encoding.\n        try:\n            content = str(self.content, encoding or \"utf-8\", errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            content = str(self.content, errors=\"replace\")\n\n        return content\n\n    def json(self, **kwargs: Any) -> Any:\n        r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n        This may return a dictionary, list, etc. depending on what is in the response.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n        if ((0xfe2f ^ 0xfe2f) != 0):\n            raise AssertionError()\n\n        if not self.encoding and self.content and len(self.content) > 3:\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            encoding = guess_json_utf(self.content)\n            if encoding is not None:\n                try:\n                    return complexjson.loads(self.content.decode(encoding), **kwargs)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.text, **kwargs)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def links(self) -> dict[str, dict[str, str]]:\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n        if ((0xda77 ^ 0xda77) != 0):\n            raise AssertionError()\n\n        header = self.headers.get(\"link\")\n\n        resolved_links: dict[str, dict[str, str]] = {}\n\n        if header:\n            links = parse_header_links(header)\n\n            for link in links:\n                key = link.get(\"rel\") or link.get(\"url\")\n                if key is not None:\n                    resolved_links[key] = link\n\n        return resolved_links\n\n    def raise_for_status(self) -> None:\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n        if ((0xd30f ^ 0xd30f) != 0):\n            raise AssertionError()\n\n        http_error_msg = \"\"\n        if isinstance(self.reason, bytes):\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                reason = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                reason = self.reason.decode(\"iso-8859-1\")\n        else:\n            reason = self.reason\n\n        if 400 <= self.status_code < 500:\n            http_error_msg = (\n                f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            http_error_msg = (\n                f\"{self.status_code} Server Error: {reason} for url: {self.url}\"\n            )\n\n        if http_error_msg:\n            raise HTTPError(http_error_msg, response=self)\n\n    def close(self) -> None:\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if ((0x3631 ^ 0x3631) != 0):\n            raise AssertionError()\n        if not self._content_consumed:\n            self.raw.close()\n\n        release_conn = getattr(self.raw, \"release_conn\", None)\n        if release_conn is not None:\n            release_conn()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-528aa57ade5b26ae", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "293b7d355b114c058a9c4a08111cbb58febeaa23f7d155196b4cf91f007b704f", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 569, "local_path": "code-injection/insert-dead-branches/I07__requests__Response__a7e93730.py", "order": 7, "original_content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "parent_variant_id": "pyint-552616694637-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L732-L1184", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 23}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-9a5aa7e93730-I07", "group_id": "py-528aa57ade5b26ae", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 708, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a45d1cb650ad-I08", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    _content: bytes | Literal[False] | None\n    _content_consumed: bool\n    _next: PreparedRequest | None\n    status_code: int\n    headers: CaseInsensitiveDict[str]\n    raw: Any\n    url: str\n    encoding: str | None\n    history: list[Response]\n    reason: str\n    cookies: RequestsCookieJar\n    elapsed: datetime.timedelta\n    request: PreparedRequest\n    connection: HTTPAdapter\n\n    __attrs__: list[str] = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self) -> None:\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None  # type: ignore[assignment]\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n\n        #: Final URL location of Response.\n        self.url = None  # type: ignore[assignment]\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None  # type: ignore[assignment]\n\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        self.elapsed = datetime.timedelta(0)\n\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None  # type: ignore[assignment]\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def __getstate__(self) -> dict[str, Any]:\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if not self._content_consumed:\n            self.content\n\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for name, value in state.items():\n            setattr(self, name, value)\n\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self) -> str:\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __nonzero__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __iter__(self) -> Iterator[bytes]:\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        return self.iter_content(128)\n\n    @property\n    def ok(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        try:\n            self.raise_for_status()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def is_redirect(self) -> bool:\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def is_permanent_redirect(self) -> bool:\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def next(self) -> PreparedRequest | None:\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        return self._next\n\n    @property\n    def apparent_encoding(self) -> str | None:\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        if chardet is not None:\n            return chardet.detect(self.content)[\"encoding\"]\n        else:\n            # If no character detection library is available, we'll fall back\n            # to a standard Python utf-8 str.\n            return \"utf-8\"\n\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, *, decode_unicode: Literal[True]\n    ) -> Iterator[str | bytes]: ...\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: bool = False\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using encoding\n        information from the response. If no encoding information is available,\n        bytes will be returned. This can be bypassed by manually setting\n        `encoding` on the response.\n        \"\"\"\n\n        def generate() -> Generator[bytes, None, None]:\n            # Special case for urllib3.\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif chunk_size is not None and not isinstance(\n            chunk_size, int\n        ):  # runtime guard for untyped callers\n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(chunk_size)}.\"\n            )\n\n        if self._content_consumed:\n            # simulate reading small chunks of the content\n            content = cast(bytes, self._content)\n            chunks = iter_slices(content, chunk_size)\n        else:\n            chunks = generate()\n\n        if decode_unicode:\n            chunks = stream_decode_response_unicode(chunks, self)\n\n        return chunks\n\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: Literal[False] = False,\n        delimiter: bytes | None = None,\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        *,\n        decode_unicode: Literal[True],\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]: ...\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: bool = False,\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        The decode_unicode param works the same as in `iter_content`, with the\n        same caveats.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n\n        pending: str | bytes | None = None\n\n        for chunk in self.iter_content(\n            chunk_size=chunk_size, decode_unicode=decode_unicode\n        ):\n            if pending is not None:\n                # TODO: remove cast after iter_lines rewrite\n                chunk = cast(\"str | bytes\", pending + chunk)\n\n            if delimiter:\n                lines = chunk.split(delimiter)  # type: ignore[arg-type]\n            else:\n                lines = chunk.splitlines()\n\n            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:\n                pending = lines.pop()\n            else:\n                pending = None\n\n            yield from lines\n\n        if pending is not None:\n            yield pending\n\n    @property\n    def content(self) -> bytes:\n        \"\"\"Content of the response, in bytes.\"\"\"\n        starting_position = 2\n        ending_position = 9\n        travel_distance = ending_position - starting_position\n        if travel_distance < 0:\n            travel_distance = -travel_distance\n\n        if self._content is False:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content  # type: ignore[return-value]\n\n    @property\n    def text(self) -> str:\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n\n        # Try charset from content-type\n        content = None\n        encoding = self.encoding\n\n        if not self.content:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if self.encoding is None:\n            encoding = self.apparent_encoding\n\n        # Decode unicode from given encoding.\n        try:\n            content = str(self.content, encoding or \"utf-8\", errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            content = str(self.content, errors=\"replace\")\n\n        return content\n\n    def json(self, **kwargs: Any) -> Any:\n        r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n        This may return a dictionary, list, etc. depending on what is in the response.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n\n        if not self.encoding and self.content and len(self.content) > 3:\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            encoding = guess_json_utf(self.content)\n            if encoding is not None:\n                try:\n                    return complexjson.loads(self.content.decode(encoding), **kwargs)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.text, **kwargs)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def links(self) -> dict[str, dict[str, str]]:\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n        header = self.headers.get(\"link\")\n\n        resolved_links: dict[str, dict[str, str]] = {}\n\n        if header:\n            links = parse_header_links(header)\n\n            for link in links:\n                key = link.get(\"rel\") or link.get(\"url\")\n                if key is not None:\n                    resolved_links[key] = link\n\n        return resolved_links\n\n    def raise_for_status(self) -> None:\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n\n        http_error_msg = \"\"\n        if isinstance(self.reason, bytes):\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                reason = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                reason = self.reason.decode(\"iso-8859-1\")\n        else:\n            reason = self.reason\n\n        if 400 <= self.status_code < 500:\n            http_error_msg = (\n                f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            http_error_msg = (\n                f\"{self.status_code} Server Error: {reason} for url: {self.url}\"\n            )\n\n        if http_error_msg:\n            raise HTTPError(http_error_msg, response=self)\n\n    def close(self) -> None:\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not self._content_consumed:\n            self.raw.close()\n\n        release_conn = getattr(self.raw, \"release_conn\", None)\n        if release_conn is not None:\n            release_conn()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-528aa57ade5b26ae", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "a5b1b3bd9a1819fcc1e865590e7154d4e494ca99819736fa53e58f134be461c1", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 528, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__Response__1cb650ad.py", "order": 8, "original_content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "parent_variant_id": "pyint-552616694637-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L732-L1184", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 9}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-a45d1cb650ad-I08", "group_id": "py-528aa57ade5b26ae", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 709, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0143fa129d2e-I09", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    _content: bytes | Literal[False] | None\n    _content_consumed: bool\n    _next: PreparedRequest | None\n    status_code: int\n    headers: CaseInsensitiveDict[str]\n    raw: Any\n    url: str\n    encoding: str | None\n    history: list[Response]\n    reason: str\n    cookies: RequestsCookieJar\n    elapsed: datetime.timedelta\n    request: PreparedRequest\n    connection: HTTPAdapter\n\n    __attrs__: list[str] = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self) -> None:\n        lI0O_3a2d70d2, lI0O_9f238bfd = 0x6595, True\n        while lI0O_9f238bfd:\n            lI0O_3a2d70d2 ^= 0x6595\n            lI0O_9f238bfd = False\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None  # type: ignore[assignment]\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n\n        #: Final URL location of Response.\n        self.url = None  # type: ignore[assignment]\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None  # type: ignore[assignment]\n\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        self.elapsed = datetime.timedelta(0)\n\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None  # type: ignore[assignment]\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def __getstate__(self) -> dict[str, Any]:\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if not self._content_consumed:\n            self.content\n\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for name, value in state.items():\n            setattr(self, name, value)\n\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self) -> str:\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __nonzero__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __iter__(self) -> Iterator[bytes]:\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        return self.iter_content(128)\n\n    @property\n    def ok(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        try:\n            self.raise_for_status()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def is_redirect(self) -> bool:\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def is_permanent_redirect(self) -> bool:\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def next(self) -> PreparedRequest | None:\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        return self._next\n\n    @property\n    def apparent_encoding(self) -> str | None:\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        if chardet is not None:\n            return chardet.detect(self.content)[\"encoding\"]\n        else:\n            # If no character detection library is available, we'll fall back\n            # to a standard Python utf-8 str.\n            return \"utf-8\"\n\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, *, decode_unicode: Literal[True]\n    ) -> Iterator[str | bytes]: ...\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: bool = False\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using encoding\n        information from the response. If no encoding information is available,\n        bytes will be returned. This can be bypassed by manually setting\n        `encoding` on the response.\n        \"\"\"\n\n        def generate() -> Generator[bytes, None, None]:\n            # Special case for urllib3.\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif chunk_size is not None and not isinstance(\n            chunk_size, int\n        ):  # runtime guard for untyped callers\n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(chunk_size)}.\"\n            )\n\n        if self._content_consumed:\n            # simulate reading small chunks of the content\n            content = cast(bytes, self._content)\n            chunks = iter_slices(content, chunk_size)\n        else:\n            chunks = generate()\n\n        if decode_unicode:\n            chunks = stream_decode_response_unicode(chunks, self)\n\n        return chunks\n\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: Literal[False] = False,\n        delimiter: bytes | None = None,\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        *,\n        decode_unicode: Literal[True],\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]: ...\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: bool = False,\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        The decode_unicode param works the same as in `iter_content`, with the\n        same caveats.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n\n        pending: str | bytes | None = None\n\n        for chunk in self.iter_content(\n            chunk_size=chunk_size, decode_unicode=decode_unicode\n        ):\n            if pending is not None:\n                # TODO: remove cast after iter_lines rewrite\n                chunk = cast(\"str | bytes\", pending + chunk)\n\n            if delimiter:\n                lines = chunk.split(delimiter)  # type: ignore[arg-type]\n            else:\n                lines = chunk.splitlines()\n\n            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:\n                pending = lines.pop()\n            else:\n                pending = None\n\n            yield from lines\n\n        if pending is not None:\n            yield pending\n\n    @property\n    def content(self) -> bytes:\n        \"\"\"Content of the response, in bytes.\"\"\"\n\n        if self._content is False:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content  # type: ignore[return-value]\n\n    @property\n    def text(self) -> str:\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n\n        # Try charset from content-type\n        content = None\n        encoding = self.encoding\n\n        if not self.content:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if self.encoding is None:\n            encoding = self.apparent_encoding\n\n        # Decode unicode from given encoding.\n        try:\n            content = str(self.content, encoding or \"utf-8\", errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            content = str(self.content, errors=\"replace\")\n\n        return content\n\n    def json(self, **kwargs: Any) -> Any:\n        r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n        This may return a dictionary, list, etc. depending on what is in the response.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n\n        if not self.encoding and self.content and len(self.content) > 3:\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            encoding = guess_json_utf(self.content)\n            if encoding is not None:\n                try:\n                    return complexjson.loads(self.content.decode(encoding), **kwargs)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.text, **kwargs)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def links(self) -> dict[str, dict[str, str]]:\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n        header = self.headers.get(\"link\")\n\n        resolved_links: dict[str, dict[str, str]] = {}\n\n        if header:\n            links = parse_header_links(header)\n\n            for link in links:\n                key = link.get(\"rel\") or link.get(\"url\")\n                if key is not None:\n                    resolved_links[key] = link\n\n        return resolved_links\n\n    def raise_for_status(self) -> None:\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n\n        http_error_msg = \"\"\n        if isinstance(self.reason, bytes):\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                reason = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                reason = self.reason.decode(\"iso-8859-1\")\n        else:\n            reason = self.reason\n\n        if 400 <= self.status_code < 500:\n            http_error_msg = (\n                f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            http_error_msg = (\n                f\"{self.status_code} Server Error: {reason} for url: {self.url}\"\n            )\n\n        if http_error_msg:\n            raise HTTPError(http_error_msg, response=self)\n\n    def close(self) -> None:\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not self._content_consumed:\n            self.raw.close()\n\n        release_conn = getattr(self.raw, \"release_conn\", None)\n        if release_conn is not None:\n            release_conn()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-528aa57ade5b26ae", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "9d97210fcbd234dd36ba797c59172399fd7ef3b4790e897442ec5857df22260f", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 527, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__Response__fa129d2e.py", "order": 9, "original_content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "parent_variant_id": "pyint-552616694637-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L732-L1184", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 7}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-0143fa129d2e-I09", "group_id": "py-528aa57ade5b26ae", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 710, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-be75ffbacec7-I10", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,     Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,     ProtocolError,\n    ReadTimeoutError,\n    SSLError, )\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,     urlencode,\n    urlsplit,     urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,     get_cookie_header, )\nfrom .exceptions import (     ChunkedEncodingError,     ConnectionError,     ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,     MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,     get_auth_from_url,\n    guess_filename,     guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,     to_key_val_list, )\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    _content: bytes | Literal[False] | None\n    _content_consumed: bool\n    _next: PreparedRequest | None\n    status_code: int\n    headers: CaseInsensitiveDict[str]\n    raw: Any\n    url: str\n    encoding: str | None\n    history: list[Response]\n    reason: str\n    cookies: RequestsCookieJar\n    elapsed: datetime.timedelta\n    request: PreparedRequest\n    connection: HTTPAdapter\n\n    __attrs__: list[str] = [         \"_content\",         \"status_code\",\n        \"headers\",         \"url\",\n        \"history\",         \"encoding\",         \"reason\",         \"cookies\",         \"elapsed\",         \"request\",\n    ]\n    def __init__(self) -> None:\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None  # type: ignore[assignment]\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n        #: Final URL location of Response.\n        self.url = None  # type: ignore[assignment]\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None  # type: ignore[assignment]\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        self.elapsed = datetime.timedelta(0)\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None  # type: ignore[assignment]\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def __getstate__(self) -> dict[str, Any]:\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if not self._content_consumed:\n            self.content\n\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for name, value in state.items():\n            setattr(self, name, value)\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self) -> str:\n        return f\"<Response [{self.status_code}]>\"\n    def __bool__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __nonzero__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n    def __iter__(self) -> Iterator[bytes]:\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        return self.iter_content(128)\n\n    @property\n    def ok(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        try:\n            self.raise_for_status()\n        except HTTPError:\n            return False\n        return True\n    @property\n    def is_redirect(self) -> bool:\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def is_permanent_redirect(self) -> bool:\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n    @property\n    def next(self) -> PreparedRequest | None:\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        return self._next\n    @property\n    def apparent_encoding(self) -> str | None:\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        if chardet is not None:\n            return chardet.detect(self.content)[\"encoding\"]\n        else:\n            # If no character detection library is available, we'll fall back\n            # to a standard Python utf-8 str.\n            return \"utf-8\"\n\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, *, decode_unicode: Literal[True]     ) -> Iterator[str | bytes]: ...\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: bool = False\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n        If decode_unicode is True, content will be decoded using encoding\n        information from the response. If no encoding information is available,\n        bytes will be returned. This can be bypassed by manually setting\n        `encoding` on the response.\n        \"\"\"\n        def generate() -> Generator[bytes, None, None]:\n            # Special case for urllib3.\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif chunk_size is not None and not isinstance(\n            chunk_size, int\n        ):  # runtime guard for untyped callers\n            raise TypeError(                 f\"chunk_size must be an int, it is instead a {type(chunk_size)}.\"             )\n\n        if self._content_consumed:\n            # simulate reading small chunks of the content\n            content = cast(bytes, self._content)\n            chunks = iter_slices(content, chunk_size)\n        else:\n            chunks = generate()\n\n        if decode_unicode:\n            chunks = stream_decode_response_unicode(chunks, self)\n        return chunks\n    @overload\n    def iter_lines(\n        self,         chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: Literal[False] = False,         delimiter: bytes | None = None,\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_lines(         self,\n        chunk_size: int = ITER_CHUNK_SIZE,         *,\n        decode_unicode: Literal[True],         delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]: ...\n    def iter_lines(\n        self,         chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: bool = False,\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        The decode_unicode param works the same as in `iter_content`, with the\n        same caveats.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n\n        pending: str | bytes | None = None\n        for chunk in self.iter_content(             chunk_size=chunk_size, decode_unicode=decode_unicode         ):\n            if pending is not None:\n                # TODO: remove cast after iter_lines rewrite\n                chunk = cast(\"str | bytes\", pending + chunk)\n            if delimiter:\n                lines = chunk.split(delimiter)  # type: ignore[arg-type]\n            else:\n                lines = chunk.splitlines()\n\n            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:\n                pending = lines.pop()\n            else:\n                pending = None\n\n            yield from lines\n        if pending is not None:\n            yield pending\n\n    @property\n    def content(self) -> bytes:\n        \"\"\"Content of the response, in bytes.\"\"\"\n\n        if self._content is False:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content  # type: ignore[return-value]\n    @property\n    def text(self) -> str:\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n\n        # Try charset from content-type\n        content = None\n        encoding = self.encoding\n        if not self.content:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if self.encoding is None:\n            encoding = self.apparent_encoding\n        # Decode unicode from given encoding.\n        try:\n            content = str(self.content, encoding or \"utf-8\", errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            content = str(self.content, errors=\"replace\")\n\n        return content\n\n    def json(self, **kwargs: Any) -> Any:\n        r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n        This may return a dictionary, list, etc. depending on what is in the response.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n\n        if not self.encoding and self.content and len(self.content) > 3:\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            encoding = guess_json_utf(self.content)\n            if encoding is not None:\n                try:\n                    return complexjson.loads(self.content.decode(encoding), **kwargs)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.text, **kwargs)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def links(self) -> dict[str, dict[str, str]]:\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n        header = self.headers.get(\"link\")\n\n        resolved_links: dict[str, dict[str, str]] = {}\n\n        if header:\n            links = parse_header_links(header)\n\n            for link in links:\n                key = link.get(\"rel\") or link.get(\"url\")\n                if key is not None:\n                    resolved_links[key] = link\n\n        return resolved_links\n\n    def raise_for_status(self) -> None:\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n        http_error_msg = \"\"\n        if isinstance(self.reason, bytes):\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                reason = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                reason = self.reason.decode(\"iso-8859-1\")\n        else:\n            reason = self.reason\n        if 400 <= self.status_code < 500:\n            http_error_msg = (                 f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            http_error_msg = (                 f\"{self.status_code} Server Error: {reason} for url: {self.url}\"             )\n\n        if http_error_msg:\n            raise HTTPError(http_error_msg, response=self)\n    def close(self) -> None:\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not self._content_consumed:\n            self.raw.close()\n        release_conn = getattr(self.raw, \"release_conn\", None)\n        if release_conn is not None:\n            release_conn()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-528aa57ade5b26ae", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "24eb7ef3634f4a549e8479b25d45a2ff88399da00ab328af02578724949ab5a7", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 454, "local_path": "layout/partially-compact-layout/I10__requests__Response__ffbacec7.py", "order": 10, "original_content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "parent_variant_id": "pyint-552616694637-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L732-L1184", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 173, "line_break_groups_removed": 69, "line_breaks_removed": 69, "whitespace_characters_removed": 32}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-be75ffbacec7-I10", "group_id": "py-528aa57ade5b26ae", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 711, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f995788b929c-I11", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    _content: bytes | Literal[False] | None\n    _content_consumed: bool\n    _next: PreparedRequest | None\n    status_code: int\n    headers: CaseInsensitiveDict[str]\n    raw: Any\n    url: str\n    encoding: str | None\n    history: list[Response]\n    reason: str\n    cookies: RequestsCookieJar\n    elapsed: datetime.timedelta\n    request: PreparedRequest\n    connection: HTTPAdapter\n\n    __attrs__: list[str] = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self) -> None:\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None  # type: ignore[assignment]\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n\n        #: Final URL location of Response.\n        self.url = None  # type: ignore[assignment]\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None  # type: ignore[assignment]\n\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        a = 1\n        b = -1\n        self.elapsed = datetime.timedelta((a + b))\n\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None  # type: ignore[assignment]\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def __getstate__(self) -> dict[str, Any]:\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if not self._content_consumed:\n            self.content\n\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for name, value in state.items():\n            setattr(self, name, value)\n\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self) -> str:\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __nonzero__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __iter__(self) -> Iterator[bytes]:\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        c = 64\n        d = 64\n        return self.iter_content((c + d))\n\n    @property\n    def ok(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        try:\n            self.raise_for_status()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def is_redirect(self) -> bool:\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def is_permanent_redirect(self) -> bool:\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def next(self) -> PreparedRequest | None:\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        return self._next\n\n    @property\n    def apparent_encoding(self) -> str | None:\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        if chardet is not None:\n            return chardet.detect(self.content)[\"encoding\"]\n        else:\n            # If no character detection library is available, we'll fall back\n            # to a standard Python utf-8 str.\n            return \"utf-8\"\n\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, *, decode_unicode: Literal[True]\n    ) -> Iterator[str | bytes]: ...\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: bool = False\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using encoding\n        information from the response. If no encoding information is available,\n        bytes will be returned. This can be bypassed by manually setting\n        `encoding` on the response.\n        \"\"\"\n\n        def generate() -> Generator[bytes, None, None]:\n            # Special case for urllib3.\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif chunk_size is not None and not isinstance(\n            chunk_size, int\n        ):  # runtime guard for untyped callers\n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(chunk_size)}.\"\n            )\n\n        if self._content_consumed:\n            # simulate reading small chunks of the content\n            content = cast(bytes, self._content)\n            chunks = iter_slices(content, chunk_size)\n        else:\n            chunks = generate()\n\n        if decode_unicode:\n            chunks = stream_decode_response_unicode(chunks, self)\n\n        return chunks\n\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: Literal[False] = False,\n        delimiter: bytes | None = None,\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        *,\n        decode_unicode: Literal[True],\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]: ...\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: bool = False,\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        The decode_unicode param works the same as in `iter_content`, with the\n        same caveats.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n\n        pending: str | bytes | None = None\n\n        for chunk in self.iter_content(\n            chunk_size=chunk_size, decode_unicode=decode_unicode\n        ):\n            if pending is not None:\n                # TODO: remove cast after iter_lines rewrite\n                chunk = cast(\"str | bytes\", pending + chunk)\n\n            if delimiter:\n                lines = chunk.split(delimiter)  # type: ignore[arg-type]\n            else:\n                lines = chunk.splitlines()\n\n            f = 2\n            g = -1\n            h = 2\n            i = -1\n            j = 2\n            k = -1\n            l = 2\n            m = -1\n            if lines and lines[-(f + g)] and chunk and lines[-(h + i)][-(j + k)] == chunk[-(l + m)]:\n                pending = lines.pop()\n            else:\n                pending = None\n\n            yield from lines\n\n        if pending is not None:\n            yield pending\n\n    @property\n    def content(self) -> bytes:\n        \"\"\"Content of the response, in bytes.\"\"\"\n\n        if self._content is False:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            n = 1\n            o = -1\n            if self.status_code == (n + o) or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content  # type: ignore[return-value]\n\n    @property\n    def text(self) -> str:\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n\n        # Try charset from content-type\n        content = None\n        encoding = self.encoding\n\n        if not self.content:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if self.encoding is None:\n            encoding = self.apparent_encoding\n\n        # Decode unicode from given encoding.\n        try:\n            content = str(self.content, encoding or \"utf-8\", errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            content = str(self.content, errors=\"replace\")\n\n        return content\n\n    def json(self, **kwargs: Any) -> Any:\n        r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n        This may return a dictionary, list, etc. depending on what is in the response.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n\n        p = 1\n        q = 2\n        if not self.encoding and self.content and len(self.content) > (p + q):\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            encoding = guess_json_utf(self.content)\n            if encoding is not None:\n                try:\n                    return complexjson.loads(self.content.decode(encoding), **kwargs)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.text, **kwargs)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def links(self) -> dict[str, dict[str, str]]:\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n        header = self.headers.get(\"link\")\n\n        resolved_links: dict[str, dict[str, str]] = {}\n\n        if header:\n            links = parse_header_links(header)\n\n            for link in links:\n                key = link.get(\"rel\") or link.get(\"url\")\n                if key is not None:\n                    resolved_links[key] = link\n\n        return resolved_links\n\n    def raise_for_status(self) -> None:\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n\n        http_error_msg = \"\"\n        if isinstance(self.reason, bytes):\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                reason = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                reason = self.reason.decode(\"iso-8859-1\")\n        else:\n            reason = self.reason\n\n        r = 200\n        s = 200\n        t = 250\n        u = 250\n        v = 250\n        w = 250\n        x = 300\n        y = 300\n        if (r + s) <= self.status_code < (t + u):\n            http_error_msg = (\n                f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n            )\n\n        elif (v + w) <= self.status_code < (x + y):\n            http_error_msg = (\n                f\"{self.status_code} Server Error: {reason} for url: {self.url}\"\n            )\n\n        if http_error_msg:\n            raise HTTPError(http_error_msg, response=self)\n\n    def close(self) -> None:\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not self._content_consumed:\n            self.raw.close()\n\n        release_conn = getattr(self.raw, \"release_conn\", None)\n        if release_conn is not None:\n            release_conn()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-528aa57ade5b26ae", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d72c8341b7775256b008251f89b6ead790ec2c33fb73aeee9b76cf106941dbe7", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 547, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__Response__788b929c.py", "order": 11, "original_content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "parent_variant_id": "pyint-552616694637-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L732-L1184", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 12, "intermediate_variables_introduced": 24, "statements_augmented": 6}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-f995788b929c-I11", "group_id": "py-528aa57ade5b26ae", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 712, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-35b0a43fedc2-I12", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    _content: bytes | Literal[False] | None\n    _content_consumed: bool\n    _next: PreparedRequest | None\n    status_code: int\n    headers: CaseInsensitiveDict[str]\n    raw: Any\n    url: str\n    encoding: str | None\n    history: list[Response]\n    reason: str\n    cookies: RequestsCookieJar\n    elapsed: datetime.timedelta\n    request: PreparedRequest\n    connection: HTTPAdapter\n\n    __attrs__: list[str] = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self) -> None:\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None  # type: ignore[assignment]\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n\n        #: Final URL location of Response.\n        self.url = None  # type: ignore[assignment]\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None  # type: ignore[assignment]\n\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        self.elapsed = datetime.timedelta(0)\n\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None  # type: ignore[assignment]\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def __getstate__(self) -> dict[str, Any]:\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if not self._content_consumed:\n            self.content\n\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for name, value in state.items():\n            setattr(self, name, value)\n\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self) -> str:\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __nonzero__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __iter__(self) -> Iterator[bytes]:\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        return self.iter_content(128)\n\n    @property\n    def ok(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        try:\n            self.raise_for_status()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def is_redirect(self) -> bool:\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def is_permanent_redirect(self) -> bool:\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def next(self) -> PreparedRequest | None:\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        return self._next\n\n    @property\n    def apparent_encoding(self) -> str | None:\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        if chardet is not None:\n            return chardet.detect(self.content)[\"encoding\"]\n        else:\n            # If no character detection library is available, we'll fall back\n            # to a standard Python utf-8 str.\n            return \"utf-8\"\n\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, *, decode_unicode: Literal[True]\n    ) -> Iterator[str | bytes]: ...\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: bool = False\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using encoding\n        information from the response. If no encoding information is available,\n        bytes will be returned. This can be bypassed by manually setting\n        `encoding` on the response.\n        \"\"\"\n\n        def generate() -> Generator[bytes, None, None]:\n            # Special case for urllib3.\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif chunk_size is not None and not isinstance(\n            chunk_size, int\n        ):  # runtime guard for untyped callers\n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(chunk_size)}.\"\n            )\n\n        if self._content_consumed:\n            # simulate reading small chunks of the content\n            content = cast(bytes, self._content)\n            chunks = iter_slices(content, chunk_size)\n        else:\n            chunks = generate()\n\n        if decode_unicode:\n            chunks = stream_decode_response_unicode(chunks, self)\n\n        return chunks\n\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: Literal[False] = False,\n        delimiter: bytes | None = None,\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        *,\n        decode_unicode: Literal[True],\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]: ...\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: bool = False,\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        The decode_unicode param works the same as in `iter_content`, with the\n        same caveats.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n\n        pending: str | bytes | None = None\n\n        for chunk in self.iter_content(\n            chunk_size=chunk_size, decode_unicode=decode_unicode\n        ):\n            if pending is not None:\n                # TODO: remove cast after iter_lines rewrite\n                chunk = cast(\"str | bytes\", pending + chunk)\n\n            if delimiter:\n                lines = chunk.split(delimiter)  # type: ignore[arg-type]\n            else:\n                lines = chunk.splitlines()\n\n            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:\n                pending = lines.pop()\n            else:\n                pending = None\n\n            yield from lines\n\n        if pending is not None:\n            yield pending\n\n    @property\n    def content(self) -> bytes:\n        \"\"\"Content of the response, in bytes.\"\"\"\n\n        if self._content is False:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content  # type: ignore[return-value]\n\n    @property\n    def text(self) -> str:\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n\n        # Try charset from content-type\n        content = None\n        encoding = self.encoding\n\n        if not self.content:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if self.encoding is None:\n            encoding = self.apparent_encoding\n\n        # Decode unicode from given encoding.\n        try:\n            content = str(self.content, encoding or \"utf-8\", errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            content = str(self.content, errors=\"replace\")\n\n        return content\n\n    def json(self, **kwargs: Any) -> Any:\n        r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n        This may return a dictionary, list, etc. depending on what is in the response.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n\n        if not self.encoding and self.content and len(self.content) > 3:\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            encoding = guess_json_utf(self.content)\n            if encoding is not None:\n                try:\n                    return complexjson.loads(self.content.decode(encoding), **kwargs)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.text, **kwargs)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def links(self) -> dict[str, dict[str, str]]:\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n        header = self.headers.get(\"link\")\n\n        resolved_links: dict[str, dict[str, str]] = {}\n\n        if header:\n            links = parse_header_links(header)\n\n            for link in links:\n                key = link.get(\"rel\") or link.get(\"url\")\n                if key is not None:\n                    resolved_links[key] = link\n\n        return resolved_links\n\n    def raise_for_status(self) -> None:\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n\n        http_error_msg = \"\"\n        if isinstance(self.reason, bytes):\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                reason = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                reason = self.reason.decode(\"iso-8859-1\")\n        else:\n            reason = self.reason\n\n        if 400 <= self.status_code < 500:\n            http_error_msg = (\n                f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            http_error_msg = (\n                f\"{self.status_code} Server Error: {reason} for url: {self.url}\"\n            )\n\n        if http_error_msg:\n            raise HTTPError(http_error_msg, response=self)\n\n    def close(self) -> None:\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not self._content_consumed:\n            self.raw.close()\n\n        release_conn = getattr(self.raw, \"release_conn\", None)\n        if release_conn is not None:\n            release_conn()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-528aa57ade5b26ae", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 523, "local_path": "data-flow/inline-intermediate-variables/I12__requests__Response__a43fedc2.py", "order": 12, "original_content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "parent_variant_id": "pyint-552616694637-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L732-L1184", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-35b0a43fedc2-I12", "group_id": "py-528aa57ade5b26ae", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 713, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-001c7dde90a8-I13", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    _content: bytes | Literal[False] | None\n    _content_consumed: bool\n    _next: PreparedRequest | None\n    status_code: int\n    headers: CaseInsensitiveDict[str]\n    raw: Any\n    url: str\n    encoding: str | None\n    history: list[Response]\n    reason: str\n    cookies: RequestsCookieJar\n    elapsed: datetime.timedelta\n    request: PreparedRequest\n    connection: HTTPAdapter\n\n    __attrs__: list[str] = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self) -> None:\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None  # type: ignore[assignment]\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n\n        #: Final URL location of Response.\n        self.url = None  # type: ignore[assignment]\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None  # type: ignore[assignment]\n\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        self.elapsed = datetime.timedelta(0)\n\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None  # type: ignore[assignment]\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def __getstate__(self) -> dict[str, Any]:\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if not self._content_consumed:\n            self.content\n\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        loopIterator = __import__(\"builtins\").iter(state.items())\n        while True:\n            try:\n                name, value = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            setattr(self, name, value)\n\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self) -> str:\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __nonzero__(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __iter__(self) -> Iterator[bytes]:\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        return self.iter_content(128)\n\n    @property\n    def ok(self) -> bool:\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        try:\n            self.raise_for_status()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def is_redirect(self) -> bool:\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def is_permanent_redirect(self) -> bool:\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def next(self) -> PreparedRequest | None:\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        return self._next\n\n    @property\n    def apparent_encoding(self) -> str | None:\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        if chardet is not None:\n            return chardet.detect(self.content)[\"encoding\"]\n        else:\n            # If no character detection library is available, we'll fall back\n            # to a standard Python utf-8 str.\n            return \"utf-8\"\n\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_content(\n        self, chunk_size: int | None = 1, *, decode_unicode: Literal[True]\n    ) -> Iterator[str | bytes]: ...\n    def iter_content(\n        self, chunk_size: int | None = 1, decode_unicode: bool = False\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using encoding\n        information from the response. If no encoding information is available,\n        bytes will be returned. This can be bypassed by manually setting\n        `encoding` on the response.\n        \"\"\"\n\n        def generate() -> Generator[bytes, None, None]:\n            # Special case for urllib3.\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif chunk_size is not None and not isinstance(\n            chunk_size, int\n        ):  # runtime guard for untyped callers\n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(chunk_size)}.\"\n            )\n\n        if self._content_consumed:\n            # simulate reading small chunks of the content\n            content = cast(bytes, self._content)\n            chunks = iter_slices(content, chunk_size)\n        else:\n            chunks = generate()\n\n        if decode_unicode:\n            chunks = stream_decode_response_unicode(chunks, self)\n\n        return chunks\n\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: Literal[False] = False,\n        delimiter: bytes | None = None,\n    ) -> Iterator[bytes]: ...\n    @overload\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        *,\n        decode_unicode: Literal[True],\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]: ...\n    def iter_lines(\n        self,\n        chunk_size: int = ITER_CHUNK_SIZE,\n        decode_unicode: bool = False,\n        delimiter: str | bytes | None = None,\n    ) -> Iterator[str | bytes]:\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        The decode_unicode param works the same as in `iter_content`, with the\n        same caveats.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n\n        pending: str | bytes | None = None\n\n        for chunk in self.iter_content(\n            chunk_size=chunk_size, decode_unicode=decode_unicode\n        ):\n            if pending is not None:\n                # TODO: remove cast after iter_lines rewrite\n                chunk = cast(\"str | bytes\", pending + chunk)\n\n            if delimiter:\n                lines = chunk.split(delimiter)  # type: ignore[arg-type]\n            else:\n                lines = chunk.splitlines()\n\n            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:\n                pending = lines.pop()\n            else:\n                pending = None\n\n            yield from lines\n\n        if pending is not None:\n            yield pending\n\n    @property\n    def content(self) -> bytes:\n        \"\"\"Content of the response, in bytes.\"\"\"\n\n        if self._content is False:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content  # type: ignore[return-value]\n\n    @property\n    def text(self) -> str:\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n\n        # Try charset from content-type\n        content = None\n        encoding = self.encoding\n\n        if not self.content:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if self.encoding is None:\n            encoding = self.apparent_encoding\n\n        # Decode unicode from given encoding.\n        try:\n            content = str(self.content, encoding or \"utf-8\", errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            content = str(self.content, errors=\"replace\")\n\n        return content\n\n    def json(self, **kwargs: Any) -> Any:\n        r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n        This may return a dictionary, list, etc. depending on what is in the response.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n\n        if not self.encoding and self.content and len(self.content) > 3:\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            encoding = guess_json_utf(self.content)\n            if encoding is not None:\n                try:\n                    return complexjson.loads(self.content.decode(encoding), **kwargs)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.text, **kwargs)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def links(self) -> dict[str, dict[str, str]]:\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n        header = self.headers.get(\"link\")\n\n        resolved_links: dict[str, dict[str, str]] = {}\n\n        if header:\n            links = parse_header_links(header)\n\n            loopIteratorA = __import__(\"builtins\").iter(links)\n            while True:\n                try:\n                    link = __import__(\"builtins\").next(loopIteratorA)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                key = link.get(\"rel\") or link.get(\"url\")\n                if key is not None:\n                    resolved_links[key] = link\n\n        return resolved_links\n\n    def raise_for_status(self) -> None:\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n\n        http_error_msg = \"\"\n        if isinstance(self.reason, bytes):\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                reason = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                reason = self.reason.decode(\"iso-8859-1\")\n        else:\n            reason = self.reason\n\n        if 400 <= self.status_code < 500:\n            http_error_msg = (\n                f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            http_error_msg = (\n                f\"{self.status_code} Server Error: {reason} for url: {self.url}\"\n            )\n\n        if http_error_msg:\n            raise HTTPError(http_error_msg, response=self)\n\n    def close(self) -> None:\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not self._content_consumed:\n            self.raw.close()\n\n        release_conn = getattr(self.raw, \"release_conn\", None)\n        if release_conn is not None:\n            release_conn()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-528aa57ade5b26ae", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d46477b7351d64b9b21199f81e5f66a6cf788e8c62ea22f7348921b3bf8d3849", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 533, "local_path": "control-flow/lower-for-to-while/I13__requests__Response__7dde90a8.py", "order": 13, "original_content_sha256": "14913be3f44c729b832098f2f6c362b34f3e10df8349682335c77cdb005079a3", "parent_variant_id": "pyint-552616694637-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L732-L1184", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 2, "for_loops_skipped_for_comment": 1, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 2, "synchronous_for_loops_eligible": 2, "synchronous_for_loops_found": 3}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-001c7dde90a8-I13", "group_id": "py-528aa57ade5b26ae", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 714, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-27a5b9e57405-SRC", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass MethodView(View):\n    \"\"\"Dispatches request methods to the corresponding instance methods.\n    For example, if you implement a ``get`` method, it will be used to\n    handle ``GET`` requests.\n\n    This can be useful for defining a REST API.\n\n    :attr:`methods` is automatically set based on the methods defined on\n    the class.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class CounterAPI(MethodView):\n            def get(self):\n                return str(session.get(\"counter\", 0))\n\n            def post(self):\n                session[\"counter\"] = session.get(\"counter\", 0) + 1\n                return redirect(url_for(\"counter\"))\n\n        app.add_url_rule(\n            \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n        )\n    \"\"\"\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        super().__init_subclass__(**kwargs)\n\n        if \"methods\" not in cls.__dict__:\n            methods = set()\n\n            for base in cls.__bases__:\n                if getattr(base, \"methods\", None):\n                    methods.update(base.methods)  # type: ignore[attr-defined]\n\n            for key in http_method_funcs:\n                if hasattr(cls, key):\n                    methods.add(key.upper())\n\n            if methods:\n                cls.methods = methods\n\n    def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:\n        meth = getattr(self, request.method.lower(), None)\n\n        # If the request method is HEAD and we don't have a handler for it\n        # retry with GET.\n        if meth is None and request.method == \"HEAD\":\n            meth = getattr(self, \"get\", None)\n\n        assert meth is not None, f\"Unimplemented method {request.method!r}\"\n        return current_app.ensure_sync(meth)(**kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-53030aa4369f3f61", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 60, "local_path": "source-original/SRC__flask__MethodView__b9e57405.py", "order": 0, "original_content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L138-L191", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "MethodView", "variant_id": "pyint-27a5b9e57405-SRC", "group_id": "py-53030aa4369f3f61", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 589, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bc9ca2593629-I01", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass MethodView(View):\n    \n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        super().__init_subclass__(**kwargs)\n\n        if \"methods\" not in cls.__dict__:\n            methods = set()\n\n            for base in cls.__bases__:\n                if getattr(base, \"methods\", None):\n                    methods.update(base.methods)   \n\n            for key in http_method_funcs:\n                if hasattr(cls, key):\n                    methods.add(key.upper())\n\n            if methods:\n                cls.methods = methods\n\n    def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:\n        meth = getattr(self, request.method.lower(), None)\n\n         \n         \n        if meth is None and request.method == \"HEAD\":\n            meth = getattr(self, \"get\", None)\n\n        assert meth is not None, f\"Unimplemented method {request.method!r}\"\n        return current_app.ensure_sync(meth)(**kwargs)   \n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-53030aa4369f3f61", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "74e560b51ca9084390db6b4671d40c95e654a1ff7eb8de33953064da383a8158", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 36, "local_path": "comments/remove-comments/I01__flask__MethodView__a2593629.py", "order": 1, "original_content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "parent_variant_id": "pyint-27a5b9e57405-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L138-L191", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 891, "comments_removed": 5, "docstrings_removed": 1, "line_comments_removed": 4}, "unit_kind": "class", "unit_name": "MethodView", "variant_id": "pyint-bc9ca2593629-I01", "group_id": "py-53030aa4369f3f61", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 590, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-431120fd198b-I02", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass MethodView(View):\n    \"\"\"Dispatches request methods to the corresponding instance methods.\n    For example, if you implement a ``get`` method, it will be used to\n    handle ``GET`` requests.\n\n    This can be useful for defining a REST API.\n\n    :attr:`methods` is automatically set based on the methods defined on\n    the class.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class CounterAPI(MethodView):\n            def get(self):\n                return str(session.get(\"counter\", 0))\n\n            def post(self):\n                session[\"counter\"] = session.get(\"counter\", 0) + 1\n                return redirect(url_for(\"counter\"))\n\n        app.add_url_rule(\n            \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n        )\n    \"\"\"\n\n    def __init_subclass__(cls, **kwa: t.Any) -> None:\n        super().__init_subclass__(**kwa)\n\n        if \"methods\" not in cls.__dict__:\n            met = set()\n\n            for bas in cls.__bases__:\n                if getattr(bas, \"methods\", None):\n                    met.update(bas.methods)  # type: ignore[attr-defined]\n\n            for key2 in http_method_funcs:\n                if hasattr(cls, key2):\n                    met.add(key2.upper())\n\n            if met:\n                cls.methods = met\n\n    def dispatch(self, **kwa2: t.Any) -> ft.ResponseReturnValue:\n        met2 = getattr(self, request.method.lower(), None)\n\n        # If the request method is HEAD and we don't have a handler for it\n        # retry with GET.\n        if met2 is None and request.method == \"HEAD\":\n            met2 = getattr(self, \"get\", None)\n\n        assert met2 is not None, f\"Unimplemented method {request.method!r}\"\n        return current_app.ensure_sync(met2)(**kwa2)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-53030aa4369f3f61", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "71ffa608cb6556f958c3421805f6a92f9c18cfaaf0c5377c7596f40ff4378c6b", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 60, "local_path": "identifiers/shorten-identifiers/I02__flask__MethodView__20fd198b.py", "order": 2, "original_content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "parent_variant_id": "pyint-27a5b9e57405-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L138-L191", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 21, "identifiers_declared": 7}, "unit_kind": "class", "unit_name": "MethodView", "variant_id": "pyint-431120fd198b-I02", "group_id": "py-53030aa4369f3f61", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 591, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-46c59e7e1a66-I03", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass MethodView(View):\n    \"\"\"Dispatches request methods to the corresponding instance methods.\n    For example, if you implement a ``get`` method, it will be used to\n    handle ``GET`` requests.\n\n    This can be useful for defining a REST API.\n\n    :attr:`methods` is automatically set based on the methods defined on\n    the class.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class CounterAPI(MethodView):\n            def get(self):\n                return str(session.get(\"counter\", 0))\n\n            def post(self):\n                session[\"counter\"] = session.get(\"counter\", 0) + 1\n                return redirect(url_for(\"counter\"))\n\n        app.add_url_rule(\n            \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n        )\n    \"\"\"\n\n    def __init_subclass__(cls, **amount: t.Any) -> None:\n        super().__init_subclass__(**amount)\n\n        if \"methods\" not in cls.__dict__:\n            channel = set()\n\n            for node in cls.__bases__:\n                if getattr(node, \"methods\", None):\n                    channel.update(node.methods)  # type: ignore[attr-defined]\n\n            for map in http_method_funcs:\n                if hasattr(cls, map):\n                    channel.add(map.upper())\n\n            if channel:\n                cls.methods = channel\n\n    def validateBalance(self, **amount: t.Any) -> ft.ResponseReturnValue:\n        item = getattr(self, request.method.lower(), None)\n\n        # If the request method is HEAD and we don't have a handler for it\n        # retry with GET.\n        if item is None and request.method == \"HEAD\":\n            item = getattr(self, \"get\", None)\n\n        assert item is not None, f\"Unimplemented method {request.method!r}\"\n        return current_app.ensure_sync(item)(**amount)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-53030aa4369f3f61", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "531b4473221ce974df114b43f6bd690239657cd13a6749c011a1c1bfc3b158a7", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 60, "local_path": "identifiers/mislead-identifiers/I03__flask__MethodView__9e7e1a66.py", "order": 3, "original_content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "parent_variant_id": "pyint-27a5b9e57405-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L138-L191", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 21, "identifiers_declared": 7, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 6, "local_random_pool_selections": 6, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 1, "method_total_length_difference": 1}, "unit_kind": "class", "unit_name": "MethodView", "variant_id": "pyint-46c59e7e1a66-I03", "group_id": "py-53030aa4369f3f61", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 592, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b39a70bd97ec-I04", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass MethodView(View):\n    \"\"\"Dispatches request methods to the corresponding instance methods.\n    For example, if you implement a ``get`` method, it will be used to\n    handle ``GET`` requests.\n\n    This can be useful for defining a REST API.\n\n    :attr:`methods` is automatically set based on the methods defined on\n    the class.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class CounterAPI(MethodView):\n            def get(self):\n                return str(session.get(\"counter\", 0))\n\n            def post(self):\n                session[\"counter\"] = session.get(\"counter\", 0) + 1\n                return redirect(url_for(\"counter\"))\n\n        app.add_url_rule(\n            \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n        )\n    \"\"\"\n\n    def __init_subclass__(cls, **b: t.Any) -> None:\n        super().__init_subclass__(**b)\n\n        if \"methods\" not in cls.__dict__:\n            c = set()\n\n            for d in cls.__bases__:\n                if getattr(d, \"methods\", None):\n                    c.update(d.methods)  # type: ignore[attr-defined]\n\n            for e in http_method_funcs:\n                if hasattr(cls, e):\n                    c.add(e.upper())\n\n            if c:\n                cls.methods = c\n\n    def a(self, **f: t.Any) -> ft.ResponseReturnValue:\n        g = getattr(self, request.method.lower(), None)\n\n        # If the request method is HEAD and we don't have a handler for it\n        # retry with GET.\n        if g is None and request.method == \"HEAD\":\n            g = getattr(self, \"get\", None)\n\n        assert g is not None, f\"Unimplemented method {request.method!r}\"\n        return current_app.ensure_sync(g)(**f)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-53030aa4369f3f61", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "a90e88f733c70f5c91568fc448fe468eb6333d86e3a922c0397d150b6f70ada9", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 60, "local_path": "identifiers/garble-identifiers/I04__flask__MethodView__70bd97ec.py", "order": 4, "original_content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "parent_variant_id": "pyint-27a5b9e57405-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L138-L191", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 21, "identifiers_declared": 7}, "unit_kind": "class", "unit_name": "MethodView", "variant_id": "pyint-b39a70bd97ec-I04", "group_id": "py-53030aa4369f3f61", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 593, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-80c60901d2be-I05", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass MethodView(View):\n    \"\"\"Dispatches request methods to the corresponding instance methods.\n    For example, if you implement a ``get`` method, it will be used to\n    handle ``GET`` requests.\n\n    This can be useful for defining a REST API.\n\n    :attr:`methods` is automatically set based on the methods defined on\n    the class.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class CounterAPI(MethodView):\n            def get(self):\n                return str(session.get(\"counter\", 0))\n\n            def post(self):\n                session[\"counter\"] = session.get(\"counter\", 0) + 1\n                return redirect(url_for(\"counter\"))\n\n        app.add_url_rule(\n            \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n        )\n    \"\"\"\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        super().__init_subclass__(**kwargs)\n\n        if \"methods\" not in cls.__dict__:\n            methods = set()\n\n            for base in cls.__bases__:\n                if getattr(base, \"methods\", None):\n                    methods.update(base.methods)  # type: ignore[attr-defined]\n\n            for key in http_method_funcs:\n                if hasattr(cls, key):\n                    methods.add(key.upper())\n\n            if methods:\n                cls.methods = methods\n\n    def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:\n        meth = getattr(self, request.method.lower(), None)\n\n        # If the request method is HEAD and we don't have a handler for it\n        # retry with GET.\n        if meth is None and request.method == \"HEAD\":\n            meth = getattr(self, \"get\", None)\n\n        assert meth is not None, f\"Unimplemented method {request.method!r}\"\n        return current_app.ensure_sync(meth)(**kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-53030aa4369f3f61", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 60, "local_path": "expressions/encode-integer-literals/I05__flask__MethodView__0901d2be.py", "order": 5, "original_content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "parent_variant_id": "pyint-27a5b9e57405-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L138-L191", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "MethodView", "variant_id": "pyint-80c60901d2be-I05", "group_id": "py-53030aa4369f3f61", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 594, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-22c1a849cf92-I06", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass MethodView(View):\n    \"\"\"Dispatches request methods to the corresponding instance methods.\n    For example, if you implement a ``get`` method, it will be used to\n    handle ``GET`` requests.\n\n    This can be useful for defining a REST API.\n\n    :attr:`methods` is automatically set based on the methods defined on\n    the class.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class CounterAPI(MethodView):\n            def get(self):\n                return str(session.get(\"counter\", 0))\n\n            def post(self):\n                session[\"counter\"] = session.get(\"counter\", 0) + 1\n                return redirect(url_for(\"counter\"))\n\n        app.add_url_rule(\n            \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n        )\n    \"\"\"\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        super().__init_subclass__(**kwargs)\n\n        if not (\"methods\" not in cls.__dict__):\n            pass\n        else:\n            methods = set()\n\n            for base in cls.__bases__:\n                if getattr(base, \"methods\", None):\n                    methods.update(base.methods)  # type: ignore[attr-defined]\n\n            for key in http_method_funcs:\n                if hasattr(cls, key):\n                    methods.add(key.upper())\n\n            if methods:\n                cls.methods = methods\n\n    def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:\n        meth = getattr(self, request.method.lower(), None)\n\n        # If the request method is HEAD and we don't have a handler for it\n        # retry with GET.\n        if not (meth is None and request.method == \"HEAD\"):\n            pass\n        else:\n            meth = getattr(self, \"get\", None)\n\n        assert meth is not None, f\"Unimplemented method {request.method!r}\"\n        return current_app.ensure_sync(meth)(**kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-53030aa4369f3f61", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "877ff3818073b48666dd28e3e9a5d1c3d53a27b1684bfd7da44e21595b4d8cbd", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 64, "local_path": "expressions/invert-conditions/I06__flask__MethodView__a849cf92.py", "order": 6, "original_content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "parent_variant_id": "pyint-27a5b9e57405-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L138-L191", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 2}, "unit_kind": "class", "unit_name": "MethodView", "variant_id": "pyint-22c1a849cf92-I06", "group_id": "py-53030aa4369f3f61", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 595, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0e88e19db323-I07", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass MethodView(View):\n    \"\"\"Dispatches request methods to the corresponding instance methods.\n    For example, if you implement a ``get`` method, it will be used to\n    handle ``GET`` requests.\n\n    This can be useful for defining a REST API.\n\n    :attr:`methods` is automatically set based on the methods defined on\n    the class.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class CounterAPI(MethodView):\n            def get(self):\n                return str(session.get(\"counter\", 0))\n\n            def post(self):\n                session[\"counter\"] = session.get(\"counter\", 0) + 1\n                return redirect(url_for(\"counter\"))\n\n        app.add_url_rule(\n            \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n        )\n    \"\"\"\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        if ((0xb32d ^ 0xb32d) != 0):\n            raise AssertionError()\n        super().__init_subclass__(**kwargs)\n\n        if \"methods\" not in cls.__dict__:\n            methods = set()\n\n            for base in cls.__bases__:\n                if getattr(base, \"methods\", None):\n                    methods.update(base.methods)  # type: ignore[attr-defined]\n\n            for key in http_method_funcs:\n                if hasattr(cls, key):\n                    methods.add(key.upper())\n\n            if methods:\n                cls.methods = methods\n\n    def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:\n        if ((0xa1f7 ^ 0xa1f7) != 0):\n            raise AssertionError()\n        meth = getattr(self, request.method.lower(), None)\n\n        # If the request method is HEAD and we don't have a handler for it\n        # retry with GET.\n        if meth is None and request.method == \"HEAD\":\n            meth = getattr(self, \"get\", None)\n\n        assert meth is not None, f\"Unimplemented method {request.method!r}\"\n        return current_app.ensure_sync(meth)(**kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-53030aa4369f3f61", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "b2b6ed9b1c92d115458f6599a033ec69859a29e740cbf90096d1eba2afd7808c", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 64, "local_path": "code-injection/insert-dead-branches/I07__flask__MethodView__e19db323.py", "order": 7, "original_content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "parent_variant_id": "pyint-27a5b9e57405-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L138-L191", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "MethodView", "variant_id": "pyint-0e88e19db323-I07", "group_id": "py-53030aa4369f3f61", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 596, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-04523175076d-I08", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass MethodView(View):\n    \"\"\"Dispatches request methods to the corresponding instance methods.\n    For example, if you implement a ``get`` method, it will be used to\n    handle ``GET`` requests.\n\n    This can be useful for defining a REST API.\n\n    :attr:`methods` is automatically set based on the methods defined on\n    the class.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class CounterAPI(MethodView):\n            def get(self):\n                return str(session.get(\"counter\", 0))\n\n            def post(self):\n                session[\"counter\"] = session.get(\"counter\", 0) + 1\n                return redirect(url_for(\"counter\"))\n\n        app.add_url_rule(\n            \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n        )\n    \"\"\"\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        super().__init_subclass__(**kwargs)\n\n        if \"methods\" not in cls.__dict__:\n            methods = set()\n\n            for base in cls.__bases__:\n                if getattr(base, \"methods\", None):\n                    methods.update(base.methods)  # type: ignore[attr-defined]\n\n            for key in http_method_funcs:\n                if hasattr(cls, key):\n                    methods.add(key.upper())\n\n            if methods:\n                cls.methods = methods\n\n    def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:\n        even_number_count = 0\n        for candidate_number in range(6):\n            if candidate_number % 2 == 0:\n                even_number_count += 1\n        meth = getattr(self, request.method.lower(), None)\n\n        # If the request method is HEAD and we don't have a handler for it\n        # retry with GET.\n        if meth is None and request.method == \"HEAD\":\n            meth = getattr(self, \"get\", None)\n\n        assert meth is not None, f\"Unimplemented method {request.method!r}\"\n        return current_app.ensure_sync(meth)(**kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-53030aa4369f3f61", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "064d9f1857e065bea0bad94d087f65c4cb1f56b161d37f36fa20f31a8dd74d09", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 64, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__MethodView__3175076d.py", "order": 8, "original_content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "parent_variant_id": "pyint-27a5b9e57405-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L138-L191", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 4, "readable_template_index": 2}, "unit_kind": "class", "unit_name": "MethodView", "variant_id": "pyint-04523175076d-I08", "group_id": "py-53030aa4369f3f61", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 597, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fdca0c0ea79d-I09", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass MethodView(View):\n    \"\"\"Dispatches request methods to the corresponding instance methods.\n    For example, if you implement a ``get`` method, it will be used to\n    handle ``GET`` requests.\n\n    This can be useful for defining a REST API.\n\n    :attr:`methods` is automatically set based on the methods defined on\n    the class.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class CounterAPI(MethodView):\n            def get(self):\n                return str(session.get(\"counter\", 0))\n\n            def post(self):\n                session[\"counter\"] = session.get(\"counter\", 0) + 1\n                return redirect(url_for(\"counter\"))\n\n        app.add_url_rule(\n            \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n        )\n    \"\"\"\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        lI0O_d97b1735, lI0O_81dd00fe = 0, 0\n        while lI0O_81dd00fe < 2:\n            lI0O_d97b1735 ^= (lI0O_81dd00fe << 1) ^ 0xd\n            lI0O_81dd00fe += 1\n        lI0O_d97b1735 ^= lI0O_d97b1735\n        super().__init_subclass__(**kwargs)\n\n        if \"methods\" not in cls.__dict__:\n            methods = set()\n\n            for base in cls.__bases__:\n                if getattr(base, \"methods\", None):\n                    methods.update(base.methods)  # type: ignore[attr-defined]\n\n            for key in http_method_funcs:\n                if hasattr(cls, key):\n                    methods.add(key.upper())\n\n            if methods:\n                cls.methods = methods\n\n    def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:\n        meth = getattr(self, request.method.lower(), None)\n\n        # If the request method is HEAD and we don't have a handler for it\n        # retry with GET.\n        if meth is None and request.method == \"HEAD\":\n            meth = getattr(self, \"get\", None)\n\n        assert meth is not None, f\"Unimplemented method {request.method!r}\"\n        return current_app.ensure_sync(meth)(**kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-53030aa4369f3f61", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "9f5205e656f1da7aed4031c24a50bac9567c3eac4107ab2fe544c05aa3e6c3ef", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 65, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__MethodView__0c0ea79d.py", "order": 9, "original_content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "parent_variant_id": "pyint-27a5b9e57405-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L138-L191", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 2}, "unit_kind": "class", "unit_name": "MethodView", "variant_id": "pyint-fdca0c0ea79d-I09", "group_id": "py-53030aa4369f3f61", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 598, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-12c5e9767d0d-I10", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass MethodView(View):\n    \"\"\"Dispatches request methods to the corresponding instance methods.\n    For example, if you implement a ``get`` method, it will be used to\n    handle ``GET`` requests.\n\n    This can be useful for defining a REST API.\n    :attr:`methods` is automatically set based on the methods defined on\n    the class.\n\n    See :doc:`views` for a detailed guide.\n    .. code-block:: python\n\n        class CounterAPI(MethodView):\n            def get(self):\n                return str(session.get(\"counter\", 0))\n\n            def post(self):\n                session[\"counter\"] = session.get(\"counter\", 0) + 1\n                return redirect(url_for(\"counter\"))\n\n        app.add_url_rule(\n            \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n        )\n    \"\"\"\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        super().__init_subclass__(**kwargs)\n\n        if \"methods\" not in cls.__dict__:\n            methods = set()\n            for base in cls.__bases__:\n                if getattr(base, \"methods\", None):\n                    methods.update(base.methods)  # type: ignore[attr-defined]\n            for key in http_method_funcs:\n                if hasattr(cls, key):\n                    methods.add(key.upper())\n\n            if methods:\n                cls.methods = methods\n\n    def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:\n        meth = getattr(self, request.method.lower(), None)\n\n        # If the request method is HEAD and we don't have a handler for it\n        # retry with GET.\n        if meth is None and request.method == \"HEAD\":\n            meth = getattr(self, \"get\", None)\n        assert meth is not None, f\"Unimplemented method {request.method!r}\"\n        return current_app.ensure_sync(meth)(**kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-53030aa4369f3f61", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "3c825e501c867feb738af596f61a4e12e5d1e0370ce20f0b0de2cb5c72711eb2", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 54, "local_path": "layout/partially-compact-layout/I10__flask__MethodView__e9767d0d.py", "order": 10, "original_content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "parent_variant_id": "pyint-27a5b9e57405-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L138-L191", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 16, "line_break_groups_removed": 6, "line_breaks_removed": 6, "whitespace_characters_removed": 6}, "unit_kind": "class", "unit_name": "MethodView", "variant_id": "pyint-12c5e9767d0d-I10", "group_id": "py-53030aa4369f3f61", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 599, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ca1f37ea3e51-I11", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass MethodView(View):\n    \"\"\"Dispatches request methods to the corresponding instance methods.\n    For example, if you implement a ``get`` method, it will be used to\n    handle ``GET`` requests.\n\n    This can be useful for defining a REST API.\n\n    :attr:`methods` is automatically set based on the methods defined on\n    the class.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class CounterAPI(MethodView):\n            def get(self):\n                return str(session.get(\"counter\", 0))\n\n            def post(self):\n                session[\"counter\"] = session.get(\"counter\", 0) + 1\n                return redirect(url_for(\"counter\"))\n\n        app.add_url_rule(\n            \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n        )\n    \"\"\"\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        super().__init_subclass__(**kwargs)\n\n        if \"methods\" not in cls.__dict__:\n            methods = set()\n\n            for base in cls.__bases__:\n                if getattr(base, \"methods\", None):\n                    methods.update(base.methods)  # type: ignore[attr-defined]\n\n            for key in http_method_funcs:\n                if hasattr(cls, key):\n                    methods.add(key.upper())\n\n            if methods:\n                cls.methods = methods\n\n    def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:\n        meth = getattr(self, request.method.lower(), None)\n\n        # If the request method is HEAD and we don't have a handler for it\n        # retry with GET.\n        if meth is None and request.method == \"HEAD\":\n            meth = getattr(self, \"get\", None)\n\n        assert meth is not None, f\"Unimplemented method {request.method!r}\"\n        return current_app.ensure_sync(meth)(**kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-53030aa4369f3f61", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 60, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__MethodView__37ea3e51.py", "order": 11, "original_content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "parent_variant_id": "pyint-27a5b9e57405-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L138-L191", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "MethodView", "variant_id": "pyint-ca1f37ea3e51-I11", "group_id": "py-53030aa4369f3f61", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 600, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-65d306754447-I12", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass MethodView(View):\n    \"\"\"Dispatches request methods to the corresponding instance methods.\n    For example, if you implement a ``get`` method, it will be used to\n    handle ``GET`` requests.\n\n    This can be useful for defining a REST API.\n\n    :attr:`methods` is automatically set based on the methods defined on\n    the class.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class CounterAPI(MethodView):\n            def get(self):\n                return str(session.get(\"counter\", 0))\n\n            def post(self):\n                session[\"counter\"] = session.get(\"counter\", 0) + 1\n                return redirect(url_for(\"counter\"))\n\n        app.add_url_rule(\n            \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n        )\n    \"\"\"\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        super().__init_subclass__(**kwargs)\n\n        if \"methods\" not in cls.__dict__:\n            methods = set()\n\n            for base in cls.__bases__:\n                if getattr(base, \"methods\", None):\n                    methods.update(base.methods)  # type: ignore[attr-defined]\n\n            for key in http_method_funcs:\n                if hasattr(cls, key):\n                    methods.add(key.upper())\n\n            if methods:\n                cls.methods = methods\n\n    def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:\n        meth = getattr(self, request.method.lower(), None)\n\n        # If the request method is HEAD and we don't have a handler for it\n        # retry with GET.\n        if meth is None and request.method == \"HEAD\":\n            meth = getattr(self, \"get\", None)\n\n        assert meth is not None, f\"Unimplemented method {request.method!r}\"\n        return current_app.ensure_sync(meth)(**kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-53030aa4369f3f61", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 60, "local_path": "data-flow/inline-intermediate-variables/I12__flask__MethodView__06754447.py", "order": 12, "original_content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "parent_variant_id": "pyint-27a5b9e57405-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L138-L191", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "MethodView", "variant_id": "pyint-65d306754447-I12", "group_id": "py-53030aa4369f3f61", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 601, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fd94ee8f8f2a-I13", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass MethodView(View):\n    \"\"\"Dispatches request methods to the corresponding instance methods.\n    For example, if you implement a ``get`` method, it will be used to\n    handle ``GET`` requests.\n\n    This can be useful for defining a REST API.\n\n    :attr:`methods` is automatically set based on the methods defined on\n    the class.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class CounterAPI(MethodView):\n            def get(self):\n                return str(session.get(\"counter\", 0))\n\n            def post(self):\n                session[\"counter\"] = session.get(\"counter\", 0) + 1\n                return redirect(url_for(\"counter\"))\n\n        app.add_url_rule(\n            \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n        )\n    \"\"\"\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        super().__init_subclass__(**kwargs)\n\n        if \"methods\" not in cls.__dict__:\n            methods = set()\n\n            loopIterator = __import__(\"builtins\").iter(cls.__bases__)\n            while True:\n                try:\n                    base = __import__(\"builtins\").next(loopIterator)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                if getattr(base, \"methods\", None):\n                    methods.update(base.methods)  # type: ignore[attr-defined]\n\n            loopIteratorA = __import__(\"builtins\").iter(http_method_funcs)\n            while True:\n                try:\n                    key = __import__(\"builtins\").next(loopIteratorA)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                if hasattr(cls, key):\n                    methods.add(key.upper())\n\n            if methods:\n                cls.methods = methods\n\n    def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:\n        meth = getattr(self, request.method.lower(), None)\n\n        # If the request method is HEAD and we don't have a handler for it\n        # retry with GET.\n        if meth is None and request.method == \"HEAD\":\n            meth = getattr(self, \"get\", None)\n\n        assert meth is not None, f\"Unimplemented method {request.method!r}\"\n        return current_app.ensure_sync(meth)(**kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-53030aa4369f3f61", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "1aa830c278e16f869dd0dd0a7e9e681dcf1309a4cbcbc2cea2fe0aa3b1cd92ba", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 70, "local_path": "control-flow/lower-for-to-while/I13__flask__MethodView__ee8f8f2a.py", "order": 13, "original_content_sha256": "45cd6ee349bc51602aff9b9ca9aef9e68fd44ef132c49a989264916d7b195cfd", "parent_variant_id": "pyint-27a5b9e57405-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L138-L191", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 2, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 2, "synchronous_for_loops_eligible": 2, "synchronous_for_loops_found": 2}, "unit_kind": "class", "unit_name": "MethodView", "variant_id": "pyint-fd94ee8f8f2a-I13", "group_id": "py-53030aa4369f3f61", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 602, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b5fc1bbe0d0b-SRC", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=False, unsafe_hash=True)\nclass _IsCallableValidator:\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not callable(value):\n            message = (\n                \"'{name}' must be callable \"\n                \"(got {value!r} that is a {actual!r}).\"\n            )\n            raise NotCallableError(\n                msg=message.format(\n                    name=attr.name, value=value, actual=value.__class__\n                ),\n                value=value,\n            )\n\n    def __repr__(self):\n        return \"<is_callable validator>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-59e0a6f88057eb38", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 29, "local_path": "source-original/SRC__attrs___IsCallableValidator__1bbe0d0b.py", "order": 0, "original_content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L296-L314", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_IsCallableValidator", "variant_id": "pyint-b5fc1bbe0d0b-SRC", "group_id": "py-59e0a6f88057eb38", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1303, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-99802a916285-I01", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=False, unsafe_hash=True)\nclass _IsCallableValidator:\n    def __call__(self, inst, attr, value):\n        \n        if not callable(value):\n            message = (\n                \"'{name}' must be callable \"\n                \"(got {value!r} that is a {actual!r}).\"\n            )\n            raise NotCallableError(\n                msg=message.format(\n                    name=attr.name, value=value, actual=value.__class__\n                ),\n                value=value,\n            )\n\n    def __repr__(self):\n        return \"<is_callable validator>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-59e0a6f88057eb38", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "09afb2f483b7e3904c3b785570350d06a624424585a94edad08dbf896d49d213", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 27, "local_path": "comments/remove-comments/I01__attrs___IsCallableValidator__2a916285.py", "order": 1, "original_content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "parent_variant_id": "pyint-b5fc1bbe0d0b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L296-L314", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 86, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "_IsCallableValidator", "variant_id": "pyint-99802a916285-I01", "group_id": "py-59e0a6f88057eb38", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1304, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-663027115a63-I02", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=False, unsafe_hash=True)\nclass _IsCallableValidator:\n    def __call__(self, ins, att, val):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not callable(val):\n            mes = (\n                \"'{name}' must be callable \"\n                \"(got {value!r} that is a {actual!r}).\"\n            )\n            raise NotCallableError(\n                msg=mes.format(\n                    name=att.name, value=val, actual=val.__class__\n                ),\n                value=val,\n            )\n\n    def __repr__(self):\n        return \"<is_callable validator>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-59e0a6f88057eb38", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d9fa20e68a11cce434da9bd352c7d26239da0f8055b10a01b565a2e5eff4538e", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 29, "local_path": "identifiers/shorten-identifiers/I02__attrs___IsCallableValidator__27115a63.py", "order": 2, "original_content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "parent_variant_id": "pyint-b5fc1bbe0d0b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L296-L314", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 10, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_IsCallableValidator", "variant_id": "pyint-663027115a63-I02", "group_id": "py-59e0a6f88057eb38", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1305, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1efaf8b0eef6-I03", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=False, unsafe_hash=True)\nclass _IsCallableValidator:\n    def __call__(self, step, item, group):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not callable(group):\n            channel = (\n                \"'{name}' must be callable \"\n                \"(got {value!r} that is a {actual!r}).\"\n            )\n            raise NotCallableError(\n                msg=channel.format(\n                    name=item.name, value=group, actual=group.__class__\n                ),\n                value=group,\n            )\n\n    def __repr__(self):\n        return \"<is_callable validator>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-59e0a6f88057eb38", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "54735dd5d2159cec501bc01a9f953e80e23220d77b735777ff0e910a1c786413", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 29, "local_path": "identifiers/mislead-identifiers/I03__attrs___IsCallableValidator__f8b0eef6.py", "order": 3, "original_content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "parent_variant_id": "pyint-b5fc1bbe0d0b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L296-L314", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 10, "identifiers_declared": 4, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 4, "local_random_pool_selections": 4, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_IsCallableValidator", "variant_id": "pyint-1efaf8b0eef6-I03", "group_id": "py-59e0a6f88057eb38", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1306, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f4ae3cb27f55-I04", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=False, unsafe_hash=True)\nclass _IsCallableValidator:\n    def __call__(self, a, b, c):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not callable(c):\n            d = (\n                \"'{name}' must be callable \"\n                \"(got {value!r} that is a {actual!r}).\"\n            )\n            raise NotCallableError(\n                msg=d.format(\n                    name=b.name, value=c, actual=c.__class__\n                ),\n                value=c,\n            )\n\n    def __repr__(self):\n        return \"<is_callable validator>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-59e0a6f88057eb38", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d7eaa1cef8227d1d3f7c83b56b7f253a7dee9cdbbe65a02fb701f71cb90db280", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 29, "local_path": "identifiers/garble-identifiers/I04__attrs___IsCallableValidator__3cb27f55.py", "order": 4, "original_content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "parent_variant_id": "pyint-b5fc1bbe0d0b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L296-L314", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 10, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_IsCallableValidator", "variant_id": "pyint-f4ae3cb27f55-I04", "group_id": "py-59e0a6f88057eb38", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1307, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c9b9bbb00195-I05", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=False, unsafe_hash=True)\nclass _IsCallableValidator:\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not callable(value):\n            message = (\n                \"'{name}' must be callable \"\n                \"(got {value!r} that is a {actual!r}).\"\n            )\n            raise NotCallableError(\n                msg=message.format(\n                    name=attr.name, value=value, actual=value.__class__\n                ),\n                value=value,\n            )\n\n    def __repr__(self):\n        return \"<is_callable validator>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-59e0a6f88057eb38", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 29, "local_path": "expressions/encode-integer-literals/I05__attrs___IsCallableValidator__bbb00195.py", "order": 5, "original_content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "parent_variant_id": "pyint-b5fc1bbe0d0b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L296-L314", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "_IsCallableValidator", "variant_id": "pyint-c9b9bbb00195-I05", "group_id": "py-59e0a6f88057eb38", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1308, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ff4a7ca07b91-I06", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=False, unsafe_hash=True)\nclass _IsCallableValidator:\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not (not callable(value)):\n            pass\n        else:\n            message = (\n                \"'{name}' must be callable \"\n                \"(got {value!r} that is a {actual!r}).\"\n            )\n            raise NotCallableError(\n                msg=message.format(\n                    name=attr.name, value=value, actual=value.__class__\n                ),\n                value=value,\n            )\n\n    def __repr__(self):\n        return \"<is_callable validator>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-59e0a6f88057eb38", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "472bfc0b0d84b443f69d39a58e60848f31c7f9abcd9eef0426b27171b12ea367", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 31, "local_path": "expressions/invert-conditions/I06__attrs___IsCallableValidator__7ca07b91.py", "order": 6, "original_content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "parent_variant_id": "pyint-b5fc1bbe0d0b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L296-L314", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "_IsCallableValidator", "variant_id": "pyint-ff4a7ca07b91-I06", "group_id": "py-59e0a6f88057eb38", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1309, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d1127475f1df-I07", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=False, unsafe_hash=True)\nclass _IsCallableValidator:\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if ((0x308c ^ 0x308c) != 0):\n            raise AssertionError()\n        if not callable(value):\n            message = (\n                \"'{name}' must be callable \"\n                \"(got {value!r} that is a {actual!r}).\"\n            )\n            raise NotCallableError(\n                msg=message.format(\n                    name=attr.name, value=value, actual=value.__class__\n                ),\n                value=value,\n            )\n\n    def __repr__(self):\n        if ((0x59fa ^ 0x59fa) != 0):\n            raise AssertionError()\n        return \"<is_callable validator>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-59e0a6f88057eb38", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "2fb19921426f4cc5df761344d57776066990fe42895fdf7f2b195b3da3d6da95", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 33, "local_path": "code-injection/insert-dead-branches/I07__attrs___IsCallableValidator__7475f1df.py", "order": 7, "original_content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "parent_variant_id": "pyint-b5fc1bbe0d0b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L296-L314", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "_IsCallableValidator", "variant_id": "pyint-d1127475f1df-I07", "group_id": "py-59e0a6f88057eb38", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1310, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-23c21b2d1ebe-I08", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=False, unsafe_hash=True)\nclass _IsCallableValidator:\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        first_score = 72\n        second_score = 85\n        if first_score > second_score:\n            higher_score = first_score\n        else:\n            higher_score = second_score\n        if not callable(value):\n            message = (\n                \"'{name}' must be callable \"\n                \"(got {value!r} that is a {actual!r}).\"\n            )\n            raise NotCallableError(\n                msg=message.format(\n                    name=attr.name, value=value, actual=value.__class__\n                ),\n                value=value,\n            )\n\n    def __repr__(self):\n        return \"<is_callable validator>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-59e0a6f88057eb38", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "65949926f87cc690b56c31f0f9e2edcecf930d70b59f85f04c03d9f20a334d5a", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 35, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___IsCallableValidator__1b2d1ebe.py", "order": 8, "original_content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "parent_variant_id": "pyint-b5fc1bbe0d0b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L296-L314", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 3}, "unit_kind": "class", "unit_name": "_IsCallableValidator", "variant_id": "pyint-23c21b2d1ebe-I08", "group_id": "py-59e0a6f88057eb38", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1311, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7724c4f2bc1a-I09", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=False, unsafe_hash=True)\nclass _IsCallableValidator:\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not callable(value):\n            message = (\n                \"'{name}' must be callable \"\n                \"(got {value!r} that is a {actual!r}).\"\n            )\n            raise NotCallableError(\n                msg=message.format(\n                    name=attr.name, value=value, actual=value.__class__\n                ),\n                value=value,\n            )\n\n    def __repr__(self):\n        lI0O_24c0fc6e = 0xa23e - 0xa23e\n        lI0O_24c0fc6e = (lI0O_24c0fc6e | 0) if lI0O_24c0fc6e == 0 else (lI0O_24c0fc6e & 0)\n        return \"<is_callable validator>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-59e0a6f88057eb38", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "0a5cb220734e94a50bd3b65246d058af4610cfe494c3d5884c0ac03fa2174747", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 31, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___IsCallableValidator__c4f2bc1a.py", "order": 9, "original_content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "parent_variant_id": "pyint-b5fc1bbe0d0b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L296-L314", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 1}, "unit_kind": "class", "unit_name": "_IsCallableValidator", "variant_id": "pyint-7724c4f2bc1a-I09", "group_id": "py-59e0a6f88057eb38", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1312, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8b368132230c-I10", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n@attrs(repr=False, slots=False, unsafe_hash=True)\nclass _IsCallableValidator:\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not callable(value):\n            message = (\n                \"'{name}' must be callable \"\n                \"(got {value!r} that is a {actual!r}).\"\n            )\n            raise NotCallableError(\n                msg=message.format(\n                    name=attr.name, value=value, actual=value.__class__\n                ),                 value=value,             )\n    def __repr__(self):\n        return \"<is_callable validator>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-59e0a6f88057eb38", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "7596e4f78e5ca78f48d13b2431f2d3472fa9776ebecddd3944cfa87dd99d3537", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 25, "local_path": "layout/partially-compact-layout/I10__attrs___IsCallableValidator__8132230c.py", "order": 10, "original_content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "parent_variant_id": "pyint-b5fc1bbe0d0b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L296-L314", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 10, "line_break_groups_removed": 4, "line_breaks_removed": 4, "whitespace_characters_removed": 2}, "unit_kind": "class", "unit_name": "_IsCallableValidator", "variant_id": "pyint-8b368132230c-I10", "group_id": "py-59e0a6f88057eb38", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1313, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9888b0b752ff-I11", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=False, unsafe_hash=True)\nclass _IsCallableValidator:\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not callable(value):\n            message = (\n                \"'{name}' must be callable \"\n                \"(got {value!r} that is a {actual!r}).\"\n            )\n            raise NotCallableError(\n                msg=message.format(\n                    name=attr.name, value=value, actual=value.__class__\n                ),\n                value=value,\n            )\n\n    def __repr__(self):\n        return \"<is_callable validator>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-59e0a6f88057eb38", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 29, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___IsCallableValidator__b0b752ff.py", "order": 11, "original_content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "parent_variant_id": "pyint-b5fc1bbe0d0b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L296-L314", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "_IsCallableValidator", "variant_id": "pyint-9888b0b752ff-I11", "group_id": "py-59e0a6f88057eb38", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1314, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-852621786022-I12", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=False, unsafe_hash=True)\nclass _IsCallableValidator:\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not callable(value):\n            \n            raise NotCallableError(\n                msg=(\"'{name}' must be callable \"\n                \"(got {value!r} that is a {actual!r}).\").format(\n                    name=attr.name, value=value, actual=value.__class__\n                ),\n                value=value,\n            )\n\n    def __repr__(self):\n        return \"<is_callable validator>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-59e0a6f88057eb38", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a5aac876c038e19dd12cf59ff1690866a4e97648c57a33dfaeddc390725a6e91", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 27, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___IsCallableValidator__21786022.py", "order": 12, "original_content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "parent_variant_id": "pyint-b5fc1bbe0d0b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L296-L314", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_IsCallableValidator", "variant_id": "pyint-852621786022-I12", "group_id": "py-59e0a6f88057eb38", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1315, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-401dd3330b56-I13", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=False, unsafe_hash=True)\nclass _IsCallableValidator:\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not callable(value):\n            message = (\n                \"'{name}' must be callable \"\n                \"(got {value!r} that is a {actual!r}).\"\n            )\n            raise NotCallableError(\n                msg=message.format(\n                    name=attr.name, value=value, actual=value.__class__\n                ),\n                value=value,\n            )\n\n    def __repr__(self):\n        return \"<is_callable validator>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-59e0a6f88057eb38", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 29, "local_path": "control-flow/lower-for-to-while/I13__attrs___IsCallableValidator__d3330b56.py", "order": 13, "original_content_sha256": "e3080db396ef689c7405c5b490e798abe6464e1aec08065b181f88cddbb3372e", "parent_variant_id": "pyint-b5fc1bbe0d0b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L296-L314", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "_IsCallableValidator", "variant_id": "pyint-401dd3330b56-I13", "group_id": "py-59e0a6f88057eb38", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1316, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bb7b21d0098b-SRC", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestHooksMixin:\n    hooks: dict[str, list[_t.HookType]]\n\n    def register_hook(\n        self, event: str, hook: Iterable[_t.HookType] | _t.HookType\n    ) -> None:\n        \"\"\"Properly register a hook.\"\"\"\n\n        if event not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n\n        if isinstance(hook, Callable):\n            self.hooks[event].append(hook)\n        elif hasattr(hook, \"__iter__\"):\n            self.hooks[event].extend(\n                h for h in hook if isinstance(h, Callable)\n            )  # defensive runtime filter\n\n    def deregister_hook(self, event: str, hook: _t.HookType) -> bool:\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n\n        try:\n            self.hooks[event].remove(hook)\n            return True\n        except ValueError:\n            return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-59edb3b9f1cdb5a5", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 98, "local_path": "source-original/SRC__requests__RequestHooksMixin__21d0098b.py", "order": 0, "original_content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L254-L281", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "RequestHooksMixin", "variant_id": "pyint-bb7b21d0098b-SRC", "group_id": "py-59edb3b9f1cdb5a5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 841, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-07a593de36a9-I01", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna   \nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestHooksMixin:\n    hooks: dict[str, list[_t.HookType]]\n\n    def register_hook(\n        self, event: str, hook: Iterable[_t.HookType] | _t.HookType\n    ) -> None:\n        \n\n        if event not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n\n        if isinstance(hook, Callable):\n            self.hooks[event].append(hook)\n        elif hasattr(hook, \"__iter__\"):\n            self.hooks[event].extend(\n                h for h in hook if isinstance(h, Callable)\n            )   \n\n    def deregister_hook(self, event: str, hook: _t.HookType) -> bool:\n        \n\n        try:\n            self.hooks[event].remove(hook)\n            return True\n        except ValueError:\n            return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-59edb3b9f1cdb5a5", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "daece359dc854c05bad6dd60eef2094c7084dc94abbc37b82804f5a9ffc7e6c0", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 96, "local_path": "comments/remove-comments/I01__requests__RequestHooksMixin__93de36a9.py", "order": 1, "original_content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "parent_variant_id": "pyint-bb7b21d0098b-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L254-L281", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 178, "comments_removed": 4, "docstrings_removed": 2, "line_comments_removed": 2}, "unit_kind": "class", "unit_name": "RequestHooksMixin", "variant_id": "pyint-07a593de36a9-I01", "group_id": "py-59edb3b9f1cdb5a5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 842, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7120cb631091-I02", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestHooksMixin:\n    hooks: dict[str, list[_t.HookType]]\n\n    def register(\n        self, eve: str, hoo: Iterable[_t.HookType] | _t.HookType\n    ) -> None:\n        \"\"\"Properly register a hook.\"\"\"\n\n        if eve not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{eve}\"')\n\n        if isinstance(hoo, Callable):\n            self.hooks[eve].append(hoo)\n        elif hasattr(hoo, \"__iter__\"):\n            self.hooks[eve].extend(\n                h2 for h2 in hoo if isinstance(h2, Callable)\n            )  # defensive runtime filter\n\n    def deregister(self, eve2: str, hoo2: _t.HookType) -> bool:\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n\n        try:\n            self.hooks[eve2].remove(hoo2)\n            return True\n        except ValueError:\n            return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-59edb3b9f1cdb5a5", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "799e19ad11caae9ec5f13447633a8cac4ebd50da9faf5f26837e0197c7318742", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 98, "local_path": "identifiers/shorten-identifiers/I02__requests__RequestHooksMixin__cb631091.py", "order": 2, "original_content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "parent_variant_id": "pyint-bb7b21d0098b-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L254-L281", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 19, "identifiers_declared": 7}, "unit_kind": "class", "unit_name": "RequestHooksMixin", "variant_id": "pyint-7120cb631091-I02", "group_id": "py-59edb3b9f1cdb5a5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 843, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b025d7dbcd75-I03", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestHooksMixin:\n    hooks: dict[str, list[_t.HookType]]\n\n    def removeMessage(\n        self, order: str, user: Iterable[_t.HookType] | _t.HookType\n    ) -> None:\n        \"\"\"Properly register a hook.\"\"\"\n\n        if order not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{order}\"')\n\n        if isinstance(user, Callable):\n            self.hooks[order].append(user)\n        elif hasattr(user, \"__iter__\"):\n            self.hooks[order].extend(\n                map for map in user if isinstance(map, Callable)\n            )  # defensive runtime filter\n\n    def validateAddress(self, total: str, node: _t.HookType) -> bool:\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n\n        try:\n            self.hooks[total].remove(node)\n            return True\n        except ValueError:\n            return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-59edb3b9f1cdb5a5", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "8ed8054bbf14fba944e98c6483053ffbaf7697c59ce64b56e719aa47461697c1", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 98, "local_path": "identifiers/mislead-identifiers/I03__requests__RequestHooksMixin__d7dbcd75.py", "order": 3, "original_content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "parent_variant_id": "pyint-bb7b21d0098b-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L254-L281", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 19, "identifiers_declared": 7, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 4, "local_random_pool_selections": 5, "local_total_length_difference": 2, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 2, "method_random_pool_selections": 2, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "RequestHooksMixin", "variant_id": "pyint-b025d7dbcd75-I03", "group_id": "py-59edb3b9f1cdb5a5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 844, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-43ce15ee5b8d-I04", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestHooksMixin:\n    hooks: dict[str, list[_t.HookType]]\n\n    def a(\n        self, c: str, d: Iterable[_t.HookType] | _t.HookType\n    ) -> None:\n        \"\"\"Properly register a hook.\"\"\"\n\n        if c not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{c}\"')\n\n        if isinstance(d, Callable):\n            self.hooks[c].append(d)\n        elif hasattr(d, \"__iter__\"):\n            self.hooks[c].extend(\n                e for e in d if isinstance(e, Callable)\n            )  # defensive runtime filter\n\n    def b(self, f: str, g: _t.HookType) -> bool:\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n\n        try:\n            self.hooks[f].remove(g)\n            return True\n        except ValueError:\n            return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-59edb3b9f1cdb5a5", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "652ab50b1d8454885ee27fdc47417fe6e245e78f332e21440d88c709a6f6d0f0", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 98, "local_path": "identifiers/garble-identifiers/I04__requests__RequestHooksMixin__15ee5b8d.py", "order": 4, "original_content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "parent_variant_id": "pyint-bb7b21d0098b-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L254-L281", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 19, "identifiers_declared": 7}, "unit_kind": "class", "unit_name": "RequestHooksMixin", "variant_id": "pyint-43ce15ee5b8d-I04", "group_id": "py-59edb3b9f1cdb5a5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 845, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-25f1fdce3145-I05", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestHooksMixin:\n    hooks: dict[str, list[_t.HookType]]\n\n    def register_hook(\n        self, event: str, hook: Iterable[_t.HookType] | _t.HookType\n    ) -> None:\n        \"\"\"Properly register a hook.\"\"\"\n\n        if event not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n\n        if isinstance(hook, Callable):\n            self.hooks[event].append(hook)\n        elif hasattr(hook, \"__iter__\"):\n            self.hooks[event].extend(\n                h for h in hook if isinstance(h, Callable)\n            )  # defensive runtime filter\n\n    def deregister_hook(self, event: str, hook: _t.HookType) -> bool:\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n\n        try:\n            self.hooks[event].remove(hook)\n            return True\n        except ValueError:\n            return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-59edb3b9f1cdb5a5", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 98, "local_path": "expressions/encode-integer-literals/I05__requests__RequestHooksMixin__fdce3145.py", "order": 5, "original_content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "parent_variant_id": "pyint-bb7b21d0098b-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L254-L281", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "RequestHooksMixin", "variant_id": "pyint-25f1fdce3145-I05", "group_id": "py-59edb3b9f1cdb5a5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 846, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-db004d5daaa3-I06", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestHooksMixin:\n    hooks: dict[str, list[_t.HookType]]\n\n    def register_hook(\n        self, event: str, hook: Iterable[_t.HookType] | _t.HookType\n    ) -> None:\n        \"\"\"Properly register a hook.\"\"\"\n\n        if not (event not in self.hooks):\n            pass\n        else:\n            raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n\n        if isinstance(hook, Callable):\n            self.hooks[event].append(hook)\n        elif hasattr(hook, \"__iter__\"):\n            self.hooks[event].extend(\n                h for h in hook if isinstance(h, Callable)\n            )  # defensive runtime filter\n\n    def deregister_hook(self, event: str, hook: _t.HookType) -> bool:\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n\n        try:\n            self.hooks[event].remove(hook)\n            return True\n        except ValueError:\n            return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-59edb3b9f1cdb5a5", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "91de1b996f83f01c04ceffdfd74f8154843476ad973b9a4792954dd94d17c5c4", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 100, "local_path": "expressions/invert-conditions/I06__requests__RequestHooksMixin__4d5daaa3.py", "order": 6, "original_content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "parent_variant_id": "pyint-bb7b21d0098b-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L254-L281", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "RequestHooksMixin", "variant_id": "pyint-db004d5daaa3-I06", "group_id": "py-59edb3b9f1cdb5a5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 847, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2de1eb339257-I07", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestHooksMixin:\n    hooks: dict[str, list[_t.HookType]]\n\n    def register_hook(\n        self, event: str, hook: Iterable[_t.HookType] | _t.HookType\n    ) -> None:\n        \"\"\"Properly register a hook.\"\"\"\n        if ((0xa84e ^ 0xa84e) != 0):\n            raise AssertionError()\n\n        if event not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n\n        if isinstance(hook, Callable):\n            self.hooks[event].append(hook)\n        elif hasattr(hook, \"__iter__\"):\n            self.hooks[event].extend(\n                h for h in hook if isinstance(h, Callable)\n            )  # defensive runtime filter\n\n    def deregister_hook(self, event: str, hook: _t.HookType) -> bool:\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n        if ((0x10ec ^ 0x10ec) != 0):\n            raise AssertionError()\n\n        try:\n            self.hooks[event].remove(hook)\n            return True\n        except ValueError:\n            return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-59edb3b9f1cdb5a5", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "2b2e4dd3b7ba859512413ecc96d2ea7669b65ebcccf8a36cc44f43d71e726183", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 102, "local_path": "code-injection/insert-dead-branches/I07__requests__RequestHooksMixin__eb339257.py", "order": 7, "original_content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "parent_variant_id": "pyint-bb7b21d0098b-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L254-L281", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "RequestHooksMixin", "variant_id": "pyint-2de1eb339257-I07", "group_id": "py-59edb3b9f1cdb5a5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 848, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-60127c3f1791-I08", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestHooksMixin:\n    hooks: dict[str, list[_t.HookType]]\n\n    def register_hook(\n        self, event: str, hook: Iterable[_t.HookType] | _t.HookType\n    ) -> None:\n        \"\"\"Properly register a hook.\"\"\"\n        feature_enabled = False\n        for toggle_count in range(3):\n            feature_enabled = not feature_enabled\n\n        if event not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n\n        if isinstance(hook, Callable):\n            self.hooks[event].append(hook)\n        elif hasattr(hook, \"__iter__\"):\n            self.hooks[event].extend(\n                h for h in hook if isinstance(h, Callable)\n            )  # defensive runtime filter\n\n    def deregister_hook(self, event: str, hook: _t.HookType) -> bool:\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n\n        try:\n            self.hooks[event].remove(hook)\n            return True\n        except ValueError:\n            return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-59edb3b9f1cdb5a5", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d15d23d2be890a32e07c98f2d4ec953ccaeedf315a52231956cc8dc6de5cc905", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 101, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__RequestHooksMixin__7c3f1791.py", "order": 8, "original_content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "parent_variant_id": "pyint-bb7b21d0098b-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L254-L281", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 7}, "unit_kind": "class", "unit_name": "RequestHooksMixin", "variant_id": "pyint-60127c3f1791-I08", "group_id": "py-59edb3b9f1cdb5a5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 849, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dd91f8886d4f-I09", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestHooksMixin:\n    hooks: dict[str, list[_t.HookType]]\n\n    def register_hook(\n        self, event: str, hook: Iterable[_t.HookType] | _t.HookType\n    ) -> None:\n        \"\"\"Properly register a hook.\"\"\"\n\n        if event not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n\n        if isinstance(hook, Callable):\n            self.hooks[event].append(hook)\n        elif hasattr(hook, \"__iter__\"):\n            self.hooks[event].extend(\n                h for h in hook if isinstance(h, Callable)\n            )  # defensive runtime filter\n\n    def deregister_hook(self, event: str, hook: _t.HookType) -> bool:\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n        lI0O_dd5ffdc2 = 0x7aef - 0x7aef\n        lI0O_dd5ffdc2 = (lI0O_dd5ffdc2 | 0) if lI0O_dd5ffdc2 == 0 else (lI0O_dd5ffdc2 & 0)\n\n        try:\n            self.hooks[event].remove(hook)\n            return True\n        except ValueError:\n            return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-59edb3b9f1cdb5a5", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "b9af77a96a263673d54d99ad391d06a2023c27fedd0acb9c499d821e95ee7c3c", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 100, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__RequestHooksMixin__f8886d4f.py", "order": 9, "original_content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "parent_variant_id": "pyint-bb7b21d0098b-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L254-L281", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 1}, "unit_kind": "class", "unit_name": "RequestHooksMixin", "variant_id": "pyint-dd91f8886d4f-I09", "group_id": "py-59edb3b9f1cdb5a5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 850, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-52a272e84757-I10", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,     Final,\n    Literal,     cast,\n    overload,\n)\nfrom urllib3.exceptions import (     DecodeError,     LocationParseError,\n    ProtocolError,     ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,     builtin_str,\n    chardet,\n    cookielib,\n    urlencode,     urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (     _copy_cookie_jar,\n    cookiejar_from_dict,     get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,     HTTPError,\n    InvalidJSONError,     InvalidURL,\n    MissingSchema,     StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (     check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,     requote_uri,     stream_decode_response_unicode,     super_len,     to_key_val_list, )\n\nclass RequestHooksMixin:\n    hooks: dict[str, list[_t.HookType]]\n    def register_hook(\n        self, event: str, hook: Iterable[_t.HookType] | _t.HookType     ) -> None:\n        \"\"\"Properly register a hook.\"\"\"\n\n        if event not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n        if isinstance(hook, Callable):\n            self.hooks[event].append(hook)\n        elif hasattr(hook, \"__iter__\"):\n            self.hooks[event].extend(\n                h for h in hook if isinstance(h, Callable)\n            )  # defensive runtime filter\n    def deregister_hook(self, event: str, hook: _t.HookType) -> bool:\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n\n        try:\n            self.hooks[event].remove(hook)\n            return True\n        except ValueError:\n            return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-59edb3b9f1cdb5a5", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "f1717699b0f5e7728135d207d9f70228de5e7bf18a3aa9b27240e998af6e128c", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 76, "local_path": "layout/partially-compact-layout/I10__requests__RequestHooksMixin__72e84757.py", "order": 10, "original_content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "parent_variant_id": "pyint-bb7b21d0098b-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L254-L281", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 56, "line_break_groups_removed": 22, "line_breaks_removed": 22, "whitespace_characters_removed": 3}, "unit_kind": "class", "unit_name": "RequestHooksMixin", "variant_id": "pyint-52a272e84757-I10", "group_id": "py-59edb3b9f1cdb5a5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 851, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-df450b3790af-I11", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestHooksMixin:\n    hooks: dict[str, list[_t.HookType]]\n\n    def register_hook(\n        self, event: str, hook: Iterable[_t.HookType] | _t.HookType\n    ) -> None:\n        \"\"\"Properly register a hook.\"\"\"\n\n        if event not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n\n        if isinstance(hook, Callable):\n            self.hooks[event].append(hook)\n        elif hasattr(hook, \"__iter__\"):\n            self.hooks[event].extend(\n                h for h in hook if isinstance(h, Callable)\n            )  # defensive runtime filter\n\n    def deregister_hook(self, event: str, hook: _t.HookType) -> bool:\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n\n        try:\n            self.hooks[event].remove(hook)\n            return True\n        except ValueError:\n            return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-59edb3b9f1cdb5a5", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 98, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__RequestHooksMixin__0b3790af.py", "order": 11, "original_content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "parent_variant_id": "pyint-bb7b21d0098b-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L254-L281", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "RequestHooksMixin", "variant_id": "pyint-df450b3790af-I11", "group_id": "py-59edb3b9f1cdb5a5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 852, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-03e50fd988ae-I12", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestHooksMixin:\n    hooks: dict[str, list[_t.HookType]]\n\n    def register_hook(\n        self, event: str, hook: Iterable[_t.HookType] | _t.HookType\n    ) -> None:\n        \"\"\"Properly register a hook.\"\"\"\n\n        if event not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n\n        if isinstance(hook, Callable):\n            self.hooks[event].append(hook)\n        elif hasattr(hook, \"__iter__\"):\n            self.hooks[event].extend(\n                h for h in hook if isinstance(h, Callable)\n            )  # defensive runtime filter\n\n    def deregister_hook(self, event: str, hook: _t.HookType) -> bool:\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n\n        try:\n            self.hooks[event].remove(hook)\n            return True\n        except ValueError:\n            return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-59edb3b9f1cdb5a5", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 98, "local_path": "data-flow/inline-intermediate-variables/I12__requests__RequestHooksMixin__0fd988ae.py", "order": 12, "original_content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "parent_variant_id": "pyint-bb7b21d0098b-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L254-L281", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "RequestHooksMixin", "variant_id": "pyint-03e50fd988ae-I12", "group_id": "py-59edb3b9f1cdb5a5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 853, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0959f447832e-I13", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestHooksMixin:\n    hooks: dict[str, list[_t.HookType]]\n\n    def register_hook(\n        self, event: str, hook: Iterable[_t.HookType] | _t.HookType\n    ) -> None:\n        \"\"\"Properly register a hook.\"\"\"\n\n        if event not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n\n        if isinstance(hook, Callable):\n            self.hooks[event].append(hook)\n        elif hasattr(hook, \"__iter__\"):\n            self.hooks[event].extend(\n                h for h in hook if isinstance(h, Callable)\n            )  # defensive runtime filter\n\n    def deregister_hook(self, event: str, hook: _t.HookType) -> bool:\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n\n        try:\n            self.hooks[event].remove(hook)\n            return True\n        except ValueError:\n            return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-59edb3b9f1cdb5a5", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 98, "local_path": "control-flow/lower-for-to-while/I13__requests__RequestHooksMixin__f447832e.py", "order": 13, "original_content_sha256": "ad7a519168d233b7af582829cf6f8fbbb83eb089e1b38fdac09228614b8b0e0d", "parent_variant_id": "pyint-bb7b21d0098b-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L254-L281", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "RequestHooksMixin", "variant_id": "pyint-0959f447832e-I13", "group_id": "py-59edb3b9f1cdb5a5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 854, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2e34081a0f33-SRC", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.\n\n    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    type: str\n\n    def __init__(self, request: PreparedRequest) -> None:\n        assert _is_prepared(request)\n        self._r = request\n        self._new_headers: dict[str, str] = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def get_type(self) -> str:\n        return self.type\n\n    def get_host(self) -> str:\n        return urlparse(self._r.url).netloc\n\n    def get_origin_req_host(self) -> str:\n        return self.get_host()\n\n    def get_full_url(self) -> str:\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        host = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        parsed = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [\n                parsed.scheme,\n                host,\n                parsed.path,\n                parsed.params,\n                parsed.query,\n                parsed.fragment,\n            ]\n        )\n\n    def is_unverifiable(self) -> bool:\n        return True\n\n    def has_header(self, name: str) -> bool:\n        return name in self._r.headers or name in self._new_headers\n\n    def get_header(self, name: str, default: str | None = None) -> str | None:\n        return self._r.headers.get(name, self._new_headers.get(name, default))  # type: ignore[return-value]\n\n    def add_header(self, key: str, val: str) -> None:\n        \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def add_unredirected_header(self, name: str, value: str) -> None:\n        self._new_headers[name] = value\n\n    def get_new_headers(self) -> dict[str, str]:\n        return self._new_headers\n\n    @property\n    def unverifiable(self) -> bool:\n        return self.is_unverifiable()\n\n    @property\n    def origin_req_host(self) -> str:\n        return self.get_origin_req_host()\n\n    @property\n    def host(self) -> str:\n        return self.get_host()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-5b7b1f1a659a916f", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 93, "local_path": "source-original/SRC__requests__MockRequest__081a0f33.py", "order": 0, "original_content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L31-L111", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "MockRequest", "variant_id": "pyint-2e34081a0f33-SRC", "group_id": "py-5b7b1f1a659a916f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 813, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6b48fd984b9f-I01", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockRequest:\n    \n\n    type: str\n\n    def __init__(self, request: PreparedRequest) -> None:\n        assert _is_prepared(request)\n        self._r = request\n        self._new_headers: dict[str, str] = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def get_type(self) -> str:\n        return self.type\n\n    def get_host(self) -> str:\n        return urlparse(self._r.url).netloc\n\n    def get_origin_req_host(self) -> str:\n        return self.get_host()\n\n    def get_full_url(self) -> str:\n         \n         \n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n         \n        host = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        parsed = urlparse(self._r.url)\n         \n        return urlunparse(\n            [\n                parsed.scheme,\n                host,\n                parsed.path,\n                parsed.params,\n                parsed.query,\n                parsed.fragment,\n            ]\n        )\n\n    def is_unverifiable(self) -> bool:\n        return True\n\n    def has_header(self, name: str) -> bool:\n        return name in self._r.headers or name in self._new_headers\n\n    def get_header(self, name: str, default: str | None = None) -> str | None:\n        return self._r.headers.get(name, self._new_headers.get(name, default))   \n\n    def add_header(self, key: str, val: str) -> None:\n        \n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def add_unredirected_header(self, name: str, value: str) -> None:\n        self._new_headers[name] = value\n\n    def get_new_headers(self) -> dict[str, str]:\n        return self._new_headers\n\n    @property\n    def unverifiable(self) -> bool:\n        return self.is_unverifiable()\n\n    @property\n    def origin_req_host(self) -> str:\n        return self.get_origin_req_host()\n\n    @property\n    def host(self) -> str:\n        return self.get_host()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-5b7b1f1a659a916f", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "8c21707c0a7f5b922a749a57670a7abeb44a4ef6587e519ff2d202675020ca97", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 84, "local_path": "comments/remove-comments/I01__requests__MockRequest__fd984b9f.py", "order": 1, "original_content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "parent_variant_id": "pyint-2e34081a0f33-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L31-L111", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 801, "comments_removed": 7, "docstrings_removed": 2, "line_comments_removed": 5}, "unit_kind": "class", "unit_name": "MockRequest", "variant_id": "pyint-6b48fd984b9f-I01", "group_id": "py-5b7b1f1a659a916f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 814, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f91f026097f3-I02", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.\n\n    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    type: str\n\n    def __init__(self, req: PreparedRequest) -> None:\n        assert _is_prepared(req)\n        self._r = req\n        self._new_headers: dict[str, str] = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def get2(self) -> str:\n        return self.type\n\n    def get3(self) -> str:\n        return urlparse(self._r.url).netloc\n\n    def get4(self) -> str:\n        return self.get3()\n\n    def get5(self) -> str:\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        hos2 = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        par = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [\n                par.scheme,\n                hos2,\n                par.path,\n                par.params,\n                par.query,\n                par.fragment,\n            ]\n        )\n\n    def is2(self) -> bool:\n        return True\n\n    def has(self, nam: str) -> bool:\n        return nam in self._r.headers or nam in self._new_headers\n\n    def get6(self, nam2: str, def2: str | None = None) -> str | None:\n        return self._r.headers.get(nam2, self._new_headers.get(nam2, def2))  # type: ignore[return-value]\n\n    def add(self, key: str, val: str) -> None:\n        \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def add2(self, nam3: str, val2: str) -> None:\n        self._new_headers[nam3] = val2\n\n    def get7(self) -> dict[str, str]:\n        return self._new_headers\n\n    @property\n    def unv(self) -> bool:\n        return self.is2()\n\n    @property\n    def origin(self) -> str:\n        return self.get4()\n\n    @property\n    def hos(self) -> str:\n        return self.get3()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-5b7b1f1a659a916f", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "de1d95bd1acb6a3b3dc87148a5baf010f2f71c7f426d43ee990888d0701db33b", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 93, "local_path": "identifiers/shorten-identifiers/I02__requests__MockRequest__026097f3.py", "order": 2, "original_content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "parent_variant_id": "pyint-2e34081a0f33-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L31-L111", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 42, "identifiers_declared": 23}, "unit_kind": "class", "unit_name": "MockRequest", "variant_id": "pyint-f91f026097f3-I02", "group_id": "py-5b7b1f1a659a916f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 815, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6623cec71992-I03", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.\n\n    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    type: str\n\n    def __init__(self, feature: PreparedRequest) -> None:\n        assert _is_prepared(feature)\n        self._r = feature\n        self._new_headers: dict[str, str] = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def parseKey(self) -> str:\n        return self.type\n\n    def findItem(self) -> str:\n        return urlparse(self._r.url).netloc\n\n    def validateMessage(self) -> str:\n        return self.findItem()\n\n    def validatePath(self) -> str:\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        mode = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        offset = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [\n                offset.scheme,\n                mode,\n                offset.path,\n                offset.params,\n                offset.query,\n                offset.fragment,\n            ]\n        )\n\n    def validateBalance(self) -> bool:\n        return True\n\n    def removeUser(self, node: str) -> bool:\n        return node in self._r.headers or node in self._new_headers\n\n    def findStatus(self, step: str, feature: str | None = None) -> str | None:\n        return self._r.headers.get(step, self._new_headers.get(step, feature))  # type: ignore[return-value]\n\n    def findConfig(self, age: str, map: str) -> None:\n        \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def validateAddress(self, date: str, price: str) -> None:\n        self._new_headers[date] = price\n\n    def validateRequest(self) -> dict[str, str]:\n        return self._new_headers\n\n    @property\n    def refreshOrder(self) -> bool:\n        return self.validateBalance()\n\n    @property\n    def validateAccount(self) -> str:\n        return self.validateMessage()\n\n    @property\n    def send(self) -> str:\n        return self.findItem()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-5b7b1f1a659a916f", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "a94a85bd94ca29d32d1b8e3bc66fa96c387c927841bb1f9b62744679bae40eed", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 93, "local_path": "identifiers/mislead-identifiers/I03__requests__MockRequest__cec71992.py", "order": 3, "original_content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "parent_variant_id": "pyint-2e34081a0f33-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L31-L111", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 42, "identifiers_declared": 23, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 2, "local_exact_length_matches": 10, "local_random_pool_selections": 10, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 2, "method_exact_length_matches": 11, "method_random_pool_selections": 13, "method_total_length_difference": 12}, "unit_kind": "class", "unit_name": "MockRequest", "variant_id": "pyint-6623cec71992-I03", "group_id": "py-5b7b1f1a659a916f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 816, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-caba59e50ed2-I04", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.\n\n    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    type: str\n\n    def __init__(self, n: PreparedRequest) -> None:\n        assert _is_prepared(n)\n        self._r = n\n        self._new_headers: dict[str, str] = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def a(self) -> str:\n        return self.type\n\n    def b(self) -> str:\n        return urlparse(self._r.url).netloc\n\n    def c(self) -> str:\n        return self.b()\n\n    def d(self) -> str:\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        o = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        p = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [\n                p.scheme,\n                o,\n                p.path,\n                p.params,\n                p.query,\n                p.fragment,\n            ]\n        )\n\n    def e(self) -> bool:\n        return True\n\n    def f(self, q: str) -> bool:\n        return q in self._r.headers or q in self._new_headers\n\n    def g(self, r: str, s: str | None = None) -> str | None:\n        return self._r.headers.get(r, self._new_headers.get(r, s))  # type: ignore[return-value]\n\n    def h(self, t: str, u: str) -> None:\n        \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def i(self, v: str, w: str) -> None:\n        self._new_headers[v] = w\n\n    def j(self) -> dict[str, str]:\n        return self._new_headers\n\n    @property\n    def k(self) -> bool:\n        return self.e()\n\n    @property\n    def l(self) -> str:\n        return self.c()\n\n    @property\n    def m(self) -> str:\n        return self.b()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-5b7b1f1a659a916f", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "eecc1362f622ee7851eff9a490ad0e672fbcda63555370cd13d42f8d6a8c44b9", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 93, "local_path": "identifiers/garble-identifiers/I04__requests__MockRequest__59e50ed2.py", "order": 4, "original_content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "parent_variant_id": "pyint-2e34081a0f33-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L31-L111", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 42, "identifiers_declared": 23}, "unit_kind": "class", "unit_name": "MockRequest", "variant_id": "pyint-caba59e50ed2-I04", "group_id": "py-5b7b1f1a659a916f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 817, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1eccfb5ca06a-I05", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.\n\n    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    type: str\n\n    def __init__(self, request: PreparedRequest) -> None:\n        assert _is_prepared(request)\n        self._r = request\n        self._new_headers: dict[str, str] = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def get_type(self) -> str:\n        return self.type\n\n    def get_host(self) -> str:\n        return urlparse(self._r.url).netloc\n\n    def get_origin_req_host(self) -> str:\n        return self.get_host()\n\n    def get_full_url(self) -> str:\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        host = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        parsed = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [\n                parsed.scheme,\n                host,\n                parsed.path,\n                parsed.params,\n                parsed.query,\n                parsed.fragment,\n            ]\n        )\n\n    def is_unverifiable(self) -> bool:\n        return True\n\n    def has_header(self, name: str) -> bool:\n        return name in self._r.headers or name in self._new_headers\n\n    def get_header(self, name: str, default: str | None = None) -> str | None:\n        return self._r.headers.get(name, self._new_headers.get(name, default))  # type: ignore[return-value]\n\n    def add_header(self, key: str, val: str) -> None:\n        \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def add_unredirected_header(self, name: str, value: str) -> None:\n        self._new_headers[name] = value\n\n    def get_new_headers(self) -> dict[str, str]:\n        return self._new_headers\n\n    @property\n    def unverifiable(self) -> bool:\n        return self.is_unverifiable()\n\n    @property\n    def origin_req_host(self) -> str:\n        return self.get_origin_req_host()\n\n    @property\n    def host(self) -> str:\n        return self.get_host()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-5b7b1f1a659a916f", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 93, "local_path": "expressions/encode-integer-literals/I05__requests__MockRequest__fb5ca06a.py", "order": 5, "original_content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "parent_variant_id": "pyint-2e34081a0f33-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L31-L111", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "MockRequest", "variant_id": "pyint-1eccfb5ca06a-I05", "group_id": "py-5b7b1f1a659a916f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 818, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-def6fe16c343-I06", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.\n\n    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    type: str\n\n    def __init__(self, request: PreparedRequest) -> None:\n        assert _is_prepared(request)\n        self._r = request\n        self._new_headers: dict[str, str] = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def get_type(self) -> str:\n        return self.type\n\n    def get_host(self) -> str:\n        return urlparse(self._r.url).netloc\n\n    def get_origin_req_host(self) -> str:\n        return self.get_host()\n\n    def get_full_url(self) -> str:\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if not (not self._r.headers.get(\"Host\")):\n            pass\n        else:\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        host = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        parsed = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [\n                parsed.scheme,\n                host,\n                parsed.path,\n                parsed.params,\n                parsed.query,\n                parsed.fragment,\n            ]\n        )\n\n    def is_unverifiable(self) -> bool:\n        return True\n\n    def has_header(self, name: str) -> bool:\n        return name in self._r.headers or name in self._new_headers\n\n    def get_header(self, name: str, default: str | None = None) -> str | None:\n        return self._r.headers.get(name, self._new_headers.get(name, default))  # type: ignore[return-value]\n\n    def add_header(self, key: str, val: str) -> None:\n        \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def add_unredirected_header(self, name: str, value: str) -> None:\n        self._new_headers[name] = value\n\n    def get_new_headers(self) -> dict[str, str]:\n        return self._new_headers\n\n    @property\n    def unverifiable(self) -> bool:\n        return self.is_unverifiable()\n\n    @property\n    def origin_req_host(self) -> str:\n        return self.get_origin_req_host()\n\n    @property\n    def host(self) -> str:\n        return self.get_host()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-5b7b1f1a659a916f", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "b8d4395ee3c4acd9b48b9d2d8f5ecdd396d7cb4c44e88c9de63d38e80e549782", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 95, "local_path": "expressions/invert-conditions/I06__requests__MockRequest__fe16c343.py", "order": 6, "original_content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "parent_variant_id": "pyint-2e34081a0f33-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L31-L111", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "MockRequest", "variant_id": "pyint-def6fe16c343-I06", "group_id": "py-5b7b1f1a659a916f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 819, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7323875deb20-I07", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.\n\n    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    type: str\n\n    def __init__(self, request: PreparedRequest) -> None:\n        if ((0xc51d ^ 0xc51d) != 0):\n            raise AssertionError()\n        assert _is_prepared(request)\n        self._r = request\n        self._new_headers: dict[str, str] = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def get_type(self) -> str:\n        if ((0x22b5 ^ 0x22b5) != 0):\n            raise AssertionError()\n        return self.type\n\n    def get_host(self) -> str:\n        if ((0x1f0b ^ 0x1f0b) != 0):\n            raise AssertionError()\n        return urlparse(self._r.url).netloc\n\n    def get_origin_req_host(self) -> str:\n        if ((0x3d ^ 0x3d) != 0):\n            raise AssertionError()\n        return self.get_host()\n\n    def get_full_url(self) -> str:\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if ((0xb22f ^ 0xb22f) != 0):\n            raise AssertionError()\n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        host = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        parsed = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [\n                parsed.scheme,\n                host,\n                parsed.path,\n                parsed.params,\n                parsed.query,\n                parsed.fragment,\n            ]\n        )\n\n    def is_unverifiable(self) -> bool:\n        if ((0x853a ^ 0x853a) != 0):\n            raise AssertionError()\n        return True\n\n    def has_header(self, name: str) -> bool:\n        if ((0xc97 ^ 0xc97) != 0):\n            raise AssertionError()\n        return name in self._r.headers or name in self._new_headers\n\n    def get_header(self, name: str, default: str | None = None) -> str | None:\n        if ((0x8299 ^ 0x8299) != 0):\n            raise AssertionError()\n        return self._r.headers.get(name, self._new_headers.get(name, default))  # type: ignore[return-value]\n\n    def add_header(self, key: str, val: str) -> None:\n        \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n        if ((0xc3c ^ 0xc3c) != 0):\n            raise AssertionError()\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def add_unredirected_header(self, name: str, value: str) -> None:\n        if ((0x1b49 ^ 0x1b49) != 0):\n            raise AssertionError()\n        self._new_headers[name] = value\n\n    def get_new_headers(self) -> dict[str, str]:\n        if ((0xd345 ^ 0xd345) != 0):\n            raise AssertionError()\n        return self._new_headers\n\n    @property\n    def unverifiable(self) -> bool:\n        if ((0xd29c ^ 0xd29c) != 0):\n            raise AssertionError()\n        return self.is_unverifiable()\n\n    @property\n    def origin_req_host(self) -> str:\n        if ((0x3d5a ^ 0x3d5a) != 0):\n            raise AssertionError()\n        return self.get_origin_req_host()\n\n    @property\n    def host(self) -> str:\n        if ((0xf4e3 ^ 0xf4e3) != 0):\n            raise AssertionError()\n        return self.get_host()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-5b7b1f1a659a916f", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "698bef20b2084f44fec3334cfa7f590b7716c529f37b439f3f96788fa15cf755", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 121, "local_path": "code-injection/insert-dead-branches/I07__requests__MockRequest__875deb20.py", "order": 7, "original_content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "parent_variant_id": "pyint-2e34081a0f33-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L31-L111", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 14}, "unit_kind": "class", "unit_name": "MockRequest", "variant_id": "pyint-7323875deb20-I07", "group_id": "py-5b7b1f1a659a916f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 820, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a2b2051a3815-I08", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.\n\n    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    type: str\n\n    def __init__(self, request: PreparedRequest) -> None:\n        assert _is_prepared(request)\n        self._r = request\n        self._new_headers: dict[str, str] = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def get_type(self) -> str:\n        return self.type\n\n    def get_host(self) -> str:\n        return urlparse(self._r.url).netloc\n\n    def get_origin_req_host(self) -> str:\n        return self.get_host()\n\n    def get_full_url(self) -> str:\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        host = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        parsed = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [\n                parsed.scheme,\n                host,\n                parsed.path,\n                parsed.params,\n                parsed.query,\n                parsed.fragment,\n            ]\n        )\n\n    def is_unverifiable(self) -> bool:\n        return True\n\n    def has_header(self, name: str) -> bool:\n        return name in self._r.headers or name in self._new_headers\n\n    def get_header(self, name: str, default: str | None = None) -> str | None:\n        return self._r.headers.get(name, self._new_headers.get(name, default))  # type: ignore[return-value]\n\n    def add_header(self, key: str, val: str) -> None:\n        \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def add_unredirected_header(self, name: str, value: str) -> None:\n        self._new_headers[name] = value\n\n    def get_new_headers(self) -> dict[str, str]:\n        remaining_steps = 3\n        while remaining_steps > 0:\n            remaining_steps -= 1\n        return self._new_headers\n\n    @property\n    def unverifiable(self) -> bool:\n        return self.is_unverifiable()\n\n    @property\n    def origin_req_host(self) -> str:\n        return self.get_origin_req_host()\n\n    @property\n    def host(self) -> str:\n        return self.get_host()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-5b7b1f1a659a916f", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "0a0b1e649791e1dd255da59c26be53d9d2751dcd3263a41810e4b58c7ada0ce1", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 96, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__MockRequest__051a3815.py", "order": 8, "original_content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "parent_variant_id": "pyint-2e34081a0f33-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L31-L111", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 1}, "unit_kind": "class", "unit_name": "MockRequest", "variant_id": "pyint-a2b2051a3815-I08", "group_id": "py-5b7b1f1a659a916f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 821, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-71361bdf495a-I09", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.\n\n    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    type: str\n\n    def __init__(self, request: PreparedRequest) -> None:\n        assert _is_prepared(request)\n        self._r = request\n        self._new_headers: dict[str, str] = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def get_type(self) -> str:\n        return self.type\n\n    def get_host(self) -> str:\n        return urlparse(self._r.url).netloc\n\n    def get_origin_req_host(self) -> str:\n        return self.get_host()\n\n    def get_full_url(self) -> str:\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        host = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        parsed = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [\n                parsed.scheme,\n                host,\n                parsed.path,\n                parsed.params,\n                parsed.query,\n                parsed.fragment,\n            ]\n        )\n\n    def is_unverifiable(self) -> bool:\n        return True\n\n    def has_header(self, name: str) -> bool:\n        return name in self._r.headers or name in self._new_headers\n\n    def get_header(self, name: str, default: str | None = None) -> str | None:\n        return self._r.headers.get(name, self._new_headers.get(name, default))  # type: ignore[return-value]\n\n    def add_header(self, key: str, val: str) -> None:\n        \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def add_unredirected_header(self, name: str, value: str) -> None:\n        self._new_headers[name] = value\n\n    def get_new_headers(self) -> dict[str, str]:\n        return self._new_headers\n\n    @property\n    def unverifiable(self) -> bool:\n        return self.is_unverifiable()\n\n    @property\n    def origin_req_host(self) -> str:\n        return self.get_origin_req_host()\n\n    @property\n    def host(self) -> str:\n        lI0O_27c1193e, lI0O_965327c3 = 0xf9aa, True\n        while lI0O_965327c3:\n            lI0O_27c1193e ^= 0xf9aa\n            lI0O_965327c3 = False\n        return self.get_host()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-5b7b1f1a659a916f", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "5ede3be026f2020340b421a341e0f7776260233f095470ee5a7b0aaa392618dc", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 97, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__MockRequest__1bdf495a.py", "order": 9, "original_content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "parent_variant_id": "pyint-2e34081a0f33-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L31-L111", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 7}, "unit_kind": "class", "unit_name": "MockRequest", "variant_id": "pyint-71361bdf495a-I09", "group_id": "py-5b7b1f1a659a916f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 822, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bac66b12db64-I10", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.\n\n    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    type: str\n    def __init__(self, request: PreparedRequest) -> None:\n        assert _is_prepared(request)\n        self._r = request\n        self._new_headers: dict[str, str] = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def get_type(self) -> str:\n        return self.type\n    def get_host(self) -> str:\n        return urlparse(self._r.url).netloc\n\n    def get_origin_req_host(self) -> str:\n        return self.get_host()\n\n    def get_full_url(self) -> str:\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        host = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        parsed = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [                 parsed.scheme,                 host,\n                parsed.path,\n                parsed.params,\n                parsed.query,\n                parsed.fragment,\n            ]\n        )\n    def is_unverifiable(self) -> bool:\n        return True\n\n    def has_header(self, name: str) -> bool:\n        return name in self._r.headers or name in self._new_headers\n    def get_header(self, name: str, default: str | None = None) -> str | None:\n        return self._r.headers.get(name, self._new_headers.get(name, default))  # type: ignore[return-value]\n    def add_header(self, key: str, val: str) -> None:\n        \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n    def add_unredirected_header(self, name: str, value: str) -> None:\n        self._new_headers[name] = value\n    def get_new_headers(self) -> dict[str, str]:\n        return self._new_headers\n\n    @property\n    def unverifiable(self) -> bool:\n        return self.is_unverifiable()\n\n    @property\n    def origin_req_host(self) -> str:\n        return self.get_origin_req_host()\n    @property\n    def host(self) -> str:\n        return self.get_host()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-5b7b1f1a659a916f", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "93a48dbe48da57030a28920a1d00ce1ed3027754fba76ee1cc5a2f6c1d8d427a", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 82, "local_path": "layout/partially-compact-layout/I10__requests__MockRequest__6b12db64.py", "order": 10, "original_content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "parent_variant_id": "pyint-2e34081a0f33-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L31-L111", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 29, "line_break_groups_removed": 11, "line_breaks_removed": 11, "whitespace_characters_removed": 9}, "unit_kind": "class", "unit_name": "MockRequest", "variant_id": "pyint-bac66b12db64-I10", "group_id": "py-5b7b1f1a659a916f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 823, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3e1e29457241-I11", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.\n\n    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    type: str\n\n    def __init__(self, request: PreparedRequest) -> None:\n        assert _is_prepared(request)\n        self._r = request\n        self._new_headers: dict[str, str] = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def get_type(self) -> str:\n        return self.type\n\n    def get_host(self) -> str:\n        return urlparse(self._r.url).netloc\n\n    def get_origin_req_host(self) -> str:\n        return self.get_host()\n\n    def get_full_url(self) -> str:\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        host = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        parsed = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [\n                parsed.scheme,\n                host,\n                parsed.path,\n                parsed.params,\n                parsed.query,\n                parsed.fragment,\n            ]\n        )\n\n    def is_unverifiable(self) -> bool:\n        return True\n\n    def has_header(self, name: str) -> bool:\n        return name in self._r.headers or name in self._new_headers\n\n    def get_header(self, name: str, default: str | None = None) -> str | None:\n        return self._r.headers.get(name, self._new_headers.get(name, default))  # type: ignore[return-value]\n\n    def add_header(self, key: str, val: str) -> None:\n        \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def add_unredirected_header(self, name: str, value: str) -> None:\n        self._new_headers[name] = value\n\n    def get_new_headers(self) -> dict[str, str]:\n        return self._new_headers\n\n    @property\n    def unverifiable(self) -> bool:\n        return self.is_unverifiable()\n\n    @property\n    def origin_req_host(self) -> str:\n        return self.get_origin_req_host()\n\n    @property\n    def host(self) -> str:\n        return self.get_host()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-5b7b1f1a659a916f", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 93, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__MockRequest__29457241.py", "order": 11, "original_content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "parent_variant_id": "pyint-2e34081a0f33-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L31-L111", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "MockRequest", "variant_id": "pyint-3e1e29457241-I11", "group_id": "py-5b7b1f1a659a916f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 824, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-14e07ea0e65a-I12", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.\n\n    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    type: str\n\n    def __init__(self, request: PreparedRequest) -> None:\n        assert _is_prepared(request)\n        self._r = request\n        self._new_headers: dict[str, str] = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def get_type(self) -> str:\n        return self.type\n\n    def get_host(self) -> str:\n        return urlparse(self._r.url).netloc\n\n    def get_origin_req_host(self) -> str:\n        return self.get_host()\n\n    def get_full_url(self) -> str:\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        \n        parsed = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [\n                parsed.scheme,\n                (to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")),\n                parsed.path,\n                parsed.params,\n                parsed.query,\n                parsed.fragment,\n            ]\n        )\n\n    def is_unverifiable(self) -> bool:\n        return True\n\n    def has_header(self, name: str) -> bool:\n        return name in self._r.headers or name in self._new_headers\n\n    def get_header(self, name: str, default: str | None = None) -> str | None:\n        return self._r.headers.get(name, self._new_headers.get(name, default))  # type: ignore[return-value]\n\n    def add_header(self, key: str, val: str) -> None:\n        \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def add_unredirected_header(self, name: str, value: str) -> None:\n        self._new_headers[name] = value\n\n    def get_new_headers(self) -> dict[str, str]:\n        return self._new_headers\n\n    @property\n    def unverifiable(self) -> bool:\n        return self.is_unverifiable()\n\n    @property\n    def origin_req_host(self) -> str:\n        return self.get_origin_req_host()\n\n    @property\n    def host(self) -> str:\n        return self.get_host()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-5b7b1f1a659a916f", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a2cd7b608d06ac050c06294c59ff2a24a94d0f6f59ee48e43fc810a998c07dcf", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 93, "local_path": "data-flow/inline-intermediate-variables/I12__requests__MockRequest__7ea0e65a.py", "order": 12, "original_content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "parent_variant_id": "pyint-2e34081a0f33-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L31-L111", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "MockRequest", "variant_id": "pyint-14e07ea0e65a-I12", "group_id": "py-5b7b1f1a659a916f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 825, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-82d5b73279fd-I13", "source": "from __future__ import annotations\nimport calendar\nimport copy\nimport time\nfrom collections.abc import Iterator, MutableMapping\nfrom http.cookiejar import Cookie, CookieJar, CookiePolicy\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .compat import Morsel, cookielib, urlparse, urlunparse\nimport threading\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.\n\n    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    type: str\n\n    def __init__(self, request: PreparedRequest) -> None:\n        assert _is_prepared(request)\n        self._r = request\n        self._new_headers: dict[str, str] = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def get_type(self) -> str:\n        return self.type\n\n    def get_host(self) -> str:\n        return urlparse(self._r.url).netloc\n\n    def get_origin_req_host(self) -> str:\n        return self.get_host()\n\n    def get_full_url(self) -> str:\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        host = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        parsed = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [\n                parsed.scheme,\n                host,\n                parsed.path,\n                parsed.params,\n                parsed.query,\n                parsed.fragment,\n            ]\n        )\n\n    def is_unverifiable(self) -> bool:\n        return True\n\n    def has_header(self, name: str) -> bool:\n        return name in self._r.headers or name in self._new_headers\n\n    def get_header(self, name: str, default: str | None = None) -> str | None:\n        return self._r.headers.get(name, self._new_headers.get(name, default))  # type: ignore[return-value]\n\n    def add_header(self, key: str, val: str) -> None:\n        \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def add_unredirected_header(self, name: str, value: str) -> None:\n        self._new_headers[name] = value\n\n    def get_new_headers(self) -> dict[str, str]:\n        return self._new_headers\n\n    @property\n    def unverifiable(self) -> bool:\n        return self.is_unverifiable()\n\n    @property\n    def origin_req_host(self) -> str:\n        return self.get_origin_req_host()\n\n    @property\n    def host(self) -> str:\n        return self.get_host()\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-5b7b1f1a659a916f", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 93, "local_path": "control-flow/lower-for-to-while/I13__requests__MockRequest__b73279fd.py", "order": 13, "original_content_sha256": "2187d2be87b92fb61c1283ba06944461c79ab70a20794a85944ffeb8441f554a", "parent_variant_id": "pyint-2e34081a0f33-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/cookies.py#L31-L111", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "MockRequest", "variant_id": "pyint-82d5b73279fd-I13", "group_id": "py-5b7b1f1a659a916f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 826, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-140ed9846741-SRC", "source": "from django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import (\n    CharField,\n    Expression,\n    Field,\n    FloatField,\n    Func,\n    Lookup,\n    TextField,\n    Value,\n)\nfrom django.db.models.expressions import CombinedExpression, register_combinable_fields\nfrom django.db.models.functions import Cast, Coalesce\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom .utils import CheckPostgresInstalledMixin\n\nclass LexemeCombinable:\n    BITAND = \"&\"\n    BITOR = \"|\"\n\n    def _combine(self, other, connector, reversed):\n        if not isinstance(other, LexemeCombinable):\n            raise TypeError(\n                \"A Lexeme can only be combined with another Lexeme, \"\n                f\"got {other.__class__.__name__}.\"\n            )\n        if reversed:\n            return CombinedLexeme(other, connector, self)\n        return CombinedLexeme(self, connector, other)\n\n    # On Combinable, these are not implemented to reduce confusion with Q. In\n    # this case we are actually (ab)using them to do logical combination so\n    # it's consistent with other usage in Django.\n    def __or__(self, other):\n        return self._combine(other, self.BITOR, False)\n\n    def __ror__(self, other):\n        return self._combine(other, self.BITOR, True)\n\n    def __and__(self, other):\n        return self._combine(other, self.BITAND, False)\n\n    def __rand__(self, other):\n        return self._combine(other, self.BITAND, True)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-5b87b277db5324de", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 44, "local_path": "source-original/SRC__django__LexemeCombinable__d9846741.py", "order": 0, "original_content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/postgres/search.py#L428-L455", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "LexemeCombinable", "variant_id": "pyint-140ed9846741-SRC", "group_id": "py-5b87b277db5324de", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 141, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1a54a1591d33-I01", "source": "from django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import (\n    CharField,\n    Expression,\n    Field,\n    FloatField,\n    Func,\n    Lookup,\n    TextField,\n    Value,\n)\nfrom django.db.models.expressions import CombinedExpression, register_combinable_fields\nfrom django.db.models.functions import Cast, Coalesce\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom .utils import CheckPostgresInstalledMixin\n\nclass LexemeCombinable:\n    BITAND = \"&\"\n    BITOR = \"|\"\n\n    def _combine(self, other, connector, reversed):\n        if not isinstance(other, LexemeCombinable):\n            raise TypeError(\n                \"A Lexeme can only be combined with another Lexeme, \"\n                f\"got {other.__class__.__name__}.\"\n            )\n        if reversed:\n            return CombinedLexeme(other, connector, self)\n        return CombinedLexeme(self, connector, other)\n\n     \n     \n     \n    def __or__(self, other):\n        return self._combine(other, self.BITOR, False)\n\n    def __ror__(self, other):\n        return self._combine(other, self.BITOR, True)\n\n    def __and__(self, other):\n        return self._combine(other, self.BITAND, False)\n\n    def __rand__(self, other):\n        return self._combine(other, self.BITAND, True)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-5b87b277db5324de", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "d113d87956d7f86301dece503e016a5cc0d451f6c6e48bd1d2da6e211ed80197", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 44, "local_path": "comments/remove-comments/I01__django__LexemeCombinable__a1591d33.py", "order": 1, "original_content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "parent_variant_id": "pyint-140ed9846741-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/postgres/search.py#L428-L455", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 186, "comments_removed": 3, "docstrings_removed": 0, "line_comments_removed": 3}, "unit_kind": "class", "unit_name": "LexemeCombinable", "variant_id": "pyint-1a54a1591d33-I01", "group_id": "py-5b87b277db5324de", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 142, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-30a9da4f1617-I02", "source": "from django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import (\n    CharField,\n    Expression,\n    Field,\n    FloatField,\n    Func,\n    Lookup,\n    TextField,\n    Value,\n)\nfrom django.db.models.expressions import CombinedExpression, register_combinable_fields\nfrom django.db.models.functions import Cast, Coalesce\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom .utils import CheckPostgresInstalledMixin\n\nclass LexemeCombinable:\n    BITAND = \"&\"\n    BITOR = \"|\"\n\n    def com(self, oth, con, rev):\n        if not isinstance(oth, LexemeCombinable):\n            raise TypeError(\n                \"A Lexeme can only be combined with another Lexeme, \"\n                f\"got {oth.__class__.__name__}.\"\n            )\n        if rev:\n            return CombinedLexeme(oth, con, self)\n        return CombinedLexeme(self, con, oth)\n\n    # On Combinable, these are not implemented to reduce confusion with Q. In\n    # this case we are actually (ab)using them to do logical combination so\n    # it's consistent with other usage in Django.\n    def __or__(self, oth2):\n        return self.com(oth2, self.BITOR, False)\n\n    def __ror__(self, oth3):\n        return self.com(oth3, self.BITOR, True)\n\n    def __and__(self, oth4):\n        return self.com(oth4, self.BITAND, False)\n\n    def __rand__(self, oth5):\n        return self.com(oth5, self.BITAND, True)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-5b87b277db5324de", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "0cb2dd542ff8fa5dab540c29ed347fc93bc19297e9fa8afbd87b532e7ae4516a", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 44, "local_path": "identifiers/shorten-identifiers/I02__django__LexemeCombinable__da4f1617.py", "order": 2, "original_content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "parent_variant_id": "pyint-140ed9846741-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/postgres/search.py#L428-L455", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 23, "identifiers_declared": 8}, "unit_kind": "class", "unit_name": "LexemeCombinable", "variant_id": "pyint-30a9da4f1617-I02", "group_id": "py-5b87b277db5324de", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 143, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ea2431e8e74a-I03", "source": "from django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import (\n    CharField,\n    Expression,\n    Field,\n    FloatField,\n    Func,\n    Lookup,\n    TextField,\n    Value,\n)\nfrom django.db.models.expressions import CombinedExpression, register_combinable_fields\nfrom django.db.models.functions import Cast, Coalesce\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom .utils import CheckPostgresInstalledMixin\n\nclass LexemeCombinable:\n    BITAND = \"&\"\n    BITOR = \"|\"\n\n    def organize(self, group, reference, schedule):\n        if not isinstance(group, LexemeCombinable):\n            raise TypeError(\n                \"A Lexeme can only be combined with another Lexeme, \"\n                f\"got {group.__class__.__name__}.\"\n            )\n        if schedule:\n            return CombinedLexeme(group, reference, self)\n        return CombinedLexeme(self, reference, group)\n\n    # On Combinable, these are not implemented to reduce confusion with Q. In\n    # this case we are actually (ab)using them to do logical combination so\n    # it's consistent with other usage in Django.\n    def __or__(self, value):\n        return self.organize(value, self.BITOR, False)\n\n    def __ror__(self, score):\n        return self.organize(score, self.BITOR, True)\n\n    def __and__(self, index):\n        return self.organize(index, self.BITAND, False)\n\n    def __rand__(self, cache):\n        return self.organize(cache, self.BITAND, True)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-5b87b277db5324de", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "61f5a2e291d80295d36dfc3beccda72d6c5b7541bc6cd533f46f2b6c836e44c8", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 44, "local_path": "identifiers/mislead-identifiers/I03__django__LexemeCombinable__31e8e74a.py", "order": 3, "original_content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "parent_variant_id": "pyint-140ed9846741-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/postgres/search.py#L428-L455", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 23, "identifiers_declared": 8, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 7, "local_random_pool_selections": 7, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "LexemeCombinable", "variant_id": "pyint-ea2431e8e74a-I03", "group_id": "py-5b87b277db5324de", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 144, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3a84ac2b3582-I04", "source": "from django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import (\n    CharField,\n    Expression,\n    Field,\n    FloatField,\n    Func,\n    Lookup,\n    TextField,\n    Value,\n)\nfrom django.db.models.expressions import CombinedExpression, register_combinable_fields\nfrom django.db.models.functions import Cast, Coalesce\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom .utils import CheckPostgresInstalledMixin\n\nclass LexemeCombinable:\n    BITAND = \"&\"\n    BITOR = \"|\"\n\n    def a(self, b, c, d):\n        if not isinstance(b, LexemeCombinable):\n            raise TypeError(\n                \"A Lexeme can only be combined with another Lexeme, \"\n                f\"got {b.__class__.__name__}.\"\n            )\n        if d:\n            return CombinedLexeme(b, c, self)\n        return CombinedLexeme(self, c, b)\n\n    # On Combinable, these are not implemented to reduce confusion with Q. In\n    # this case we are actually (ab)using them to do logical combination so\n    # it's consistent with other usage in Django.\n    def __or__(self, e):\n        return self.a(e, self.BITOR, False)\n\n    def __ror__(self, f):\n        return self.a(f, self.BITOR, True)\n\n    def __and__(self, g):\n        return self.a(g, self.BITAND, False)\n\n    def __rand__(self, h):\n        return self.a(h, self.BITAND, True)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-5b87b277db5324de", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "e0516b00de67e9a3b195dbdc9ffd2028a1a904285096bfc448adc697f3433b79", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 44, "local_path": "identifiers/garble-identifiers/I04__django__LexemeCombinable__ac2b3582.py", "order": 4, "original_content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "parent_variant_id": "pyint-140ed9846741-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/postgres/search.py#L428-L455", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 23, "identifiers_declared": 8}, "unit_kind": "class", "unit_name": "LexemeCombinable", "variant_id": "pyint-3a84ac2b3582-I04", "group_id": "py-5b87b277db5324de", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 145, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-07af6c6cb0aa-I05", "source": "from django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import (\n    CharField,\n    Expression,\n    Field,\n    FloatField,\n    Func,\n    Lookup,\n    TextField,\n    Value,\n)\nfrom django.db.models.expressions import CombinedExpression, register_combinable_fields\nfrom django.db.models.functions import Cast, Coalesce\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom .utils import CheckPostgresInstalledMixin\n\nclass LexemeCombinable:\n    BITAND = \"&\"\n    BITOR = \"|\"\n\n    def _combine(self, other, connector, reversed):\n        if not isinstance(other, LexemeCombinable):\n            raise TypeError(\n                \"A Lexeme can only be combined with another Lexeme, \"\n                f\"got {other.__class__.__name__}.\"\n            )\n        if reversed:\n            return CombinedLexeme(other, connector, self)\n        return CombinedLexeme(self, connector, other)\n\n    # On Combinable, these are not implemented to reduce confusion with Q. In\n    # this case we are actually (ab)using them to do logical combination so\n    # it's consistent with other usage in Django.\n    def __or__(self, other):\n        return self._combine(other, self.BITOR, False)\n\n    def __ror__(self, other):\n        return self._combine(other, self.BITOR, True)\n\n    def __and__(self, other):\n        return self._combine(other, self.BITAND, False)\n\n    def __rand__(self, other):\n        return self._combine(other, self.BITAND, True)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-5b87b277db5324de", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 44, "local_path": "expressions/encode-integer-literals/I05__django__LexemeCombinable__6c6cb0aa.py", "order": 5, "original_content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "parent_variant_id": "pyint-140ed9846741-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/postgres/search.py#L428-L455", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "LexemeCombinable", "variant_id": "pyint-07af6c6cb0aa-I05", "group_id": "py-5b87b277db5324de", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 146, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-676d71ae47d8-I06", "source": "from django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import (\n    CharField,\n    Expression,\n    Field,\n    FloatField,\n    Func,\n    Lookup,\n    TextField,\n    Value,\n)\nfrom django.db.models.expressions import CombinedExpression, register_combinable_fields\nfrom django.db.models.functions import Cast, Coalesce\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom .utils import CheckPostgresInstalledMixin\n\nclass LexemeCombinable:\n    BITAND = \"&\"\n    BITOR = \"|\"\n\n    def _combine(self, other, connector, reversed):\n        if not (not isinstance(other, LexemeCombinable)):\n            pass\n        else:\n            raise TypeError(\n                \"A Lexeme can only be combined with another Lexeme, \"\n                f\"got {other.__class__.__name__}.\"\n            )\n        if not (reversed):\n            pass\n        else:\n            return CombinedLexeme(other, connector, self)\n        return CombinedLexeme(self, connector, other)\n\n    # On Combinable, these are not implemented to reduce confusion with Q. In\n    # this case we are actually (ab)using them to do logical combination so\n    # it's consistent with other usage in Django.\n    def __or__(self, other):\n        return self._combine(other, self.BITOR, False)\n\n    def __ror__(self, other):\n        return self._combine(other, self.BITOR, True)\n\n    def __and__(self, other):\n        return self._combine(other, self.BITAND, False)\n\n    def __rand__(self, other):\n        return self._combine(other, self.BITAND, True)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-5b87b277db5324de", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "3e4059c3d79465aeecff4112852e74c1a180e0600730e635cc38d5e626ff0394", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 48, "local_path": "expressions/invert-conditions/I06__django__LexemeCombinable__71ae47d8.py", "order": 6, "original_content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "parent_variant_id": "pyint-140ed9846741-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/postgres/search.py#L428-L455", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 2}, "unit_kind": "class", "unit_name": "LexemeCombinable", "variant_id": "pyint-676d71ae47d8-I06", "group_id": "py-5b87b277db5324de", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 147, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e6ecfb88d3a4-I07", "source": "from django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import (\n    CharField,\n    Expression,\n    Field,\n    FloatField,\n    Func,\n    Lookup,\n    TextField,\n    Value,\n)\nfrom django.db.models.expressions import CombinedExpression, register_combinable_fields\nfrom django.db.models.functions import Cast, Coalesce\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom .utils import CheckPostgresInstalledMixin\n\nclass LexemeCombinable:\n    BITAND = \"&\"\n    BITOR = \"|\"\n\n    def _combine(self, other, connector, reversed):\n        if ((0x912a ^ 0x912a) != 0):\n            raise AssertionError()\n        if not isinstance(other, LexemeCombinable):\n            raise TypeError(\n                \"A Lexeme can only be combined with another Lexeme, \"\n                f\"got {other.__class__.__name__}.\"\n            )\n        if reversed:\n            return CombinedLexeme(other, connector, self)\n        return CombinedLexeme(self, connector, other)\n\n    # On Combinable, these are not implemented to reduce confusion with Q. In\n    # this case we are actually (ab)using them to do logical combination so\n    # it's consistent with other usage in Django.\n    def __or__(self, other):\n        if ((0x8a4 ^ 0x8a4) != 0):\n            raise AssertionError()\n        return self._combine(other, self.BITOR, False)\n\n    def __ror__(self, other):\n        if ((0xe843 ^ 0xe843) != 0):\n            raise AssertionError()\n        return self._combine(other, self.BITOR, True)\n\n    def __and__(self, other):\n        if ((0x952 ^ 0x952) != 0):\n            raise AssertionError()\n        return self._combine(other, self.BITAND, False)\n\n    def __rand__(self, other):\n        if ((0x337 ^ 0x337) != 0):\n            raise AssertionError()\n        return self._combine(other, self.BITAND, True)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-5b87b277db5324de", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "e9f257c79f79de3d63ed37ae8b1a9e9ddd5447987e5d465064049743c1887786", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 54, "local_path": "code-injection/insert-dead-branches/I07__django__LexemeCombinable__fb88d3a4.py", "order": 7, "original_content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "parent_variant_id": "pyint-140ed9846741-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/postgres/search.py#L428-L455", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 5}, "unit_kind": "class", "unit_name": "LexemeCombinable", "variant_id": "pyint-e6ecfb88d3a4-I07", "group_id": "py-5b87b277db5324de", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 148, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9621180184b4-I08", "source": "from django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import (\n    CharField,\n    Expression,\n    Field,\n    FloatField,\n    Func,\n    Lookup,\n    TextField,\n    Value,\n)\nfrom django.db.models.expressions import CombinedExpression, register_combinable_fields\nfrom django.db.models.functions import Cast, Coalesce\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom .utils import CheckPostgresInstalledMixin\n\nclass LexemeCombinable:\n    BITAND = \"&\"\n    BITOR = \"|\"\n\n    def _combine(self, other, connector, reversed):\n        if not isinstance(other, LexemeCombinable):\n            raise TypeError(\n                \"A Lexeme can only be combined with another Lexeme, \"\n                f\"got {other.__class__.__name__}.\"\n            )\n        if reversed:\n            return CombinedLexeme(other, connector, self)\n        return CombinedLexeme(self, connector, other)\n\n    # On Combinable, these are not implemented to reduce confusion with Q. In\n    # this case we are actually (ab)using them to do logical combination so\n    # it's consistent with other usage in Django.\n    def __or__(self, other):\n        return self._combine(other, self.BITOR, False)\n\n    def __ror__(self, other):\n        even_number_count = 0\n        for candidate_number in range(6):\n            if candidate_number % 2 == 0:\n                even_number_count += 1\n        return self._combine(other, self.BITOR, True)\n\n    def __and__(self, other):\n        return self._combine(other, self.BITAND, False)\n\n    def __rand__(self, other):\n        return self._combine(other, self.BITAND, True)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-5b87b277db5324de", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "98c4505f62aa1fcf949a776e685c7c804221b6432c4669ba9f63931666478d76", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 48, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__LexemeCombinable__180184b4.py", "order": 8, "original_content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "parent_variant_id": "pyint-140ed9846741-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/postgres/search.py#L428-L455", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 4, "readable_template_index": 2}, "unit_kind": "class", "unit_name": "LexemeCombinable", "variant_id": "pyint-9621180184b4-I08", "group_id": "py-5b87b277db5324de", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 149, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ea288579ef2d-I09", "source": "from django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import (\n    CharField,\n    Expression,\n    Field,\n    FloatField,\n    Func,\n    Lookup,\n    TextField,\n    Value,\n)\nfrom django.db.models.expressions import CombinedExpression, register_combinable_fields\nfrom django.db.models.functions import Cast, Coalesce\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom .utils import CheckPostgresInstalledMixin\n\nclass LexemeCombinable:\n    BITAND = \"&\"\n    BITOR = \"|\"\n\n    def _combine(self, other, connector, reversed):\n        if not isinstance(other, LexemeCombinable):\n            raise TypeError(\n                \"A Lexeme can only be combined with another Lexeme, \"\n                f\"got {other.__class__.__name__}.\"\n            )\n        if reversed:\n            return CombinedLexeme(other, connector, self)\n        return CombinedLexeme(self, connector, other)\n\n    # On Combinable, these are not implemented to reduce confusion with Q. In\n    # this case we are actually (ab)using them to do logical combination so\n    # it's consistent with other usage in Django.\n    def __or__(self, other):\n        lI0O_0009bfe0 = 0xa85c ^ 0xa85c\n        if lI0O_0009bfe0 != 0:\n            if ((lI0O_0009bfe0 | 1) & 1) == 0:\n                lI0O_0009bfe0 += 1\n            else:\n                lI0O_0009bfe0 -= 1\n        return self._combine(other, self.BITOR, False)\n\n    def __ror__(self, other):\n        return self._combine(other, self.BITOR, True)\n\n    def __and__(self, other):\n        return self._combine(other, self.BITAND, False)\n\n    def __rand__(self, other):\n        return self._combine(other, self.BITAND, True)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-5b87b277db5324de", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "1cf0af2b54d6a7680fc62fa2783cbf86994362a5ffa8c0bc05f61cf942d76a62", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 50, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__LexemeCombinable__8579ef2d.py", "order": 9, "original_content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "parent_variant_id": "pyint-140ed9846741-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/postgres/search.py#L428-L455", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 5}, "unit_kind": "class", "unit_name": "LexemeCombinable", "variant_id": "pyint-ea288579ef2d-I09", "group_id": "py-5b87b277db5324de", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 150, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-961a064bda70-I10", "source": "from django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import (     CharField,     Expression,\n    Field,\n    FloatField,\n    Func,     Lookup,\n    TextField,     Value,\n)\nfrom django.db.models.expressions import CombinedExpression, register_combinable_fields\nfrom django.db.models.functions import Cast, Coalesce\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom .utils import CheckPostgresInstalledMixin\nclass LexemeCombinable:\n    BITAND = \"&\"\n    BITOR = \"|\"\n\n    def _combine(self, other, connector, reversed):\n        if not isinstance(other, LexemeCombinable):\n            raise TypeError(\n                \"A Lexeme can only be combined with another Lexeme, \"\n                f\"got {other.__class__.__name__}.\"             )\n        if reversed:\n            return CombinedLexeme(other, connector, self)\n        return CombinedLexeme(self, connector, other)\n\n    # On Combinable, these are not implemented to reduce confusion with Q. In\n    # this case we are actually (ab)using them to do logical combination so\n    # it's consistent with other usage in Django.\n    def __or__(self, other):\n        return self._combine(other, self.BITOR, False)\n    def __ror__(self, other):\n        return self._combine(other, self.BITOR, True)\n\n    def __and__(self, other):\n        return self._combine(other, self.BITAND, False)\n\n    def __rand__(self, other):\n        return self._combine(other, self.BITAND, True)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-5b87b277db5324de", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "bf3cb53d274cb3161e11198d63174aa035eec09679a41f8cdfb390bac5a39cfd", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 37, "local_path": "layout/partially-compact-layout/I10__django__LexemeCombinable__064bda70.py", "order": 10, "original_content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "parent_variant_id": "pyint-140ed9846741-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/postgres/search.py#L428-L455", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 18, "line_break_groups_removed": 7, "line_breaks_removed": 7, "whitespace_characters_removed": 2}, "unit_kind": "class", "unit_name": "LexemeCombinable", "variant_id": "pyint-961a064bda70-I10", "group_id": "py-5b87b277db5324de", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 151, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c7fbebcac5f1-I11", "source": "from django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import (\n    CharField,\n    Expression,\n    Field,\n    FloatField,\n    Func,\n    Lookup,\n    TextField,\n    Value,\n)\nfrom django.db.models.expressions import CombinedExpression, register_combinable_fields\nfrom django.db.models.functions import Cast, Coalesce\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom .utils import CheckPostgresInstalledMixin\n\nclass LexemeCombinable:\n    BITAND = \"&\"\n    BITOR = \"|\"\n\n    def _combine(self, other, connector, reversed):\n        if not isinstance(other, LexemeCombinable):\n            raise TypeError(\n                \"A Lexeme can only be combined with another Lexeme, \"\n                f\"got {other.__class__.__name__}.\"\n            )\n        if reversed:\n            return CombinedLexeme(other, connector, self)\n        return CombinedLexeme(self, connector, other)\n\n    # On Combinable, these are not implemented to reduce confusion with Q. In\n    # this case we are actually (ab)using them to do logical combination so\n    # it's consistent with other usage in Django.\n    def __or__(self, other):\n        return self._combine(other, self.BITOR, False)\n\n    def __ror__(self, other):\n        return self._combine(other, self.BITOR, True)\n\n    def __and__(self, other):\n        return self._combine(other, self.BITAND, False)\n\n    def __rand__(self, other):\n        return self._combine(other, self.BITAND, True)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-5b87b277db5324de", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 44, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__LexemeCombinable__ebcac5f1.py", "order": 11, "original_content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "parent_variant_id": "pyint-140ed9846741-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/postgres/search.py#L428-L455", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "LexemeCombinable", "variant_id": "pyint-c7fbebcac5f1-I11", "group_id": "py-5b87b277db5324de", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 152, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-18e372e84c38-I12", "source": "from django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import (\n    CharField,\n    Expression,\n    Field,\n    FloatField,\n    Func,\n    Lookup,\n    TextField,\n    Value,\n)\nfrom django.db.models.expressions import CombinedExpression, register_combinable_fields\nfrom django.db.models.functions import Cast, Coalesce\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom .utils import CheckPostgresInstalledMixin\n\nclass LexemeCombinable:\n    BITAND = \"&\"\n    BITOR = \"|\"\n\n    def _combine(self, other, connector, reversed):\n        if not isinstance(other, LexemeCombinable):\n            raise TypeError(\n                \"A Lexeme can only be combined with another Lexeme, \"\n                f\"got {other.__class__.__name__}.\"\n            )\n        if reversed:\n            return CombinedLexeme(other, connector, self)\n        return CombinedLexeme(self, connector, other)\n\n    # On Combinable, these are not implemented to reduce confusion with Q. In\n    # this case we are actually (ab)using them to do logical combination so\n    # it's consistent with other usage in Django.\n    def __or__(self, other):\n        return self._combine(other, self.BITOR, False)\n\n    def __ror__(self, other):\n        return self._combine(other, self.BITOR, True)\n\n    def __and__(self, other):\n        return self._combine(other, self.BITAND, False)\n\n    def __rand__(self, other):\n        return self._combine(other, self.BITAND, True)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-5b87b277db5324de", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 44, "local_path": "data-flow/inline-intermediate-variables/I12__django__LexemeCombinable__72e84c38.py", "order": 12, "original_content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "parent_variant_id": "pyint-140ed9846741-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/postgres/search.py#L428-L455", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "LexemeCombinable", "variant_id": "pyint-18e372e84c38-I12", "group_id": "py-5b87b277db5324de", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 153, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-78ae0e10f261-I13", "source": "from django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import (\n    CharField,\n    Expression,\n    Field,\n    FloatField,\n    Func,\n    Lookup,\n    TextField,\n    Value,\n)\nfrom django.db.models.expressions import CombinedExpression, register_combinable_fields\nfrom django.db.models.functions import Cast, Coalesce\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom .utils import CheckPostgresInstalledMixin\n\nclass LexemeCombinable:\n    BITAND = \"&\"\n    BITOR = \"|\"\n\n    def _combine(self, other, connector, reversed):\n        if not isinstance(other, LexemeCombinable):\n            raise TypeError(\n                \"A Lexeme can only be combined with another Lexeme, \"\n                f\"got {other.__class__.__name__}.\"\n            )\n        if reversed:\n            return CombinedLexeme(other, connector, self)\n        return CombinedLexeme(self, connector, other)\n\n    # On Combinable, these are not implemented to reduce confusion with Q. In\n    # this case we are actually (ab)using them to do logical combination so\n    # it's consistent with other usage in Django.\n    def __or__(self, other):\n        return self._combine(other, self.BITOR, False)\n\n    def __ror__(self, other):\n        return self._combine(other, self.BITOR, True)\n\n    def __and__(self, other):\n        return self._combine(other, self.BITAND, False)\n\n    def __rand__(self, other):\n        return self._combine(other, self.BITAND, True)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-5b87b277db5324de", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 44, "local_path": "control-flow/lower-for-to-while/I13__django__LexemeCombinable__0e10f261.py", "order": 13, "original_content_sha256": "79ca64b2ce5d12221a2203823a94581c6a77c8c960c3579447102ae28c6d8891", "parent_variant_id": "pyint-140ed9846741-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/postgres/search.py#L428-L455", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "LexemeCombinable", "variant_id": "pyint-78ae0e10f261-I13", "group_id": "py-5b87b277db5324de", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 154, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2bc28b0c1661-SRC", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsRead(Protocol[_T_co]):\n    def read(self, length: int = ..., /) -> _T_co: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-5bbec0b06712337d", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 14, "local_path": "source-original/SRC__requests__SupportsRead__8b0c1661.py", "order": 0, "original_content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L28-L29", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "SupportsRead", "variant_id": "pyint-2bc28b0c1661-SRC", "group_id": "py-5bbec0b06712337d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 981, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2a5ab0c6b657-I01", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsRead(Protocol[_T_co]):\n    def read(self, length: int = ..., /) -> _T_co: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-5bbec0b06712337d", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 14, "local_path": "comments/remove-comments/I01__requests__SupportsRead__b0c6b657.py", "order": 1, "original_content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "parent_variant_id": "pyint-2bc28b0c1661-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L28-L29", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "SupportsRead", "variant_id": "pyint-2a5ab0c6b657-I01", "group_id": "py-5bbec0b06712337d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 982, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dd14208a86fb-I02", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsRead(Protocol[_T_co]):\n    def rea(self, len: int = ..., /) -> _T_co: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-5bbec0b06712337d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "4deb90006df59932e45703cd7148f37c7e915766c3e67ea9c9fb2b0ad8d3d848", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 14, "local_path": "identifiers/shorten-identifiers/I02__requests__SupportsRead__208a86fb.py", "order": 2, "original_content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "parent_variant_id": "pyint-2bc28b0c1661-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L28-L29", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2, "identifiers_declared": 2}, "unit_kind": "class", "unit_name": "SupportsRead", "variant_id": "pyint-dd14208a86fb-I02", "group_id": "py-5bbec0b06712337d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 983, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cb9d100fca44-I03", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsRead(Protocol[_T_co]):\n    def join(self, option: int = ..., /) -> _T_co: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-5bbec0b06712337d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "01396a01577e56ca2cf908e53b81e36a09f8749477b884f73646b52315e35064", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 14, "local_path": "identifiers/mislead-identifiers/I03__requests__SupportsRead__100fca44.py", "order": 3, "original_content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "parent_variant_id": "pyint-2bc28b0c1661-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L28-L29", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2, "identifiers_declared": 2, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 1, "local_random_pool_selections": 1, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "SupportsRead", "variant_id": "pyint-cb9d100fca44-I03", "group_id": "py-5bbec0b06712337d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 984, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a2e58266742c-I04", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsRead(Protocol[_T_co]):\n    def a(self, b: int = ..., /) -> _T_co: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-5bbec0b06712337d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "66ec594b221c932b6c1bc9f128c4d02b33cf05d464427aea7c2a8149f215c6e2", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 14, "local_path": "identifiers/garble-identifiers/I04__requests__SupportsRead__8266742c.py", "order": 4, "original_content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "parent_variant_id": "pyint-2bc28b0c1661-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L28-L29", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2, "identifiers_declared": 2}, "unit_kind": "class", "unit_name": "SupportsRead", "variant_id": "pyint-a2e58266742c-I04", "group_id": "py-5bbec0b06712337d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 985, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-55681adba177-I05", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsRead(Protocol[_T_co]):\n    def read(self, length: int = ..., /) -> _T_co: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-5bbec0b06712337d", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 14, "local_path": "expressions/encode-integer-literals/I05__requests__SupportsRead__1adba177.py", "order": 5, "original_content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "parent_variant_id": "pyint-2bc28b0c1661-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L28-L29", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "SupportsRead", "variant_id": "pyint-55681adba177-I05", "group_id": "py-5bbec0b06712337d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 986, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c20d4715171f-I06", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsRead(Protocol[_T_co]):\n    def read(self, length: int = ..., /) -> _T_co: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-5bbec0b06712337d", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 14, "local_path": "expressions/invert-conditions/I06__requests__SupportsRead__4715171f.py", "order": 6, "original_content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "parent_variant_id": "pyint-2bc28b0c1661-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L28-L29", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "SupportsRead", "variant_id": "pyint-c20d4715171f-I06", "group_id": "py-5bbec0b06712337d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 987, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ca85fb6f7b93-I07", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsRead(Protocol[_T_co]):\n    def read(self, length: int = ..., /) -> _T_co: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-5bbec0b06712337d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 14, "local_path": "code-injection/insert-dead-branches/I07__requests__SupportsRead__fb6f7b93.py", "order": 7, "original_content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "parent_variant_id": "pyint-2bc28b0c1661-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L28-L29", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 0}, "unit_kind": "class", "unit_name": "SupportsRead", "variant_id": "pyint-ca85fb6f7b93-I07", "group_id": "py-5bbec0b06712337d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 988, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9efa3a1a85e0-I08", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsRead(Protocol[_T_co]):\n    def read(self, length: int = ..., /) -> _T_co: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-5bbec0b06712337d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 14, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__SupportsRead__3a1a85e0.py", "order": 8, "original_content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "parent_variant_id": "pyint-2bc28b0c1661-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L28-L29", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 0, "readable_lines_injected": 0, "readable_template_index": -1}, "unit_kind": "class", "unit_name": "SupportsRead", "variant_id": "pyint-9efa3a1a85e0-I08", "group_id": "py-5bbec0b06712337d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 989, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5f705337b238-I09", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsRead(Protocol[_T_co]):\n    def read(self, length: int = ..., /) -> _T_co: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-5bbec0b06712337d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 14, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__SupportsRead__5337b238.py", "order": 9, "original_content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "parent_variant_id": "pyint-2bc28b0c1661-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L28-L29", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 0, "low_readability_template_index": -1}, "unit_kind": "class", "unit_name": "SupportsRead", "variant_id": "pyint-5f705337b238-I09", "group_id": "py-5bbec0b06712337d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 990, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b28360e02eac-I10", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,     Any,     Protocol,     TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsRead(Protocol[_T_co]):\n    def read(self, length: int = ..., /) -> _T_co: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-5bbec0b06712337d", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "afb206e6bd436f523c2b93f0b6a6735e6d1b2d2d197e6e5fd7e3653fc1dfbb1a", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 11, "local_path": "layout/partially-compact-layout/I10__requests__SupportsRead__60e02eac.py", "order": 10, "original_content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "parent_variant_id": "pyint-2bc28b0c1661-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L28-L29", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 8, "line_break_groups_removed": 3, "line_breaks_removed": 3, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "SupportsRead", "variant_id": "pyint-b28360e02eac-I10", "group_id": "py-5bbec0b06712337d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 991, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b49e52296b5d-I11", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsRead(Protocol[_T_co]):\n    def read(self, length: int = ..., /) -> _T_co: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-5bbec0b06712337d", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 14, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__SupportsRead__52296b5d.py", "order": 11, "original_content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "parent_variant_id": "pyint-2bc28b0c1661-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L28-L29", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "SupportsRead", "variant_id": "pyint-b49e52296b5d-I11", "group_id": "py-5bbec0b06712337d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 992, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-21509da6ce7b-I12", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsRead(Protocol[_T_co]):\n    def read(self, length: int = ..., /) -> _T_co: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-5bbec0b06712337d", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 14, "local_path": "data-flow/inline-intermediate-variables/I12__requests__SupportsRead__9da6ce7b.py", "order": 12, "original_content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "parent_variant_id": "pyint-2bc28b0c1661-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L28-L29", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "SupportsRead", "variant_id": "pyint-21509da6ce7b-I12", "group_id": "py-5bbec0b06712337d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 993, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7d50e63d98a1-I13", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsRead(Protocol[_T_co]):\n    def read(self, length: int = ..., /) -> _T_co: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-5bbec0b06712337d", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 14, "local_path": "control-flow/lower-for-to-while/I13__requests__SupportsRead__e63d98a1.py", "order": 13, "original_content_sha256": "e1d756ac2c1101cf302ab513a124c37a0b9f51a63ec86726d692f177cac30439", "parent_variant_id": "pyint-2bc28b0c1661-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L28-L29", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "SupportsRead", "variant_id": "pyint-7d50e63d98a1-I13", "group_id": "py-5bbec0b06712337d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 994, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-38e7391d459e-SRC", "source": "from django.apps import AppConfig\nfrom django.contrib.messages.storage import base\nfrom django.contrib.messages.utils import get_level_tags\nfrom django.core.signals import setting_changed\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy as _\n\nclass MessagesConfig(AppConfig):\n    name = \"django.contrib.messages\"\n    verbose_name = _(\"Messages\")\n\n    def ready(self):\n        setting_changed.connect(update_level_tags)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-5c8dec39f6907826", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 13, "local_path": "source-original/SRC__django__MessagesConfig__391d459e.py", "order": 0, "original_content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/messages/apps.py#L14-L19", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "MessagesConfig", "variant_id": "pyint-38e7391d459e-SRC", "group_id": "py-5c8dec39f6907826", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 57, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-63e3cb60c1bc-I01", "source": "from django.apps import AppConfig\nfrom django.contrib.messages.storage import base\nfrom django.contrib.messages.utils import get_level_tags\nfrom django.core.signals import setting_changed\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy as _\n\nclass MessagesConfig(AppConfig):\n    name = \"django.contrib.messages\"\n    verbose_name = _(\"Messages\")\n\n    def ready(self):\n        setting_changed.connect(update_level_tags)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-5c8dec39f6907826", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 13, "local_path": "comments/remove-comments/I01__django__MessagesConfig__cb60c1bc.py", "order": 1, "original_content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "parent_variant_id": "pyint-38e7391d459e-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/messages/apps.py#L14-L19", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "MessagesConfig", "variant_id": "pyint-63e3cb60c1bc-I01", "group_id": "py-5c8dec39f6907826", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 58, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1bfa96335a19-I02", "source": "from django.apps import AppConfig\nfrom django.contrib.messages.storage import base\nfrom django.contrib.messages.utils import get_level_tags\nfrom django.core.signals import setting_changed\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy as _\n\nclass MessagesConfig(AppConfig):\n    name = \"django.contrib.messages\"\n    verbose_name = _(\"Messages\")\n\n    def rea(self):\n        setting_changed.connect(update_level_tags)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-5c8dec39f6907826", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "8c37891334e1010234310c903aa75a6d7efbb3d46d292e900f24643c522cd76b", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 13, "local_path": "identifiers/shorten-identifiers/I02__django__MessagesConfig__96335a19.py", "order": 2, "original_content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "parent_variant_id": "pyint-38e7391d459e-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/messages/apps.py#L14-L19", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "MessagesConfig", "variant_id": "pyint-1bfa96335a19-I02", "group_id": "py-5c8dec39f6907826", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 59, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7a95100d45a7-I03", "source": "from django.apps import AppConfig\nfrom django.contrib.messages.storage import base\nfrom django.contrib.messages.utils import get_level_tags\nfrom django.core.signals import setting_changed\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy as _\n\nclass MessagesConfig(AppConfig):\n    name = \"django.contrib.messages\"\n    verbose_name = _(\"Messages\")\n\n    def parse(self):\n        setting_changed.connect(update_level_tags)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-5c8dec39f6907826", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "01d5e7541b529ea7e8ec4454dc06d5ca887477d17b48d4027ed6f8294c3d6a6e", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 13, "local_path": "identifiers/mislead-identifiers/I03__django__MessagesConfig__100d45a7.py", "order": 3, "original_content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "parent_variant_id": "pyint-38e7391d459e-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/messages/apps.py#L14-L19", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 0, "local_random_pool_selections": 0, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "MessagesConfig", "variant_id": "pyint-7a95100d45a7-I03", "group_id": "py-5c8dec39f6907826", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 60, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-45f1f4b1f86e-I04", "source": "from django.apps import AppConfig\nfrom django.contrib.messages.storage import base\nfrom django.contrib.messages.utils import get_level_tags\nfrom django.core.signals import setting_changed\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy as _\n\nclass MessagesConfig(AppConfig):\n    name = \"django.contrib.messages\"\n    verbose_name = _(\"Messages\")\n\n    def a(self):\n        setting_changed.connect(update_level_tags)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-5c8dec39f6907826", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d48abc6ec4b0974b69053e92f4ebe74181cc5b4275b81a09cbbd5f708c66f1af", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 13, "local_path": "identifiers/garble-identifiers/I04__django__MessagesConfig__f4b1f86e.py", "order": 4, "original_content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "parent_variant_id": "pyint-38e7391d459e-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/messages/apps.py#L14-L19", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "MessagesConfig", "variant_id": "pyint-45f1f4b1f86e-I04", "group_id": "py-5c8dec39f6907826", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 61, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7c2bb026b379-I05", "source": "from django.apps import AppConfig\nfrom django.contrib.messages.storage import base\nfrom django.contrib.messages.utils import get_level_tags\nfrom django.core.signals import setting_changed\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy as _\n\nclass MessagesConfig(AppConfig):\n    name = \"django.contrib.messages\"\n    verbose_name = _(\"Messages\")\n\n    def ready(self):\n        setting_changed.connect(update_level_tags)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-5c8dec39f6907826", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 13, "local_path": "expressions/encode-integer-literals/I05__django__MessagesConfig__b026b379.py", "order": 5, "original_content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "parent_variant_id": "pyint-38e7391d459e-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/messages/apps.py#L14-L19", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "MessagesConfig", "variant_id": "pyint-7c2bb026b379-I05", "group_id": "py-5c8dec39f6907826", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 62, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-35f9d5772f7d-I06", "source": "from django.apps import AppConfig\nfrom django.contrib.messages.storage import base\nfrom django.contrib.messages.utils import get_level_tags\nfrom django.core.signals import setting_changed\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy as _\n\nclass MessagesConfig(AppConfig):\n    name = \"django.contrib.messages\"\n    verbose_name = _(\"Messages\")\n\n    def ready(self):\n        setting_changed.connect(update_level_tags)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-5c8dec39f6907826", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 13, "local_path": "expressions/invert-conditions/I06__django__MessagesConfig__d5772f7d.py", "order": 6, "original_content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "parent_variant_id": "pyint-38e7391d459e-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/messages/apps.py#L14-L19", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "MessagesConfig", "variant_id": "pyint-35f9d5772f7d-I06", "group_id": "py-5c8dec39f6907826", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 63, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-41a7c0fcff9e-I07", "source": "from django.apps import AppConfig\nfrom django.contrib.messages.storage import base\nfrom django.contrib.messages.utils import get_level_tags\nfrom django.core.signals import setting_changed\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy as _\n\nclass MessagesConfig(AppConfig):\n    name = \"django.contrib.messages\"\n    verbose_name = _(\"Messages\")\n\n    def ready(self):\n        if ((0xf8fb ^ 0xf8fb) != 0):\n            raise AssertionError()\n        setting_changed.connect(update_level_tags)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-5c8dec39f6907826", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "05026ae38c1d7667c65b52ffab6d2ece6f46692f68c50b334ec638f52fbba67a", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 15, "local_path": "code-injection/insert-dead-branches/I07__django__MessagesConfig__c0fcff9e.py", "order": 7, "original_content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "parent_variant_id": "pyint-38e7391d459e-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/messages/apps.py#L14-L19", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "MessagesConfig", "variant_id": "pyint-41a7c0fcff9e-I07", "group_id": "py-5c8dec39f6907826", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 64, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a2d2583dc2ea-I08", "source": "from django.apps import AppConfig\nfrom django.contrib.messages.storage import base\nfrom django.contrib.messages.utils import get_level_tags\nfrom django.core.signals import setting_changed\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy as _\n\nclass MessagesConfig(AppConfig):\n    name = \"django.contrib.messages\"\n    verbose_name = _(\"Messages\")\n\n    def ready(self):\n        running_total = 0\n        for current_number in range(1, 6):\n            running_total += current_number\n        setting_changed.connect(update_level_tags)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-5c8dec39f6907826", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "713835307f3eed6403a11315d08d3f38dd3dbd933210c4adc2d8c58667b086a9", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 16, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__MessagesConfig__583dc2ea.py", "order": 8, "original_content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "parent_variant_id": "pyint-38e7391d459e-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/messages/apps.py#L14-L19", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 0}, "unit_kind": "class", "unit_name": "MessagesConfig", "variant_id": "pyint-a2d2583dc2ea-I08", "group_id": "py-5c8dec39f6907826", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 65, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ef3b2b5f86c2-I09", "source": "from django.apps import AppConfig\nfrom django.contrib.messages.storage import base\nfrom django.contrib.messages.utils import get_level_tags\nfrom django.core.signals import setting_changed\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy as _\n\nclass MessagesConfig(AppConfig):\n    name = \"django.contrib.messages\"\n    verbose_name = _(\"Messages\")\n\n    def ready(self):\n        lI0O_61c912bf = 0xbbb5\n        lI0O_61c912bf = ((lI0O_61c912bf ^ 0xbbb5) | 0) & -1\n        if (lI0O_61c912bf & 1) == 1:\n            lI0O_61c912bf ^= lI0O_61c912bf\n        setting_changed.connect(update_level_tags)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-5c8dec39f6907826", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "1d41188b8d8b2d2eeb8692ff67dda66f9e3533d0d8af0da74ab495fc8450336e", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 17, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__MessagesConfig__2b5f86c2.py", "order": 9, "original_content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "parent_variant_id": "pyint-38e7391d459e-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/messages/apps.py#L14-L19", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 0}, "unit_kind": "class", "unit_name": "MessagesConfig", "variant_id": "pyint-ef3b2b5f86c2-I09", "group_id": "py-5c8dec39f6907826", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 66, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1b0e8ac63e7a-I10", "source": "from django.apps import AppConfig\nfrom django.contrib.messages.storage import base\nfrom django.contrib.messages.utils import get_level_tags\nfrom django.core.signals import setting_changed\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy as _\n\nclass MessagesConfig(AppConfig):\n    name = \"django.contrib.messages\"\n    verbose_name = _(\"Messages\")\n\n    def ready(self):\n        setting_changed.connect(update_level_tags)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-5c8dec39f6907826", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 13, "local_path": "layout/partially-compact-layout/I10__django__MessagesConfig__8ac63e7a.py", "order": 10, "original_content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "parent_variant_id": "pyint-38e7391d459e-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/messages/apps.py#L14-L19", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 2, "line_break_groups_removed": 0, "line_breaks_removed": 0, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "MessagesConfig", "variant_id": "pyint-1b0e8ac63e7a-I10", "group_id": "py-5c8dec39f6907826", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 67, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b1ae04f36043-I11", "source": "from django.apps import AppConfig\nfrom django.contrib.messages.storage import base\nfrom django.contrib.messages.utils import get_level_tags\nfrom django.core.signals import setting_changed\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy as _\n\nclass MessagesConfig(AppConfig):\n    name = \"django.contrib.messages\"\n    verbose_name = _(\"Messages\")\n\n    def ready(self):\n        setting_changed.connect(update_level_tags)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-5c8dec39f6907826", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 13, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__MessagesConfig__04f36043.py", "order": 11, "original_content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "parent_variant_id": "pyint-38e7391d459e-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/messages/apps.py#L14-L19", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "MessagesConfig", "variant_id": "pyint-b1ae04f36043-I11", "group_id": "py-5c8dec39f6907826", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 68, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7ecf5f21bd3d-I12", "source": "from django.apps import AppConfig\nfrom django.contrib.messages.storage import base\nfrom django.contrib.messages.utils import get_level_tags\nfrom django.core.signals import setting_changed\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy as _\n\nclass MessagesConfig(AppConfig):\n    name = \"django.contrib.messages\"\n    verbose_name = _(\"Messages\")\n\n    def ready(self):\n        setting_changed.connect(update_level_tags)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-5c8dec39f6907826", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 13, "local_path": "data-flow/inline-intermediate-variables/I12__django__MessagesConfig__5f21bd3d.py", "order": 12, "original_content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "parent_variant_id": "pyint-38e7391d459e-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/messages/apps.py#L14-L19", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "MessagesConfig", "variant_id": "pyint-7ecf5f21bd3d-I12", "group_id": "py-5c8dec39f6907826", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 69, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-49b4c6d86903-I13", "source": "from django.apps import AppConfig\nfrom django.contrib.messages.storage import base\nfrom django.contrib.messages.utils import get_level_tags\nfrom django.core.signals import setting_changed\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy as _\n\nclass MessagesConfig(AppConfig):\n    name = \"django.contrib.messages\"\n    verbose_name = _(\"Messages\")\n\n    def ready(self):\n        setting_changed.connect(update_level_tags)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-5c8dec39f6907826", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 13, "local_path": "control-flow/lower-for-to-while/I13__django__MessagesConfig__c6d86903.py", "order": 13, "original_content_sha256": "b05c952c8ec020557f3c2c82ff98556f6bb4685be7bbcabc730155d021de5217", "parent_variant_id": "pyint-38e7391d459e-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/messages/apps.py#L14-L19", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "MessagesConfig", "variant_id": "pyint-49b4c6d86903-I13", "group_id": "py-5c8dec39f6907826", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 70, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ac92533db2e3-SRC", "source": "import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import (\n    BaseDetailView,\n    SingleObjectTemplateResponseMixin,\n)\nfrom django.views.generic.list import (\n    MultipleObjectMixin,\n    MultipleObjectTemplateResponseMixin,\n)\n\nclass BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):\n    \"\"\"\n    Base detail view for a single object on a single date; this differs from\n    the standard DetailView by accepting a year/month/day in the URL.\n\n    This requires subclassing to provide a response mixin.\n    \"\"\"\n\n    def get_object(self, queryset=None):\n        \"\"\"Get the object this request displays.\"\"\"\n        year = self.get_year()\n        month = self.get_month()\n        day = self.get_day()\n        date = _date_from_string(\n            year,\n            self.get_year_format(),\n            month,\n            self.get_month_format(),\n            day,\n            self.get_day_format(),\n        )\n\n        # Use a custom queryset if provided\n        qs = self.get_queryset() if queryset is None else queryset\n\n        if not self.get_allow_future() and date > datetime.date.today():\n            raise Http404(\n                _(\n                    \"Future %(verbose_name_plural)s not available because \"\n                    \"%(class_name)s.allow_future is False.\"\n                )\n                % {\n                    \"verbose_name_plural\": qs.model._meta.verbose_name_plural,\n                    \"class_name\": self.__class__.__name__,\n                }\n            )\n\n        # Filter down a queryset from self.queryset using the date from the\n        # URL. This'll get passed as the queryset to DetailView.get_object,\n        # which'll handle the 404\n        lookup_kwargs = self._make_single_date_lookup(date)\n        qs = qs.filter(**lookup_kwargs)\n\n        return super().get_object(queryset=qs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-5d4513f302b68cd7", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 62, "local_path": "source-original/SRC__django__BaseDateDetailView__533db2e3.py", "order": 0, "original_content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/dates.py#L652-L695", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "BaseDateDetailView", "variant_id": "pyint-ac92533db2e3-SRC", "group_id": "py-5d4513f302b68cd7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 197, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2f6dce5cc0c4-I01", "source": "import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import (\n    BaseDetailView,\n    SingleObjectTemplateResponseMixin,\n)\nfrom django.views.generic.list import (\n    MultipleObjectMixin,\n    MultipleObjectTemplateResponseMixin,\n)\n\nclass BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):\n    \n\n    def get_object(self, queryset=None):\n        \n        year = self.get_year()\n        month = self.get_month()\n        day = self.get_day()\n        date = _date_from_string(\n            year,\n            self.get_year_format(),\n            month,\n            self.get_month_format(),\n            day,\n            self.get_day_format(),\n        )\n\n         \n        qs = self.get_queryset() if queryset is None else queryset\n\n        if not self.get_allow_future() and date > datetime.date.today():\n            raise Http404(\n                _(\n                    \"Future %(verbose_name_plural)s not available because \"\n                    \"%(class_name)s.allow_future is False.\"\n                )\n                % {\n                    \"verbose_name_plural\": qs.model._meta.verbose_name_plural,\n                    \"class_name\": self.__class__.__name__,\n                }\n            )\n\n         \n         \n         \n        lookup_kwargs = self._make_single_date_lookup(date)\n        qs = qs.filter(**lookup_kwargs)\n\n        return super().get_object(queryset=qs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-5d4513f302b68cd7", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "460a6f6d9c6f717195935f1cdc1385851cc8c3bc1de3907bc65eb14c4932f72e", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 57, "local_path": "comments/remove-comments/I01__django__BaseDateDetailView__ce5cc0c4.py", "order": 1, "original_content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "parent_variant_id": "pyint-ac92533db2e3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/dates.py#L652-L695", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 451, "comments_removed": 6, "docstrings_removed": 2, "line_comments_removed": 4}, "unit_kind": "class", "unit_name": "BaseDateDetailView", "variant_id": "pyint-2f6dce5cc0c4-I01", "group_id": "py-5d4513f302b68cd7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 198, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-824ff40ea0ea-I02", "source": "import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import (\n    BaseDetailView,\n    SingleObjectTemplateResponseMixin,\n)\nfrom django.views.generic.list import (\n    MultipleObjectMixin,\n    MultipleObjectTemplateResponseMixin,\n)\n\nclass BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):\n    \"\"\"\n    Base detail view for a single object on a single date; this differs from\n    the standard DetailView by accepting a year/month/day in the URL.\n\n    This requires subclassing to provide a response mixin.\n    \"\"\"\n\n    def get(self, que=None):\n        \"\"\"Get the object this request displays.\"\"\"\n        yea = self.get_year()\n        mon = self.get_month()\n        day2 = self.get_day()\n        dat = _date_from_string(\n            yea,\n            self.get_year_format(),\n            mon,\n            self.get_month_format(),\n            day2,\n            self.get_day_format(),\n        )\n\n        # Use a custom queryset if provided\n        qs2 = self.get_queryset() if que is None else que\n\n        if not self.get_allow_future() and dat > datetime.date.today():\n            raise Http404(\n                _(\n                    \"Future %(verbose_name_plural)s not available because \"\n                    \"%(class_name)s.allow_future is False.\"\n                )\n                % {\n                    \"verbose_name_plural\": qs2.model._meta.verbose_name_plural,\n                    \"class_name\": self.__class__.__name__,\n                }\n            )\n\n        # Filter down a queryset from self.queryset using the date from the\n        # URL. This'll get passed as the queryset to DetailView.get_object,\n        # which'll handle the 404\n        lookup = self._make_single_date_lookup(dat)\n        qs2 = qs2.filter(**lookup)\n\n        return super().get_object(queryset=qs2)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-5d4513f302b68cd7", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "ce49b599ec223afffa20a9edc51b15f326a2d60a45d6dac4314d741ffa8ec34a", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 62, "local_path": "identifiers/shorten-identifiers/I02__django__BaseDateDetailView__f40ea0ea.py", "order": 2, "original_content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "parent_variant_id": "pyint-ac92533db2e3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/dates.py#L652-L695", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 20, "identifiers_declared": 8}, "unit_kind": "class", "unit_name": "BaseDateDetailView", "variant_id": "pyint-824ff40ea0ea-I02", "group_id": "py-5d4513f302b68cd7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 199, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e39ebde5a784-I03", "source": "import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import (\n    BaseDetailView,\n    SingleObjectTemplateResponseMixin,\n)\nfrom django.views.generic.list import (\n    MultipleObjectMixin,\n    MultipleObjectTemplateResponseMixin,\n)\n\nclass BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):\n    \"\"\"\n    Base detail view for a single object on a single date; this differs from\n    the standard DetailView by accepting a year/month/day in the URL.\n\n    This requires subclassing to provide a response mixin.\n    \"\"\"\n\n    def checkState(self, category=None):\n        \"\"\"Get the object this request displays.\"\"\"\n        size = self.get_year()\n        group = self.get_month()\n        age = self.get_day()\n        node = _date_from_string(\n            size,\n            self.get_year_format(),\n            group,\n            self.get_month_format(),\n            age,\n            self.get_day_format(),\n        )\n\n        # Use a custom queryset if provided\n        key = self.get_queryset() if category is None else category\n\n        if not self.get_allow_future() and node > datetime.date.today():\n            raise Http404(\n                _(\n                    \"Future %(verbose_name_plural)s not available because \"\n                    \"%(class_name)s.allow_future is False.\"\n                )\n                % {\n                    \"verbose_name_plural\": key.model._meta.verbose_name_plural,\n                    \"class_name\": self.__class__.__name__,\n                }\n            )\n\n        # Filter down a queryset from self.queryset using the date from the\n        # URL. This'll get passed as the queryset to DetailView.get_object,\n        # which'll handle the 404\n        cachedMessage = self._make_single_date_lookup(node)\n        key = key.filter(**cachedMessage)\n\n        return super().get_object(queryset=key)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-5d4513f302b68cd7", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "8c0e31e7a97fe8ca324dd9394ea3c7a6130536bc1437a1786973570965e5f97e", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 62, "local_path": "identifiers/mislead-identifiers/I03__django__BaseDateDetailView__bde5a784.py", "order": 3, "original_content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "parent_variant_id": "pyint-ac92533db2e3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/dates.py#L652-L695", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 20, "identifiers_declared": 8, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 6, "local_random_pool_selections": 7, "local_total_length_difference": 1, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "BaseDateDetailView", "variant_id": "pyint-e39ebde5a784-I03", "group_id": "py-5d4513f302b68cd7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 200, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-afd4a9c92359-I04", "source": "import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import (\n    BaseDetailView,\n    SingleObjectTemplateResponseMixin,\n)\nfrom django.views.generic.list import (\n    MultipleObjectMixin,\n    MultipleObjectTemplateResponseMixin,\n)\n\nclass BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):\n    \"\"\"\n    Base detail view for a single object on a single date; this differs from\n    the standard DetailView by accepting a year/month/day in the URL.\n\n    This requires subclassing to provide a response mixin.\n    \"\"\"\n\n    def a(self, b=None):\n        \"\"\"Get the object this request displays.\"\"\"\n        c = self.get_year()\n        d = self.get_month()\n        e = self.get_day()\n        f = _date_from_string(\n            c,\n            self.get_year_format(),\n            d,\n            self.get_month_format(),\n            e,\n            self.get_day_format(),\n        )\n\n        # Use a custom queryset if provided\n        g = self.get_queryset() if b is None else b\n\n        if not self.get_allow_future() and f > datetime.date.today():\n            raise Http404(\n                _(\n                    \"Future %(verbose_name_plural)s not available because \"\n                    \"%(class_name)s.allow_future is False.\"\n                )\n                % {\n                    \"verbose_name_plural\": g.model._meta.verbose_name_plural,\n                    \"class_name\": self.__class__.__name__,\n                }\n            )\n\n        # Filter down a queryset from self.queryset using the date from the\n        # URL. This'll get passed as the queryset to DetailView.get_object,\n        # which'll handle the 404\n        h = self._make_single_date_lookup(f)\n        g = g.filter(**h)\n\n        return super().get_object(queryset=g)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-5d4513f302b68cd7", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "6fe80ceab78d67183f4f638f395c3d10d777e01c3e10c860ec9fd21192d6c2ee", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 62, "local_path": "identifiers/garble-identifiers/I04__django__BaseDateDetailView__a9c92359.py", "order": 4, "original_content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "parent_variant_id": "pyint-ac92533db2e3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/dates.py#L652-L695", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 20, "identifiers_declared": 8}, "unit_kind": "class", "unit_name": "BaseDateDetailView", "variant_id": "pyint-afd4a9c92359-I04", "group_id": "py-5d4513f302b68cd7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 201, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c0abd95df7d9-I05", "source": "import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import (\n    BaseDetailView,\n    SingleObjectTemplateResponseMixin,\n)\nfrom django.views.generic.list import (\n    MultipleObjectMixin,\n    MultipleObjectTemplateResponseMixin,\n)\n\nclass BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):\n    \"\"\"\n    Base detail view for a single object on a single date; this differs from\n    the standard DetailView by accepting a year/month/day in the URL.\n\n    This requires subclassing to provide a response mixin.\n    \"\"\"\n\n    def get_object(self, queryset=None):\n        \"\"\"Get the object this request displays.\"\"\"\n        year = self.get_year()\n        month = self.get_month()\n        day = self.get_day()\n        date = _date_from_string(\n            year,\n            self.get_year_format(),\n            month,\n            self.get_month_format(),\n            day,\n            self.get_day_format(),\n        )\n\n        # Use a custom queryset if provided\n        qs = self.get_queryset() if queryset is None else queryset\n\n        if not self.get_allow_future() and date > datetime.date.today():\n            raise Http404(\n                _(\n                    \"Future %(verbose_name_plural)s not available because \"\n                    \"%(class_name)s.allow_future is False.\"\n                )\n                % {\n                    \"verbose_name_plural\": qs.model._meta.verbose_name_plural,\n                    \"class_name\": self.__class__.__name__,\n                }\n            )\n\n        # Filter down a queryset from self.queryset using the date from the\n        # URL. This'll get passed as the queryset to DetailView.get_object,\n        # which'll handle the 404\n        lookup_kwargs = self._make_single_date_lookup(date)\n        qs = qs.filter(**lookup_kwargs)\n\n        return super().get_object(queryset=qs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-5d4513f302b68cd7", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 62, "local_path": "expressions/encode-integer-literals/I05__django__BaseDateDetailView__d95df7d9.py", "order": 5, "original_content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "parent_variant_id": "pyint-ac92533db2e3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/dates.py#L652-L695", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "BaseDateDetailView", "variant_id": "pyint-c0abd95df7d9-I05", "group_id": "py-5d4513f302b68cd7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 202, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c63662bc16d1-I06", "source": "import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import (\n    BaseDetailView,\n    SingleObjectTemplateResponseMixin,\n)\nfrom django.views.generic.list import (\n    MultipleObjectMixin,\n    MultipleObjectTemplateResponseMixin,\n)\n\nclass BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):\n    \"\"\"\n    Base detail view for a single object on a single date; this differs from\n    the standard DetailView by accepting a year/month/day in the URL.\n\n    This requires subclassing to provide a response mixin.\n    \"\"\"\n\n    def get_object(self, queryset=None):\n        \"\"\"Get the object this request displays.\"\"\"\n        year = self.get_year()\n        month = self.get_month()\n        day = self.get_day()\n        date = _date_from_string(\n            year,\n            self.get_year_format(),\n            month,\n            self.get_month_format(),\n            day,\n            self.get_day_format(),\n        )\n\n        # Use a custom queryset if provided\n        qs = self.get_queryset() if queryset is None else queryset\n\n        if not (not self.get_allow_future() and date > datetime.date.today()):\n            pass\n        else:\n            raise Http404(\n                _(\n                    \"Future %(verbose_name_plural)s not available because \"\n                    \"%(class_name)s.allow_future is False.\"\n                )\n                % {\n                    \"verbose_name_plural\": qs.model._meta.verbose_name_plural,\n                    \"class_name\": self.__class__.__name__,\n                }\n            )\n\n        # Filter down a queryset from self.queryset using the date from the\n        # URL. This'll get passed as the queryset to DetailView.get_object,\n        # which'll handle the 404\n        lookup_kwargs = self._make_single_date_lookup(date)\n        qs = qs.filter(**lookup_kwargs)\n\n        return super().get_object(queryset=qs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-5d4513f302b68cd7", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "b4ffcecea43b978b4fbbccf91231733aa1a23e4c53a9017be6b1cff0925b2568", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 64, "local_path": "expressions/invert-conditions/I06__django__BaseDateDetailView__62bc16d1.py", "order": 6, "original_content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "parent_variant_id": "pyint-ac92533db2e3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/dates.py#L652-L695", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "BaseDateDetailView", "variant_id": "pyint-c63662bc16d1-I06", "group_id": "py-5d4513f302b68cd7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 203, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fef123c7b13d-I07", "source": "import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import (\n    BaseDetailView,\n    SingleObjectTemplateResponseMixin,\n)\nfrom django.views.generic.list import (\n    MultipleObjectMixin,\n    MultipleObjectTemplateResponseMixin,\n)\n\nclass BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):\n    \"\"\"\n    Base detail view for a single object on a single date; this differs from\n    the standard DetailView by accepting a year/month/day in the URL.\n\n    This requires subclassing to provide a response mixin.\n    \"\"\"\n\n    def get_object(self, queryset=None):\n        \"\"\"Get the object this request displays.\"\"\"\n        if ((0x27bd ^ 0x27bd) != 0):\n            raise AssertionError()\n        year = self.get_year()\n        month = self.get_month()\n        day = self.get_day()\n        date = _date_from_string(\n            year,\n            self.get_year_format(),\n            month,\n            self.get_month_format(),\n            day,\n            self.get_day_format(),\n        )\n\n        # Use a custom queryset if provided\n        qs = self.get_queryset() if queryset is None else queryset\n\n        if not self.get_allow_future() and date > datetime.date.today():\n            raise Http404(\n                _(\n                    \"Future %(verbose_name_plural)s not available because \"\n                    \"%(class_name)s.allow_future is False.\"\n                )\n                % {\n                    \"verbose_name_plural\": qs.model._meta.verbose_name_plural,\n                    \"class_name\": self.__class__.__name__,\n                }\n            )\n\n        # Filter down a queryset from self.queryset using the date from the\n        # URL. This'll get passed as the queryset to DetailView.get_object,\n        # which'll handle the 404\n        lookup_kwargs = self._make_single_date_lookup(date)\n        qs = qs.filter(**lookup_kwargs)\n\n        return super().get_object(queryset=qs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-5d4513f302b68cd7", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "e7af6d9f52d0642837ab75d1c10842b629b2c866e97fc100ca90e27ff3c8422b", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 64, "local_path": "code-injection/insert-dead-branches/I07__django__BaseDateDetailView__23c7b13d.py", "order": 7, "original_content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "parent_variant_id": "pyint-ac92533db2e3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/dates.py#L652-L695", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "BaseDateDetailView", "variant_id": "pyint-fef123c7b13d-I07", "group_id": "py-5d4513f302b68cd7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 204, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-311378c2f996-I08", "source": "import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import (\n    BaseDetailView,\n    SingleObjectTemplateResponseMixin,\n)\nfrom django.views.generic.list import (\n    MultipleObjectMixin,\n    MultipleObjectTemplateResponseMixin,\n)\n\nclass BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):\n    \"\"\"\n    Base detail view for a single object on a single date; this differs from\n    the standard DetailView by accepting a year/month/day in the URL.\n\n    This requires subclassing to provide a response mixin.\n    \"\"\"\n\n    def get_object(self, queryset=None):\n        \"\"\"Get the object this request displays.\"\"\"\n        running_total = 0\n        for current_number in range(1, 6):\n            running_total += current_number\n        year = self.get_year()\n        month = self.get_month()\n        day = self.get_day()\n        date = _date_from_string(\n            year,\n            self.get_year_format(),\n            month,\n            self.get_month_format(),\n            day,\n            self.get_day_format(),\n        )\n\n        # Use a custom queryset if provided\n        qs = self.get_queryset() if queryset is None else queryset\n\n        if not self.get_allow_future() and date > datetime.date.today():\n            raise Http404(\n                _(\n                    \"Future %(verbose_name_plural)s not available because \"\n                    \"%(class_name)s.allow_future is False.\"\n                )\n                % {\n                    \"verbose_name_plural\": qs.model._meta.verbose_name_plural,\n                    \"class_name\": self.__class__.__name__,\n                }\n            )\n\n        # Filter down a queryset from self.queryset using the date from the\n        # URL. This'll get passed as the queryset to DetailView.get_object,\n        # which'll handle the 404\n        lookup_kwargs = self._make_single_date_lookup(date)\n        qs = qs.filter(**lookup_kwargs)\n\n        return super().get_object(queryset=qs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-5d4513f302b68cd7", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d76b56b5698770f5108a085a916a82c5523f0cea5b080202bec77d7ca96fdf32", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 65, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__BaseDateDetailView__78c2f996.py", "order": 8, "original_content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "parent_variant_id": "pyint-ac92533db2e3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/dates.py#L652-L695", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 0}, "unit_kind": "class", "unit_name": "BaseDateDetailView", "variant_id": "pyint-311378c2f996-I08", "group_id": "py-5d4513f302b68cd7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 205, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-78696aa17bff-I09", "source": "import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import (\n    BaseDetailView,\n    SingleObjectTemplateResponseMixin,\n)\nfrom django.views.generic.list import (\n    MultipleObjectMixin,\n    MultipleObjectTemplateResponseMixin,\n)\n\nclass BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):\n    \"\"\"\n    Base detail view for a single object on a single date; this differs from\n    the standard DetailView by accepting a year/month/day in the URL.\n\n    This requires subclassing to provide a response mixin.\n    \"\"\"\n\n    def get_object(self, queryset=None):\n        \"\"\"Get the object this request displays.\"\"\"\n        lI0O_bbc80b2d = ((0xcf16 ^ 0xcf16) != 0)\n        lI0O_bbc80b2d = not (not lI0O_bbc80b2d)\n        year = self.get_year()\n        month = self.get_month()\n        day = self.get_day()\n        date = _date_from_string(\n            year,\n            self.get_year_format(),\n            month,\n            self.get_month_format(),\n            day,\n            self.get_day_format(),\n        )\n\n        # Use a custom queryset if provided\n        qs = self.get_queryset() if queryset is None else queryset\n\n        if not self.get_allow_future() and date > datetime.date.today():\n            raise Http404(\n                _(\n                    \"Future %(verbose_name_plural)s not available because \"\n                    \"%(class_name)s.allow_future is False.\"\n                )\n                % {\n                    \"verbose_name_plural\": qs.model._meta.verbose_name_plural,\n                    \"class_name\": self.__class__.__name__,\n                }\n            )\n\n        # Filter down a queryset from self.queryset using the date from the\n        # URL. This'll get passed as the queryset to DetailView.get_object,\n        # which'll handle the 404\n        lookup_kwargs = self._make_single_date_lookup(date)\n        qs = qs.filter(**lookup_kwargs)\n\n        return super().get_object(queryset=qs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-5d4513f302b68cd7", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "050e6075663b8427d970294ee87868b044212791c56ca5d917ef2cdf3fd4097e", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 64, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__BaseDateDetailView__6aa17bff.py", "order": 9, "original_content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "parent_variant_id": "pyint-ac92533db2e3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/dates.py#L652-L695", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 4}, "unit_kind": "class", "unit_name": "BaseDateDetailView", "variant_id": "pyint-78696aa17bff-I09", "group_id": "py-5d4513f302b68cd7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 206, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ec6345afcc3b-I10", "source": "import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import (     BaseDetailView,     SingleObjectTemplateResponseMixin, )\nfrom django.views.generic.list import (\n    MultipleObjectMixin,\n    MultipleObjectTemplateResponseMixin, )\n\nclass BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):\n    \"\"\"\n    Base detail view for a single object on a single date; this differs from\n    the standard DetailView by accepting a year/month/day in the URL.\n    This requires subclassing to provide a response mixin.\n    \"\"\"\n\n    def get_object(self, queryset=None):\n        \"\"\"Get the object this request displays.\"\"\"\n        year = self.get_year()\n        month = self.get_month()\n        day = self.get_day()\n        date = _date_from_string(\n            year,\n            self.get_year_format(),\n            month,\n            self.get_month_format(),\n            day,             self.get_day_format(),\n        )\n        # Use a custom queryset if provided\n        qs = self.get_queryset() if queryset is None else queryset\n\n        if not self.get_allow_future() and date > datetime.date.today():\n            raise Http404(\n                _(\n                    \"Future %(verbose_name_plural)s not available because \"\n                    \"%(class_name)s.allow_future is False.\"                 )                 % {                     \"verbose_name_plural\": qs.model._meta.verbose_name_plural,\n                    \"class_name\": self.__class__.__name__,\n                }\n            )\n\n        # Filter down a queryset from self.queryset using the date from the\n        # URL. This'll get passed as the queryset to DetailView.get_object,\n        # which'll handle the 404\n        lookup_kwargs = self._make_single_date_lookup(date)\n        qs = qs.filter(**lookup_kwargs)\n        return super().get_object(queryset=qs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-5d4513f302b68cd7", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "a5db3e3cd342c2c8282d05a2a38517f18ff90bd971c5d36def3a0dbc5051d068", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 51, "local_path": "layout/partially-compact-layout/I10__django__BaseDateDetailView__45afcc3b.py", "order": 10, "original_content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "parent_variant_id": "pyint-ac92533db2e3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/dates.py#L652-L695", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 29, "line_break_groups_removed": 11, "line_breaks_removed": 11, "whitespace_characters_removed": 3}, "unit_kind": "class", "unit_name": "BaseDateDetailView", "variant_id": "pyint-ec6345afcc3b-I10", "group_id": "py-5d4513f302b68cd7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 207, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7842407f842f-I11", "source": "import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import (\n    BaseDetailView,\n    SingleObjectTemplateResponseMixin,\n)\nfrom django.views.generic.list import (\n    MultipleObjectMixin,\n    MultipleObjectTemplateResponseMixin,\n)\n\nclass BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):\n    \"\"\"\n    Base detail view for a single object on a single date; this differs from\n    the standard DetailView by accepting a year/month/day in the URL.\n\n    This requires subclassing to provide a response mixin.\n    \"\"\"\n\n    def get_object(self, queryset=None):\n        \"\"\"Get the object this request displays.\"\"\"\n        year = self.get_year()\n        month = self.get_month()\n        day = self.get_day()\n        date = _date_from_string(\n            year,\n            self.get_year_format(),\n            month,\n            self.get_month_format(),\n            day,\n            self.get_day_format(),\n        )\n\n        # Use a custom queryset if provided\n        qs = self.get_queryset() if queryset is None else queryset\n\n        if not self.get_allow_future() and date > datetime.date.today():\n            raise Http404(\n                _(\n                    \"Future %(verbose_name_plural)s not available because \"\n                    \"%(class_name)s.allow_future is False.\"\n                )\n                % {\n                    \"verbose_name_plural\": qs.model._meta.verbose_name_plural,\n                    \"class_name\": self.__class__.__name__,\n                }\n            )\n\n        # Filter down a queryset from self.queryset using the date from the\n        # URL. This'll get passed as the queryset to DetailView.get_object,\n        # which'll handle the 404\n        lookup_kwargs = self._make_single_date_lookup(date)\n        qs = qs.filter(**lookup_kwargs)\n\n        return super().get_object(queryset=qs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-5d4513f302b68cd7", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 62, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__BaseDateDetailView__407f842f.py", "order": 11, "original_content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "parent_variant_id": "pyint-ac92533db2e3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/dates.py#L652-L695", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "BaseDateDetailView", "variant_id": "pyint-7842407f842f-I11", "group_id": "py-5d4513f302b68cd7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 208, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-28b1c761299c-I12", "source": "import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import (\n    BaseDetailView,\n    SingleObjectTemplateResponseMixin,\n)\nfrom django.views.generic.list import (\n    MultipleObjectMixin,\n    MultipleObjectTemplateResponseMixin,\n)\n\nclass BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):\n    \"\"\"\n    Base detail view for a single object on a single date; this differs from\n    the standard DetailView by accepting a year/month/day in the URL.\n\n    This requires subclassing to provide a response mixin.\n    \"\"\"\n\n    def get_object(self, queryset=None):\n        \"\"\"Get the object this request displays.\"\"\"\n        year = self.get_year()\n        month = self.get_month()\n        day = self.get_day()\n        date = _date_from_string(\n            year,\n            self.get_year_format(),\n            month,\n            self.get_month_format(),\n            day,\n            self.get_day_format(),\n        )\n\n        # Use a custom queryset if provided\n        qs = self.get_queryset() if queryset is None else queryset\n\n        if not self.get_allow_future() and date > datetime.date.today():\n            raise Http404(\n                _(\n                    \"Future %(verbose_name_plural)s not available because \"\n                    \"%(class_name)s.allow_future is False.\"\n                )\n                % {\n                    \"verbose_name_plural\": qs.model._meta.verbose_name_plural,\n                    \"class_name\": self.__class__.__name__,\n                }\n            )\n\n        # Filter down a queryset from self.queryset using the date from the\n        # URL. This'll get passed as the queryset to DetailView.get_object,\n        # which'll handle the 404\n        lookup_kwargs = self._make_single_date_lookup(date)\n        qs = qs.filter(**lookup_kwargs)\n\n        return super().get_object(queryset=qs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-5d4513f302b68cd7", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 62, "local_path": "data-flow/inline-intermediate-variables/I12__django__BaseDateDetailView__c761299c.py", "order": 12, "original_content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "parent_variant_id": "pyint-ac92533db2e3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/dates.py#L652-L695", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "BaseDateDetailView", "variant_id": "pyint-28b1c761299c-I12", "group_id": "py-5d4513f302b68cd7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 209, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a0efaa60fb1f-I13", "source": "import datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext as _\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import (\n    BaseDetailView,\n    SingleObjectTemplateResponseMixin,\n)\nfrom django.views.generic.list import (\n    MultipleObjectMixin,\n    MultipleObjectTemplateResponseMixin,\n)\n\nclass BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):\n    \"\"\"\n    Base detail view for a single object on a single date; this differs from\n    the standard DetailView by accepting a year/month/day in the URL.\n\n    This requires subclassing to provide a response mixin.\n    \"\"\"\n\n    def get_object(self, queryset=None):\n        \"\"\"Get the object this request displays.\"\"\"\n        year = self.get_year()\n        month = self.get_month()\n        day = self.get_day()\n        date = _date_from_string(\n            year,\n            self.get_year_format(),\n            month,\n            self.get_month_format(),\n            day,\n            self.get_day_format(),\n        )\n\n        # Use a custom queryset if provided\n        qs = self.get_queryset() if queryset is None else queryset\n\n        if not self.get_allow_future() and date > datetime.date.today():\n            raise Http404(\n                _(\n                    \"Future %(verbose_name_plural)s not available because \"\n                    \"%(class_name)s.allow_future is False.\"\n                )\n                % {\n                    \"verbose_name_plural\": qs.model._meta.verbose_name_plural,\n                    \"class_name\": self.__class__.__name__,\n                }\n            )\n\n        # Filter down a queryset from self.queryset using the date from the\n        # URL. This'll get passed as the queryset to DetailView.get_object,\n        # which'll handle the 404\n        lookup_kwargs = self._make_single_date_lookup(date)\n        qs = qs.filter(**lookup_kwargs)\n\n        return super().get_object(queryset=qs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-5d4513f302b68cd7", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 62, "local_path": "control-flow/lower-for-to-while/I13__django__BaseDateDetailView__aa60fb1f.py", "order": 13, "original_content_sha256": "bdbf10cdf6a7f2b2c17247b128aa616579375c263c54d076f5b702d55a56fff0", "parent_variant_id": "pyint-ac92533db2e3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/views/generic/dates.py#L652-L695", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "BaseDateDetailView", "variant_id": "pyint-a0efaa60fb1f-I13", "group_id": "py-5d4513f302b68cd7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 210, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-782e6c4aa7fa-SRC", "source": "import operator\nfrom functools import reduce\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import Case, When\nfrom django.db.models.functions import Mod\nfrom django.db.models.lookups import Exact\nfrom django.utils import tree\nfrom django.utils.functional import cached_property\n\nclass ExtraWhere:\n    # The contents are a black box - assume no aggregates or windows are used.\n    contains_aggregate = False\n    contains_over_clause = False\n\n    def __init__(self, sqls, params):\n        self.sqls = sqls\n        self.params = params\n\n    def as_sql(self, compiler=None, connection=None):\n        sqls = [\"(%s)\" % sql for sql in self.sqls]\n        return \" AND \".join(sqls), list(self.params or ())\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-5d73a063b4b60c37", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 21, "local_path": "source-original/SRC__django__ExtraWhere__6c4aa7fa.py", "order": 0, "original_content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/where.py#L334-L345", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "ExtraWhere", "variant_id": "pyint-782e6c4aa7fa-SRC", "group_id": "py-5d73a063b4b60c37", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 309, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-74323d253e10-I01", "source": "import operator\nfrom functools import reduce\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import Case, When\nfrom django.db.models.functions import Mod\nfrom django.db.models.lookups import Exact\nfrom django.utils import tree\nfrom django.utils.functional import cached_property\n\nclass ExtraWhere:\n     \n    contains_aggregate = False\n    contains_over_clause = False\n\n    def __init__(self, sqls, params):\n        self.sqls = sqls\n        self.params = params\n\n    def as_sql(self, compiler=None, connection=None):\n        sqls = [\"(%s)\" % sql for sql in self.sqls]\n        return \" AND \".join(sqls), list(self.params or ())\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-5d73a063b4b60c37", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "7afa936a3529a65417a76a5bd658c1c5b4ca519a032be683beaf7b7097f3cbb9", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 21, "local_path": "comments/remove-comments/I01__django__ExtraWhere__3d253e10.py", "order": 1, "original_content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "parent_variant_id": "pyint-782e6c4aa7fa-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/where.py#L334-L345", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 73, "comments_removed": 1, "docstrings_removed": 0, "line_comments_removed": 1}, "unit_kind": "class", "unit_name": "ExtraWhere", "variant_id": "pyint-74323d253e10-I01", "group_id": "py-5d73a063b4b60c37", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 310, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bc3e1eb17b91-I02", "source": "import operator\nfrom functools import reduce\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import Case, When\nfrom django.db.models.functions import Mod\nfrom django.db.models.lookups import Exact\nfrom django.utils import tree\nfrom django.utils.functional import cached_property\n\nclass ExtraWhere:\n    # The contents are a black box - assume no aggregates or windows are used.\n    contains_aggregate = False\n    contains_over_clause = False\n\n    def __init__(self, sql2, par):\n        self.sqls = sql2\n        self.params = par\n\n    def as2(self, com=None, con=None):\n        sql3 = [\"(%s)\" % sql4 for sql4 in self.sqls]\n        return \" AND \".join(sql3), list(self.params or ())\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-5d73a063b4b60c37", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "56c7988800d65a73f891ef396ca04ed924b8b02ce0bc4ac755132d5589447df0", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 21, "local_path": "identifiers/shorten-identifiers/I02__django__ExtraWhere__1eb17b91.py", "order": 2, "original_content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "parent_variant_id": "pyint-782e6c4aa7fa-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/where.py#L334-L345", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 11, "identifiers_declared": 7}, "unit_kind": "class", "unit_name": "ExtraWhere", "variant_id": "pyint-bc3e1eb17b91-I02", "group_id": "py-5d73a063b4b60c37", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 311, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7bfec4655652-I03", "source": "import operator\nfrom functools import reduce\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import Case, When\nfrom django.db.models.functions import Mod\nfrom django.db.models.lookups import Exact\nfrom django.utils import tree\nfrom django.utils.functional import cached_property\n\nclass ExtraWhere:\n    # The contents are a black box - assume no aggregates or windows are used.\n    contains_aggregate = False\n    contains_over_clause = False\n\n    def __init__(self, data, client):\n        self.sqls = data\n        self.params = client\n\n    def delete(self, localKey=None, finalScore=None):\n        step = [\"(%s)\" % key for key in self.sqls]\n        return \" AND \".join(step), list(self.params or ())\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-5d73a063b4b60c37", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d26c1cc12f08c0ad1dca5c214430f4c79b97f07f04c1f6250a1d6b4fb0ebeae2", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 21, "local_path": "identifiers/mislead-identifiers/I03__django__ExtraWhere__c4655652.py", "order": 3, "original_content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "parent_variant_id": "pyint-782e6c4aa7fa-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/where.py#L334-L345", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 11, "identifiers_declared": 7, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 6, "local_random_pool_selections": 6, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "ExtraWhere", "variant_id": "pyint-7bfec4655652-I03", "group_id": "py-5d73a063b4b60c37", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 312, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ee893cf45aa5-I04", "source": "import operator\nfrom functools import reduce\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import Case, When\nfrom django.db.models.functions import Mod\nfrom django.db.models.lookups import Exact\nfrom django.utils import tree\nfrom django.utils.functional import cached_property\n\nclass ExtraWhere:\n    # The contents are a black box - assume no aggregates or windows are used.\n    contains_aggregate = False\n    contains_over_clause = False\n\n    def __init__(self, b, c):\n        self.sqls = b\n        self.params = c\n\n    def a(self, d=None, e=None):\n        f = [\"(%s)\" % g for g in self.sqls]\n        return \" AND \".join(f), list(self.params or ())\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-5d73a063b4b60c37", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "041a0e527527abae479c94b623b4c77c19a94d0f6f70e304457d6ee748f1410d", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 21, "local_path": "identifiers/garble-identifiers/I04__django__ExtraWhere__3cf45aa5.py", "order": 4, "original_content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "parent_variant_id": "pyint-782e6c4aa7fa-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/where.py#L334-L345", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 11, "identifiers_declared": 7}, "unit_kind": "class", "unit_name": "ExtraWhere", "variant_id": "pyint-ee893cf45aa5-I04", "group_id": "py-5d73a063b4b60c37", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 313, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-794ee150d6a4-I05", "source": "import operator\nfrom functools import reduce\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import Case, When\nfrom django.db.models.functions import Mod\nfrom django.db.models.lookups import Exact\nfrom django.utils import tree\nfrom django.utils.functional import cached_property\n\nclass ExtraWhere:\n    # The contents are a black box - assume no aggregates or windows are used.\n    contains_aggregate = False\n    contains_over_clause = False\n\n    def __init__(self, sqls, params):\n        self.sqls = sqls\n        self.params = params\n\n    def as_sql(self, compiler=None, connection=None):\n        sqls = [\"(%s)\" % sql for sql in self.sqls]\n        return \" AND \".join(sqls), list(self.params or ())\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-5d73a063b4b60c37", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 21, "local_path": "expressions/encode-integer-literals/I05__django__ExtraWhere__e150d6a4.py", "order": 5, "original_content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "parent_variant_id": "pyint-782e6c4aa7fa-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/where.py#L334-L345", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "ExtraWhere", "variant_id": "pyint-794ee150d6a4-I05", "group_id": "py-5d73a063b4b60c37", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 314, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-090fb2fba545-I06", "source": "import operator\nfrom functools import reduce\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import Case, When\nfrom django.db.models.functions import Mod\nfrom django.db.models.lookups import Exact\nfrom django.utils import tree\nfrom django.utils.functional import cached_property\n\nclass ExtraWhere:\n    # The contents are a black box - assume no aggregates or windows are used.\n    contains_aggregate = False\n    contains_over_clause = False\n\n    def __init__(self, sqls, params):\n        self.sqls = sqls\n        self.params = params\n\n    def as_sql(self, compiler=None, connection=None):\n        sqls = [\"(%s)\" % sql for sql in self.sqls]\n        return \" AND \".join(sqls), list(self.params or ())\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-5d73a063b4b60c37", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 21, "local_path": "expressions/invert-conditions/I06__django__ExtraWhere__b2fba545.py", "order": 6, "original_content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "parent_variant_id": "pyint-782e6c4aa7fa-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/where.py#L334-L345", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "ExtraWhere", "variant_id": "pyint-090fb2fba545-I06", "group_id": "py-5d73a063b4b60c37", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 315, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1cb2089bf1ef-I07", "source": "import operator\nfrom functools import reduce\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import Case, When\nfrom django.db.models.functions import Mod\nfrom django.db.models.lookups import Exact\nfrom django.utils import tree\nfrom django.utils.functional import cached_property\n\nclass ExtraWhere:\n    # The contents are a black box - assume no aggregates or windows are used.\n    contains_aggregate = False\n    contains_over_clause = False\n\n    def __init__(self, sqls, params):\n        if ((0x2483 ^ 0x2483) != 0):\n            raise AssertionError()\n        self.sqls = sqls\n        self.params = params\n\n    def as_sql(self, compiler=None, connection=None):\n        if ((0xcdd2 ^ 0xcdd2) != 0):\n            raise AssertionError()\n        sqls = [\"(%s)\" % sql for sql in self.sqls]\n        return \" AND \".join(sqls), list(self.params or ())\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-5d73a063b4b60c37", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "94c56a43646dcfe47a2ee6991e945b2383eb3e94ed3f5b499f61a8d8225d5146", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 25, "local_path": "code-injection/insert-dead-branches/I07__django__ExtraWhere__089bf1ef.py", "order": 7, "original_content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "parent_variant_id": "pyint-782e6c4aa7fa-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/where.py#L334-L345", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "ExtraWhere", "variant_id": "pyint-1cb2089bf1ef-I07", "group_id": "py-5d73a063b4b60c37", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 316, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-402ff3fe566a-I08", "source": "import operator\nfrom functools import reduce\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import Case, When\nfrom django.db.models.functions import Mod\nfrom django.db.models.lookups import Exact\nfrom django.utils import tree\nfrom django.utils.functional import cached_property\n\nclass ExtraWhere:\n    # The contents are a black box - assume no aggregates or windows are used.\n    contains_aggregate = False\n    contains_over_clause = False\n\n    def __init__(self, sqls, params):\n        self.sqls = sqls\n        self.params = params\n\n    def as_sql(self, compiler=None, connection=None):\n        starting_position = 2\n        ending_position = 9\n        travel_distance = ending_position - starting_position\n        if travel_distance < 0:\n            travel_distance = -travel_distance\n        sqls = [\"(%s)\" % sql for sql in self.sqls]\n        return \" AND \".join(sqls), list(self.params or ())\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-5d73a063b4b60c37", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "c2dd55668668e5b898f945d0e0580fbb54a0d223d76caeb88c8c08011289b097", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 26, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__ExtraWhere__f3fe566a.py", "order": 8, "original_content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "parent_variant_id": "pyint-782e6c4aa7fa-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/where.py#L334-L345", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 9}, "unit_kind": "class", "unit_name": "ExtraWhere", "variant_id": "pyint-402ff3fe566a-I08", "group_id": "py-5d73a063b4b60c37", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 317, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7f18b11efffc-I09", "source": "import operator\nfrom functools import reduce\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import Case, When\nfrom django.db.models.functions import Mod\nfrom django.db.models.lookups import Exact\nfrom django.utils import tree\nfrom django.utils.functional import cached_property\n\nclass ExtraWhere:\n    # The contents are a black box - assume no aggregates or windows are used.\n    contains_aggregate = False\n    contains_over_clause = False\n\n    def __init__(self, sqls, params):\n        self.sqls = sqls\n        self.params = params\n\n    def as_sql(self, compiler=None, connection=None):\n        lI0O_8b6b35b4 = 0x1969 - 0x1969\n        lI0O_8b6b35b4 = (lI0O_8b6b35b4 | 0) if lI0O_8b6b35b4 == 0 else (lI0O_8b6b35b4 & 0)\n        sqls = [\"(%s)\" % sql for sql in self.sqls]\n        return \" AND \".join(sqls), list(self.params or ())\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-5d73a063b4b60c37", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "02fa9ca4b82bb5e1b2b04b7498c791d75f83a4ade0250cdb1e667092a3051b24", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 23, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__ExtraWhere__b11efffc.py", "order": 9, "original_content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "parent_variant_id": "pyint-782e6c4aa7fa-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/where.py#L334-L345", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 1}, "unit_kind": "class", "unit_name": "ExtraWhere", "variant_id": "pyint-7f18b11efffc-I09", "group_id": "py-5d73a063b4b60c37", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 318, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-620236e5d668-I10", "source": "import operator\nfrom functools import reduce\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import Case, When\nfrom django.db.models.functions import Mod\nfrom django.db.models.lookups import Exact\nfrom django.utils import tree\nfrom django.utils.functional import cached_property\n\nclass ExtraWhere:\n    # The contents are a black box - assume no aggregates or windows are used.\n    contains_aggregate = False\n    contains_over_clause = False\n    def __init__(self, sqls, params):\n        self.sqls = sqls\n        self.params = params\n\n    def as_sql(self, compiler=None, connection=None):\n        sqls = [\"(%s)\" % sql for sql in self.sqls]\n        return \" AND \".join(sqls), list(self.params or ())\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-5d73a063b4b60c37", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "13ce96187228922679b3748ecf06f105ef18a05fd4d7a0ec70563824029fe436", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 20, "local_path": "layout/partially-compact-layout/I10__django__ExtraWhere__36e5d668.py", "order": 10, "original_content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "parent_variant_id": "pyint-782e6c4aa7fa-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/where.py#L334-L345", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 3, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "ExtraWhere", "variant_id": "pyint-620236e5d668-I10", "group_id": "py-5d73a063b4b60c37", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 319, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2ba8c85c3fb1-I11", "source": "import operator\nfrom functools import reduce\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import Case, When\nfrom django.db.models.functions import Mod\nfrom django.db.models.lookups import Exact\nfrom django.utils import tree\nfrom django.utils.functional import cached_property\n\nclass ExtraWhere:\n    # The contents are a black box - assume no aggregates or windows are used.\n    contains_aggregate = False\n    contains_over_clause = False\n\n    def __init__(self, sqls, params):\n        self.sqls = sqls\n        self.params = params\n\n    def as_sql(self, compiler=None, connection=None):\n        sqls = [\"(%s)\" % sql for sql in self.sqls]\n        return \" AND \".join(sqls), list(self.params or ())\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-5d73a063b4b60c37", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 21, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__ExtraWhere__c85c3fb1.py", "order": 11, "original_content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "parent_variant_id": "pyint-782e6c4aa7fa-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/where.py#L334-L345", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "ExtraWhere", "variant_id": "pyint-2ba8c85c3fb1-I11", "group_id": "py-5d73a063b4b60c37", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 320, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-834df07fd5b0-I12", "source": "import operator\nfrom functools import reduce\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import Case, When\nfrom django.db.models.functions import Mod\nfrom django.db.models.lookups import Exact\nfrom django.utils import tree\nfrom django.utils.functional import cached_property\n\nclass ExtraWhere:\n    # The contents are a black box - assume no aggregates or windows are used.\n    contains_aggregate = False\n    contains_over_clause = False\n\n    def __init__(self, sqls, params):\n        self.sqls = sqls\n        self.params = params\n\n    def as_sql(self, compiler=None, connection=None):\n        \n        return \" AND \".join(([\"(%s)\" % sql for sql in self.sqls])), list(self.params or ())\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-5d73a063b4b60c37", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "3ea65f0983b53f656edee868b6c4e69a601a6d89662f5b63abe7b80dee40491e", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 21, "local_path": "data-flow/inline-intermediate-variables/I12__django__ExtraWhere__f07fd5b0.py", "order": 12, "original_content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "parent_variant_id": "pyint-782e6c4aa7fa-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/where.py#L334-L345", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "ExtraWhere", "variant_id": "pyint-834df07fd5b0-I12", "group_id": "py-5d73a063b4b60c37", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 321, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-06d05ebdd1a5-I13", "source": "import operator\nfrom functools import reduce\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import Case, When\nfrom django.db.models.functions import Mod\nfrom django.db.models.lookups import Exact\nfrom django.utils import tree\nfrom django.utils.functional import cached_property\n\nclass ExtraWhere:\n    # The contents are a black box - assume no aggregates or windows are used.\n    contains_aggregate = False\n    contains_over_clause = False\n\n    def __init__(self, sqls, params):\n        self.sqls = sqls\n        self.params = params\n\n    def as_sql(self, compiler=None, connection=None):\n        sqls = [\"(%s)\" % sql for sql in self.sqls]\n        return \" AND \".join(sqls), list(self.params or ())\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-5d73a063b4b60c37", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 21, "local_path": "control-flow/lower-for-to-while/I13__django__ExtraWhere__5ebdd1a5.py", "order": 13, "original_content_sha256": "9b77bd991a931d363f2ee69371e1997a89cf147860bef1bfd2330810273ec9fc", "parent_variant_id": "pyint-782e6c4aa7fa-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/where.py#L334-L345", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "ExtraWhere", "variant_id": "pyint-06d05ebdd1a5-I13", "group_id": "py-5d73a063b4b60c37", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 322, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e2d436f63449-SRC", "source": "from django.core.exceptions import FieldError, FullResultSet\nfrom django.db.models.expressions import Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n    def as_sql(self):\n        # Prefer the non-standard DELETE FROM syntax over the SQL generated by\n        # the SQLDeleteCompiler's default implementation when multiple tables\n        # are involved since MySQL/MariaDB will generate a more efficient query\n        # plan than when using a subquery.\n        where, having, qualify = self.query.where.split_having_qualify(\n            must_group_by=self.query.group_by is not None\n        )\n        if self.single_alias or having or qualify:\n            # DELETE FROM cannot be used when filtering against aggregates or\n            # window functions as it doesn't allow for GROUP BY/HAVING clauses\n            # and the subquery wrapping (necessary to emulate QUALIFY).\n            return super().as_sql()\n        result = [\"DELETE %s FROM\" % self.quote_name(self.query.get_initial_alias())]\n        from_sql, params = self.get_from_clause()\n        result.extend(from_sql)\n        try:\n            where_sql, where_params = self.compile(where)\n        except FullResultSet:\n            pass\n        else:\n            result.append(\"WHERE %s\" % where_sql)\n            params.extend(where_params)\n        return \" \".join(result), tuple(params)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-5df6b3b965ffc5d9", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 32, "local_path": "source-original/SRC__django__SQLDeleteCompiler__36f63449.py", "order": 0, "original_content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/backends/mysql/compiler.py#L17-L41", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "SQLDeleteCompiler", "variant_id": "pyint-e2d436f63449-SRC", "group_id": "py-5df6b3b965ffc5d9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 211, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-39dfda29486e-I01", "source": "from django.core.exceptions import FieldError, FullResultSet\nfrom django.db.models.expressions import Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n    def as_sql(self):\n         \n         \n         \n         \n        where, having, qualify = self.query.where.split_having_qualify(\n            must_group_by=self.query.group_by is not None\n        )\n        if self.single_alias or having or qualify:\n             \n             \n             \n            return super().as_sql()\n        result = [\"DELETE %s FROM\" % self.quote_name(self.query.get_initial_alias())]\n        from_sql, params = self.get_from_clause()\n        result.extend(from_sql)\n        try:\n            where_sql, where_params = self.compile(where)\n        except FullResultSet:\n            pass\n        else:\n            result.append(\"WHERE %s\" % where_sql)\n            params.extend(where_params)\n        return \" \".join(result), tuple(params)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-5df6b3b965ffc5d9", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "62448c8295ec09f209dba731d8e58d5a0cd8527223b28091e5156e5e0799682f", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 32, "local_path": "comments/remove-comments/I01__django__SQLDeleteCompiler__da29486e.py", "order": 1, "original_content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "parent_variant_id": "pyint-e2d436f63449-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/backends/mysql/compiler.py#L17-L41", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 427, "comments_removed": 7, "docstrings_removed": 0, "line_comments_removed": 7}, "unit_kind": "class", "unit_name": "SQLDeleteCompiler", "variant_id": "pyint-39dfda29486e-I01", "group_id": "py-5df6b3b965ffc5d9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 212, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7d6f64c586d9-I02", "source": "from django.core.exceptions import FieldError, FullResultSet\nfrom django.db.models.expressions import Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n    def as2(self):\n        # Prefer the non-standard DELETE FROM syntax over the SQL generated by\n        # the SQLDeleteCompiler's default implementation when multiple tables\n        # are involved since MySQL/MariaDB will generate a more efficient query\n        # plan than when using a subquery.\n        whe, hav, qua = self.query.where.split_having_qualify(\n            must_group_by=self.query.group_by is not None\n        )\n        if self.single_alias or hav or qua:\n            # DELETE FROM cannot be used when filtering against aggregates or\n            # window functions as it doesn't allow for GROUP BY/HAVING clauses\n            # and the subquery wrapping (necessary to emulate QUALIFY).\n            return super().as_sql()\n        res = [\"DELETE %s FROM\" % self.quote_name(self.query.get_initial_alias())]\n        from2, par = self.get_from_clause()\n        res.extend(from2)\n        try:\n            where2, where3 = self.compile(whe)\n        except FullResultSet:\n            pass\n        else:\n            res.append(\"WHERE %s\" % where2)\n            par.extend(where3)\n        return \" \".join(res), tuple(par)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-5df6b3b965ffc5d9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "0344c137934775aa38ccb7ccb0a6425e8ad2f6343d071ab564a52ed3b93252ca", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 32, "local_path": "identifiers/shorten-identifiers/I02__django__SQLDeleteCompiler__64c586d9.py", "order": 2, "original_content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "parent_variant_id": "pyint-e2d436f63449-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/backends/mysql/compiler.py#L17-L41", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 20, "identifiers_declared": 9}, "unit_kind": "class", "unit_name": "SQLDeleteCompiler", "variant_id": "pyint-7d6f64c586d9-I02", "group_id": "py-5df6b3b965ffc5d9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 213, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-99a4b85217f3-I03", "source": "from django.core.exceptions import FieldError, FullResultSet\nfrom django.db.models.expressions import Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n    def delete(self):\n        # Prefer the non-standard DELETE FROM syntax over the SQL generated by\n        # the SQLDeleteCompiler's default implementation when multiple tables\n        # are involved since MySQL/MariaDB will generate a more efficient query\n        # plan than when using a subquery.\n        token, record, balance = self.query.where.split_having_qualify(\n            must_group_by=self.query.group_by is not None\n        )\n        if self.single_alias or record or balance:\n            # DELETE FROM cannot be used when filtering against aggregates or\n            # window functions as it doesn't allow for GROUP BY/HAVING clauses\n            # and the subquery wrapping (necessary to emulate QUALIFY).\n            return super().as_sql()\n        region = [\"DELETE %s FROM\" % self.quote_name(self.query.get_initial_alias())]\n        duration, source = self.get_from_clause()\n        region.extend(duration)\n        try:\n            localItem, pendingEvent = self.compile(token)\n        except FullResultSet:\n            pass\n        else:\n            region.append(\"WHERE %s\" % localItem)\n            source.extend(pendingEvent)\n        return \" \".join(region), tuple(source)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-5df6b3b965ffc5d9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "5eb6b058f8e7dfa1f17402367586ea8e713ce8df0697f073a06daa75bf5cd46b", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 32, "local_path": "identifiers/mislead-identifiers/I03__django__SQLDeleteCompiler__b85217f3.py", "order": 3, "original_content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "parent_variant_id": "pyint-e2d436f63449-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/backends/mysql/compiler.py#L17-L41", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 20, "identifiers_declared": 9, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 8, "local_random_pool_selections": 8, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "SQLDeleteCompiler", "variant_id": "pyint-99a4b85217f3-I03", "group_id": "py-5df6b3b965ffc5d9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 214, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-283de971a52c-I04", "source": "from django.core.exceptions import FieldError, FullResultSet\nfrom django.db.models.expressions import Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n    def a(self):\n        # Prefer the non-standard DELETE FROM syntax over the SQL generated by\n        # the SQLDeleteCompiler's default implementation when multiple tables\n        # are involved since MySQL/MariaDB will generate a more efficient query\n        # plan than when using a subquery.\n        b, c, d = self.query.where.split_having_qualify(\n            must_group_by=self.query.group_by is not None\n        )\n        if self.single_alias or c or d:\n            # DELETE FROM cannot be used when filtering against aggregates or\n            # window functions as it doesn't allow for GROUP BY/HAVING clauses\n            # and the subquery wrapping (necessary to emulate QUALIFY).\n            return super().as_sql()\n        e = [\"DELETE %s FROM\" % self.quote_name(self.query.get_initial_alias())]\n        f, g = self.get_from_clause()\n        e.extend(f)\n        try:\n            h, i = self.compile(b)\n        except FullResultSet:\n            pass\n        else:\n            e.append(\"WHERE %s\" % h)\n            g.extend(i)\n        return \" \".join(e), tuple(g)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-5df6b3b965ffc5d9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "51546b62fba4fb9c5ef07d4cf0bfd03b29380c5d21b2ac519f28c7e8804fedec", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 32, "local_path": "identifiers/garble-identifiers/I04__django__SQLDeleteCompiler__e971a52c.py", "order": 4, "original_content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "parent_variant_id": "pyint-e2d436f63449-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/backends/mysql/compiler.py#L17-L41", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 20, "identifiers_declared": 9}, "unit_kind": "class", "unit_name": "SQLDeleteCompiler", "variant_id": "pyint-283de971a52c-I04", "group_id": "py-5df6b3b965ffc5d9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 215, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f7d3062cfe8f-I05", "source": "from django.core.exceptions import FieldError, FullResultSet\nfrom django.db.models.expressions import Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n    def as_sql(self):\n        # Prefer the non-standard DELETE FROM syntax over the SQL generated by\n        # the SQLDeleteCompiler's default implementation when multiple tables\n        # are involved since MySQL/MariaDB will generate a more efficient query\n        # plan than when using a subquery.\n        where, having, qualify = self.query.where.split_having_qualify(\n            must_group_by=self.query.group_by is not None\n        )\n        if self.single_alias or having or qualify:\n            # DELETE FROM cannot be used when filtering against aggregates or\n            # window functions as it doesn't allow for GROUP BY/HAVING clauses\n            # and the subquery wrapping (necessary to emulate QUALIFY).\n            return super().as_sql()\n        result = [\"DELETE %s FROM\" % self.quote_name(self.query.get_initial_alias())]\n        from_sql, params = self.get_from_clause()\n        result.extend(from_sql)\n        try:\n            where_sql, where_params = self.compile(where)\n        except FullResultSet:\n            pass\n        else:\n            result.append(\"WHERE %s\" % where_sql)\n            params.extend(where_params)\n        return \" \".join(result), tuple(params)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-5df6b3b965ffc5d9", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 32, "local_path": "expressions/encode-integer-literals/I05__django__SQLDeleteCompiler__062cfe8f.py", "order": 5, "original_content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "parent_variant_id": "pyint-e2d436f63449-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/backends/mysql/compiler.py#L17-L41", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "SQLDeleteCompiler", "variant_id": "pyint-f7d3062cfe8f-I05", "group_id": "py-5df6b3b965ffc5d9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 216, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6f07806793b9-I06", "source": "from django.core.exceptions import FieldError, FullResultSet\nfrom django.db.models.expressions import Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n    def as_sql(self):\n        # Prefer the non-standard DELETE FROM syntax over the SQL generated by\n        # the SQLDeleteCompiler's default implementation when multiple tables\n        # are involved since MySQL/MariaDB will generate a more efficient query\n        # plan than when using a subquery.\n        where, having, qualify = self.query.where.split_having_qualify(\n            must_group_by=self.query.group_by is not None\n        )\n        if not (self.single_alias or having or qualify):\n            pass\n        else:\n            # DELETE FROM cannot be used when filtering against aggregates or\n            # window functions as it doesn't allow for GROUP BY/HAVING clauses\n            # and the subquery wrapping (necessary to emulate QUALIFY).\n            return super().as_sql()\n        result = [\"DELETE %s FROM\" % self.quote_name(self.query.get_initial_alias())]\n        from_sql, params = self.get_from_clause()\n        result.extend(from_sql)\n        try:\n            where_sql, where_params = self.compile(where)\n        except FullResultSet:\n            pass\n        else:\n            result.append(\"WHERE %s\" % where_sql)\n            params.extend(where_params)\n        return \" \".join(result), tuple(params)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-5df6b3b965ffc5d9", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "0c220cee9f4faa6fc2edf9c0c5d624e83ca5d3ff5a3455942e3f4082b65d45a0", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 34, "local_path": "expressions/invert-conditions/I06__django__SQLDeleteCompiler__806793b9.py", "order": 6, "original_content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "parent_variant_id": "pyint-e2d436f63449-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/backends/mysql/compiler.py#L17-L41", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "SQLDeleteCompiler", "variant_id": "pyint-6f07806793b9-I06", "group_id": "py-5df6b3b965ffc5d9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 217, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-938995589b2d-I07", "source": "from django.core.exceptions import FieldError, FullResultSet\nfrom django.db.models.expressions import Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n    def as_sql(self):\n        # Prefer the non-standard DELETE FROM syntax over the SQL generated by\n        # the SQLDeleteCompiler's default implementation when multiple tables\n        # are involved since MySQL/MariaDB will generate a more efficient query\n        # plan than when using a subquery.\n        if ((0x3a14 ^ 0x3a14) != 0):\n            raise AssertionError()\n        where, having, qualify = self.query.where.split_having_qualify(\n            must_group_by=self.query.group_by is not None\n        )\n        if self.single_alias or having or qualify:\n            # DELETE FROM cannot be used when filtering against aggregates or\n            # window functions as it doesn't allow for GROUP BY/HAVING clauses\n            # and the subquery wrapping (necessary to emulate QUALIFY).\n            return super().as_sql()\n        result = [\"DELETE %s FROM\" % self.quote_name(self.query.get_initial_alias())]\n        from_sql, params = self.get_from_clause()\n        result.extend(from_sql)\n        try:\n            where_sql, where_params = self.compile(where)\n        except FullResultSet:\n            pass\n        else:\n            result.append(\"WHERE %s\" % where_sql)\n            params.extend(where_params)\n        return \" \".join(result), tuple(params)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-5df6b3b965ffc5d9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "5a5c1fec284f7189e9909fc6bdb9399b2055ee78e3f874df544902af5beaadcb", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 34, "local_path": "code-injection/insert-dead-branches/I07__django__SQLDeleteCompiler__95589b2d.py", "order": 7, "original_content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "parent_variant_id": "pyint-e2d436f63449-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/backends/mysql/compiler.py#L17-L41", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "SQLDeleteCompiler", "variant_id": "pyint-938995589b2d-I07", "group_id": "py-5df6b3b965ffc5d9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 218, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-71d67d383df4-I08", "source": "from django.core.exceptions import FieldError, FullResultSet\nfrom django.db.models.expressions import Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n    def as_sql(self):\n        # Prefer the non-standard DELETE FROM syntax over the SQL generated by\n        # the SQLDeleteCompiler's default implementation when multiple tables\n        # are involved since MySQL/MariaDB will generate a more efficient query\n        # plan than when using a subquery.\n        running_total = 0\n        for current_number in range(1, 6):\n            running_total += current_number\n        where, having, qualify = self.query.where.split_having_qualify(\n            must_group_by=self.query.group_by is not None\n        )\n        if self.single_alias or having or qualify:\n            # DELETE FROM cannot be used when filtering against aggregates or\n            # window functions as it doesn't allow for GROUP BY/HAVING clauses\n            # and the subquery wrapping (necessary to emulate QUALIFY).\n            return super().as_sql()\n        result = [\"DELETE %s FROM\" % self.quote_name(self.query.get_initial_alias())]\n        from_sql, params = self.get_from_clause()\n        result.extend(from_sql)\n        try:\n            where_sql, where_params = self.compile(where)\n        except FullResultSet:\n            pass\n        else:\n            result.append(\"WHERE %s\" % where_sql)\n            params.extend(where_params)\n        return \" \".join(result), tuple(params)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-5df6b3b965ffc5d9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "266baa229b65f083cd725ec477456ecac55778dc6ec2c1a6a6b78ef978a8de79", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 35, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__SQLDeleteCompiler__7d383df4.py", "order": 8, "original_content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "parent_variant_id": "pyint-e2d436f63449-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/backends/mysql/compiler.py#L17-L41", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 0}, "unit_kind": "class", "unit_name": "SQLDeleteCompiler", "variant_id": "pyint-71d67d383df4-I08", "group_id": "py-5df6b3b965ffc5d9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 219, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b887252c2834-I09", "source": "from django.core.exceptions import FieldError, FullResultSet\nfrom django.db.models.expressions import Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n    def as_sql(self):\n        # Prefer the non-standard DELETE FROM syntax over the SQL generated by\n        # the SQLDeleteCompiler's default implementation when multiple tables\n        # are involved since MySQL/MariaDB will generate a more efficient query\n        # plan than when using a subquery.\n        lI0O_4ccf0fd3 = 0xb4ae\n        lI0O_4ccf0fd3 = ((lI0O_4ccf0fd3 ^ 0xb4ae) | 0) & -1\n        if (lI0O_4ccf0fd3 & 1) == 1:\n            lI0O_4ccf0fd3 ^= lI0O_4ccf0fd3\n        where, having, qualify = self.query.where.split_having_qualify(\n            must_group_by=self.query.group_by is not None\n        )\n        if self.single_alias or having or qualify:\n            # DELETE FROM cannot be used when filtering against aggregates or\n            # window functions as it doesn't allow for GROUP BY/HAVING clauses\n            # and the subquery wrapping (necessary to emulate QUALIFY).\n            return super().as_sql()\n        result = [\"DELETE %s FROM\" % self.quote_name(self.query.get_initial_alias())]\n        from_sql, params = self.get_from_clause()\n        result.extend(from_sql)\n        try:\n            where_sql, where_params = self.compile(where)\n        except FullResultSet:\n            pass\n        else:\n            result.append(\"WHERE %s\" % where_sql)\n            params.extend(where_params)\n        return \" \".join(result), tuple(params)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-5df6b3b965ffc5d9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "5d7cae385bf9a78070c72f39ca1fa716f2ad965b3873794f8be0c53b7360f1e6", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 36, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__SQLDeleteCompiler__252c2834.py", "order": 9, "original_content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "parent_variant_id": "pyint-e2d436f63449-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/backends/mysql/compiler.py#L17-L41", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 0}, "unit_kind": "class", "unit_name": "SQLDeleteCompiler", "variant_id": "pyint-b887252c2834-I09", "group_id": "py-5df6b3b965ffc5d9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 220, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fc2df7c20a74-I10", "source": "from django.core.exceptions import FieldError, FullResultSet\nfrom django.db.models.expressions import Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n    def as_sql(self):\n        # Prefer the non-standard DELETE FROM syntax over the SQL generated by\n        # the SQLDeleteCompiler's default implementation when multiple tables\n        # are involved since MySQL/MariaDB will generate a more efficient query\n        # plan than when using a subquery.\n        where, having, qualify = self.query.where.split_having_qualify(             must_group_by=self.query.group_by is not None\n        )\n        if self.single_alias or having or qualify:\n            # DELETE FROM cannot be used when filtering against aggregates or\n            # window functions as it doesn't allow for GROUP BY/HAVING clauses\n            # and the subquery wrapping (necessary to emulate QUALIFY).\n            return super().as_sql()\n        result = [\"DELETE %s FROM\" % self.quote_name(self.query.get_initial_alias())]\n        from_sql, params = self.get_from_clause()\n        result.extend(from_sql)\n        try:\n            where_sql, where_params = self.compile(where)\n        except FullResultSet:\n            pass\n        else:\n            result.append(\"WHERE %s\" % where_sql)\n            params.extend(where_params)\n        return \" \".join(result), tuple(params)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-5df6b3b965ffc5d9", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "2bed792df5bc56be5a6ffddf3220f054a618fbd246e5461bfc697fbea36b35ce", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 31, "local_path": "layout/partially-compact-layout/I10__django__SQLDeleteCompiler__f7c20a74.py", "order": 10, "original_content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "parent_variant_id": "pyint-e2d436f63449-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/backends/mysql/compiler.py#L17-L41", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 3, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "SQLDeleteCompiler", "variant_id": "pyint-fc2df7c20a74-I10", "group_id": "py-5df6b3b965ffc5d9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 221, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a5a716bb4dfc-I11", "source": "from django.core.exceptions import FieldError, FullResultSet\nfrom django.db.models.expressions import Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n    def as_sql(self):\n        # Prefer the non-standard DELETE FROM syntax over the SQL generated by\n        # the SQLDeleteCompiler's default implementation when multiple tables\n        # are involved since MySQL/MariaDB will generate a more efficient query\n        # plan than when using a subquery.\n        where, having, qualify = self.query.where.split_having_qualify(\n            must_group_by=self.query.group_by is not None\n        )\n        if self.single_alias or having or qualify:\n            # DELETE FROM cannot be used when filtering against aggregates or\n            # window functions as it doesn't allow for GROUP BY/HAVING clauses\n            # and the subquery wrapping (necessary to emulate QUALIFY).\n            return super().as_sql()\n        result = [\"DELETE %s FROM\" % self.quote_name(self.query.get_initial_alias())]\n        from_sql, params = self.get_from_clause()\n        result.extend(from_sql)\n        try:\n            where_sql, where_params = self.compile(where)\n        except FullResultSet:\n            pass\n        else:\n            result.append(\"WHERE %s\" % where_sql)\n            params.extend(where_params)\n        return \" \".join(result), tuple(params)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-5df6b3b965ffc5d9", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 32, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__SQLDeleteCompiler__16bb4dfc.py", "order": 11, "original_content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "parent_variant_id": "pyint-e2d436f63449-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/backends/mysql/compiler.py#L17-L41", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "SQLDeleteCompiler", "variant_id": "pyint-a5a716bb4dfc-I11", "group_id": "py-5df6b3b965ffc5d9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 222, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4a3b6c2c9df5-I12", "source": "from django.core.exceptions import FieldError, FullResultSet\nfrom django.db.models.expressions import Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n    def as_sql(self):\n        # Prefer the non-standard DELETE FROM syntax over the SQL generated by\n        # the SQLDeleteCompiler's default implementation when multiple tables\n        # are involved since MySQL/MariaDB will generate a more efficient query\n        # plan than when using a subquery.\n        where, having, qualify = self.query.where.split_having_qualify(\n            must_group_by=self.query.group_by is not None\n        )\n        if self.single_alias or having or qualify:\n            # DELETE FROM cannot be used when filtering against aggregates or\n            # window functions as it doesn't allow for GROUP BY/HAVING clauses\n            # and the subquery wrapping (necessary to emulate QUALIFY).\n            return super().as_sql()\n        result = [\"DELETE %s FROM\" % self.quote_name(self.query.get_initial_alias())]\n        from_sql, params = self.get_from_clause()\n        result.extend(from_sql)\n        try:\n            where_sql, where_params = self.compile(where)\n        except FullResultSet:\n            pass\n        else:\n            result.append(\"WHERE %s\" % where_sql)\n            params.extend(where_params)\n        return \" \".join(result), tuple(params)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-5df6b3b965ffc5d9", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 32, "local_path": "data-flow/inline-intermediate-variables/I12__django__SQLDeleteCompiler__6c2c9df5.py", "order": 12, "original_content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "parent_variant_id": "pyint-e2d436f63449-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/backends/mysql/compiler.py#L17-L41", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "SQLDeleteCompiler", "variant_id": "pyint-4a3b6c2c9df5-I12", "group_id": "py-5df6b3b965ffc5d9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 223, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-abf79745baba-I13", "source": "from django.core.exceptions import FieldError, FullResultSet\nfrom django.db.models.expressions import Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n    def as_sql(self):\n        # Prefer the non-standard DELETE FROM syntax over the SQL generated by\n        # the SQLDeleteCompiler's default implementation when multiple tables\n        # are involved since MySQL/MariaDB will generate a more efficient query\n        # plan than when using a subquery.\n        where, having, qualify = self.query.where.split_having_qualify(\n            must_group_by=self.query.group_by is not None\n        )\n        if self.single_alias or having or qualify:\n            # DELETE FROM cannot be used when filtering against aggregates or\n            # window functions as it doesn't allow for GROUP BY/HAVING clauses\n            # and the subquery wrapping (necessary to emulate QUALIFY).\n            return super().as_sql()\n        result = [\"DELETE %s FROM\" % self.quote_name(self.query.get_initial_alias())]\n        from_sql, params = self.get_from_clause()\n        result.extend(from_sql)\n        try:\n            where_sql, where_params = self.compile(where)\n        except FullResultSet:\n            pass\n        else:\n            result.append(\"WHERE %s\" % where_sql)\n            params.extend(where_params)\n        return \" \".join(result), tuple(params)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-5df6b3b965ffc5d9", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 32, "local_path": "control-flow/lower-for-to-while/I13__django__SQLDeleteCompiler__9745baba.py", "order": 13, "original_content_sha256": "4d096d543b997af08d9a4205b3013b07b81b6f0e7f7b05bf41ab390b358a3451", "parent_variant_id": "pyint-e2d436f63449-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/backends/mysql/compiler.py#L17-L41", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "SQLDeleteCompiler", "variant_id": "pyint-abf79745baba-I13", "group_id": "py-5df6b3b965ffc5d9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 224, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-319b85ef565e-SRC", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CacheHashWrapper(int):\n    \"\"\"\n    An integer subclass that pickles / copies as None\n\n    This is used for non-slots classes with ``cache_hash=True``, to avoid\n    serializing a potentially (even likely) invalid hash value. Since `None`\n    is the default value for uncalculated hashes, whenever this is copied,\n    the copy's value for the hash should automatically reset.\n\n    See GH #613 for more details.\n    \"\"\"\n\n    def __reduce__(self, _none_constructor=type(None), _args=()):  # noqa: B008\n        return _none_constructor, _args\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-620e79c3dad34bdf", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 43, "local_path": "source-original/SRC__attrs___CacheHashWrapper__85ef565e.py", "order": 0, "original_content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L88-L101", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_CacheHashWrapper", "variant_id": "pyint-319b85ef565e-SRC", "group_id": "py-620e79c3dad34bdf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1219, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-81501ca82fb1-I01", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CacheHashWrapper(int):\n    \n\n    def __reduce__(self, _none_constructor=type(None), _args=()):   \n        return _none_constructor, _args\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-620e79c3dad34bdf", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "78872e117b9519ab66c3b8aae938d94c6e5ea77f57266c603d2c22ca94015c22", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 34, "local_path": "comments/remove-comments/I01__attrs___CacheHashWrapper__1ca82fb1.py", "order": 1, "original_content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "parent_variant_id": "pyint-319b85ef565e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L88-L101", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 400, "comments_removed": 2, "docstrings_removed": 1, "line_comments_removed": 1}, "unit_kind": "class", "unit_name": "_CacheHashWrapper", "variant_id": "pyint-81501ca82fb1-I01", "group_id": "py-620e79c3dad34bdf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1220, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a92946dff6b4-I02", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CacheHashWrapper(int):\n    \"\"\"\n    An integer subclass that pickles / copies as None\n\n    This is used for non-slots classes with ``cache_hash=True``, to avoid\n    serializing a potentially (even likely) invalid hash value. Since `None`\n    is the default value for uncalculated hashes, whenever this is copied,\n    the copy's value for the hash should automatically reset.\n\n    See GH #613 for more details.\n    \"\"\"\n\n    def __reduce__(self, none=type(None), arg=()):  # noqa: B008\n        return none, arg\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-620e79c3dad34bdf", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "3e33a270b7f48317fa689fdb1743ee44549bab3256f9449eb730d5804d452a46", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 43, "local_path": "identifiers/shorten-identifiers/I02__attrs___CacheHashWrapper__46dff6b4.py", "order": 2, "original_content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "parent_variant_id": "pyint-319b85ef565e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L88-L101", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 4, "identifiers_declared": 2}, "unit_kind": "class", "unit_name": "_CacheHashWrapper", "variant_id": "pyint-a92946dff6b4-I02", "group_id": "py-620e79c3dad34bdf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1221, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-53b9f6091a29-I03", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CacheHashWrapper(int):\n    \"\"\"\n    An integer subclass that pickles / copies as None\n\n    This is used for non-slots classes with ``cache_hash=True``, to avoid\n    serializing a potentially (even likely) invalid hash value. Since `None`\n    is the default value for uncalculated hashes, whenever this is copied,\n    the copy's value for the hash should automatically reset.\n\n    See GH #613 for more details.\n    \"\"\"\n\n    def __reduce__(self, currentBalance=type(None), total=()):  # noqa: B008\n        return currentBalance, total\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-620e79c3dad34bdf", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "89bad0e88645d9d253006494bf41ca930f448e78a75c751f27bcd98bb56897f1", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 43, "local_path": "identifiers/mislead-identifiers/I03__attrs___CacheHashWrapper__f6091a29.py", "order": 3, "original_content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "parent_variant_id": "pyint-319b85ef565e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L88-L101", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 4, "identifiers_declared": 2, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 1, "local_random_pool_selections": 2, "local_total_length_difference": 3, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_CacheHashWrapper", "variant_id": "pyint-53b9f6091a29-I03", "group_id": "py-620e79c3dad34bdf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1222, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-66f8adc13010-I04", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CacheHashWrapper(int):\n    \"\"\"\n    An integer subclass that pickles / copies as None\n\n    This is used for non-slots classes with ``cache_hash=True``, to avoid\n    serializing a potentially (even likely) invalid hash value. Since `None`\n    is the default value for uncalculated hashes, whenever this is copied,\n    the copy's value for the hash should automatically reset.\n\n    See GH #613 for more details.\n    \"\"\"\n\n    def __reduce__(self, a=type(None), b=()):  # noqa: B008\n        return a, b\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-620e79c3dad34bdf", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "1fd77c306591415cab97f0f2066bb18ce1000d3e762b133c35c04c59aa8cc243", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 43, "local_path": "identifiers/garble-identifiers/I04__attrs___CacheHashWrapper__adc13010.py", "order": 4, "original_content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "parent_variant_id": "pyint-319b85ef565e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L88-L101", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 4, "identifiers_declared": 2}, "unit_kind": "class", "unit_name": "_CacheHashWrapper", "variant_id": "pyint-66f8adc13010-I04", "group_id": "py-620e79c3dad34bdf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1223, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1815010b9f6e-I05", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CacheHashWrapper(int):\n    \"\"\"\n    An integer subclass that pickles / copies as None\n\n    This is used for non-slots classes with ``cache_hash=True``, to avoid\n    serializing a potentially (even likely) invalid hash value. Since `None`\n    is the default value for uncalculated hashes, whenever this is copied,\n    the copy's value for the hash should automatically reset.\n\n    See GH #613 for more details.\n    \"\"\"\n\n    def __reduce__(self, _none_constructor=type(None), _args=()):  # noqa: B008\n        return _none_constructor, _args\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-620e79c3dad34bdf", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 43, "local_path": "expressions/encode-integer-literals/I05__attrs___CacheHashWrapper__010b9f6e.py", "order": 5, "original_content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "parent_variant_id": "pyint-319b85ef565e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L88-L101", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "_CacheHashWrapper", "variant_id": "pyint-1815010b9f6e-I05", "group_id": "py-620e79c3dad34bdf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1224, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-36c89db0093e-I06", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CacheHashWrapper(int):\n    \"\"\"\n    An integer subclass that pickles / copies as None\n\n    This is used for non-slots classes with ``cache_hash=True``, to avoid\n    serializing a potentially (even likely) invalid hash value. Since `None`\n    is the default value for uncalculated hashes, whenever this is copied,\n    the copy's value for the hash should automatically reset.\n\n    See GH #613 for more details.\n    \"\"\"\n\n    def __reduce__(self, _none_constructor=type(None), _args=()):  # noqa: B008\n        return _none_constructor, _args\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-620e79c3dad34bdf", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 43, "local_path": "expressions/invert-conditions/I06__attrs___CacheHashWrapper__9db0093e.py", "order": 6, "original_content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "parent_variant_id": "pyint-319b85ef565e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L88-L101", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "_CacheHashWrapper", "variant_id": "pyint-36c89db0093e-I06", "group_id": "py-620e79c3dad34bdf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1225, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bbd4e862dcb2-I07", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CacheHashWrapper(int):\n    \"\"\"\n    An integer subclass that pickles / copies as None\n\n    This is used for non-slots classes with ``cache_hash=True``, to avoid\n    serializing a potentially (even likely) invalid hash value. Since `None`\n    is the default value for uncalculated hashes, whenever this is copied,\n    the copy's value for the hash should automatically reset.\n\n    See GH #613 for more details.\n    \"\"\"\n\n    def __reduce__(self, _none_constructor=type(None), _args=()):  # noqa: B008\n        if ((0x8980 ^ 0x8980) != 0):\n            raise AssertionError()\n        return _none_constructor, _args\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-620e79c3dad34bdf", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "1b08372ca78fe13003d144b7034fa446fabb116dada2235b496cc2bb18f63796", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 45, "local_path": "code-injection/insert-dead-branches/I07__attrs___CacheHashWrapper__e862dcb2.py", "order": 7, "original_content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "parent_variant_id": "pyint-319b85ef565e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L88-L101", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "_CacheHashWrapper", "variant_id": "pyint-bbd4e862dcb2-I07", "group_id": "py-620e79c3dad34bdf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1226, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-85feaa2e947f-I08", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CacheHashWrapper(int):\n    \"\"\"\n    An integer subclass that pickles / copies as None\n\n    This is used for non-slots classes with ``cache_hash=True``, to avoid\n    serializing a potentially (even likely) invalid hash value. Since `None`\n    is the default value for uncalculated hashes, whenever this is copied,\n    the copy's value for the hash should automatically reset.\n\n    See GH #613 for more details.\n    \"\"\"\n\n    def __reduce__(self, _none_constructor=type(None), _args=()):  # noqa: B008\n        remaining_steps = 3\n        while remaining_steps > 0:\n            remaining_steps -= 1\n        return _none_constructor, _args\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-620e79c3dad34bdf", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d2f06aa081ff5841ebf9daaea558a05b7acf79bbc26164c9c8d7087c87e56079", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 46, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___CacheHashWrapper__aa2e947f.py", "order": 8, "original_content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "parent_variant_id": "pyint-319b85ef565e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L88-L101", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 1}, "unit_kind": "class", "unit_name": "_CacheHashWrapper", "variant_id": "pyint-85feaa2e947f-I08", "group_id": "py-620e79c3dad34bdf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1227, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-95ce755ecec0-I09", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CacheHashWrapper(int):\n    \"\"\"\n    An integer subclass that pickles / copies as None\n\n    This is used for non-slots classes with ``cache_hash=True``, to avoid\n    serializing a potentially (even likely) invalid hash value. Since `None`\n    is the default value for uncalculated hashes, whenever this is copied,\n    the copy's value for the hash should automatically reset.\n\n    See GH #613 for more details.\n    \"\"\"\n\n    def __reduce__(self, _none_constructor=type(None), _args=()):  # noqa: B008\n        lI0O_2bb68748 = 0xf664\n        lI0O_2bb68748 = (lI0O_2bb68748 << 1) ^ (lI0O_2bb68748 >> 1)\n        lI0O_2bb68748 &= 0\n        return _none_constructor, _args\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-620e79c3dad34bdf", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "fba53f06a5697809477cd7fc0ac5dc2c87ba3b06cac4fff8c5674d7df05a47c3", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 46, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___CacheHashWrapper__755ecec0.py", "order": 9, "original_content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "parent_variant_id": "pyint-319b85ef565e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L88-L101", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 3}, "unit_kind": "class", "unit_name": "_CacheHashWrapper", "variant_id": "pyint-95ce755ecec0-I09", "group_id": "py-620e79c3dad34bdf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1228, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8cd6b583ed10-I10", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,     PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,     get_generic_base,\n)\nfrom .exceptions import (     DefaultAlreadySetError,\n    FrozenInstanceError,     NotAnAttrsClassError,\n    UnannotatedAttributeError, )\n\nclass _CacheHashWrapper(int):\n    \"\"\"\n    An integer subclass that pickles / copies as None\n\n    This is used for non-slots classes with ``cache_hash=True``, to avoid\n    serializing a potentially (even likely) invalid hash value. Since `None`\n    is the default value for uncalculated hashes, whenever this is copied,\n    the copy's value for the hash should automatically reset.\n    See GH #613 for more details.\n    \"\"\"\n\n    def __reduce__(self, _none_constructor=type(None), _args=()):  # noqa: B008\n        return _none_constructor, _args\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-620e79c3dad34bdf", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "dd67ee6dc2fb5114ecbf9e2cbd20c14311226a19d975fbbcda276a594348e320", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 37, "local_path": "layout/partially-compact-layout/I10__attrs___CacheHashWrapper__b583ed10.py", "order": 10, "original_content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "parent_variant_id": "pyint-319b85ef565e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L88-L101", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 16, "line_break_groups_removed": 6, "line_breaks_removed": 6, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "_CacheHashWrapper", "variant_id": "pyint-8cd6b583ed10-I10", "group_id": "py-620e79c3dad34bdf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1229, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b98456e13625-I11", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CacheHashWrapper(int):\n    \"\"\"\n    An integer subclass that pickles / copies as None\n\n    This is used for non-slots classes with ``cache_hash=True``, to avoid\n    serializing a potentially (even likely) invalid hash value. Since `None`\n    is the default value for uncalculated hashes, whenever this is copied,\n    the copy's value for the hash should automatically reset.\n\n    See GH #613 for more details.\n    \"\"\"\n\n    def __reduce__(self, _none_constructor=type(None), _args=()):  # noqa: B008\n        return _none_constructor, _args\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-620e79c3dad34bdf", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 43, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___CacheHashWrapper__56e13625.py", "order": 11, "original_content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "parent_variant_id": "pyint-319b85ef565e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L88-L101", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "_CacheHashWrapper", "variant_id": "pyint-b98456e13625-I11", "group_id": "py-620e79c3dad34bdf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1230, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cab027c123cf-I12", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CacheHashWrapper(int):\n    \"\"\"\n    An integer subclass that pickles / copies as None\n\n    This is used for non-slots classes with ``cache_hash=True``, to avoid\n    serializing a potentially (even likely) invalid hash value. Since `None`\n    is the default value for uncalculated hashes, whenever this is copied,\n    the copy's value for the hash should automatically reset.\n\n    See GH #613 for more details.\n    \"\"\"\n\n    def __reduce__(self, _none_constructor=type(None), _args=()):  # noqa: B008\n        return _none_constructor, _args\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-620e79c3dad34bdf", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 43, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___CacheHashWrapper__27c123cf.py", "order": 12, "original_content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "parent_variant_id": "pyint-319b85ef565e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L88-L101", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_CacheHashWrapper", "variant_id": "pyint-cab027c123cf-I12", "group_id": "py-620e79c3dad34bdf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1231, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-947b12771942-I13", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CacheHashWrapper(int):\n    \"\"\"\n    An integer subclass that pickles / copies as None\n\n    This is used for non-slots classes with ``cache_hash=True``, to avoid\n    serializing a potentially (even likely) invalid hash value. Since `None`\n    is the default value for uncalculated hashes, whenever this is copied,\n    the copy's value for the hash should automatically reset.\n\n    See GH #613 for more details.\n    \"\"\"\n\n    def __reduce__(self, _none_constructor=type(None), _args=()):  # noqa: B008\n        return _none_constructor, _args\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-620e79c3dad34bdf", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 43, "local_path": "control-flow/lower-for-to-while/I13__attrs___CacheHashWrapper__12771942.py", "order": 13, "original_content_sha256": "98f8720c9ebf5725a5e2e8824e213a24e63da365182490d88da6eb96ea6b94f2", "parent_variant_id": "pyint-319b85ef565e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L88-L101", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "_CacheHashWrapper", "variant_id": "pyint-947b12771942-I13", "group_id": "py-620e79c3dad34bdf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1232, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c3d5b0857a14-SRC", "source": "from __future__ import annotations\nimport copy\nimport re\nimport sys\nfrom typing import Any\nimport attrs\n\n@attrs.define(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-6283dd31af1c7c8d", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 13, "local_path": "source-original/SRC__attrs__AutoDetect__b0857a14.py", "order": 0, "original_content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/pyrefly.py#L341-L345", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-c3d5b0857a14-SRC", "group_id": "py-6283dd31af1c7c8d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1317, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-78c589572b16-I01", "source": "from __future__ import annotations\nimport copy\nimport re\nimport sys\nfrom typing import Any\nimport attrs\n\n@attrs.define(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-6283dd31af1c7c8d", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 13, "local_path": "comments/remove-comments/I01__attrs__AutoDetect__89572b16.py", "order": 1, "original_content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "parent_variant_id": "pyint-c3d5b0857a14-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/pyrefly.py#L341-L345", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-78c589572b16-I01", "group_id": "py-6283dd31af1c7c8d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1318, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1c00ffbdb396-I02", "source": "from __future__ import annotations\nimport copy\nimport re\nimport sys\nfrom typing import Any\nimport attrs\n\n@attrs.define(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x2: int):\n        self.x = x2\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-6283dd31af1c7c8d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b0903aaebc4fedf8ef8a2011613dab4d540588287e08703afcaa8a3fa0077658", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 13, "local_path": "identifiers/shorten-identifiers/I02__attrs__AutoDetect__ffbdb396.py", "order": 2, "original_content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "parent_variant_id": "pyint-c3d5b0857a14-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/pyrefly.py#L341-L345", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-1c00ffbdb396-I02", "group_id": "py-6283dd31af1c7c8d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1319, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a4bbf4dd8029-I03", "source": "from __future__ import annotations\nimport copy\nimport re\nimport sys\nfrom typing import Any\nimport attrs\n\n@attrs.define(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, age: int):\n        self.x = age\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-6283dd31af1c7c8d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "0d83adda287126f6e303ac9b2d6509a9f40fe955c1dcdb0548d7838f219c7a7d", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 13, "local_path": "identifiers/mislead-identifiers/I03__attrs__AutoDetect__f4dd8029.py", "order": 3, "original_content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "parent_variant_id": "pyint-c3d5b0857a14-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/pyrefly.py#L341-L345", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2, "identifiers_declared": 1, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 0, "local_random_pool_selections": 1, "local_total_length_difference": 2, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-a4bbf4dd8029-I03", "group_id": "py-6283dd31af1c7c8d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1320, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-af7e2b1da101-I04", "source": "from __future__ import annotations\nimport copy\nimport re\nimport sys\nfrom typing import Any\nimport attrs\n\n@attrs.define(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, a: int):\n        self.x = a\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-6283dd31af1c7c8d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "f94829d2a33eff6625ab24216ef0cc6496ee3ca7aebd42dde822cbbb4548dbc2", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 13, "local_path": "identifiers/garble-identifiers/I04__attrs__AutoDetect__2b1da101.py", "order": 4, "original_content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "parent_variant_id": "pyint-c3d5b0857a14-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/pyrefly.py#L341-L345", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-af7e2b1da101-I04", "group_id": "py-6283dd31af1c7c8d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1321, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-932b332fbe23-I05", "source": "from __future__ import annotations\nimport copy\nimport re\nimport sys\nfrom typing import Any\nimport attrs\n\n@attrs.define(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-6283dd31af1c7c8d", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 13, "local_path": "expressions/encode-integer-literals/I05__attrs__AutoDetect__332fbe23.py", "order": 5, "original_content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "parent_variant_id": "pyint-c3d5b0857a14-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/pyrefly.py#L341-L345", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-932b332fbe23-I05", "group_id": "py-6283dd31af1c7c8d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1322, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ac2d553ca8df-I06", "source": "from __future__ import annotations\nimport copy\nimport re\nimport sys\nfrom typing import Any\nimport attrs\n\n@attrs.define(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-6283dd31af1c7c8d", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 13, "local_path": "expressions/invert-conditions/I06__attrs__AutoDetect__553ca8df.py", "order": 6, "original_content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "parent_variant_id": "pyint-c3d5b0857a14-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/pyrefly.py#L341-L345", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-ac2d553ca8df-I06", "group_id": "py-6283dd31af1c7c8d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1323, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9d36d927e815-I07", "source": "from __future__ import annotations\nimport copy\nimport re\nimport sys\nfrom typing import Any\nimport attrs\n\n@attrs.define(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        if ((0x7e6c ^ 0x7e6c) != 0):\n            raise AssertionError()\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-6283dd31af1c7c8d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "36a8ce3e6f1a6ce3a7cdb84cbd1736e25d927e2c4e83a7bcbeaf25952cb7dc4a", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 15, "local_path": "code-injection/insert-dead-branches/I07__attrs__AutoDetect__d927e815.py", "order": 7, "original_content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "parent_variant_id": "pyint-c3d5b0857a14-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/pyrefly.py#L341-L345", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-9d36d927e815-I07", "group_id": "py-6283dd31af1c7c8d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1324, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8e5d1ebbc6f3-I08", "source": "from __future__ import annotations\nimport copy\nimport re\nimport sys\nfrom typing import Any\nimport attrs\n\n@attrs.define(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        previous_number = 0\n        current_number = 1\n        for sequence_step in range(4):\n            next_number = previous_number + current_number\n            previous_number = current_number\n            current_number = next_number\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-6283dd31af1c7c8d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "a7f74715d2a3aca3cba3ad00dfb90013b69e9ab27c3b39e01bbc6eef18fa84a6", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 19, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs__AutoDetect__1ebbc6f3.py", "order": 8, "original_content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "parent_variant_id": "pyint-c3d5b0857a14-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/pyrefly.py#L341-L345", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 8}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-8e5d1ebbc6f3-I08", "group_id": "py-6283dd31af1c7c8d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1325, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3c6f798ff544-I09", "source": "from __future__ import annotations\nimport copy\nimport re\nimport sys\nfrom typing import Any\nimport attrs\n\n@attrs.define(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        lI0O_393a05ef, lI0O_07d7d152 = 0x786f, True\n        while lI0O_07d7d152:\n            lI0O_393a05ef ^= 0x786f\n            lI0O_07d7d152 = False\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-6283dd31af1c7c8d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "fd1f97f2d5368ee061ec95805cd00ec812dca57aa3d493d6fe85e7838d13c1ce", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 17, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs__AutoDetect__798ff544.py", "order": 9, "original_content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "parent_variant_id": "pyint-c3d5b0857a14-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/pyrefly.py#L341-L345", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 7}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-3c6f798ff544-I09", "group_id": "py-6283dd31af1c7c8d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1326, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c2c9ead16622-I10", "source": "from __future__ import annotations\nimport copy\nimport re\nimport sys\nfrom typing import Any\nimport attrs\n\n@attrs.define(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-6283dd31af1c7c8d", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 13, "local_path": "layout/partially-compact-layout/I10__attrs__AutoDetect__ead16622.py", "order": 10, "original_content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "parent_variant_id": "pyint-c3d5b0857a14-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/pyrefly.py#L341-L345", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 2, "line_break_groups_removed": 0, "line_breaks_removed": 0, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-c2c9ead16622-I10", "group_id": "py-6283dd31af1c7c8d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1327, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5aa9a9be5a4d-I11", "source": "from __future__ import annotations\nimport copy\nimport re\nimport sys\nfrom typing import Any\nimport attrs\n\n@attrs.define(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-6283dd31af1c7c8d", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 13, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs__AutoDetect__a9be5a4d.py", "order": 11, "original_content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "parent_variant_id": "pyint-c3d5b0857a14-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/pyrefly.py#L341-L345", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-5aa9a9be5a4d-I11", "group_id": "py-6283dd31af1c7c8d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1328, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-55748655a7f3-I12", "source": "from __future__ import annotations\nimport copy\nimport re\nimport sys\nfrom typing import Any\nimport attrs\n\n@attrs.define(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-6283dd31af1c7c8d", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 13, "local_path": "data-flow/inline-intermediate-variables/I12__attrs__AutoDetect__8655a7f3.py", "order": 12, "original_content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "parent_variant_id": "pyint-c3d5b0857a14-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/pyrefly.py#L341-L345", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-55748655a7f3-I12", "group_id": "py-6283dd31af1c7c8d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1329, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4855b15aeca9-I13", "source": "from __future__ import annotations\nimport copy\nimport re\nimport sys\nfrom typing import Any\nimport attrs\n\n@attrs.define(auto_detect=True)\nclass AutoDetect:\n    x: int\n\n    def __init__(self, x: int):\n        self.x = x\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-6283dd31af1c7c8d", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 13, "local_path": "control-flow/lower-for-to-while/I13__attrs__AutoDetect__b15aeca9.py", "order": 13, "original_content_sha256": "6a17b25a72463ca4471716537a37022146da9399f6f2689f4f781db4a62f7b1d", "parent_variant_id": "pyint-c3d5b0857a14-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "typing_tests/pyrefly.py#L341-L345", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "AutoDetect", "variant_id": "pyint-4855b15aeca9-I13", "group_id": "py-6283dd31af1c7c8d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1330, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-348ec9ce990f-SRC", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-65f4e9759b321adc", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 12, "local_path": "source-original/SRC__requests__Timeout__c9ce990f.py", "order": 0, "original_content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L82-L88", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Timeout", "variant_id": "pyint-348ec9ce990f-SRC", "group_id": "py-65f4e9759b321adc", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1023, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-12fbb5bd34b1-I01", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass Timeout(RequestException):\n    pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-65f4e9759b321adc", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "0d8f3d6be547a0435d488fb7e4894ddb80bb891ec1819f6f5d9d27c1895ae929", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 7, "local_path": "comments/remove-comments/I01__requests__Timeout__b5bd34b1.py", "order": 1, "original_content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "parent_variant_id": "pyint-348ec9ce990f-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L82-L88", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 173, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "Timeout", "variant_id": "pyint-12fbb5bd34b1-I01", "group_id": "py-65f4e9759b321adc", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1024, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d3a0a0b73377-I02", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-65f4e9759b321adc", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 12, "local_path": "identifiers/shorten-identifiers/I02__requests__Timeout__a0b73377.py", "order": 2, "original_content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "parent_variant_id": "pyint-348ec9ce990f-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L82-L88", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 0, "identifiers_declared": 0}, "unit_kind": "class", "unit_name": "Timeout", "variant_id": "pyint-d3a0a0b73377-I02", "group_id": "py-65f4e9759b321adc", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1025, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0b47fc781739-I03", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-65f4e9759b321adc", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 12, "local_path": "identifiers/mislead-identifiers/I03__requests__Timeout__fc781739.py", "order": 3, "original_content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "parent_variant_id": "pyint-348ec9ce990f-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L82-L88", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 0, "identifiers_declared": 0, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 0, "local_random_pool_selections": 0, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "Timeout", "variant_id": "pyint-0b47fc781739-I03", "group_id": "py-65f4e9759b321adc", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1026, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0d5b85a73f12-I04", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-65f4e9759b321adc", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 12, "local_path": "identifiers/garble-identifiers/I04__requests__Timeout__85a73f12.py", "order": 4, "original_content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "parent_variant_id": "pyint-348ec9ce990f-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L82-L88", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 0, "identifiers_declared": 0}, "unit_kind": "class", "unit_name": "Timeout", "variant_id": "pyint-0d5b85a73f12-I04", "group_id": "py-65f4e9759b321adc", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1027, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1c5994b3720a-I05", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-65f4e9759b321adc", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 12, "local_path": "expressions/encode-integer-literals/I05__requests__Timeout__94b3720a.py", "order": 5, "original_content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "parent_variant_id": "pyint-348ec9ce990f-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L82-L88", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "Timeout", "variant_id": "pyint-1c5994b3720a-I05", "group_id": "py-65f4e9759b321adc", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1028, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3bb22d343f3b-I06", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-65f4e9759b321adc", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 12, "local_path": "expressions/invert-conditions/I06__requests__Timeout__2d343f3b.py", "order": 6, "original_content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "parent_variant_id": "pyint-348ec9ce990f-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L82-L88", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "Timeout", "variant_id": "pyint-3bb22d343f3b-I06", "group_id": "py-65f4e9759b321adc", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1029, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1983e638f62a-I07", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-65f4e9759b321adc", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 12, "local_path": "code-injection/insert-dead-branches/I07__requests__Timeout__e638f62a.py", "order": 7, "original_content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "parent_variant_id": "pyint-348ec9ce990f-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L82-L88", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 0}, "unit_kind": "class", "unit_name": "Timeout", "variant_id": "pyint-1983e638f62a-I07", "group_id": "py-65f4e9759b321adc", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1030, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e77483ee28b1-I08", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-65f4e9759b321adc", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 12, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__Timeout__83ee28b1.py", "order": 8, "original_content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "parent_variant_id": "pyint-348ec9ce990f-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L82-L88", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 0, "readable_lines_injected": 0, "readable_template_index": -1}, "unit_kind": "class", "unit_name": "Timeout", "variant_id": "pyint-e77483ee28b1-I08", "group_id": "py-65f4e9759b321adc", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1031, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ea64df68304c-I09", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-65f4e9759b321adc", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 12, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__Timeout__df68304c.py", "order": 9, "original_content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "parent_variant_id": "pyint-348ec9ce990f-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L82-L88", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 0, "low_readability_template_index": -1}, "unit_kind": "class", "unit_name": "Timeout", "variant_id": "pyint-ea64df68304c-I09", "group_id": "py-65f4e9759b321adc", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1032, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c80cf78fc48a-I10", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-65f4e9759b321adc", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 12, "local_path": "layout/partially-compact-layout/I10__requests__Timeout__f78fc48a.py", "order": 10, "original_content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "parent_variant_id": "pyint-348ec9ce990f-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L82-L88", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 2, "line_break_groups_removed": 0, "line_breaks_removed": 0, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "Timeout", "variant_id": "pyint-c80cf78fc48a-I10", "group_id": "py-65f4e9759b321adc", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1033, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4698b0e4f0b0-I11", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-65f4e9759b321adc", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 12, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__Timeout__b0e4f0b0.py", "order": 11, "original_content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "parent_variant_id": "pyint-348ec9ce990f-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L82-L88", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "Timeout", "variant_id": "pyint-4698b0e4f0b0-I11", "group_id": "py-65f4e9759b321adc", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1034, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c8fcbb975379-I12", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-65f4e9759b321adc", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 12, "local_path": "data-flow/inline-intermediate-variables/I12__requests__Timeout__bb975379.py", "order": 12, "original_content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "parent_variant_id": "pyint-348ec9ce990f-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L82-L88", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Timeout", "variant_id": "pyint-c8fcbb975379-I12", "group_id": "py-65f4e9759b321adc", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1035, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-29909a12ba00-I13", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-65f4e9759b321adc", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 12, "local_path": "control-flow/lower-for-to-while/I13__requests__Timeout__9a12ba00.py", "order": 13, "original_content_sha256": "441b117557d9e990670693d149722abda7b1fa8a572b5ed63ce994bf96c3be60", "parent_variant_id": "pyint-348ec9ce990f-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L82-L88", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "Timeout", "variant_id": "pyint-29909a12ba00-I13", "group_id": "py-65f4e9759b321adc", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1036, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-19b411536d5f-SRC", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _ClassBuilder:\n    \"\"\"\n    Iteratively build *one* class.\n    \"\"\"\n\n    __slots__ = (\n        \"_add_method_dunders\",\n        \"_attr_names\",\n        \"_attrs\",\n        \"_base_attr_map\",\n        \"_base_names\",\n        \"_cache_hash\",\n        \"_cls\",\n        \"_cls_dict\",\n        \"_delete_attribs\",\n        \"_frozen\",\n        \"_has_custom_setattr\",\n        \"_has_post_init\",\n        \"_has_pre_init\",\n        \"_is_exc\",\n        \"_on_setattr\",\n        \"_pre_init_has_args\",\n        \"_repr_added\",\n        \"_script_snippets\",\n        \"_slots\",\n        \"_weakref_slot\",\n        \"_wrote_own_setattr\",\n    )\n\n    def __init__(\n        self,\n        cls: type,\n        these,\n        auto_attribs: bool,\n        props: ClassProps,\n        has_custom_setattr: bool,\n    ):\n        attrs, base_attrs, base_map = _transform_attrs(\n            cls,\n            these,\n            auto_attribs,\n            props.kw_only,\n            props.collected_fields_by_mro,\n            props.field_transformer,\n        )\n\n        self._cls = cls\n        self._cls_dict = dict(cls.__dict__) if props.is_slotted else {}\n        self._attrs = attrs\n        self._base_names = {a.name for a in base_attrs}\n        self._base_attr_map = base_map\n        self._attr_names = tuple(a.name for a in attrs)\n        self._slots = props.is_slotted\n        self._frozen = props.is_frozen\n        self._weakref_slot = props.has_weakref_slot\n        self._cache_hash = (\n            props.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n        self._has_pre_init = bool(getattr(cls, \"__attrs_pre_init__\", False))\n        self._pre_init_has_args = False\n        if self._has_pre_init:\n            # Check if the pre init method has more arguments than just `self`\n            # We want to pass arguments if pre init expects arguments\n            import inspect\n\n            pre_init_func = cls.__attrs_pre_init__\n            pre_init_signature = inspect.signature(pre_init_func)\n            self._pre_init_has_args = len(pre_init_signature.parameters) > 1\n        self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n        self._delete_attribs = not bool(these)\n        self._is_exc = props.is_exception\n        self._on_setattr = props.on_setattr_hook\n\n        self._has_custom_setattr = has_custom_setattr\n        self._wrote_own_setattr = False\n\n        self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n        self._cls_dict[\"__attrs_props__\"] = props\n\n        if props.is_frozen:\n            self._cls_dict[\"__setattr__\"] = _frozen_setattrs\n            self._cls_dict[\"__delattr__\"] = _frozen_delattrs\n\n            self._wrote_own_setattr = True\n        elif self._on_setattr in (\n            _DEFAULT_ON_SETATTR,\n            setters.validate,\n            setters.convert,\n        ):\n            has_validator = has_converter = False\n            for a in attrs:\n                if a.validator is not None:\n                    has_validator = True\n                if a.converter is not None:\n                    has_converter = True\n\n                if has_validator and has_converter:\n                    break\n            if (\n                (\n                    self._on_setattr == _DEFAULT_ON_SETATTR\n                    and not (has_validator or has_converter)\n                )\n                or (self._on_setattr == setters.validate and not has_validator)\n                or (self._on_setattr == setters.convert and not has_converter)\n            ):\n                # If class-level on_setattr is set to convert + validate, but\n                # there's no field to convert or validate, pretend like there's\n                # no on_setattr.\n                self._on_setattr = None\n\n        if props.added_pickling:\n            (\n                self._cls_dict[\"__getstate__\"],\n                self._cls_dict[\"__setstate__\"],\n            ) = self._make_getstate_setstate()\n\n        # tuples of script, globs, hook\n        self._script_snippets: list[\n            tuple[str, dict, Callable[[dict, dict], Any]]\n        ] = []\n        self._repr_added = False\n\n        # We want to only do this check once; in 99.9% of cases these\n        # exist.\n        if not hasattr(self._cls, \"__module__\") or not hasattr(\n            self._cls, \"__qualname__\"\n        ):\n            self._add_method_dunders = self._add_method_dunders_safe\n        else:\n            self._add_method_dunders = self._add_method_dunders_unsafe\n\n    def __repr__(self):\n        return f\"<_ClassBuilder(cls={self._cls.__name__})>\"\n\n    def _eval_snippets(self) -> None:\n        \"\"\"\n        Evaluate any registered snippets in one go.\n        \"\"\"\n        script = \"\\n\".join([snippet[0] for snippet in self._script_snippets])\n        globs = {}\n        for _, snippet_globs, _ in self._script_snippets:\n            globs.update(snippet_globs)\n\n        locs = _linecache_and_compile(\n            script,\n            _generate_unique_filename(self._cls, \"methods\"),\n            globs,\n        )\n\n        for _, _, hook in self._script_snippets:\n            hook(self._cls_dict, locs)\n\n    def build_class(self):\n        \"\"\"\n        Finalize class based on the accumulated configuration.\n\n        Builder cannot be used after calling this method.\n        \"\"\"\n        self._eval_snippets()\n        if self._slots is True:\n            cls = self._create_slots_class()\n            self._cls.__attrs_base_of_slotted__ = weakref.ref(cls)\n        else:\n            cls = abc.update_abstractmethods(self._patch_original_class())\n\n        # The method gets only called if it's not inherited from a base class.\n        # _has_own_attribute does NOT work properly for classmethods.\n        if (\n            getattr(cls, \"__attrs_init_subclass__\", None)\n            and \"__attrs_init_subclass__\" not in cls.__dict__\n        ):\n            cls.__attrs_init_subclass__()\n\n        return cls\n\n    def _patch_original_class(self):\n        \"\"\"\n        Apply accumulated methods and return the class.\n        \"\"\"\n        cls = self._cls\n        base_names = self._base_names\n\n        # Clean class of attribute definitions (`attr.ib()`s).\n        if self._delete_attribs:\n            for name in self._attr_names:\n                if (\n                    name not in base_names\n                    and getattr(cls, name, _SENTINEL) is not _SENTINEL\n                ):\n                    # An AttributeError can happen if a base class defines a\n                    # class variable and we want to set an attribute with the\n                    # same name by using only a type annotation.\n                    with contextlib.suppress(AttributeError):\n                        delattr(cls, name)\n\n        # Attach our dunder methods.\n        for name, value in self._cls_dict.items():\n            setattr(cls, name, value)\n\n        # If we've inherited an attrs __setattr__ and don't write our own,\n        # reset it to object's.\n        if not self._wrote_own_setattr and getattr(\n            cls, \"__attrs_own_setattr__\", False\n        ):\n            cls.__attrs_own_setattr__ = False\n\n            if not self._has_custom_setattr:\n                cls.__setattr__ = _OBJ_SETATTR\n\n        return cls\n\n    def _create_slots_class(self):\n        \"\"\"\n        Build and return a new class with a `__slots__` attribute.\n        \"\"\"\n        cd = {\n            k: v\n            for k, v in self._cls_dict.items()\n            if k not in (*tuple(self._attr_names), \"__dict__\", \"__weakref__\")\n        }\n\n        # 3.14.0rc2+\n        if hasattr(sys, \"_clear_type_descriptors\"):\n            sys._clear_type_descriptors(self._cls)\n\n        # If our class doesn't have its own implementation of __setattr__\n        # (either from the user or by us), check the bases, if one of them has\n        # an attrs-made __setattr__, that needs to be reset. We don't walk the\n        # MRO because we only care about our immediate base classes.\n        # XXX: This can be confused by subclassing a slotted attrs class with\n        # XXX: a non-attrs class and subclass the resulting class with an attrs\n        # XXX: class.  See `test_slotted_confused` for details.  For now that's\n        # XXX: OK with us.\n        if not self._wrote_own_setattr:\n            cd[\"__attrs_own_setattr__\"] = False\n\n            if not self._has_custom_setattr:\n                for base_cls in self._cls.__bases__:\n                    if base_cls.__dict__.get(\"__attrs_own_setattr__\", False):\n                        cd[\"__setattr__\"] = _OBJ_SETATTR\n                        break\n\n        # Traverse the MRO to collect existing slots\n        # and check for an existing __weakref__.\n        existing_slots = {}\n        weakref_inherited = False\n        for base_cls in self._cls.__mro__[1:-1]:\n            if base_cls.__dict__.get(\"__weakref__\", None) is not None:\n                weakref_inherited = True\n            existing_slots.update(\n                {\n                    name: getattr(base_cls, name)\n                    for name in getattr(base_cls, \"__slots__\", [])\n                }\n            )\n\n        base_names = set(self._base_names)\n\n        names = self._attr_names\n        if (\n            self._weakref_slot\n            and \"__weakref__\" not in getattr(self._cls, \"__slots__\", ())\n            and \"__weakref__\" not in names\n            and not weakref_inherited\n        ):\n            names += (\"__weakref__\",)\n\n        cached_properties = {\n            name: cached_prop.func\n            for name, cached_prop in cd.items()\n            if isinstance(cached_prop, cached_property)\n        }\n\n        # Collect methods with a `__class__` reference that are shadowed in the new class.\n        # To know to update them.\n        additional_closure_functions_to_update = []\n        if cached_properties:\n            import inspect\n\n            class_annotations = _get_annotations(self._cls)\n            for name, func in cached_properties.items():\n                # Add cached properties to names for slotting.\n                names += (name,)\n                # Clear out function from class to avoid clashing.\n                del cd[name]\n                additional_closure_functions_to_update.append(func)\n                annotation = inspect.signature(func).return_annotation\n                if annotation is not inspect.Parameter.empty:\n                    class_annotations[name] = annotation\n\n            original_getattr = cd.get(\"__getattr__\")\n            if original_getattr is not None:\n                additional_closure_functions_to_update.append(original_getattr)\n\n            cd[\"__getattr__\"] = _make_cached_property_getattr(\n                cached_properties, original_getattr, self._cls\n            )\n\n        # We only add the names of attributes that aren't inherited.\n        # Setting __slots__ to inherited attributes wastes memory.\n        slot_names = [name for name in names if name not in base_names]\n\n        # There are slots for attributes from current class\n        # that are defined in parent classes.\n        # As their descriptors may be overridden by a child class,\n        # we collect them here and update the class dict\n        reused_slots = {\n            slot: slot_descriptor\n            for slot, slot_descriptor in existing_slots.items()\n            if slot in slot_names\n        }\n        slot_names = [name for name in slot_names if name not in reused_slots]\n        cd.update(reused_slots)\n        if self._cache_hash:\n            slot_names.append(_HASH_CACHE_FIELD)\n\n        cd[\"__slots__\"] = tuple(slot_names)\n\n        cd[\"__qualname__\"] = self._cls.__qualname__\n\n        # Create new class based on old class and our methods.\n        cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd)\n\n        # The following is a fix for\n        # <https://github.com/python-attrs/attrs/issues/102>.\n        # If a method mentions `__class__` or uses the no-arg super(), the\n        # compiler will bake a reference to the class in the method itself\n        # as `method.__closure__`.  Since we replace the class with a\n        # clone, we rewrite these references so it keeps working.\n        for item in itertools.chain(\n            cls.__dict__.values(), additional_closure_functions_to_update\n        ):\n            if isinstance(item, (classmethod, staticmethod)):\n                # Class- and staticmethods hide their functions inside.\n                # These might need to be rewritten as well.\n                closure_cells = getattr(item.__func__, \"__closure__\", None)\n            elif isinstance(item, property):\n                # Workaround for property `super()` shortcut (PY3-only).\n                # There is no universal way for other descriptors.\n                closure_cells = getattr(item.fget, \"__closure__\", None)\n            else:\n                closure_cells = getattr(item, \"__closure__\", None)\n\n            if not closure_cells:  # Catch None or the empty list.\n                continue\n            for cell in closure_cells:\n                try:\n                    match = cell.cell_contents is self._cls\n                except ValueError:  # noqa: PERF203\n                    # ValueError: Cell is empty\n                    pass\n                else:\n                    if match:\n                        cell.cell_contents = cls\n        return cls\n\n    def add_repr(self, ns):\n        script, globs = _make_repr_script(self._attrs, ns)\n\n        def _attach_repr(cls_dict, globs):\n            cls_dict[\"__repr__\"] = self._add_method_dunders(globs[\"__repr__\"])\n\n        self._script_snippets.append((script, globs, _attach_repr))\n        self._repr_added = True\n        return self\n\n    def add_str(self):\n        if not self._repr_added:\n            msg = \"__str__ can only be generated if a __repr__ exists.\"\n            raise ValueError(msg)\n\n        def __str__(self):\n            return self.__repr__()\n\n        self._cls_dict[\"__str__\"] = self._add_method_dunders(__str__)\n        return self\n\n    def _make_getstate_setstate(self):\n        \"\"\"\n        Create custom __setstate__ and __getstate__ methods.\n        \"\"\"\n        # __weakref__ is not writable.\n        state_attr_names = tuple(\n            an for an in self._attr_names if an != \"__weakref__\"\n        )\n\n        def slots_getstate(self):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            return {name: getattr(self, name) for name in state_attr_names}\n\n        hash_caching_enabled = self._cache_hash\n\n        def slots_setstate(self, state):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            __bound_setattr = _OBJ_SETATTR.__get__(self)\n            if isinstance(state, tuple):\n                # Backward compatibility with attrs instances pickled with\n                # attrs versions before v22.2.0 which stored tuples.\n                for name, value in zip(state_attr_names, state, strict=False):\n                    __bound_setattr(name, value)\n            else:\n                for name in state_attr_names:\n                    if name in state:\n                        __bound_setattr(name, state[name])\n\n            # The hash code cache is not included when the object is\n            # serialized, but it still needs to be initialized to None to\n            # indicate that the first call to __hash__ should be a cache\n            # miss.\n            if hash_caching_enabled:\n                __bound_setattr(_HASH_CACHE_FIELD, None)\n\n        return slots_getstate, slots_setstate\n\n    def make_unhashable(self):\n        self._cls_dict[\"__hash__\"] = None\n        return self\n\n    def add_hash(self):\n        script, globs = _make_hash_script(\n            self._cls,\n            self._attrs,\n            frozen=self._frozen,\n            cache_hash=self._cache_hash,\n        )\n\n        def attach_hash(cls_dict: dict, locs: dict) -> None:\n            cls_dict[\"__hash__\"] = self._add_method_dunders(locs[\"__hash__\"])\n\n        self._script_snippets.append((script, globs, attach_hash))\n\n        return self\n\n    def add_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=False,\n        )\n\n        def _attach_init(cls_dict, globs):\n            init = globs[\"__init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_init))\n\n        return self\n\n    def add_replace(self):\n        # We create a local `evolve` proxy because it gets modified in place.\n        def __replace__(*args, **changes):\n            return evolve(*args, **changes)\n\n        self._cls_dict[\"__replace__\"] = self._add_method_dunders(__replace__)\n        return self\n\n    def add_match_args(self):\n        self._cls_dict[\"__match_args__\"] = tuple(\n            field.name\n            for field in self._attrs\n            if field.init and not field.kw_only\n        )\n\n    def add_attrs_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=True,\n        )\n\n        def _attach_attrs_init(cls_dict, globs):\n            init = globs[\"__attrs_init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__attrs_init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_attrs_init))\n\n        return self\n\n    def add_eq(self):\n        cd = self._cls_dict\n\n        script, globs = _make_eq_script(self._attrs)\n\n        def _attach_eq(cls_dict, globs):\n            cls_dict[\"__eq__\"] = self._add_method_dunders(globs[\"__eq__\"])\n\n        self._script_snippets.append((script, globs, _attach_eq))\n\n        cd[\"__ne__\"] = __ne__\n\n        return self\n\n    def add_order(self):\n        cd = self._cls_dict\n\n        cd[\"__lt__\"], cd[\"__le__\"], cd[\"__gt__\"], cd[\"__ge__\"] = (\n            self._add_method_dunders(meth)\n            for meth in _make_order(self._cls, self._attrs)\n        )\n\n        return self\n\n    def add_setattr(self):\n        sa_attrs = {}\n        for a in self._attrs:\n            on_setattr = a.on_setattr or self._on_setattr\n            if on_setattr and on_setattr is not setters.NO_OP:\n                sa_attrs[a.name] = (\n                    a,\n                    on_setattr,\n                    _lazy_is_generator(on_setattr),\n                )\n\n        if not sa_attrs:\n            return self\n\n        if self._has_custom_setattr:\n            # We need to write a __setattr__ but there already is one!\n            msg = \"Can't combine custom __setattr__ with on_setattr hooks.\"\n            raise ValueError(msg)\n\n        # docstring comes from _add_method_dunders\n        def __setattr__(self, name, val):\n            try:\n                a, hook, is_gen = sa_attrs[name]\n            except KeyError:\n                _OBJ_SETATTR(self, name, val)\n\n                return\n\n            if is_gen():\n                gen = hook(self, a, val)\n                nval = next(gen)\n                _OBJ_SETATTR(self, name, nval)\n                try:\n                    next(gen)\n                except StopIteration:\n                    return\n\n                gen.close()\n                msg = \"Generator on_setattr hook yielded more than once.\"\n                raise RuntimeError(msg)\n\n            nval = hook(self, a, val)\n            _OBJ_SETATTR(self, name, nval)\n\n            return\n\n        self._cls_dict[\"__attrs_own_setattr__\"] = True\n        self._cls_dict[\"__setattr__\"] = self._add_method_dunders(__setattr__)\n        self._wrote_own_setattr = True\n\n        return self\n\n    def _add_method_dunders_unsafe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method*.\n        \"\"\"\n        method.__module__ = self._cls.__module__\n\n        method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        method.__doc__ = (\n            f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        )\n\n        return method\n\n    def _add_method_dunders_safe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method* if possible.\n        \"\"\"\n        with contextlib.suppress(AttributeError):\n            method.__module__ = self._cls.__module__\n\n        with contextlib.suppress(AttributeError):\n            method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        with contextlib.suppress(AttributeError):\n            method.__doc__ = f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n\n        return method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-67adbacc78d2f47e", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 636, "local_path": "source-original/SRC__attrs___ClassBuilder__11536d5f.py", "order": 0, "original_content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L647-L1253", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_ClassBuilder", "variant_id": "pyint-19b411536d5f-SRC", "group_id": "py-67adbacc78d2f47e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1163, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-557c4dac856c-I01", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _ClassBuilder:\n    \n\n    __slots__ = (\n        \"_add_method_dunders\",\n        \"_attr_names\",\n        \"_attrs\",\n        \"_base_attr_map\",\n        \"_base_names\",\n        \"_cache_hash\",\n        \"_cls\",\n        \"_cls_dict\",\n        \"_delete_attribs\",\n        \"_frozen\",\n        \"_has_custom_setattr\",\n        \"_has_post_init\",\n        \"_has_pre_init\",\n        \"_is_exc\",\n        \"_on_setattr\",\n        \"_pre_init_has_args\",\n        \"_repr_added\",\n        \"_script_snippets\",\n        \"_slots\",\n        \"_weakref_slot\",\n        \"_wrote_own_setattr\",\n    )\n\n    def __init__(\n        self,\n        cls: type,\n        these,\n        auto_attribs: bool,\n        props: ClassProps,\n        has_custom_setattr: bool,\n    ):\n        attrs, base_attrs, base_map = _transform_attrs(\n            cls,\n            these,\n            auto_attribs,\n            props.kw_only,\n            props.collected_fields_by_mro,\n            props.field_transformer,\n        )\n\n        self._cls = cls\n        self._cls_dict = dict(cls.__dict__) if props.is_slotted else {}\n        self._attrs = attrs\n        self._base_names = {a.name for a in base_attrs}\n        self._base_attr_map = base_map\n        self._attr_names = tuple(a.name for a in attrs)\n        self._slots = props.is_slotted\n        self._frozen = props.is_frozen\n        self._weakref_slot = props.has_weakref_slot\n        self._cache_hash = (\n            props.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n        self._has_pre_init = bool(getattr(cls, \"__attrs_pre_init__\", False))\n        self._pre_init_has_args = False\n        if self._has_pre_init:\n             \n             \n            import inspect\n\n            pre_init_func = cls.__attrs_pre_init__\n            pre_init_signature = inspect.signature(pre_init_func)\n            self._pre_init_has_args = len(pre_init_signature.parameters) > 1\n        self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n        self._delete_attribs = not bool(these)\n        self._is_exc = props.is_exception\n        self._on_setattr = props.on_setattr_hook\n\n        self._has_custom_setattr = has_custom_setattr\n        self._wrote_own_setattr = False\n\n        self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n        self._cls_dict[\"__attrs_props__\"] = props\n\n        if props.is_frozen:\n            self._cls_dict[\"__setattr__\"] = _frozen_setattrs\n            self._cls_dict[\"__delattr__\"] = _frozen_delattrs\n\n            self._wrote_own_setattr = True\n        elif self._on_setattr in (\n            _DEFAULT_ON_SETATTR,\n            setters.validate,\n            setters.convert,\n        ):\n            has_validator = has_converter = False\n            for a in attrs:\n                if a.validator is not None:\n                    has_validator = True\n                if a.converter is not None:\n                    has_converter = True\n\n                if has_validator and has_converter:\n                    break\n            if (\n                (\n                    self._on_setattr == _DEFAULT_ON_SETATTR\n                    and not (has_validator or has_converter)\n                )\n                or (self._on_setattr == setters.validate and not has_validator)\n                or (self._on_setattr == setters.convert and not has_converter)\n            ):\n                 \n                 \n                 \n                self._on_setattr = None\n\n        if props.added_pickling:\n            (\n                self._cls_dict[\"__getstate__\"],\n                self._cls_dict[\"__setstate__\"],\n            ) = self._make_getstate_setstate()\n\n         \n        self._script_snippets: list[\n            tuple[str, dict, Callable[[dict, dict], Any]]\n        ] = []\n        self._repr_added = False\n\n         \n         \n        if not hasattr(self._cls, \"__module__\") or not hasattr(\n            self._cls, \"__qualname__\"\n        ):\n            self._add_method_dunders = self._add_method_dunders_safe\n        else:\n            self._add_method_dunders = self._add_method_dunders_unsafe\n\n    def __repr__(self):\n        return f\"<_ClassBuilder(cls={self._cls.__name__})>\"\n\n    def _eval_snippets(self) -> None:\n        \n        script = \"\\n\".join([snippet[0] for snippet in self._script_snippets])\n        globs = {}\n        for _, snippet_globs, _ in self._script_snippets:\n            globs.update(snippet_globs)\n\n        locs = _linecache_and_compile(\n            script,\n            _generate_unique_filename(self._cls, \"methods\"),\n            globs,\n        )\n\n        for _, _, hook in self._script_snippets:\n            hook(self._cls_dict, locs)\n\n    def build_class(self):\n        \n        self._eval_snippets()\n        if self._slots is True:\n            cls = self._create_slots_class()\n            self._cls.__attrs_base_of_slotted__ = weakref.ref(cls)\n        else:\n            cls = abc.update_abstractmethods(self._patch_original_class())\n\n         \n         \n        if (\n            getattr(cls, \"__attrs_init_subclass__\", None)\n            and \"__attrs_init_subclass__\" not in cls.__dict__\n        ):\n            cls.__attrs_init_subclass__()\n\n        return cls\n\n    def _patch_original_class(self):\n        \n        cls = self._cls\n        base_names = self._base_names\n\n         \n        if self._delete_attribs:\n            for name in self._attr_names:\n                if (\n                    name not in base_names\n                    and getattr(cls, name, _SENTINEL) is not _SENTINEL\n                ):\n                     \n                     \n                     \n                    with contextlib.suppress(AttributeError):\n                        delattr(cls, name)\n\n         \n        for name, value in self._cls_dict.items():\n            setattr(cls, name, value)\n\n         \n         \n        if not self._wrote_own_setattr and getattr(\n            cls, \"__attrs_own_setattr__\", False\n        ):\n            cls.__attrs_own_setattr__ = False\n\n            if not self._has_custom_setattr:\n                cls.__setattr__ = _OBJ_SETATTR\n\n        return cls\n\n    def _create_slots_class(self):\n        \n        cd = {\n            k: v\n            for k, v in self._cls_dict.items()\n            if k not in (*tuple(self._attr_names), \"__dict__\", \"__weakref__\")\n        }\n\n         \n        if hasattr(sys, \"_clear_type_descriptors\"):\n            sys._clear_type_descriptors(self._cls)\n\n         \n         \n         \n         \n         \n         \n         \n         \n        if not self._wrote_own_setattr:\n            cd[\"__attrs_own_setattr__\"] = False\n\n            if not self._has_custom_setattr:\n                for base_cls in self._cls.__bases__:\n                    if base_cls.__dict__.get(\"__attrs_own_setattr__\", False):\n                        cd[\"__setattr__\"] = _OBJ_SETATTR\n                        break\n\n         \n         \n        existing_slots = {}\n        weakref_inherited = False\n        for base_cls in self._cls.__mro__[1:-1]:\n            if base_cls.__dict__.get(\"__weakref__\", None) is not None:\n                weakref_inherited = True\n            existing_slots.update(\n                {\n                    name: getattr(base_cls, name)\n                    for name in getattr(base_cls, \"__slots__\", [])\n                }\n            )\n\n        base_names = set(self._base_names)\n\n        names = self._attr_names\n        if (\n            self._weakref_slot\n            and \"__weakref__\" not in getattr(self._cls, \"__slots__\", ())\n            and \"__weakref__\" not in names\n            and not weakref_inherited\n        ):\n            names += (\"__weakref__\",)\n\n        cached_properties = {\n            name: cached_prop.func\n            for name, cached_prop in cd.items()\n            if isinstance(cached_prop, cached_property)\n        }\n\n         \n         \n        additional_closure_functions_to_update = []\n        if cached_properties:\n            import inspect\n\n            class_annotations = _get_annotations(self._cls)\n            for name, func in cached_properties.items():\n                 \n                names += (name,)\n                 \n                del cd[name]\n                additional_closure_functions_to_update.append(func)\n                annotation = inspect.signature(func).return_annotation\n                if annotation is not inspect.Parameter.empty:\n                    class_annotations[name] = annotation\n\n            original_getattr = cd.get(\"__getattr__\")\n            if original_getattr is not None:\n                additional_closure_functions_to_update.append(original_getattr)\n\n            cd[\"__getattr__\"] = _make_cached_property_getattr(\n                cached_properties, original_getattr, self._cls\n            )\n\n         \n         \n        slot_names = [name for name in names if name not in base_names]\n\n         \n         \n         \n         \n        reused_slots = {\n            slot: slot_descriptor\n            for slot, slot_descriptor in existing_slots.items()\n            if slot in slot_names\n        }\n        slot_names = [name for name in slot_names if name not in reused_slots]\n        cd.update(reused_slots)\n        if self._cache_hash:\n            slot_names.append(_HASH_CACHE_FIELD)\n\n        cd[\"__slots__\"] = tuple(slot_names)\n\n        cd[\"__qualname__\"] = self._cls.__qualname__\n\n         \n        cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd)\n\n         \n         \n         \n         \n         \n         \n        for item in itertools.chain(\n            cls.__dict__.values(), additional_closure_functions_to_update\n        ):\n            if isinstance(item, (classmethod, staticmethod)):\n                 \n                 \n                closure_cells = getattr(item.__func__, \"__closure__\", None)\n            elif isinstance(item, property):\n                 \n                 \n                closure_cells = getattr(item.fget, \"__closure__\", None)\n            else:\n                closure_cells = getattr(item, \"__closure__\", None)\n\n            if not closure_cells:   \n                continue\n            for cell in closure_cells:\n                try:\n                    match = cell.cell_contents is self._cls\n                except ValueError:   \n                     \n                    pass\n                else:\n                    if match:\n                        cell.cell_contents = cls\n        return cls\n\n    def add_repr(self, ns):\n        script, globs = _make_repr_script(self._attrs, ns)\n\n        def _attach_repr(cls_dict, globs):\n            cls_dict[\"__repr__\"] = self._add_method_dunders(globs[\"__repr__\"])\n\n        self._script_snippets.append((script, globs, _attach_repr))\n        self._repr_added = True\n        return self\n\n    def add_str(self):\n        if not self._repr_added:\n            msg = \"__str__ can only be generated if a __repr__ exists.\"\n            raise ValueError(msg)\n\n        def __str__(self):\n            return self.__repr__()\n\n        self._cls_dict[\"__str__\"] = self._add_method_dunders(__str__)\n        return self\n\n    def _make_getstate_setstate(self):\n        \n         \n        state_attr_names = tuple(\n            an for an in self._attr_names if an != \"__weakref__\"\n        )\n\n        def slots_getstate(self):\n            \n            return {name: getattr(self, name) for name in state_attr_names}\n\n        hash_caching_enabled = self._cache_hash\n\n        def slots_setstate(self, state):\n            \n            __bound_setattr = _OBJ_SETATTR.__get__(self)\n            if isinstance(state, tuple):\n                 \n                 \n                for name, value in zip(state_attr_names, state, strict=False):\n                    __bound_setattr(name, value)\n            else:\n                for name in state_attr_names:\n                    if name in state:\n                        __bound_setattr(name, state[name])\n\n             \n             \n             \n             \n            if hash_caching_enabled:\n                __bound_setattr(_HASH_CACHE_FIELD, None)\n\n        return slots_getstate, slots_setstate\n\n    def make_unhashable(self):\n        self._cls_dict[\"__hash__\"] = None\n        return self\n\n    def add_hash(self):\n        script, globs = _make_hash_script(\n            self._cls,\n            self._attrs,\n            frozen=self._frozen,\n            cache_hash=self._cache_hash,\n        )\n\n        def attach_hash(cls_dict: dict, locs: dict) -> None:\n            cls_dict[\"__hash__\"] = self._add_method_dunders(locs[\"__hash__\"])\n\n        self._script_snippets.append((script, globs, attach_hash))\n\n        return self\n\n    def add_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=False,\n        )\n\n        def _attach_init(cls_dict, globs):\n            init = globs[\"__init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_init))\n\n        return self\n\n    def add_replace(self):\n         \n        def __replace__(*args, **changes):\n            return evolve(*args, **changes)\n\n        self._cls_dict[\"__replace__\"] = self._add_method_dunders(__replace__)\n        return self\n\n    def add_match_args(self):\n        self._cls_dict[\"__match_args__\"] = tuple(\n            field.name\n            for field in self._attrs\n            if field.init and not field.kw_only\n        )\n\n    def add_attrs_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=True,\n        )\n\n        def _attach_attrs_init(cls_dict, globs):\n            init = globs[\"__attrs_init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__attrs_init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_attrs_init))\n\n        return self\n\n    def add_eq(self):\n        cd = self._cls_dict\n\n        script, globs = _make_eq_script(self._attrs)\n\n        def _attach_eq(cls_dict, globs):\n            cls_dict[\"__eq__\"] = self._add_method_dunders(globs[\"__eq__\"])\n\n        self._script_snippets.append((script, globs, _attach_eq))\n\n        cd[\"__ne__\"] = __ne__\n\n        return self\n\n    def add_order(self):\n        cd = self._cls_dict\n\n        cd[\"__lt__\"], cd[\"__le__\"], cd[\"__gt__\"], cd[\"__ge__\"] = (\n            self._add_method_dunders(meth)\n            for meth in _make_order(self._cls, self._attrs)\n        )\n\n        return self\n\n    def add_setattr(self):\n        sa_attrs = {}\n        for a in self._attrs:\n            on_setattr = a.on_setattr or self._on_setattr\n            if on_setattr and on_setattr is not setters.NO_OP:\n                sa_attrs[a.name] = (\n                    a,\n                    on_setattr,\n                    _lazy_is_generator(on_setattr),\n                )\n\n        if not sa_attrs:\n            return self\n\n        if self._has_custom_setattr:\n             \n            msg = \"Can't combine custom __setattr__ with on_setattr hooks.\"\n            raise ValueError(msg)\n\n         \n        def __setattr__(self, name, val):\n            try:\n                a, hook, is_gen = sa_attrs[name]\n            except KeyError:\n                _OBJ_SETATTR(self, name, val)\n\n                return\n\n            if is_gen():\n                gen = hook(self, a, val)\n                nval = next(gen)\n                _OBJ_SETATTR(self, name, nval)\n                try:\n                    next(gen)\n                except StopIteration:\n                    return\n\n                gen.close()\n                msg = \"Generator on_setattr hook yielded more than once.\"\n                raise RuntimeError(msg)\n\n            nval = hook(self, a, val)\n            _OBJ_SETATTR(self, name, nval)\n\n            return\n\n        self._cls_dict[\"__attrs_own_setattr__\"] = True\n        self._cls_dict[\"__setattr__\"] = self._add_method_dunders(__setattr__)\n        self._wrote_own_setattr = True\n\n        return self\n\n    def _add_method_dunders_unsafe(self, method: Callable) -> Callable:\n        \n        method.__module__ = self._cls.__module__\n\n        method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        method.__doc__ = (\n            f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        )\n\n        return method\n\n    def _add_method_dunders_safe(self, method: Callable) -> Callable:\n        \n        with contextlib.suppress(AttributeError):\n            method.__module__ = self._cls.__module__\n\n        with contextlib.suppress(AttributeError):\n            method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        with contextlib.suppress(AttributeError):\n            method.__doc__ = f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n\n        return method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-67adbacc78d2f47e", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "c38c43661306350200739dfd79ef679041753c7a03117157a44908c2c331eba5", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 614, "local_path": "comments/remove-comments/I01__attrs___ClassBuilder__4dac856c.py", "order": 1, "original_content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "parent_variant_id": "pyint-19b411536d5f-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L647-L1253", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 3777, "comments_removed": 72, "docstrings_removed": 10, "line_comments_removed": 62}, "unit_kind": "class", "unit_name": "_ClassBuilder", "variant_id": "pyint-557c4dac856c-I01", "group_id": "py-67adbacc78d2f47e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1164, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e13c91f41451-I02", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _ClassBuilder:\n    \"\"\"\n    Iteratively build *one* class.\n    \"\"\"\n\n    __slots__ = (\n        \"_add_method_dunders\",\n        \"_attr_names\",\n        \"_attrs\",\n        \"_base_attr_map\",\n        \"_base_names\",\n        \"_cache_hash\",\n        \"_cls\",\n        \"_cls_dict\",\n        \"_delete_attribs\",\n        \"_frozen\",\n        \"_has_custom_setattr\",\n        \"_has_post_init\",\n        \"_has_pre_init\",\n        \"_is_exc\",\n        \"_on_setattr\",\n        \"_pre_init_has_args\",\n        \"_repr_added\",\n        \"_script_snippets\",\n        \"_slots\",\n        \"_weakref_slot\",\n        \"_wrote_own_setattr\",\n    )\n\n    def __init__(\n        self,\n        cls: type,\n        the,\n        auto: bool,\n        pro: ClassProps,\n        has: bool,\n    ):\n        att, base, base2 = _transform_attrs(\n            cls,\n            the,\n            auto,\n            pro.kw_only,\n            pro.collected_fields_by_mro,\n            pro.field_transformer,\n        )\n\n        self._cls = cls\n        self._cls_dict = dict(cls.__dict__) if pro.is_slotted else {}\n        self._attrs = att\n        self._base_names = {a2.name for a2 in base}\n        self._base_attr_map = base2\n        self._attr_names = tuple(a2.name for a2 in att)\n        self._slots = pro.is_slotted\n        self._frozen = pro.is_frozen\n        self._weakref_slot = pro.has_weakref_slot\n        self._cache_hash = (\n            pro.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n        self._has_pre_init = bool(getattr(cls, \"__attrs_pre_init__\", False))\n        self._pre_init_has_args = False\n        if self._has_pre_init:\n            # Check if the pre init method has more arguments than just `self`\n            # We want to pass arguments if pre init expects arguments\n            import inspect\n\n            pre = cls.__attrs_pre_init__\n            pre2 = inspect.signature(pre)\n            self._pre_init_has_args = len(pre2.parameters) > 1\n        self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n        self._delete_attribs = not bool(the)\n        self._is_exc = pro.is_exception\n        self._on_setattr = pro.on_setattr_hook\n\n        self._has_custom_setattr = has\n        self._wrote_own_setattr = False\n\n        self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n        self._cls_dict[\"__attrs_props__\"] = pro\n\n        if pro.is_frozen:\n            self._cls_dict[\"__setattr__\"] = _frozen_setattrs\n            self._cls_dict[\"__delattr__\"] = _frozen_delattrs\n\n            self._wrote_own_setattr = True\n        elif self._on_setattr in (\n            _DEFAULT_ON_SETATTR,\n            setters.validate,\n            setters.convert,\n        ):\n            has2 = has3 = False\n            for a2 in att:\n                if a2.validator is not None:\n                    has2 = True\n                if a2.converter is not None:\n                    has3 = True\n\n                if has2 and has3:\n                    break\n            if (\n                (\n                    self._on_setattr == _DEFAULT_ON_SETATTR\n                    and not (has2 or has3)\n                )\n                or (self._on_setattr == setters.validate and not has2)\n                or (self._on_setattr == setters.convert and not has3)\n            ):\n                # If class-level on_setattr is set to convert + validate, but\n                # there's no field to convert or validate, pretend like there's\n                # no on_setattr.\n                self._on_setattr = None\n\n        if pro.added_pickling:\n            (\n                self._cls_dict[\"__getstate__\"],\n                self._cls_dict[\"__setstate__\"],\n            ) = self.make()\n\n        # tuples of script, globs, hook\n        self._script_snippets: list[\n            tuple[str, dict, Callable[[dict, dict], Any]]\n        ] = []\n        self._repr_added = False\n\n        # We want to only do this check once; in 99.9% of cases these\n        # exist.\n        if not hasattr(self._cls, \"__module__\") or not hasattr(\n            self._cls, \"__qualname__\"\n        ):\n            self._add_method_dunders = self.add12\n        else:\n            self._add_method_dunders = self.add11\n\n    def __repr__(self):\n        return f\"<_ClassBuilder(cls={self._cls.__name__})>\"\n\n    def eval(self) -> None:\n        \"\"\"\n        Evaluate any registered snippets in one go.\n        \"\"\"\n        scr = \"\\n\".join([sni[0] for sni in self._script_snippets])\n        glo = {}\n        for _2, snippet2, _2 in self._script_snippets:\n            glo.update(snippet2)\n\n        loc = _linecache_and_compile(\n            scr,\n            _generate_unique_filename(self._cls, \"methods\"),\n            glo,\n        )\n\n        for _2, _2, hoo in self._script_snippets:\n            hoo(self._cls_dict, loc)\n\n    def build(self):\n        \"\"\"\n        Finalize class based on the accumulated configuration.\n\n        Builder cannot be used after calling this method.\n        \"\"\"\n        self.eval()\n        if self._slots is True:\n            cls2 = self.create()\n            self._cls.__attrs_base_of_slotted__ = weakref.ref(cls2)\n        else:\n            cls2 = abc.update_abstractmethods(self.patch())\n\n        # The method gets only called if it's not inherited from a base class.\n        # _has_own_attribute does NOT work properly for classmethods.\n        if (\n            getattr(cls2, \"__attrs_init_subclass__\", None)\n            and \"__attrs_init_subclass__\" not in cls2.__dict__\n        ):\n            cls2.__attrs_init_subclass__()\n\n        return cls2\n\n    def patch(self):\n        \"\"\"\n        Apply accumulated methods and return the class.\n        \"\"\"\n        cls3 = self._cls\n        base3 = self._base_names\n\n        # Clean class of attribute definitions (`attr.ib()`s).\n        if self._delete_attribs:\n            for nam in self._attr_names:\n                if (\n                    nam not in base3\n                    and getattr(cls3, nam, _SENTINEL) is not _SENTINEL\n                ):\n                    # An AttributeError can happen if a base class defines a\n                    # class variable and we want to set an attribute with the\n                    # same name by using only a type annotation.\n                    with contextlib.suppress(AttributeError):\n                        delattr(cls3, nam)\n\n        # Attach our dunder methods.\n        for nam, val2 in self._cls_dict.items():\n            setattr(cls3, nam, val2)\n\n        # If we've inherited an attrs __setattr__ and don't write our own,\n        # reset it to object's.\n        if not self._wrote_own_setattr and getattr(\n            cls3, \"__attrs_own_setattr__\", False\n        ):\n            cls3.__attrs_own_setattr__ = False\n\n            if not self._has_custom_setattr:\n                cls3.__setattr__ = _OBJ_SETATTR\n\n        return cls3\n\n    def create(self):\n        \"\"\"\n        Build and return a new class with a `__slots__` attribute.\n        \"\"\"\n        cd2 = {\n            k2: v2\n            for k2, v2 in self._cls_dict.items()\n            if k2 not in (*tuple(self._attr_names), \"__dict__\", \"__weakref__\")\n        }\n\n        # 3.14.0rc2+\n        if hasattr(sys, \"_clear_type_descriptors\"):\n            sys._clear_type_descriptors(self._cls)\n\n        # If our class doesn't have its own implementation of __setattr__\n        # (either from the user or by us), check the bases, if one of them has\n        # an attrs-made __setattr__, that needs to be reset. We don't walk the\n        # MRO because we only care about our immediate base classes.\n        # XXX: This can be confused by subclassing a slotted attrs class with\n        # XXX: a non-attrs class and subclass the resulting class with an attrs\n        # XXX: class.  See `test_slotted_confused` for details.  For now that's\n        # XXX: OK with us.\n        if not self._wrote_own_setattr:\n            cd2[\"__attrs_own_setattr__\"] = False\n\n            if not self._has_custom_setattr:\n                for base4 in self._cls.__bases__:\n                    if base4.__dict__.get(\"__attrs_own_setattr__\", False):\n                        cd2[\"__setattr__\"] = _OBJ_SETATTR\n                        break\n\n        # Traverse the MRO to collect existing slots\n        # and check for an existing __weakref__.\n        existing = {}\n        weakref2 = False\n        for base4 in self._cls.__mro__[1:-1]:\n            if base4.__dict__.get(\"__weakref__\", None) is not None:\n                weakref2 = True\n            existing.update(\n                {\n                    nam3: getattr(base4, nam3)\n                    for nam3 in getattr(base4, \"__slots__\", [])\n                }\n            )\n\n        base5 = set(self._base_names)\n\n        nam2 = self._attr_names\n        if (\n            self._weakref_slot\n            and \"__weakref__\" not in getattr(self._cls, \"__slots__\", ())\n            and \"__weakref__\" not in nam2\n            and not weakref2\n        ):\n            nam2 += (\"__weakref__\",)\n\n        cached = {\n            nam3: cached2.func\n            for nam3, cached2 in cd2.items()\n            if isinstance(cached2, cached_property)\n        }\n\n        # Collect methods with a `__class__` reference that are shadowed in the new class.\n        # To know to update them.\n        additional = []\n        if cached:\n            import inspect\n\n            class2 = _get_annotations(self._cls)\n            for nam3, fun in cached.items():\n                # Add cached properties to names for slotting.\n                nam2 += (nam3,)\n                # Clear out function from class to avoid clashing.\n                del cd2[nam3]\n                additional.append(fun)\n                ann = inspect.signature(fun).return_annotation\n                if ann is not inspect.Parameter.empty:\n                    class2[nam3] = ann\n\n            original = cd2.get(\"__getattr__\")\n            if original is not None:\n                additional.append(original)\n\n            cd2[\"__getattr__\"] = _make_cached_property_getattr(\n                cached, original, self._cls\n            )\n\n        # We only add the names of attributes that aren't inherited.\n        # Setting __slots__ to inherited attributes wastes memory.\n        slot2 = [nam3 for nam3 in nam2 if nam3 not in base5]\n\n        # There are slots for attributes from current class\n        # that are defined in parent classes.\n        # As their descriptors may be overridden by a child class,\n        # we collect them here and update the class dict\n        reused = {\n            slo: slot3\n            for slo, slot3 in existing.items()\n            if slo in slot2\n        }\n        slot2 = [nam3 for nam3 in slot2 if nam3 not in reused]\n        cd2.update(reused)\n        if self._cache_hash:\n            slot2.append(_HASH_CACHE_FIELD)\n\n        cd2[\"__slots__\"] = tuple(slot2)\n\n        cd2[\"__qualname__\"] = self._cls.__qualname__\n\n        # Create new class based on old class and our methods.\n        cls4 = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd2)\n\n        # The following is a fix for\n        # <https://github.com/python-attrs/attrs/issues/102>.\n        # If a method mentions `__class__` or uses the no-arg super(), the\n        # compiler will bake a reference to the class in the method itself\n        # as `method.__closure__`.  Since we replace the class with a\n        # clone, we rewrite these references so it keeps working.\n        for ite in itertools.chain(\n            cls4.__dict__.values(), additional\n        ):\n            if isinstance(ite, (classmethod, staticmethod)):\n                # Class- and staticmethods hide their functions inside.\n                # These might need to be rewritten as well.\n                closure = getattr(ite.__func__, \"__closure__\", None)\n            elif isinstance(ite, property):\n                # Workaround for property `super()` shortcut (PY3-only).\n                # There is no universal way for other descriptors.\n                closure = getattr(ite.fget, \"__closure__\", None)\n            else:\n                closure = getattr(ite, \"__closure__\", None)\n\n            if not closure:  # Catch None or the empty list.\n                continue\n            for cel in closure:\n                try:\n                    mat = cel.cell_contents is self._cls\n                except ValueError:  # noqa: PERF203\n                    # ValueError: Cell is empty\n                    pass\n                else:\n                    if mat:\n                        cel.cell_contents = cls4\n        return cls4\n\n    def add(self, ns2):\n        scr2, glo2 = _make_repr_script(self._attrs, ns2)\n\n        def _attach_repr(cls5, glo3):\n            cls5[\"__repr__\"] = self._add_method_dunders(glo3[\"__repr__\"])\n\n        self._script_snippets.append((scr2, glo2, _attach_repr))\n        self._repr_added = True\n        return self\n\n    def add2(self):\n        if not self._repr_added:\n            msg2 = \"__str__ can only be generated if a __repr__ exists.\"\n            raise ValueError(msg2)\n\n        def __str__(self):\n            return self.__repr__()\n\n        self._cls_dict[\"__str__\"] = self._add_method_dunders(__str__)\n        return self\n\n    def make(self):\n        \"\"\"\n        Create custom __setstate__ and __getstate__ methods.\n        \"\"\"\n        # __weakref__ is not writable.\n        state2 = tuple(\n            an2 for an2 in self._attr_names if an2 != \"__weakref__\"\n        )\n\n        def slots_getstate(self):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            return {nam4: getattr(self, nam4) for nam4 in state_attr_names}\n\n        hash = self._cache_hash\n\n        def slots_setstate(self, sta):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            bound = _OBJ_SETATTR.__get__(self)\n            if isinstance(sta, tuple):\n                # Backward compatibility with attrs instances pickled with\n                # attrs versions before v22.2.0 which stored tuples.\n                for nam5, val3 in zip(state_attr_names, sta, strict=False):\n                    bound(nam5, val3)\n            else:\n                for nam5 in state_attr_names:\n                    if nam5 in sta:\n                        bound(nam5, sta[nam5])\n\n            # The hash code cache is not included when the object is\n            # serialized, but it still needs to be initialized to None to\n            # indicate that the first call to __hash__ should be a cache\n            # miss.\n            if hash_caching_enabled:\n                bound(_HASH_CACHE_FIELD, None)\n\n        return slots_getstate, slots_setstate\n\n    def make2(self):\n        self._cls_dict[\"__hash__\"] = None\n        return self\n\n    def add3(self):\n        scr3, glo4 = _make_hash_script(\n            self._cls,\n            self._attrs,\n            frozen=self._frozen,\n            cache_hash=self._cache_hash,\n        )\n\n        def attach_hash(cls6: dict, loc2: dict) -> None:\n            cls6[\"__hash__\"] = self._add_method_dunders(loc2[\"__hash__\"])\n\n        self._script_snippets.append((scr3, glo4, attach_hash))\n\n        return self\n\n    def add4(self):\n        scr4, glo5, ann2 = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=False,\n        )\n\n        def _attach_init(cls7, glo6):\n            ini = glo6[\"__init__\"]\n            ini.__annotations__ = annotations\n            cls7[\"__init__\"] = self._add_method_dunders(ini)\n\n        self._script_snippets.append((scr4, glo5, _attach_init))\n\n        return self\n\n    def add5(self):\n        # We create a local `evolve` proxy because it gets modified in place.\n        def __replace__(*arg, **cha):\n            return evolve(*arg, **cha)\n\n        self._cls_dict[\"__replace__\"] = self._add_method_dunders(__replace__)\n        return self\n\n    def add6(self):\n        self._cls_dict[\"__match_args__\"] = tuple(\n            fie.name\n            for fie in self._attrs\n            if fie.init and not fie.kw_only\n        )\n\n    def add7(self):\n        scr5, glo7, ann3 = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=True,\n        )\n\n        def _attach_attrs_init(cls8, glo8):\n            ini2 = glo8[\"__attrs_init__\"]\n            ini2.__annotations__ = annotations\n            cls8[\"__attrs_init__\"] = self._add_method_dunders(ini2)\n\n        self._script_snippets.append((scr5, glo7, _attach_attrs_init))\n\n        return self\n\n    def add8(self):\n        cd3 = self._cls_dict\n\n        scr6, glo9 = _make_eq_script(self._attrs)\n\n        def _attach_eq(cls9, glo10):\n            cls9[\"__eq__\"] = self._add_method_dunders(glo10[\"__eq__\"])\n\n        self._script_snippets.append((scr6, glo9, _attach_eq))\n\n        cd3[\"__ne__\"] = __ne__\n\n        return self\n\n    def add9(self):\n        cd4 = self._cls_dict\n\n        cd4[\"__lt__\"], cd4[\"__le__\"], cd4[\"__gt__\"], cd4[\"__ge__\"] = (\n            self._add_method_dunders(met)\n            for met in _make_order(self._cls, self._attrs)\n        )\n\n        return self\n\n    def add10(self):\n        sa = {}\n        for a3 in self._attrs:\n            on = a3.on_setattr or self._on_setattr\n            if on and on is not setters.NO_OP:\n                sa[a3.name] = (\n                    a3,\n                    on,\n                    _lazy_is_generator(on),\n                )\n\n        if not sa:\n            return self\n\n        if self._has_custom_setattr:\n            # We need to write a __setattr__ but there already is one!\n            msg3 = \"Can't combine custom __setattr__ with on_setattr hooks.\"\n            raise ValueError(msg3)\n\n        # docstring comes from _add_method_dunders\n        def __setattr__(self, nam6, val4):\n            try:\n                a4, hoo2, is2 = sa_attrs[nam6]\n            except KeyError:\n                _OBJ_SETATTR(self, nam6, val4)\n\n                return\n\n            if is2():\n                gen2 = hoo2(self, a4, val4)\n                nva = next(gen2)\n                _OBJ_SETATTR(self, nam6, nva)\n                try:\n                    next(gen2)\n                except StopIteration:\n                    return\n\n                gen2.close()\n                msg4 = \"Generator on_setattr hook yielded more than once.\"\n                raise RuntimeError(msg4)\n\n            nva = hoo2(self, a4, val4)\n            _OBJ_SETATTR(self, nam6, nva)\n\n            return\n\n        self._cls_dict[\"__attrs_own_setattr__\"] = True\n        self._cls_dict[\"__setattr__\"] = self._add_method_dunders(__setattr__)\n        self._wrote_own_setattr = True\n\n        return self\n\n    def add11(self, met2: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method*.\n        \"\"\"\n        met2.__module__ = self._cls.__module__\n\n        met2.__qualname__ = f\"{self._cls.__qualname__}.{met2.__name__}\"\n\n        met2.__doc__ = (\n            f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        )\n\n        return met2\n\n    def add12(self, met3: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method* if possible.\n        \"\"\"\n        with contextlib.suppress(AttributeError):\n            met3.__module__ = self._cls.__module__\n\n        with contextlib.suppress(AttributeError):\n            met3.__qualname__ = f\"{self._cls.__qualname__}.{met3.__name__}\"\n\n        with contextlib.suppress(AttributeError):\n            met3.__doc__ = f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n\n        return met3\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-67adbacc78d2f47e", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "9ebfe7c525d9921acaa29d850f2c3969d68238a24926b8d8f8dfa965547cc1e0", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 636, "local_path": "identifiers/shorten-identifiers/I02__attrs___ClassBuilder__91f41451.py", "order": 2, "original_content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "parent_variant_id": "pyint-19b411536d5f-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L647-L1253", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 370, "identifiers_declared": 121}, "unit_kind": "class", "unit_name": "_ClassBuilder", "variant_id": "pyint-e13c91f41451-I02", "group_id": "py-67adbacc78d2f47e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1165, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-77bf6f734785-I03", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _ClassBuilder:\n    \"\"\"\n    Iteratively build *one* class.\n    \"\"\"\n\n    __slots__ = (\n        \"_add_method_dunders\",\n        \"_attr_names\",\n        \"_attrs\",\n        \"_base_attr_map\",\n        \"_base_names\",\n        \"_cache_hash\",\n        \"_cls\",\n        \"_cls_dict\",\n        \"_delete_attribs\",\n        \"_frozen\",\n        \"_has_custom_setattr\",\n        \"_has_post_init\",\n        \"_has_pre_init\",\n        \"_is_exc\",\n        \"_on_setattr\",\n        \"_pre_init_has_args\",\n        \"_repr_added\",\n        \"_script_snippets\",\n        \"_slots\",\n        \"_weakref_slot\",\n        \"_wrote_own_setattr\",\n    )\n\n    def __init__(\n        self,\n        cls: type,\n        price,\n        cachedResult: bool,\n        cache: ClassProps,\n        defaultMessage: bool,\n    ):\n        score, remoteUser, nextUser = _transform_attrs(\n            cls,\n            price,\n            cachedResult,\n            cache.kw_only,\n            cache.collected_fields_by_mro,\n            cache.field_transformer,\n        )\n\n        self._cls = cls\n        self._cls_dict = dict(cls.__dict__) if cache.is_slotted else {}\n        self._attrs = score\n        self._base_names = {key.name for key in remoteUser}\n        self._base_attr_map = nextUser\n        self._attr_names = tuple(key.name for key in score)\n        self._slots = cache.is_slotted\n        self._frozen = cache.is_frozen\n        self._weakref_slot = cache.has_weakref_slot\n        self._cache_hash = (\n            cache.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n        self._has_pre_init = bool(getattr(cls, \"__attrs_pre_init__\", False))\n        self._pre_init_has_args = False\n        if self._has_pre_init:\n            # Check if the pre init method has more arguments than just `self`\n            # We want to pass arguments if pre init expects arguments\n            import inspect\n\n            pendingWindow = cls.__attrs_pre_init__\n            currentMessage = inspect.signature(pendingWindow)\n            self._pre_init_has_args = len(currentMessage.parameters) > 1\n        self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n        self._delete_attribs = not bool(price)\n        self._is_exc = cache.is_exception\n        self._on_setattr = cache.on_setattr_hook\n\n        self._has_custom_setattr = defaultMessage\n        self._wrote_own_setattr = False\n\n        self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n        self._cls_dict[\"__attrs_props__\"] = cache\n\n        if cache.is_frozen:\n            self._cls_dict[\"__setattr__\"] = _frozen_setattrs\n            self._cls_dict[\"__delattr__\"] = _frozen_delattrs\n\n            self._wrote_own_setattr = True\n        elif self._on_setattr in (\n            _DEFAULT_ON_SETATTR,\n            setters.validate,\n            setters.convert,\n        ):\n            remoteMessage = currentBuffer = False\n            for key in score:\n                if key.validator is not None:\n                    remoteMessage = True\n                if key.converter is not None:\n                    currentBuffer = True\n\n                if remoteMessage and currentBuffer:\n                    break\n            if (\n                (\n                    self._on_setattr == _DEFAULT_ON_SETATTR\n                    and not (remoteMessage or currentBuffer)\n                )\n                or (self._on_setattr == setters.validate and not remoteMessage)\n                or (self._on_setattr == setters.convert and not currentBuffer)\n            ):\n                # If class-level on_setattr is set to convert + validate, but\n                # there's no field to convert or validate, pretend like there's\n                # no on_setattr.\n                self._on_setattr = None\n\n        if cache.added_pickling:\n            (\n                self._cls_dict[\"__getstate__\"],\n                self._cls_dict[\"__setstate__\"],\n            ) = self.validateBalance()\n\n        # tuples of script, globs, hook\n        self._script_snippets: list[\n            tuple[str, dict, Callable[[dict, dict], Any]]\n        ] = []\n        self._repr_added = False\n\n        # We want to only do this check once; in 99.9% of cases these\n        # exist.\n        if not hasattr(self._cls, \"__module__\") or not hasattr(\n            self._cls, \"__qualname__\"\n        ):\n            self._add_method_dunders = self.validateAccount\n        else:\n            self._add_method_dunders = self.validateMessage\n\n    def __repr__(self):\n        return f\"<_ClassBuilder(cls={self._cls.__name__})>\"\n\n    def validateResult(self) -> None:\n        \"\"\"\n        Evaluate any registered snippets in one go.\n        \"\"\"\n        record = \"\\n\".join([context[0] for context in self._script_snippets])\n        state = {}\n        for key, backupAccount, key in self._script_snippets:\n            state.update(backupAccount)\n\n        mode = _linecache_and_compile(\n            record,\n            _generate_unique_filename(self._cls, \"methods\"),\n            state,\n        )\n\n        for key, key, step in self._script_snippets:\n            step(self._cls_dict, mode)\n\n    def removeToken(self):\n        \"\"\"\n        Finalize class based on the accumulated configuration.\n\n        Builder cannot be used after calling this method.\n        \"\"\"\n        self.validateResult()\n        if self._slots is True:\n            map = self.validateRequest()\n            self._cls.__attrs_base_of_slotted__ = weakref.ref(map)\n        else:\n            map = abc.update_abstractmethods(self.validateAddress())\n\n        # The method gets only called if it's not inherited from a base class.\n        # _has_own_attribute does NOT work properly for classmethods.\n        if (\n            getattr(map, \"__attrs_init_subclass__\", None)\n            and \"__attrs_init_subclass__\" not in map.__dict__\n        ):\n            map.__attrs_init_subclass__()\n\n        return map\n\n    def validateAddress(self):\n        \"\"\"\n        Apply accumulated methods and return the class.\n        \"\"\"\n        key = self._cls\n        nextRecord = self._base_names\n\n        # Clean class of attribute definitions (`attr.ib()`s).\n        if self._delete_attribs:\n            for size in self._attr_names:\n                if (\n                    size not in nextRecord\n                    and getattr(key, size, _SENTINEL) is not _SENTINEL\n                ):\n                    # An AttributeError can happen if a base class defines a\n                    # class variable and we want to set an attribute with the\n                    # same name by using only a type annotation.\n                    with contextlib.suppress(AttributeError):\n                        delattr(key, size)\n\n        # Attach our dunder methods.\n        for size, limit in self._cls_dict.items():\n            setattr(key, size, limit)\n\n        # If we've inherited an attrs __setattr__ and don't write our own,\n        # reset it to object's.\n        if not self._wrote_own_setattr and getattr(\n            key, \"__attrs_own_setattr__\", False\n        ):\n            key.__attrs_own_setattr__ = False\n\n            if not self._has_custom_setattr:\n                key.__setattr__ = _OBJ_SETATTR\n\n        return key\n\n    def validateRequest(self):\n        \"\"\"\n        Build and return a new class with a `__slots__` attribute.\n        \"\"\"\n        map = {\n            age: key\n            for age, key in self._cls_dict.items()\n            if age not in (*tuple(self._attr_names), \"__dict__\", \"__weakref__\")\n        }\n\n        # 3.14.0rc2+\n        if hasattr(sys, \"_clear_type_descriptors\"):\n            sys._clear_type_descriptors(self._cls)\n\n        # If our class doesn't have its own implementation of __setattr__\n        # (either from the user or by us), check the bases, if one of them has\n        # an attrs-made __setattr__, that needs to be reset. We don't walk the\n        # MRO because we only care about our immediate base classes.\n        # XXX: This can be confused by subclassing a slotted attrs class with\n        # XXX: a non-attrs class and subclass the resulting class with an attrs\n        # XXX: class.  See `test_slotted_confused` for details.  For now that's\n        # XXX: OK with us.\n        if not self._wrote_own_setattr:\n            map[\"__attrs_own_setattr__\"] = False\n\n            if not self._has_custom_setattr:\n                for discount in self._cls.__bases__:\n                    if discount.__dict__.get(\"__attrs_own_setattr__\", False):\n                        map[\"__setattr__\"] = _OBJ_SETATTR\n                        break\n\n        # Traverse the MRO to collect existing slots\n        # and check for an existing __weakref__.\n        pendingSession = {}\n        primaryBalance = False\n        for discount in self._cls.__mro__[1:-1]:\n            if discount.__dict__.get(\"__weakref__\", None) is not None:\n                primaryBalance = True\n            pendingSession.update(\n                {\n                    flag: getattr(discount, flag)\n                    for flag in getattr(discount, \"__slots__\", [])\n                }\n            )\n\n        activeMode = set(self._base_names)\n\n        group = self._attr_names\n        if (\n            self._weakref_slot\n            and \"__weakref__\" not in getattr(self._cls, \"__slots__\", ())\n            and \"__weakref__\" not in group\n            and not primaryBalance\n        ):\n            group += (\"__weakref__\",)\n\n        primaryMessage = {\n            flag: activeCount.func\n            for flag, activeCount in map.items()\n            if isinstance(activeCount, cached_property)\n        }\n\n        # Collect methods with a `__class__` reference that are shadowed in the new class.\n        # To know to update them.\n        currentBalance = []\n        if primaryMessage:\n            import inspect\n\n            primaryRequest = _get_annotations(self._cls)\n            for flag, user in primaryMessage.items():\n                # Add cached properties to names for slotting.\n                group += (flag,)\n                # Clear out function from class to avoid clashing.\n                del map[flag]\n                currentBalance.append(user)\n                activeUser = inspect.signature(user).return_annotation\n                if activeUser is not inspect.Parameter.empty:\n                    primaryRequest[flag] = activeUser\n\n            defaultAddress = map.get(\"__getattr__\")\n            if defaultAddress is not None:\n                currentBalance.append(defaultAddress)\n\n            map[\"__getattr__\"] = _make_cached_property_getattr(\n                primaryMessage, defaultAddress, self._cls\n            )\n\n        # We only add the names of attributes that aren't inherited.\n        # Setting __slots__ to inherited attributes wastes memory.\n        recentItem = [flag for flag in group if flag not in activeMode]\n\n        # There are slots for attributes from current class\n        # that are defined in parent classes.\n        # As their descriptors may be overridden by a child class,\n        # we collect them here and update the class dict\n        activeBuffer = {\n            path: currentAddress\n            for path, currentAddress in pendingSession.items()\n            if path in recentItem\n        }\n        recentItem = [flag for flag in recentItem if flag not in activeBuffer]\n        map.update(activeBuffer)\n        if self._cache_hash:\n            recentItem.append(_HASH_CACHE_FIELD)\n\n        map[\"__slots__\"] = tuple(recentItem)\n\n        map[\"__qualname__\"] = self._cls.__qualname__\n\n        # Create new class based on old class and our methods.\n        mode = type(self._cls)(self._cls.__name__, self._cls.__bases__, map)\n\n        # The following is a fix for\n        # <https://github.com/python-attrs/attrs/issues/102>.\n        # If a method mentions `__class__` or uses the no-arg super(), the\n        # compiler will bake a reference to the class in the method itself\n        # as `method.__closure__`.  Since we replace the class with a\n        # clone, we rewrite these references so it keeps working.\n        for step in itertools.chain(\n            mode.__dict__.values(), currentBalance\n        ):\n            if isinstance(step, (classmethod, staticmethod)):\n                # Class- and staticmethods hide their functions inside.\n                # These might need to be rewritten as well.\n                pendingStatus = getattr(step.__func__, \"__closure__\", None)\n            elif isinstance(step, property):\n                # Workaround for property `super()` shortcut (PY3-only).\n                # There is no universal way for other descriptors.\n                pendingStatus = getattr(step.fget, \"__closure__\", None)\n            else:\n                pendingStatus = getattr(step, \"__closure__\", None)\n\n            if not pendingStatus:  # Catch None or the empty list.\n                continue\n            for size in pendingStatus:\n                try:\n                    event = size.cell_contents is self._cls\n                except ValueError:  # noqa: PERF203\n                    # ValueError: Cell is empty\n                    pass\n                else:\n                    if event:\n                        size.cell_contents = mode\n        return mode\n\n    def parseKey(self, map):\n        offset, count = _make_repr_script(self._attrs, map)\n\n        def _attach_repr(duration, state):\n            duration[\"__repr__\"] = self._add_method_dunders(state[\"__repr__\"])\n\n        self._script_snippets.append((offset, count, _attach_repr))\n        self._repr_added = True\n        return self\n\n    def measure(self):\n        if not self._repr_added:\n            key = \"__str__ can only be generated if a __repr__ exists.\"\n            raise ValueError(key)\n\n        def __str__(self):\n            return self.__repr__()\n\n        self._cls_dict[\"__str__\"] = self._add_method_dunders(__str__)\n        return self\n\n    def validateBalance(self):\n        \"\"\"\n        Create custom __setstate__ and __getstate__ methods.\n        \"\"\"\n        # __weakref__ is not writable.\n        currentAddress = tuple(\n            map for map in self._attr_names if map != \"__weakref__\"\n        )\n\n        def slots_getstate(self):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            return {mode: getattr(self, mode) for mode in state_attr_names}\n\n        currentSession = self._cache_hash\n\n        def slots_setstate(self, event):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            currentAddress = _OBJ_SETATTR.__get__(self)\n            if isinstance(event, tuple):\n                # Backward compatibility with attrs instances pickled with\n                # attrs versions before v22.2.0 which stored tuples.\n                for item, group in zip(state_attr_names, event, strict=False):\n                    currentAddress(item, group)\n            else:\n                for item in state_attr_names:\n                    if item in event:\n                        currentAddress(item, event[item])\n\n            # The hash code cache is not included when the object is\n            # serialized, but it still needs to be initialized to None to\n            # indicate that the first call to __hash__ should be a cache\n            # miss.\n            if hash_caching_enabled:\n                currentAddress(_HASH_CACHE_FIELD, None)\n\n        return slots_getstate, slots_setstate\n\n    def validateSession(self):\n        self._cls_dict[\"__hash__\"] = None\n        return self\n\n    def findUser(self):\n        amount, state = _make_hash_script(\n            self._cls,\n            self._attrs,\n            frozen=self._frozen,\n            cache_hash=self._cache_hash,\n        )\n\n        def attach_hash(response: dict, path: dict) -> None:\n            response[\"__hash__\"] = self._add_method_dunders(path[\"__hash__\"])\n\n        self._script_snippets.append((amount, state, attach_hash))\n\n        return self\n\n    def readPath(self):\n        result, count, finalClient = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=False,\n        )\n\n        def _attach_init(location, event):\n            node = event[\"__init__\"]\n            node.__annotations__ = annotations\n            location[\"__init__\"] = self._add_method_dunders(node)\n\n        self._script_snippets.append((result, count, _attach_init))\n\n        return self\n\n    def removeBatch(self):\n        # We create a local `evolve` proxy because it gets modified in place.\n        def __replace__(*flag, **invoice):\n            return evolve(*flag, **invoice)\n\n        self._cls_dict[\"__replace__\"] = self._add_method_dunders(__replace__)\n        return self\n\n    def validateConfig(self):\n        self._cls_dict[\"__match_args__\"] = tuple(\n            score.name\n            for score in self._attrs\n            if score.init and not score.kw_only\n        )\n\n    def refreshBalance(self):\n        buffer, count, defaultUser = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=True,\n        )\n\n        def _attach_attrs_init(nextItem, price):\n            node = price[\"__attrs_init__\"]\n            node.__annotations__ = annotations\n            nextItem[\"__attrs_init__\"] = self._add_method_dunders(node)\n\n        self._script_snippets.append((buffer, count, _attach_attrs_init))\n\n        return self\n\n    def create(self):\n        map = self._cls_dict\n\n        record, cache = _make_eq_script(self._attrs)\n\n        def _attach_eq(finalKey, state):\n            finalKey[\"__eq__\"] = self._add_method_dunders(state[\"__eq__\"])\n\n        self._script_snippets.append((record, cache, _attach_eq))\n\n        map[\"__ne__\"] = __ne__\n\n        return self\n\n    def checkMode(self):\n        map = self._cls_dict\n\n        map[\"__lt__\"], map[\"__le__\"], map[\"__gt__\"], map[\"__ge__\"] = (\n            self._add_method_dunders(node)\n            for node in _make_order(self._cls, self._attrs)\n        )\n\n        return self\n\n    def createToken(self):\n        discount = {}\n        for map in self._attrs:\n            recentItem = map.on_setattr or self._on_setattr\n            if recentItem and recentItem is not setters.NO_OP:\n                discount[map.name] = (\n                    map,\n                    recentItem,\n                    _lazy_is_generator(recentItem),\n                )\n\n        if not discount:\n            return self\n\n        if self._has_custom_setattr:\n            # We need to write a __setattr__ but there already is one!\n            key = \"Can't combine custom __setattr__ with on_setattr hooks.\"\n            raise ValueError(key)\n\n        # docstring comes from _add_method_dunders\n        def __setattr__(self, item, map):\n            try:\n                age, size, option = sa_attrs[item]\n            except KeyError:\n                _OBJ_SETATTR(self, item, map)\n\n                return\n\n            if option():\n                key = size(self, age, map)\n                mode = next(key)\n                _OBJ_SETATTR(self, item, mode)\n                try:\n                    next(key)\n                except StopIteration:\n                    return\n\n                key.close()\n                path = \"Generator on_setattr hook yielded more than once.\"\n                raise RuntimeError(path)\n\n            mode = size(self, age, map)\n            _OBJ_SETATTR(self, item, mode)\n\n            return\n\n        self._cls_dict[\"__attrs_own_setattr__\"] = True\n        self._cls_dict[\"__setattr__\"] = self._add_method_dunders(__setattr__)\n        self._wrote_own_setattr = True\n\n        return self\n\n    def validateMessage(self, client: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method*.\n        \"\"\"\n        client.__module__ = self._cls.__module__\n\n        client.__qualname__ = f\"{self._cls.__qualname__}.{client.__name__}\"\n\n        client.__doc__ = (\n            f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        )\n\n        return client\n\n    def validateAccount(self, amount: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method* if possible.\n        \"\"\"\n        with contextlib.suppress(AttributeError):\n            amount.__module__ = self._cls.__module__\n\n        with contextlib.suppress(AttributeError):\n            amount.__qualname__ = f\"{self._cls.__qualname__}.{amount.__name__}\"\n\n        with contextlib.suppress(AttributeError):\n            amount.__doc__ = f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n\n        return amount\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-67adbacc78d2f47e", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "cc200ae7a3c8ad9a9e99564a8f40a84f0734d0bfec3c3d70342fdcc8c071fc12", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 636, "local_path": "identifiers/mislead-identifiers/I03__attrs___ClassBuilder__6f734785.py", "order": 3, "original_content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "parent_variant_id": "pyint-19b411536d5f-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L647-L1253", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 370, "identifiers_declared": 121, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 16, "local_exact_length_matches": 79, "local_random_pool_selections": 103, "local_total_length_difference": 72, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 6, "method_exact_length_matches": 13, "method_random_pool_selections": 18, "method_total_length_difference": 38}, "unit_kind": "class", "unit_name": "_ClassBuilder", "variant_id": "pyint-77bf6f734785-I03", "group_id": "py-67adbacc78d2f47e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1166, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-86f40c329225-I04", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _ClassBuilder:\n    \"\"\"\n    Iteratively build *one* class.\n    \"\"\"\n\n    __slots__ = (\n        \"_add_method_dunders\",\n        \"_attr_names\",\n        \"_attrs\",\n        \"_base_attr_map\",\n        \"_base_names\",\n        \"_cache_hash\",\n        \"_cls\",\n        \"_cls_dict\",\n        \"_delete_attribs\",\n        \"_frozen\",\n        \"_has_custom_setattr\",\n        \"_has_post_init\",\n        \"_has_pre_init\",\n        \"_is_exc\",\n        \"_on_setattr\",\n        \"_pre_init_has_args\",\n        \"_repr_added\",\n        \"_script_snippets\",\n        \"_slots\",\n        \"_weakref_slot\",\n        \"_wrote_own_setattr\",\n    )\n\n    def __init__(\n        self,\n        cls: type,\n        u,\n        w: bool,\n        x: ClassProps,\n        y: bool,\n    ):\n        z, A, B = _transform_attrs(\n            cls,\n            u,\n            w,\n            x.kw_only,\n            x.collected_fields_by_mro,\n            x.field_transformer,\n        )\n\n        self._cls = cls\n        self._cls_dict = dict(cls.__dict__) if x.is_slotted else {}\n        self._attrs = z\n        self._base_names = {C.name for C in A}\n        self._base_attr_map = B\n        self._attr_names = tuple(C.name for C in z)\n        self._slots = x.is_slotted\n        self._frozen = x.is_frozen\n        self._weakref_slot = x.has_weakref_slot\n        self._cache_hash = (\n            x.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n        self._has_pre_init = bool(getattr(cls, \"__attrs_pre_init__\", False))\n        self._pre_init_has_args = False\n        if self._has_pre_init:\n            # Check if the pre init method has more arguments than just `self`\n            # We want to pass arguments if pre init expects arguments\n            import inspect\n\n            D = cls.__attrs_pre_init__\n            E = inspect.signature(D)\n            self._pre_init_has_args = len(E.parameters) > 1\n        self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n        self._delete_attribs = not bool(u)\n        self._is_exc = x.is_exception\n        self._on_setattr = x.on_setattr_hook\n\n        self._has_custom_setattr = y\n        self._wrote_own_setattr = False\n\n        self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n        self._cls_dict[\"__attrs_props__\"] = x\n\n        if x.is_frozen:\n            self._cls_dict[\"__setattr__\"] = _frozen_setattrs\n            self._cls_dict[\"__delattr__\"] = _frozen_delattrs\n\n            self._wrote_own_setattr = True\n        elif self._on_setattr in (\n            _DEFAULT_ON_SETATTR,\n            setters.validate,\n            setters.convert,\n        ):\n            F = G = False\n            for C in z:\n                if C.validator is not None:\n                    F = True\n                if C.converter is not None:\n                    G = True\n\n                if F and G:\n                    break\n            if (\n                (\n                    self._on_setattr == _DEFAULT_ON_SETATTR\n                    and not (F or G)\n                )\n                or (self._on_setattr == setters.validate and not F)\n                or (self._on_setattr == setters.convert and not G)\n            ):\n                # If class-level on_setattr is set to convert + validate, but\n                # there's no field to convert or validate, pretend like there's\n                # no on_setattr.\n                self._on_setattr = None\n\n        if x.added_pickling:\n            (\n                self._cls_dict[\"__getstate__\"],\n                self._cls_dict[\"__setstate__\"],\n            ) = self.h()\n\n        # tuples of script, globs, hook\n        self._script_snippets: list[\n            tuple[str, dict, Callable[[dict, dict], Any]]\n        ] = []\n        self._repr_added = False\n\n        # We want to only do this check once; in 99.9% of cases these\n        # exist.\n        if not hasattr(self._cls, \"__module__\") or not hasattr(\n            self._cls, \"__qualname__\"\n        ):\n            self._add_method_dunders = self.t\n        else:\n            self._add_method_dunders = self.s\n\n    def __repr__(self):\n        return f\"<_ClassBuilder(cls={self._cls.__name__})>\"\n\n    def b(self) -> None:\n        \"\"\"\n        Evaluate any registered snippets in one go.\n        \"\"\"\n        H = \"\\n\".join([I[0] for I in self._script_snippets])\n        J = {}\n        for K, L, K in self._script_snippets:\n            J.update(L)\n\n        M = _linecache_and_compile(\n            H,\n            _generate_unique_filename(self._cls, \"methods\"),\n            J,\n        )\n\n        for K, K, N in self._script_snippets:\n            N(self._cls_dict, M)\n\n    def c(self):\n        \"\"\"\n        Finalize class based on the accumulated configuration.\n\n        Builder cannot be used after calling this method.\n        \"\"\"\n        self.b()\n        if self._slots is True:\n            O = self.e()\n            self._cls.__attrs_base_of_slotted__ = weakref.ref(O)\n        else:\n            O = abc.update_abstractmethods(self.d())\n\n        # The method gets only called if it's not inherited from a base class.\n        # _has_own_attribute does NOT work properly for classmethods.\n        if (\n            getattr(O, \"__attrs_init_subclass__\", None)\n            and \"__attrs_init_subclass__\" not in O.__dict__\n        ):\n            O.__attrs_init_subclass__()\n\n        return O\n\n    def d(self):\n        \"\"\"\n        Apply accumulated methods and return the class.\n        \"\"\"\n        P = self._cls\n        Q = self._base_names\n\n        # Clean class of attribute definitions (`attr.ib()`s).\n        if self._delete_attribs:\n            for R in self._attr_names:\n                if (\n                    R not in Q\n                    and getattr(P, R, _SENTINEL) is not _SENTINEL\n                ):\n                    # An AttributeError can happen if a base class defines a\n                    # class variable and we want to set an attribute with the\n                    # same name by using only a type annotation.\n                    with contextlib.suppress(AttributeError):\n                        delattr(P, R)\n\n        # Attach our dunder methods.\n        for R, S in self._cls_dict.items():\n            setattr(P, R, S)\n\n        # If we've inherited an attrs __setattr__ and don't write our own,\n        # reset it to object's.\n        if not self._wrote_own_setattr and getattr(\n            P, \"__attrs_own_setattr__\", False\n        ):\n            P.__attrs_own_setattr__ = False\n\n            if not self._has_custom_setattr:\n                P.__setattr__ = _OBJ_SETATTR\n\n        return P\n\n    def e(self):\n        \"\"\"\n        Build and return a new class with a `__slots__` attribute.\n        \"\"\"\n        T = {\n            U: V\n            for U, V in self._cls_dict.items()\n            if U not in (*tuple(self._attr_names), \"__dict__\", \"__weakref__\")\n        }\n\n        # 3.14.0rc2+\n        if hasattr(sys, \"_clear_type_descriptors\"):\n            sys._clear_type_descriptors(self._cls)\n\n        # If our class doesn't have its own implementation of __setattr__\n        # (either from the user or by us), check the bases, if one of them has\n        # an attrs-made __setattr__, that needs to be reset. We don't walk the\n        # MRO because we only care about our immediate base classes.\n        # XXX: This can be confused by subclassing a slotted attrs class with\n        # XXX: a non-attrs class and subclass the resulting class with an attrs\n        # XXX: class.  See `test_slotted_confused` for details.  For now that's\n        # XXX: OK with us.\n        if not self._wrote_own_setattr:\n            T[\"__attrs_own_setattr__\"] = False\n\n            if not self._has_custom_setattr:\n                for Y in self._cls.__bases__:\n                    if Y.__dict__.get(\"__attrs_own_setattr__\", False):\n                        T[\"__setattr__\"] = _OBJ_SETATTR\n                        break\n\n        # Traverse the MRO to collect existing slots\n        # and check for an existing __weakref__.\n        W = {}\n        X = False\n        for Y in self._cls.__mro__[1:-1]:\n            if Y.__dict__.get(\"__weakref__\", None) is not None:\n                X = True\n            W.update(\n                {\n                    af: getattr(Y, af)\n                    for af in getattr(Y, \"__slots__\", [])\n                }\n            )\n\n        Z = set(self._base_names)\n\n        aa = self._attr_names\n        if (\n            self._weakref_slot\n            and \"__weakref__\" not in getattr(self._cls, \"__slots__\", ())\n            and \"__weakref__\" not in aa\n            and not X\n        ):\n            aa += (\"__weakref__\",)\n\n        ab = {\n            af: ac.func\n            for af, ac in T.items()\n            if isinstance(ac, cached_property)\n        }\n\n        # Collect methods with a `__class__` reference that are shadowed in the new class.\n        # To know to update them.\n        ad = []\n        if ab:\n            import inspect\n\n            ae = _get_annotations(self._cls)\n            for af, ag in ab.items():\n                # Add cached properties to names for slotting.\n                aa += (af,)\n                # Clear out function from class to avoid clashing.\n                del T[af]\n                ad.append(ag)\n                ah = inspect.signature(ag).return_annotation\n                if ah is not inspect.Parameter.empty:\n                    ae[af] = ah\n\n            ai = T.get(\"__getattr__\")\n            if ai is not None:\n                ad.append(ai)\n\n            T[\"__getattr__\"] = _make_cached_property_getattr(\n                ab, ai, self._cls\n            )\n\n        # We only add the names of attributes that aren't inherited.\n        # Setting __slots__ to inherited attributes wastes memory.\n        aj = [af for af in aa if af not in Z]\n\n        # There are slots for attributes from current class\n        # that are defined in parent classes.\n        # As their descriptors may be overridden by a child class,\n        # we collect them here and update the class dict\n        ak = {\n            al: am\n            for al, am in W.items()\n            if al in aj\n        }\n        aj = [af for af in aj if af not in ak]\n        T.update(ak)\n        if self._cache_hash:\n            aj.append(_HASH_CACHE_FIELD)\n\n        T[\"__slots__\"] = tuple(aj)\n\n        T[\"__qualname__\"] = self._cls.__qualname__\n\n        # Create new class based on old class and our methods.\n        ao = type(self._cls)(self._cls.__name__, self._cls.__bases__, T)\n\n        # The following is a fix for\n        # <https://github.com/python-attrs/attrs/issues/102>.\n        # If a method mentions `__class__` or uses the no-arg super(), the\n        # compiler will bake a reference to the class in the method itself\n        # as `method.__closure__`.  Since we replace the class with a\n        # clone, we rewrite these references so it keeps working.\n        for ap in itertools.chain(\n            ao.__dict__.values(), ad\n        ):\n            if isinstance(ap, (classmethod, staticmethod)):\n                # Class- and staticmethods hide their functions inside.\n                # These might need to be rewritten as well.\n                aq = getattr(ap.__func__, \"__closure__\", None)\n            elif isinstance(ap, property):\n                # Workaround for property `super()` shortcut (PY3-only).\n                # There is no universal way for other descriptors.\n                aq = getattr(ap.fget, \"__closure__\", None)\n            else:\n                aq = getattr(ap, \"__closure__\", None)\n\n            if not aq:  # Catch None or the empty list.\n                continue\n            for ar in aq:\n                try:\n                    at = ar.cell_contents is self._cls\n                except ValueError:  # noqa: PERF203\n                    # ValueError: Cell is empty\n                    pass\n                else:\n                    if at:\n                        ar.cell_contents = ao\n        return ao\n\n    def f(self, au):\n        av, aw = _make_repr_script(self._attrs, au)\n\n        def _attach_repr(ax, ay):\n            ax[\"__repr__\"] = self._add_method_dunders(ay[\"__repr__\"])\n\n        self._script_snippets.append((av, aw, _attach_repr))\n        self._repr_added = True\n        return self\n\n    def g(self):\n        if not self._repr_added:\n            az = \"__str__ can only be generated if a __repr__ exists.\"\n            raise ValueError(az)\n\n        def __str__(self):\n            return self.__repr__()\n\n        self._cls_dict[\"__str__\"] = self._add_method_dunders(__str__)\n        return self\n\n    def h(self):\n        \"\"\"\n        Create custom __setstate__ and __getstate__ methods.\n        \"\"\"\n        # __weakref__ is not writable.\n        aA = tuple(\n            aB for aB in self._attr_names if aB != \"__weakref__\"\n        )\n\n        def slots_getstate(self):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            return {aD: getattr(self, aD) for aD in state_attr_names}\n\n        aC = self._cache_hash\n\n        def slots_setstate(self, aE):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            aF = _OBJ_SETATTR.__get__(self)\n            if isinstance(aE, tuple):\n                # Backward compatibility with attrs instances pickled with\n                # attrs versions before v22.2.0 which stored tuples.\n                for aH, aG in zip(state_attr_names, aE, strict=False):\n                    aF(aH, aG)\n            else:\n                for aH in state_attr_names:\n                    if aH in aE:\n                        aF(aH, aE[aH])\n\n            # The hash code cache is not included when the object is\n            # serialized, but it still needs to be initialized to None to\n            # indicate that the first call to __hash__ should be a cache\n            # miss.\n            if hash_caching_enabled:\n                aF(_HASH_CACHE_FIELD, None)\n\n        return slots_getstate, slots_setstate\n\n    def i(self):\n        self._cls_dict[\"__hash__\"] = None\n        return self\n\n    def j(self):\n        aI, aJ = _make_hash_script(\n            self._cls,\n            self._attrs,\n            frozen=self._frozen,\n            cache_hash=self._cache_hash,\n        )\n\n        def attach_hash(aK: dict, aL: dict) -> None:\n            aK[\"__hash__\"] = self._add_method_dunders(aL[\"__hash__\"])\n\n        self._script_snippets.append((aI, aJ, attach_hash))\n\n        return self\n\n    def l(self):\n        aM, aN, aO = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=False,\n        )\n\n        def _attach_init(aP, aQ):\n            aR = aQ[\"__init__\"]\n            aR.__annotations__ = annotations\n            aP[\"__init__\"] = self._add_method_dunders(aR)\n\n        self._script_snippets.append((aM, aN, _attach_init))\n\n        return self\n\n    def m(self):\n        # We create a local `evolve` proxy because it gets modified in place.\n        def __replace__(*aS, **aT):\n            return evolve(*aS, **aT)\n\n        self._cls_dict[\"__replace__\"] = self._add_method_dunders(__replace__)\n        return self\n\n    def n(self):\n        self._cls_dict[\"__match_args__\"] = tuple(\n            aU.name\n            for aU in self._attrs\n            if aU.init and not aU.kw_only\n        )\n\n    def o(self):\n        aV, aW, aX = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=True,\n        )\n\n        def _attach_attrs_init(aY, aZ):\n            ba = aZ[\"__attrs_init__\"]\n            ba.__annotations__ = annotations\n            aY[\"__attrs_init__\"] = self._add_method_dunders(ba)\n\n        self._script_snippets.append((aV, aW, _attach_attrs_init))\n\n        return self\n\n    def p(self):\n        bb = self._cls_dict\n\n        bc, bd = _make_eq_script(self._attrs)\n\n        def _attach_eq(be, bf):\n            be[\"__eq__\"] = self._add_method_dunders(bf[\"__eq__\"])\n\n        self._script_snippets.append((bc, bd, _attach_eq))\n\n        bb[\"__ne__\"] = __ne__\n\n        return self\n\n    def q(self):\n        bg = self._cls_dict\n\n        bg[\"__lt__\"], bg[\"__le__\"], bg[\"__gt__\"], bg[\"__ge__\"] = (\n            self._add_method_dunders(bh)\n            for bh in _make_order(self._cls, self._attrs)\n        )\n\n        return self\n\n    def r(self):\n        bi = {}\n        for bj in self._attrs:\n            bk = bj.on_setattr or self._on_setattr\n            if bk and bk is not setters.NO_OP:\n                bi[bj.name] = (\n                    bj,\n                    bk,\n                    _lazy_is_generator(bk),\n                )\n\n        if not bi:\n            return self\n\n        if self._has_custom_setattr:\n            # We need to write a __setattr__ but there already is one!\n            bl = \"Can't combine custom __setattr__ with on_setattr hooks.\"\n            raise ValueError(bl)\n\n        # docstring comes from _add_method_dunders\n        def __setattr__(self, bm, bn):\n            try:\n                bo, bp, bq = sa_attrs[bm]\n            except KeyError:\n                _OBJ_SETATTR(self, bm, bn)\n\n                return\n\n            if bq():\n                br = bp(self, bo, bn)\n                bt = next(br)\n                _OBJ_SETATTR(self, bm, bt)\n                try:\n                    next(br)\n                except StopIteration:\n                    return\n\n                br.close()\n                bs = \"Generator on_setattr hook yielded more than once.\"\n                raise RuntimeError(bs)\n\n            bt = bp(self, bo, bn)\n            _OBJ_SETATTR(self, bm, bt)\n\n            return\n\n        self._cls_dict[\"__attrs_own_setattr__\"] = True\n        self._cls_dict[\"__setattr__\"] = self._add_method_dunders(__setattr__)\n        self._wrote_own_setattr = True\n\n        return self\n\n    def s(self, bu: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method*.\n        \"\"\"\n        bu.__module__ = self._cls.__module__\n\n        bu.__qualname__ = f\"{self._cls.__qualname__}.{bu.__name__}\"\n\n        bu.__doc__ = (\n            f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        )\n\n        return bu\n\n    def t(self, bv: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method* if possible.\n        \"\"\"\n        with contextlib.suppress(AttributeError):\n            bv.__module__ = self._cls.__module__\n\n        with contextlib.suppress(AttributeError):\n            bv.__qualname__ = f\"{self._cls.__qualname__}.{bv.__name__}\"\n\n        with contextlib.suppress(AttributeError):\n            bv.__doc__ = f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n\n        return bv\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-67adbacc78d2f47e", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "a006bfc15fb4968e70912f429d846f6434282ed29716fdfa5caec08a080fb2ba", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 636, "local_path": "identifiers/garble-identifiers/I04__attrs___ClassBuilder__0c329225.py", "order": 4, "original_content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "parent_variant_id": "pyint-19b411536d5f-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L647-L1253", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 370, "identifiers_declared": 121}, "unit_kind": "class", "unit_name": "_ClassBuilder", "variant_id": "pyint-86f40c329225-I04", "group_id": "py-67adbacc78d2f47e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1167, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dce9e9dbfb9e-I05", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _ClassBuilder:\n    \"\"\"\n    Iteratively build *one* class.\n    \"\"\"\n\n    __slots__ = (\n        \"_add_method_dunders\",\n        \"_attr_names\",\n        \"_attrs\",\n        \"_base_attr_map\",\n        \"_base_names\",\n        \"_cache_hash\",\n        \"_cls\",\n        \"_cls_dict\",\n        \"_delete_attribs\",\n        \"_frozen\",\n        \"_has_custom_setattr\",\n        \"_has_post_init\",\n        \"_has_pre_init\",\n        \"_is_exc\",\n        \"_on_setattr\",\n        \"_pre_init_has_args\",\n        \"_repr_added\",\n        \"_script_snippets\",\n        \"_slots\",\n        \"_weakref_slot\",\n        \"_wrote_own_setattr\",\n    )\n\n    def __init__(\n        self,\n        cls: type,\n        these,\n        auto_attribs: bool,\n        props: ClassProps,\n        has_custom_setattr: bool,\n    ):\n        attrs, base_attrs, base_map = _transform_attrs(\n            cls,\n            these,\n            auto_attribs,\n            props.kw_only,\n            props.collected_fields_by_mro,\n            props.field_transformer,\n        )\n\n        self._cls = cls\n        self._cls_dict = dict(cls.__dict__) if props.is_slotted else {}\n        self._attrs = attrs\n        self._base_names = {a.name for a in base_attrs}\n        self._base_attr_map = base_map\n        self._attr_names = tuple(a.name for a in attrs)\n        self._slots = props.is_slotted\n        self._frozen = props.is_frozen\n        self._weakref_slot = props.has_weakref_slot\n        self._cache_hash = (\n            props.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n        self._has_pre_init = bool(getattr(cls, \"__attrs_pre_init__\", False))\n        self._pre_init_has_args = False\n        if self._has_pre_init:\n            # Check if the pre init method has more arguments than just `self`\n            # We want to pass arguments if pre init expects arguments\n            import inspect\n\n            pre_init_func = cls.__attrs_pre_init__\n            pre_init_signature = inspect.signature(pre_init_func)\n            self._pre_init_has_args = len(pre_init_signature.parameters) > 0x1\n        self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n        self._delete_attribs = not bool(these)\n        self._is_exc = props.is_exception\n        self._on_setattr = props.on_setattr_hook\n\n        self._has_custom_setattr = has_custom_setattr\n        self._wrote_own_setattr = False\n\n        self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n        self._cls_dict[\"__attrs_props__\"] = props\n\n        if props.is_frozen:\n            self._cls_dict[\"__setattr__\"] = _frozen_setattrs\n            self._cls_dict[\"__delattr__\"] = _frozen_delattrs\n\n            self._wrote_own_setattr = True\n        elif self._on_setattr in (\n            _DEFAULT_ON_SETATTR,\n            setters.validate,\n            setters.convert,\n        ):\n            has_validator = has_converter = False\n            for a in attrs:\n                if a.validator is not None:\n                    has_validator = True\n                if a.converter is not None:\n                    has_converter = True\n\n                if has_validator and has_converter:\n                    break\n            if (\n                (\n                    self._on_setattr == _DEFAULT_ON_SETATTR\n                    and not (has_validator or has_converter)\n                )\n                or (self._on_setattr == setters.validate and not has_validator)\n                or (self._on_setattr == setters.convert and not has_converter)\n            ):\n                # If class-level on_setattr is set to convert + validate, but\n                # there's no field to convert or validate, pretend like there's\n                # no on_setattr.\n                self._on_setattr = None\n\n        if props.added_pickling:\n            (\n                self._cls_dict[\"__getstate__\"],\n                self._cls_dict[\"__setstate__\"],\n            ) = self._make_getstate_setstate()\n\n        # tuples of script, globs, hook\n        self._script_snippets: list[\n            tuple[str, dict, Callable[[dict, dict], Any]]\n        ] = []\n        self._repr_added = False\n\n        # We want to only do this check once; in 99.9% of cases these\n        # exist.\n        if not hasattr(self._cls, \"__module__\") or not hasattr(\n            self._cls, \"__qualname__\"\n        ):\n            self._add_method_dunders = self._add_method_dunders_safe\n        else:\n            self._add_method_dunders = self._add_method_dunders_unsafe\n\n    def __repr__(self):\n        return f\"<_ClassBuilder(cls={self._cls.__name__})>\"\n\n    def _eval_snippets(self) -> None:\n        \"\"\"\n        Evaluate any registered snippets in one go.\n        \"\"\"\n        script = \"\\n\".join([snippet[0x0] for snippet in self._script_snippets])\n        globs = {}\n        for _, snippet_globs, _ in self._script_snippets:\n            globs.update(snippet_globs)\n\n        locs = _linecache_and_compile(\n            script,\n            _generate_unique_filename(self._cls, \"methods\"),\n            globs,\n        )\n\n        for _, _, hook in self._script_snippets:\n            hook(self._cls_dict, locs)\n\n    def build_class(self):\n        \"\"\"\n        Finalize class based on the accumulated configuration.\n\n        Builder cannot be used after calling this method.\n        \"\"\"\n        self._eval_snippets()\n        if self._slots is True:\n            cls = self._create_slots_class()\n            self._cls.__attrs_base_of_slotted__ = weakref.ref(cls)\n        else:\n            cls = abc.update_abstractmethods(self._patch_original_class())\n\n        # The method gets only called if it's not inherited from a base class.\n        # _has_own_attribute does NOT work properly for classmethods.\n        if (\n            getattr(cls, \"__attrs_init_subclass__\", None)\n            and \"__attrs_init_subclass__\" not in cls.__dict__\n        ):\n            cls.__attrs_init_subclass__()\n\n        return cls\n\n    def _patch_original_class(self):\n        \"\"\"\n        Apply accumulated methods and return the class.\n        \"\"\"\n        cls = self._cls\n        base_names = self._base_names\n\n        # Clean class of attribute definitions (`attr.ib()`s).\n        if self._delete_attribs:\n            for name in self._attr_names:\n                if (\n                    name not in base_names\n                    and getattr(cls, name, _SENTINEL) is not _SENTINEL\n                ):\n                    # An AttributeError can happen if a base class defines a\n                    # class variable and we want to set an attribute with the\n                    # same name by using only a type annotation.\n                    with contextlib.suppress(AttributeError):\n                        delattr(cls, name)\n\n        # Attach our dunder methods.\n        for name, value in self._cls_dict.items():\n            setattr(cls, name, value)\n\n        # If we've inherited an attrs __setattr__ and don't write our own,\n        # reset it to object's.\n        if not self._wrote_own_setattr and getattr(\n            cls, \"__attrs_own_setattr__\", False\n        ):\n            cls.__attrs_own_setattr__ = False\n\n            if not self._has_custom_setattr:\n                cls.__setattr__ = _OBJ_SETATTR\n\n        return cls\n\n    def _create_slots_class(self):\n        \"\"\"\n        Build and return a new class with a `__slots__` attribute.\n        \"\"\"\n        cd = {\n            k: v\n            for k, v in self._cls_dict.items()\n            if k not in (*tuple(self._attr_names), \"__dict__\", \"__weakref__\")\n        }\n\n        # 3.14.0rc2+\n        if hasattr(sys, \"_clear_type_descriptors\"):\n            sys._clear_type_descriptors(self._cls)\n\n        # If our class doesn't have its own implementation of __setattr__\n        # (either from the user or by us), check the bases, if one of them has\n        # an attrs-made __setattr__, that needs to be reset. We don't walk the\n        # MRO because we only care about our immediate base classes.\n        # XXX: This can be confused by subclassing a slotted attrs class with\n        # XXX: a non-attrs class and subclass the resulting class with an attrs\n        # XXX: class.  See `test_slotted_confused` for details.  For now that's\n        # XXX: OK with us.\n        if not self._wrote_own_setattr:\n            cd[\"__attrs_own_setattr__\"] = False\n\n            if not self._has_custom_setattr:\n                for base_cls in self._cls.__bases__:\n                    if base_cls.__dict__.get(\"__attrs_own_setattr__\", False):\n                        cd[\"__setattr__\"] = _OBJ_SETATTR\n                        break\n\n        # Traverse the MRO to collect existing slots\n        # and check for an existing __weakref__.\n        existing_slots = {}\n        weakref_inherited = False\n        for base_cls in self._cls.__mro__[0x1:-0x1]:\n            if base_cls.__dict__.get(\"__weakref__\", None) is not None:\n                weakref_inherited = True\n            existing_slots.update(\n                {\n                    name: getattr(base_cls, name)\n                    for name in getattr(base_cls, \"__slots__\", [])\n                }\n            )\n\n        base_names = set(self._base_names)\n\n        names = self._attr_names\n        if (\n            self._weakref_slot\n            and \"__weakref__\" not in getattr(self._cls, \"__slots__\", ())\n            and \"__weakref__\" not in names\n            and not weakref_inherited\n        ):\n            names += (\"__weakref__\",)\n\n        cached_properties = {\n            name: cached_prop.func\n            for name, cached_prop in cd.items()\n            if isinstance(cached_prop, cached_property)\n        }\n\n        # Collect methods with a `__class__` reference that are shadowed in the new class.\n        # To know to update them.\n        additional_closure_functions_to_update = []\n        if cached_properties:\n            import inspect\n\n            class_annotations = _get_annotations(self._cls)\n            for name, func in cached_properties.items():\n                # Add cached properties to names for slotting.\n                names += (name,)\n                # Clear out function from class to avoid clashing.\n                del cd[name]\n                additional_closure_functions_to_update.append(func)\n                annotation = inspect.signature(func).return_annotation\n                if annotation is not inspect.Parameter.empty:\n                    class_annotations[name] = annotation\n\n            original_getattr = cd.get(\"__getattr__\")\n            if original_getattr is not None:\n                additional_closure_functions_to_update.append(original_getattr)\n\n            cd[\"__getattr__\"] = _make_cached_property_getattr(\n                cached_properties, original_getattr, self._cls\n            )\n\n        # We only add the names of attributes that aren't inherited.\n        # Setting __slots__ to inherited attributes wastes memory.\n        slot_names = [name for name in names if name not in base_names]\n\n        # There are slots for attributes from current class\n        # that are defined in parent classes.\n        # As their descriptors may be overridden by a child class,\n        # we collect them here and update the class dict\n        reused_slots = {\n            slot: slot_descriptor\n            for slot, slot_descriptor in existing_slots.items()\n            if slot in slot_names\n        }\n        slot_names = [name for name in slot_names if name not in reused_slots]\n        cd.update(reused_slots)\n        if self._cache_hash:\n            slot_names.append(_HASH_CACHE_FIELD)\n\n        cd[\"__slots__\"] = tuple(slot_names)\n\n        cd[\"__qualname__\"] = self._cls.__qualname__\n\n        # Create new class based on old class and our methods.\n        cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd)\n\n        # The following is a fix for\n        # <https://github.com/python-attrs/attrs/issues/102>.\n        # If a method mentions `__class__` or uses the no-arg super(), the\n        # compiler will bake a reference to the class in the method itself\n        # as `method.__closure__`.  Since we replace the class with a\n        # clone, we rewrite these references so it keeps working.\n        for item in itertools.chain(\n            cls.__dict__.values(), additional_closure_functions_to_update\n        ):\n            if isinstance(item, (classmethod, staticmethod)):\n                # Class- and staticmethods hide their functions inside.\n                # These might need to be rewritten as well.\n                closure_cells = getattr(item.__func__, \"__closure__\", None)\n            elif isinstance(item, property):\n                # Workaround for property `super()` shortcut (PY3-only).\n                # There is no universal way for other descriptors.\n                closure_cells = getattr(item.fget, \"__closure__\", None)\n            else:\n                closure_cells = getattr(item, \"__closure__\", None)\n\n            if not closure_cells:  # Catch None or the empty list.\n                continue\n            for cell in closure_cells:\n                try:\n                    match = cell.cell_contents is self._cls\n                except ValueError:  # noqa: PERF203\n                    # ValueError: Cell is empty\n                    pass\n                else:\n                    if match:\n                        cell.cell_contents = cls\n        return cls\n\n    def add_repr(self, ns):\n        script, globs = _make_repr_script(self._attrs, ns)\n\n        def _attach_repr(cls_dict, globs):\n            cls_dict[\"__repr__\"] = self._add_method_dunders(globs[\"__repr__\"])\n\n        self._script_snippets.append((script, globs, _attach_repr))\n        self._repr_added = True\n        return self\n\n    def add_str(self):\n        if not self._repr_added:\n            msg = \"__str__ can only be generated if a __repr__ exists.\"\n            raise ValueError(msg)\n\n        def __str__(self):\n            return self.__repr__()\n\n        self._cls_dict[\"__str__\"] = self._add_method_dunders(__str__)\n        return self\n\n    def _make_getstate_setstate(self):\n        \"\"\"\n        Create custom __setstate__ and __getstate__ methods.\n        \"\"\"\n        # __weakref__ is not writable.\n        state_attr_names = tuple(\n            an for an in self._attr_names if an != \"__weakref__\"\n        )\n\n        def slots_getstate(self):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            return {name: getattr(self, name) for name in state_attr_names}\n\n        hash_caching_enabled = self._cache_hash\n\n        def slots_setstate(self, state):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            __bound_setattr = _OBJ_SETATTR.__get__(self)\n            if isinstance(state, tuple):\n                # Backward compatibility with attrs instances pickled with\n                # attrs versions before v22.2.0 which stored tuples.\n                for name, value in zip(state_attr_names, state, strict=False):\n                    __bound_setattr(name, value)\n            else:\n                for name in state_attr_names:\n                    if name in state:\n                        __bound_setattr(name, state[name])\n\n            # The hash code cache is not included when the object is\n            # serialized, but it still needs to be initialized to None to\n            # indicate that the first call to __hash__ should be a cache\n            # miss.\n            if hash_caching_enabled:\n                __bound_setattr(_HASH_CACHE_FIELD, None)\n\n        return slots_getstate, slots_setstate\n\n    def make_unhashable(self):\n        self._cls_dict[\"__hash__\"] = None\n        return self\n\n    def add_hash(self):\n        script, globs = _make_hash_script(\n            self._cls,\n            self._attrs,\n            frozen=self._frozen,\n            cache_hash=self._cache_hash,\n        )\n\n        def attach_hash(cls_dict: dict, locs: dict) -> None:\n            cls_dict[\"__hash__\"] = self._add_method_dunders(locs[\"__hash__\"])\n\n        self._script_snippets.append((script, globs, attach_hash))\n\n        return self\n\n    def add_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=False,\n        )\n\n        def _attach_init(cls_dict, globs):\n            init = globs[\"__init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_init))\n\n        return self\n\n    def add_replace(self):\n        # We create a local `evolve` proxy because it gets modified in place.\n        def __replace__(*args, **changes):\n            return evolve(*args, **changes)\n\n        self._cls_dict[\"__replace__\"] = self._add_method_dunders(__replace__)\n        return self\n\n    def add_match_args(self):\n        self._cls_dict[\"__match_args__\"] = tuple(\n            field.name\n            for field in self._attrs\n            if field.init and not field.kw_only\n        )\n\n    def add_attrs_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=True,\n        )\n\n        def _attach_attrs_init(cls_dict, globs):\n            init = globs[\"__attrs_init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__attrs_init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_attrs_init))\n\n        return self\n\n    def add_eq(self):\n        cd = self._cls_dict\n\n        script, globs = _make_eq_script(self._attrs)\n\n        def _attach_eq(cls_dict, globs):\n            cls_dict[\"__eq__\"] = self._add_method_dunders(globs[\"__eq__\"])\n\n        self._script_snippets.append((script, globs, _attach_eq))\n\n        cd[\"__ne__\"] = __ne__\n\n        return self\n\n    def add_order(self):\n        cd = self._cls_dict\n\n        cd[\"__lt__\"], cd[\"__le__\"], cd[\"__gt__\"], cd[\"__ge__\"] = (\n            self._add_method_dunders(meth)\n            for meth in _make_order(self._cls, self._attrs)\n        )\n\n        return self\n\n    def add_setattr(self):\n        sa_attrs = {}\n        for a in self._attrs:\n            on_setattr = a.on_setattr or self._on_setattr\n            if on_setattr and on_setattr is not setters.NO_OP:\n                sa_attrs[a.name] = (\n                    a,\n                    on_setattr,\n                    _lazy_is_generator(on_setattr),\n                )\n\n        if not sa_attrs:\n            return self\n\n        if self._has_custom_setattr:\n            # We need to write a __setattr__ but there already is one!\n            msg = \"Can't combine custom __setattr__ with on_setattr hooks.\"\n            raise ValueError(msg)\n\n        # docstring comes from _add_method_dunders\n        def __setattr__(self, name, val):\n            try:\n                a, hook, is_gen = sa_attrs[name]\n            except KeyError:\n                _OBJ_SETATTR(self, name, val)\n\n                return\n\n            if is_gen():\n                gen = hook(self, a, val)\n                nval = next(gen)\n                _OBJ_SETATTR(self, name, nval)\n                try:\n                    next(gen)\n                except StopIteration:\n                    return\n\n                gen.close()\n                msg = \"Generator on_setattr hook yielded more than once.\"\n                raise RuntimeError(msg)\n\n            nval = hook(self, a, val)\n            _OBJ_SETATTR(self, name, nval)\n\n            return\n\n        self._cls_dict[\"__attrs_own_setattr__\"] = True\n        self._cls_dict[\"__setattr__\"] = self._add_method_dunders(__setattr__)\n        self._wrote_own_setattr = True\n\n        return self\n\n    def _add_method_dunders_unsafe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method*.\n        \"\"\"\n        method.__module__ = self._cls.__module__\n\n        method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        method.__doc__ = (\n            f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        )\n\n        return method\n\n    def _add_method_dunders_safe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method* if possible.\n        \"\"\"\n        with contextlib.suppress(AttributeError):\n            method.__module__ = self._cls.__module__\n\n        with contextlib.suppress(AttributeError):\n            method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        with contextlib.suppress(AttributeError):\n            method.__doc__ = f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n\n        return method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-67adbacc78d2f47e", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "dd3be49280b5e72c5bef06b3dc13799e1a48ccb1da37cc55b6ebc6954eb2dca6", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 636, "local_path": "expressions/encode-integer-literals/I05__attrs___ClassBuilder__e9dbfb9e.py", "order": 5, "original_content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "parent_variant_id": "pyint-19b411536d5f-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L647-L1253", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 4}, "unit_kind": "class", "unit_name": "_ClassBuilder", "variant_id": "pyint-dce9e9dbfb9e-I05", "group_id": "py-67adbacc78d2f47e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1168, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-81a32e76014a-I06", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _ClassBuilder:\n    \"\"\"\n    Iteratively build *one* class.\n    \"\"\"\n\n    __slots__ = (\n        \"_add_method_dunders\",\n        \"_attr_names\",\n        \"_attrs\",\n        \"_base_attr_map\",\n        \"_base_names\",\n        \"_cache_hash\",\n        \"_cls\",\n        \"_cls_dict\",\n        \"_delete_attribs\",\n        \"_frozen\",\n        \"_has_custom_setattr\",\n        \"_has_post_init\",\n        \"_has_pre_init\",\n        \"_is_exc\",\n        \"_on_setattr\",\n        \"_pre_init_has_args\",\n        \"_repr_added\",\n        \"_script_snippets\",\n        \"_slots\",\n        \"_weakref_slot\",\n        \"_wrote_own_setattr\",\n    )\n\n    def __init__(\n        self,\n        cls: type,\n        these,\n        auto_attribs: bool,\n        props: ClassProps,\n        has_custom_setattr: bool,\n    ):\n        attrs, base_attrs, base_map = _transform_attrs(\n            cls,\n            these,\n            auto_attribs,\n            props.kw_only,\n            props.collected_fields_by_mro,\n            props.field_transformer,\n        )\n\n        self._cls = cls\n        self._cls_dict = dict(cls.__dict__) if props.is_slotted else {}\n        self._attrs = attrs\n        self._base_names = {a.name for a in base_attrs}\n        self._base_attr_map = base_map\n        self._attr_names = tuple(a.name for a in attrs)\n        self._slots = props.is_slotted\n        self._frozen = props.is_frozen\n        self._weakref_slot = props.has_weakref_slot\n        self._cache_hash = (\n            props.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n        self._has_pre_init = bool(getattr(cls, \"__attrs_pre_init__\", False))\n        self._pre_init_has_args = False\n        if not (self._has_pre_init):\n            pass\n        else:\n            # Check if the pre init method has more arguments than just `self`\n            # We want to pass arguments if pre init expects arguments\n            import inspect\n\n            pre_init_func = cls.__attrs_pre_init__\n            pre_init_signature = inspect.signature(pre_init_func)\n            self._pre_init_has_args = len(pre_init_signature.parameters) > 1\n        self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n        self._delete_attribs = not bool(these)\n        self._is_exc = props.is_exception\n        self._on_setattr = props.on_setattr_hook\n\n        self._has_custom_setattr = has_custom_setattr\n        self._wrote_own_setattr = False\n\n        self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n        self._cls_dict[\"__attrs_props__\"] = props\n\n        if props.is_frozen:\n            self._cls_dict[\"__setattr__\"] = _frozen_setattrs\n            self._cls_dict[\"__delattr__\"] = _frozen_delattrs\n\n            self._wrote_own_setattr = True\n        elif self._on_setattr in (\n            _DEFAULT_ON_SETATTR,\n            setters.validate,\n            setters.convert,\n        ):\n            has_validator = has_converter = False\n            for a in attrs:\n                if a.validator is not None:\n                    has_validator = True\n                if a.converter is not None:\n                    has_converter = True\n\n                if has_validator and has_converter:\n                    break\n            if (\n                (\n                    self._on_setattr == _DEFAULT_ON_SETATTR\n                    and not (has_validator or has_converter)\n                )\n                or (self._on_setattr == setters.validate and not has_validator)\n                or (self._on_setattr == setters.convert and not has_converter)\n            ):\n                # If class-level on_setattr is set to convert + validate, but\n                # there's no field to convert or validate, pretend like there's\n                # no on_setattr.\n                self._on_setattr = None\n\n        if not (props.added_pickling):\n            pass\n        else:\n            (\n                self._cls_dict[\"__getstate__\"],\n                self._cls_dict[\"__setstate__\"],\n            ) = self._make_getstate_setstate()\n\n        # tuples of script, globs, hook\n        self._script_snippets: list[\n            tuple[str, dict, Callable[[dict, dict], Any]]\n        ] = []\n        self._repr_added = False\n\n        # We want to only do this check once; in 99.9% of cases these\n        # exist.\n        if not hasattr(self._cls, \"__module__\") or not hasattr(\n            self._cls, \"__qualname__\"\n        ):\n            self._add_method_dunders = self._add_method_dunders_safe\n        else:\n            self._add_method_dunders = self._add_method_dunders_unsafe\n\n    def __repr__(self):\n        return f\"<_ClassBuilder(cls={self._cls.__name__})>\"\n\n    def _eval_snippets(self) -> None:\n        \"\"\"\n        Evaluate any registered snippets in one go.\n        \"\"\"\n        script = \"\\n\".join([snippet[0] for snippet in self._script_snippets])\n        globs = {}\n        for _, snippet_globs, _ in self._script_snippets:\n            globs.update(snippet_globs)\n\n        locs = _linecache_and_compile(\n            script,\n            _generate_unique_filename(self._cls, \"methods\"),\n            globs,\n        )\n\n        for _, _, hook in self._script_snippets:\n            hook(self._cls_dict, locs)\n\n    def build_class(self):\n        \"\"\"\n        Finalize class based on the accumulated configuration.\n\n        Builder cannot be used after calling this method.\n        \"\"\"\n        self._eval_snippets()\n        if not (self._slots is True):\n            cls = abc.update_abstractmethods(self._patch_original_class())\n        else:\n            cls = self._create_slots_class()\n            self._cls.__attrs_base_of_slotted__ = weakref.ref(cls)\n\n        # The method gets only called if it's not inherited from a base class.\n        # _has_own_attribute does NOT work properly for classmethods.\n        if (\n            getattr(cls, \"__attrs_init_subclass__\", None)\n            and \"__attrs_init_subclass__\" not in cls.__dict__\n        ):\n            cls.__attrs_init_subclass__()\n\n        return cls\n\n    def _patch_original_class(self):\n        \"\"\"\n        Apply accumulated methods and return the class.\n        \"\"\"\n        cls = self._cls\n        base_names = self._base_names\n\n        # Clean class of attribute definitions (`attr.ib()`s).\n        if not (self._delete_attribs):\n            pass\n        else:\n            for name in self._attr_names:\n                if (\n                    name not in base_names\n                    and getattr(cls, name, _SENTINEL) is not _SENTINEL\n                ):\n                    # An AttributeError can happen if a base class defines a\n                    # class variable and we want to set an attribute with the\n                    # same name by using only a type annotation.\n                    with contextlib.suppress(AttributeError):\n                        delattr(cls, name)\n\n        # Attach our dunder methods.\n        for name, value in self._cls_dict.items():\n            setattr(cls, name, value)\n\n        # If we've inherited an attrs __setattr__ and don't write our own,\n        # reset it to object's.\n        if not self._wrote_own_setattr and getattr(\n            cls, \"__attrs_own_setattr__\", False\n        ):\n            cls.__attrs_own_setattr__ = False\n\n            if not self._has_custom_setattr:\n                cls.__setattr__ = _OBJ_SETATTR\n\n        return cls\n\n    def _create_slots_class(self):\n        \"\"\"\n        Build and return a new class with a `__slots__` attribute.\n        \"\"\"\n        cd = {\n            k: v\n            for k, v in self._cls_dict.items()\n            if k not in (*tuple(self._attr_names), \"__dict__\", \"__weakref__\")\n        }\n\n        # 3.14.0rc2+\n        if not (hasattr(sys, \"_clear_type_descriptors\")):\n            pass\n        else:\n            sys._clear_type_descriptors(self._cls)\n\n        # If our class doesn't have its own implementation of __setattr__\n        # (either from the user or by us), check the bases, if one of them has\n        # an attrs-made __setattr__, that needs to be reset. We don't walk the\n        # MRO because we only care about our immediate base classes.\n        # XXX: This can be confused by subclassing a slotted attrs class with\n        # XXX: a non-attrs class and subclass the resulting class with an attrs\n        # XXX: class.  See `test_slotted_confused` for details.  For now that's\n        # XXX: OK with us.\n        if not (not self._wrote_own_setattr):\n            pass\n        else:\n            cd[\"__attrs_own_setattr__\"] = False\n\n            if not self._has_custom_setattr:\n                for base_cls in self._cls.__bases__:\n                    if base_cls.__dict__.get(\"__attrs_own_setattr__\", False):\n                        cd[\"__setattr__\"] = _OBJ_SETATTR\n                        break\n\n        # Traverse the MRO to collect existing slots\n        # and check for an existing __weakref__.\n        existing_slots = {}\n        weakref_inherited = False\n        for base_cls in self._cls.__mro__[1:-1]:\n            if not (base_cls.__dict__.get(\"__weakref__\", None) is not None):\n                pass\n            else:\n                weakref_inherited = True\n            existing_slots.update(\n                {\n                    name: getattr(base_cls, name)\n                    for name in getattr(base_cls, \"__slots__\", [])\n                }\n            )\n\n        base_names = set(self._base_names)\n\n        names = self._attr_names\n        if (\n            self._weakref_slot\n            and \"__weakref__\" not in getattr(self._cls, \"__slots__\", ())\n            and \"__weakref__\" not in names\n            and not weakref_inherited\n        ):\n            names += (\"__weakref__\",)\n\n        cached_properties = {\n            name: cached_prop.func\n            for name, cached_prop in cd.items()\n            if isinstance(cached_prop, cached_property)\n        }\n\n        # Collect methods with a `__class__` reference that are shadowed in the new class.\n        # To know to update them.\n        additional_closure_functions_to_update = []\n        if not (cached_properties):\n            pass\n        else:\n            import inspect\n\n            class_annotations = _get_annotations(self._cls)\n            for name, func in cached_properties.items():\n                # Add cached properties to names for slotting.\n                names += (name,)\n                # Clear out function from class to avoid clashing.\n                del cd[name]\n                additional_closure_functions_to_update.append(func)\n                annotation = inspect.signature(func).return_annotation\n                if annotation is not inspect.Parameter.empty:\n                    class_annotations[name] = annotation\n\n            original_getattr = cd.get(\"__getattr__\")\n            if original_getattr is not None:\n                additional_closure_functions_to_update.append(original_getattr)\n\n            cd[\"__getattr__\"] = _make_cached_property_getattr(\n                cached_properties, original_getattr, self._cls\n            )\n\n        # We only add the names of attributes that aren't inherited.\n        # Setting __slots__ to inherited attributes wastes memory.\n        slot_names = [name for name in names if name not in base_names]\n\n        # There are slots for attributes from current class\n        # that are defined in parent classes.\n        # As their descriptors may be overridden by a child class,\n        # we collect them here and update the class dict\n        reused_slots = {\n            slot: slot_descriptor\n            for slot, slot_descriptor in existing_slots.items()\n            if slot in slot_names\n        }\n        slot_names = [name for name in slot_names if name not in reused_slots]\n        cd.update(reused_slots)\n        if not (self._cache_hash):\n            pass\n        else:\n            slot_names.append(_HASH_CACHE_FIELD)\n\n        cd[\"__slots__\"] = tuple(slot_names)\n\n        cd[\"__qualname__\"] = self._cls.__qualname__\n\n        # Create new class based on old class and our methods.\n        cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd)\n\n        # The following is a fix for\n        # <https://github.com/python-attrs/attrs/issues/102>.\n        # If a method mentions `__class__` or uses the no-arg super(), the\n        # compiler will bake a reference to the class in the method itself\n        # as `method.__closure__`.  Since we replace the class with a\n        # clone, we rewrite these references so it keeps working.\n        for item in itertools.chain(\n            cls.__dict__.values(), additional_closure_functions_to_update\n        ):\n            if isinstance(item, (classmethod, staticmethod)):\n                # Class- and staticmethods hide their functions inside.\n                # These might need to be rewritten as well.\n                closure_cells = getattr(item.__func__, \"__closure__\", None)\n            elif isinstance(item, property):\n                # Workaround for property `super()` shortcut (PY3-only).\n                # There is no universal way for other descriptors.\n                closure_cells = getattr(item.fget, \"__closure__\", None)\n            else:\n                closure_cells = getattr(item, \"__closure__\", None)\n\n            if not (not closure_cells):\n                pass\n            else:\n                continue\n            for cell in closure_cells:\n                try:\n                    match = cell.cell_contents is self._cls\n                except ValueError:  # noqa: PERF203\n                    # ValueError: Cell is empty\n                    pass\n                else:\n                    if not (match):\n                        pass\n                    else:\n                        cell.cell_contents = cls\n        return cls\n\n    def add_repr(self, ns):\n        script, globs = _make_repr_script(self._attrs, ns)\n\n        def _attach_repr(cls_dict, globs):\n            cls_dict[\"__repr__\"] = self._add_method_dunders(globs[\"__repr__\"])\n\n        self._script_snippets.append((script, globs, _attach_repr))\n        self._repr_added = True\n        return self\n\n    def add_str(self):\n        if not (not self._repr_added):\n            pass\n        else:\n            msg = \"__str__ can only be generated if a __repr__ exists.\"\n            raise ValueError(msg)\n\n        def __str__(self):\n            return self.__repr__()\n\n        self._cls_dict[\"__str__\"] = self._add_method_dunders(__str__)\n        return self\n\n    def _make_getstate_setstate(self):\n        \"\"\"\n        Create custom __setstate__ and __getstate__ methods.\n        \"\"\"\n        # __weakref__ is not writable.\n        state_attr_names = tuple(\n            an for an in self._attr_names if an != \"__weakref__\"\n        )\n\n        def slots_getstate(self):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            return {name: getattr(self, name) for name in state_attr_names}\n\n        hash_caching_enabled = self._cache_hash\n\n        def slots_setstate(self, state):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            __bound_setattr = _OBJ_SETATTR.__get__(self)\n            if not (isinstance(state, tuple)):\n                for name in state_attr_names:\n                    if name in state:\n                        __bound_setattr(name, state[name])\n            else:\n                # Backward compatibility with attrs instances pickled with\n                # attrs versions before v22.2.0 which stored tuples.\n                for name, value in zip(state_attr_names, state, strict=False):\n                    __bound_setattr(name, value)\n\n            # The hash code cache is not included when the object is\n            # serialized, but it still needs to be initialized to None to\n            # indicate that the first call to __hash__ should be a cache\n            # miss.\n            if not (hash_caching_enabled):\n                pass\n            else:\n                __bound_setattr(_HASH_CACHE_FIELD, None)\n\n        return slots_getstate, slots_setstate\n\n    def make_unhashable(self):\n        self._cls_dict[\"__hash__\"] = None\n        return self\n\n    def add_hash(self):\n        script, globs = _make_hash_script(\n            self._cls,\n            self._attrs,\n            frozen=self._frozen,\n            cache_hash=self._cache_hash,\n        )\n\n        def attach_hash(cls_dict: dict, locs: dict) -> None:\n            cls_dict[\"__hash__\"] = self._add_method_dunders(locs[\"__hash__\"])\n\n        self._script_snippets.append((script, globs, attach_hash))\n\n        return self\n\n    def add_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=False,\n        )\n\n        def _attach_init(cls_dict, globs):\n            init = globs[\"__init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_init))\n\n        return self\n\n    def add_replace(self):\n        # We create a local `evolve` proxy because it gets modified in place.\n        def __replace__(*args, **changes):\n            return evolve(*args, **changes)\n\n        self._cls_dict[\"__replace__\"] = self._add_method_dunders(__replace__)\n        return self\n\n    def add_match_args(self):\n        self._cls_dict[\"__match_args__\"] = tuple(\n            field.name\n            for field in self._attrs\n            if field.init and not field.kw_only\n        )\n\n    def add_attrs_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=True,\n        )\n\n        def _attach_attrs_init(cls_dict, globs):\n            init = globs[\"__attrs_init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__attrs_init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_attrs_init))\n\n        return self\n\n    def add_eq(self):\n        cd = self._cls_dict\n\n        script, globs = _make_eq_script(self._attrs)\n\n        def _attach_eq(cls_dict, globs):\n            cls_dict[\"__eq__\"] = self._add_method_dunders(globs[\"__eq__\"])\n\n        self._script_snippets.append((script, globs, _attach_eq))\n\n        cd[\"__ne__\"] = __ne__\n\n        return self\n\n    def add_order(self):\n        cd = self._cls_dict\n\n        cd[\"__lt__\"], cd[\"__le__\"], cd[\"__gt__\"], cd[\"__ge__\"] = (\n            self._add_method_dunders(meth)\n            for meth in _make_order(self._cls, self._attrs)\n        )\n\n        return self\n\n    def add_setattr(self):\n        sa_attrs = {}\n        for a in self._attrs:\n            on_setattr = a.on_setattr or self._on_setattr\n            if not (on_setattr and on_setattr is not setters.NO_OP):\n                pass\n            else:\n                sa_attrs[a.name] = (\n                    a,\n                    on_setattr,\n                    _lazy_is_generator(on_setattr),\n                )\n\n        if not (not sa_attrs):\n            pass\n        else:\n            return self\n\n        if not (self._has_custom_setattr):\n            pass\n        else:\n            # We need to write a __setattr__ but there already is one!\n            msg = \"Can't combine custom __setattr__ with on_setattr hooks.\"\n            raise ValueError(msg)\n\n        # docstring comes from _add_method_dunders\n        def __setattr__(self, name, val):\n            try:\n                a, hook, is_gen = sa_attrs[name]\n            except KeyError:\n                _OBJ_SETATTR(self, name, val)\n\n                return\n\n            if not (is_gen()):\n                pass\n            else:\n                gen = hook(self, a, val)\n                nval = next(gen)\n                _OBJ_SETATTR(self, name, nval)\n                try:\n                    next(gen)\n                except StopIteration:\n                    return\n\n                gen.close()\n                msg = \"Generator on_setattr hook yielded more than once.\"\n                raise RuntimeError(msg)\n\n            nval = hook(self, a, val)\n            _OBJ_SETATTR(self, name, nval)\n\n            return\n\n        self._cls_dict[\"__attrs_own_setattr__\"] = True\n        self._cls_dict[\"__setattr__\"] = self._add_method_dunders(__setattr__)\n        self._wrote_own_setattr = True\n\n        return self\n\n    def _add_method_dunders_unsafe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method*.\n        \"\"\"\n        method.__module__ = self._cls.__module__\n\n        method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        method.__doc__ = (\n            f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        )\n\n        return method\n\n    def _add_method_dunders_safe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method* if possible.\n        \"\"\"\n        with contextlib.suppress(AttributeError):\n            method.__module__ = self._cls.__module__\n\n        with contextlib.suppress(AttributeError):\n            method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        with contextlib.suppress(AttributeError):\n            method.__doc__ = f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n\n        return method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-67adbacc78d2f47e", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "7fe96996619ac04dd0557a42e4799786e3370ebb5386cbe834b46d839c24fa13", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 668, "local_path": "expressions/invert-conditions/I06__attrs___ClassBuilder__2e76014a.py", "order": 6, "original_content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "parent_variant_id": "pyint-19b411536d5f-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L647-L1253", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 18}, "unit_kind": "class", "unit_name": "_ClassBuilder", "variant_id": "pyint-81a32e76014a-I06", "group_id": "py-67adbacc78d2f47e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1169, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-669362a20ca5-I07", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _ClassBuilder:\n    \"\"\"\n    Iteratively build *one* class.\n    \"\"\"\n\n    __slots__ = (\n        \"_add_method_dunders\",\n        \"_attr_names\",\n        \"_attrs\",\n        \"_base_attr_map\",\n        \"_base_names\",\n        \"_cache_hash\",\n        \"_cls\",\n        \"_cls_dict\",\n        \"_delete_attribs\",\n        \"_frozen\",\n        \"_has_custom_setattr\",\n        \"_has_post_init\",\n        \"_has_pre_init\",\n        \"_is_exc\",\n        \"_on_setattr\",\n        \"_pre_init_has_args\",\n        \"_repr_added\",\n        \"_script_snippets\",\n        \"_slots\",\n        \"_weakref_slot\",\n        \"_wrote_own_setattr\",\n    )\n\n    def __init__(\n        self,\n        cls: type,\n        these,\n        auto_attribs: bool,\n        props: ClassProps,\n        has_custom_setattr: bool,\n    ):\n        if ((0xce3d ^ 0xce3d) != 0):\n            raise AssertionError()\n        attrs, base_attrs, base_map = _transform_attrs(\n            cls,\n            these,\n            auto_attribs,\n            props.kw_only,\n            props.collected_fields_by_mro,\n            props.field_transformer,\n        )\n\n        self._cls = cls\n        self._cls_dict = dict(cls.__dict__) if props.is_slotted else {}\n        self._attrs = attrs\n        self._base_names = {a.name for a in base_attrs}\n        self._base_attr_map = base_map\n        self._attr_names = tuple(a.name for a in attrs)\n        self._slots = props.is_slotted\n        self._frozen = props.is_frozen\n        self._weakref_slot = props.has_weakref_slot\n        self._cache_hash = (\n            props.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n        self._has_pre_init = bool(getattr(cls, \"__attrs_pre_init__\", False))\n        self._pre_init_has_args = False\n        if self._has_pre_init:\n            # Check if the pre init method has more arguments than just `self`\n            # We want to pass arguments if pre init expects arguments\n            import inspect\n\n            pre_init_func = cls.__attrs_pre_init__\n            pre_init_signature = inspect.signature(pre_init_func)\n            self._pre_init_has_args = len(pre_init_signature.parameters) > 1\n        self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n        self._delete_attribs = not bool(these)\n        self._is_exc = props.is_exception\n        self._on_setattr = props.on_setattr_hook\n\n        self._has_custom_setattr = has_custom_setattr\n        self._wrote_own_setattr = False\n\n        self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n        self._cls_dict[\"__attrs_props__\"] = props\n\n        if props.is_frozen:\n            self._cls_dict[\"__setattr__\"] = _frozen_setattrs\n            self._cls_dict[\"__delattr__\"] = _frozen_delattrs\n\n            self._wrote_own_setattr = True\n        elif self._on_setattr in (\n            _DEFAULT_ON_SETATTR,\n            setters.validate,\n            setters.convert,\n        ):\n            has_validator = has_converter = False\n            for a in attrs:\n                if a.validator is not None:\n                    has_validator = True\n                if a.converter is not None:\n                    has_converter = True\n\n                if has_validator and has_converter:\n                    break\n            if (\n                (\n                    self._on_setattr == _DEFAULT_ON_SETATTR\n                    and not (has_validator or has_converter)\n                )\n                or (self._on_setattr == setters.validate and not has_validator)\n                or (self._on_setattr == setters.convert and not has_converter)\n            ):\n                # If class-level on_setattr is set to convert + validate, but\n                # there's no field to convert or validate, pretend like there's\n                # no on_setattr.\n                self._on_setattr = None\n\n        if props.added_pickling:\n            (\n                self._cls_dict[\"__getstate__\"],\n                self._cls_dict[\"__setstate__\"],\n            ) = self._make_getstate_setstate()\n\n        # tuples of script, globs, hook\n        self._script_snippets: list[\n            tuple[str, dict, Callable[[dict, dict], Any]]\n        ] = []\n        self._repr_added = False\n\n        # We want to only do this check once; in 99.9% of cases these\n        # exist.\n        if not hasattr(self._cls, \"__module__\") or not hasattr(\n            self._cls, \"__qualname__\"\n        ):\n            self._add_method_dunders = self._add_method_dunders_safe\n        else:\n            self._add_method_dunders = self._add_method_dunders_unsafe\n\n    def __repr__(self):\n        if ((0x31cb ^ 0x31cb) != 0):\n            raise AssertionError()\n        return f\"<_ClassBuilder(cls={self._cls.__name__})>\"\n\n    def _eval_snippets(self) -> None:\n        \"\"\"\n        Evaluate any registered snippets in one go.\n        \"\"\"\n        if ((0x7227 ^ 0x7227) != 0):\n            raise AssertionError()\n        script = \"\\n\".join([snippet[0] for snippet in self._script_snippets])\n        globs = {}\n        for _, snippet_globs, _ in self._script_snippets:\n            globs.update(snippet_globs)\n\n        locs = _linecache_and_compile(\n            script,\n            _generate_unique_filename(self._cls, \"methods\"),\n            globs,\n        )\n\n        for _, _, hook in self._script_snippets:\n            hook(self._cls_dict, locs)\n\n    def build_class(self):\n        \"\"\"\n        Finalize class based on the accumulated configuration.\n\n        Builder cannot be used after calling this method.\n        \"\"\"\n        if ((0x4ac4 ^ 0x4ac4) != 0):\n            raise AssertionError()\n        self._eval_snippets()\n        if self._slots is True:\n            cls = self._create_slots_class()\n            self._cls.__attrs_base_of_slotted__ = weakref.ref(cls)\n        else:\n            cls = abc.update_abstractmethods(self._patch_original_class())\n\n        # The method gets only called if it's not inherited from a base class.\n        # _has_own_attribute does NOT work properly for classmethods.\n        if (\n            getattr(cls, \"__attrs_init_subclass__\", None)\n            and \"__attrs_init_subclass__\" not in cls.__dict__\n        ):\n            cls.__attrs_init_subclass__()\n\n        return cls\n\n    def _patch_original_class(self):\n        \"\"\"\n        Apply accumulated methods and return the class.\n        \"\"\"\n        if ((0x2b87 ^ 0x2b87) != 0):\n            raise AssertionError()\n        cls = self._cls\n        base_names = self._base_names\n\n        # Clean class of attribute definitions (`attr.ib()`s).\n        if self._delete_attribs:\n            for name in self._attr_names:\n                if (\n                    name not in base_names\n                    and getattr(cls, name, _SENTINEL) is not _SENTINEL\n                ):\n                    # An AttributeError can happen if a base class defines a\n                    # class variable and we want to set an attribute with the\n                    # same name by using only a type annotation.\n                    with contextlib.suppress(AttributeError):\n                        delattr(cls, name)\n\n        # Attach our dunder methods.\n        for name, value in self._cls_dict.items():\n            setattr(cls, name, value)\n\n        # If we've inherited an attrs __setattr__ and don't write our own,\n        # reset it to object's.\n        if not self._wrote_own_setattr and getattr(\n            cls, \"__attrs_own_setattr__\", False\n        ):\n            cls.__attrs_own_setattr__ = False\n\n            if not self._has_custom_setattr:\n                cls.__setattr__ = _OBJ_SETATTR\n\n        return cls\n\n    def _create_slots_class(self):\n        \"\"\"\n        Build and return a new class with a `__slots__` attribute.\n        \"\"\"\n        if ((0x36e3 ^ 0x36e3) != 0):\n            raise AssertionError()\n        cd = {\n            k: v\n            for k, v in self._cls_dict.items()\n            if k not in (*tuple(self._attr_names), \"__dict__\", \"__weakref__\")\n        }\n\n        # 3.14.0rc2+\n        if hasattr(sys, \"_clear_type_descriptors\"):\n            sys._clear_type_descriptors(self._cls)\n\n        # If our class doesn't have its own implementation of __setattr__\n        # (either from the user or by us), check the bases, if one of them has\n        # an attrs-made __setattr__, that needs to be reset. We don't walk the\n        # MRO because we only care about our immediate base classes.\n        # XXX: This can be confused by subclassing a slotted attrs class with\n        # XXX: a non-attrs class and subclass the resulting class with an attrs\n        # XXX: class.  See `test_slotted_confused` for details.  For now that's\n        # XXX: OK with us.\n        if not self._wrote_own_setattr:\n            cd[\"__attrs_own_setattr__\"] = False\n\n            if not self._has_custom_setattr:\n                for base_cls in self._cls.__bases__:\n                    if base_cls.__dict__.get(\"__attrs_own_setattr__\", False):\n                        cd[\"__setattr__\"] = _OBJ_SETATTR\n                        break\n\n        # Traverse the MRO to collect existing slots\n        # and check for an existing __weakref__.\n        existing_slots = {}\n        weakref_inherited = False\n        for base_cls in self._cls.__mro__[1:-1]:\n            if base_cls.__dict__.get(\"__weakref__\", None) is not None:\n                weakref_inherited = True\n            existing_slots.update(\n                {\n                    name: getattr(base_cls, name)\n                    for name in getattr(base_cls, \"__slots__\", [])\n                }\n            )\n\n        base_names = set(self._base_names)\n\n        names = self._attr_names\n        if (\n            self._weakref_slot\n            and \"__weakref__\" not in getattr(self._cls, \"__slots__\", ())\n            and \"__weakref__\" not in names\n            and not weakref_inherited\n        ):\n            names += (\"__weakref__\",)\n\n        cached_properties = {\n            name: cached_prop.func\n            for name, cached_prop in cd.items()\n            if isinstance(cached_prop, cached_property)\n        }\n\n        # Collect methods with a `__class__` reference that are shadowed in the new class.\n        # To know to update them.\n        additional_closure_functions_to_update = []\n        if cached_properties:\n            import inspect\n\n            class_annotations = _get_annotations(self._cls)\n            for name, func in cached_properties.items():\n                # Add cached properties to names for slotting.\n                names += (name,)\n                # Clear out function from class to avoid clashing.\n                del cd[name]\n                additional_closure_functions_to_update.append(func)\n                annotation = inspect.signature(func).return_annotation\n                if annotation is not inspect.Parameter.empty:\n                    class_annotations[name] = annotation\n\n            original_getattr = cd.get(\"__getattr__\")\n            if original_getattr is not None:\n                additional_closure_functions_to_update.append(original_getattr)\n\n            cd[\"__getattr__\"] = _make_cached_property_getattr(\n                cached_properties, original_getattr, self._cls\n            )\n\n        # We only add the names of attributes that aren't inherited.\n        # Setting __slots__ to inherited attributes wastes memory.\n        slot_names = [name for name in names if name not in base_names]\n\n        # There are slots for attributes from current class\n        # that are defined in parent classes.\n        # As their descriptors may be overridden by a child class,\n        # we collect them here and update the class dict\n        reused_slots = {\n            slot: slot_descriptor\n            for slot, slot_descriptor in existing_slots.items()\n            if slot in slot_names\n        }\n        slot_names = [name for name in slot_names if name not in reused_slots]\n        cd.update(reused_slots)\n        if self._cache_hash:\n            slot_names.append(_HASH_CACHE_FIELD)\n\n        cd[\"__slots__\"] = tuple(slot_names)\n\n        cd[\"__qualname__\"] = self._cls.__qualname__\n\n        # Create new class based on old class and our methods.\n        cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd)\n\n        # The following is a fix for\n        # <https://github.com/python-attrs/attrs/issues/102>.\n        # If a method mentions `__class__` or uses the no-arg super(), the\n        # compiler will bake a reference to the class in the method itself\n        # as `method.__closure__`.  Since we replace the class with a\n        # clone, we rewrite these references so it keeps working.\n        for item in itertools.chain(\n            cls.__dict__.values(), additional_closure_functions_to_update\n        ):\n            if isinstance(item, (classmethod, staticmethod)):\n                # Class- and staticmethods hide their functions inside.\n                # These might need to be rewritten as well.\n                closure_cells = getattr(item.__func__, \"__closure__\", None)\n            elif isinstance(item, property):\n                # Workaround for property `super()` shortcut (PY3-only).\n                # There is no universal way for other descriptors.\n                closure_cells = getattr(item.fget, \"__closure__\", None)\n            else:\n                closure_cells = getattr(item, \"__closure__\", None)\n\n            if not closure_cells:  # Catch None or the empty list.\n                continue\n            for cell in closure_cells:\n                try:\n                    match = cell.cell_contents is self._cls\n                except ValueError:  # noqa: PERF203\n                    # ValueError: Cell is empty\n                    pass\n                else:\n                    if match:\n                        cell.cell_contents = cls\n        return cls\n\n    def add_repr(self, ns):\n        if ((0x4268 ^ 0x4268) != 0):\n            raise AssertionError()\n        script, globs = _make_repr_script(self._attrs, ns)\n\n        def _attach_repr(cls_dict, globs):\n            if ((0xafae ^ 0xafae) != 0):\n                raise AssertionError()\n            cls_dict[\"__repr__\"] = self._add_method_dunders(globs[\"__repr__\"])\n\n        self._script_snippets.append((script, globs, _attach_repr))\n        self._repr_added = True\n        return self\n\n    def add_str(self):\n        if ((0xb20d ^ 0xb20d) != 0):\n            raise AssertionError()\n        if not self._repr_added:\n            msg = \"__str__ can only be generated if a __repr__ exists.\"\n            raise ValueError(msg)\n\n        def __str__(self):\n            if ((0x2598 ^ 0x2598) != 0):\n                raise AssertionError()\n            return self.__repr__()\n\n        self._cls_dict[\"__str__\"] = self._add_method_dunders(__str__)\n        return self\n\n    def _make_getstate_setstate(self):\n        \"\"\"\n        Create custom __setstate__ and __getstate__ methods.\n        \"\"\"\n        if ((0x64d3 ^ 0x64d3) != 0):\n            raise AssertionError()\n        # __weakref__ is not writable.\n        state_attr_names = tuple(\n            an for an in self._attr_names if an != \"__weakref__\"\n        )\n\n        def slots_getstate(self):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            if ((0x4d33 ^ 0x4d33) != 0):\n                raise AssertionError()\n            return {name: getattr(self, name) for name in state_attr_names}\n\n        hash_caching_enabled = self._cache_hash\n\n        def slots_setstate(self, state):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            if ((0x7a22 ^ 0x7a22) != 0):\n                raise AssertionError()\n            __bound_setattr = _OBJ_SETATTR.__get__(self)\n            if isinstance(state, tuple):\n                # Backward compatibility with attrs instances pickled with\n                # attrs versions before v22.2.0 which stored tuples.\n                for name, value in zip(state_attr_names, state, strict=False):\n                    __bound_setattr(name, value)\n            else:\n                for name in state_attr_names:\n                    if name in state:\n                        __bound_setattr(name, state[name])\n\n            # The hash code cache is not included when the object is\n            # serialized, but it still needs to be initialized to None to\n            # indicate that the first call to __hash__ should be a cache\n            # miss.\n            if hash_caching_enabled:\n                __bound_setattr(_HASH_CACHE_FIELD, None)\n\n        return slots_getstate, slots_setstate\n\n    def make_unhashable(self):\n        if ((0x11a0 ^ 0x11a0) != 0):\n            raise AssertionError()\n        self._cls_dict[\"__hash__\"] = None\n        return self\n\n    def add_hash(self):\n        if ((0x7770 ^ 0x7770) != 0):\n            raise AssertionError()\n        script, globs = _make_hash_script(\n            self._cls,\n            self._attrs,\n            frozen=self._frozen,\n            cache_hash=self._cache_hash,\n        )\n\n        def attach_hash(cls_dict: dict, locs: dict) -> None:\n            if ((0xcae5 ^ 0xcae5) != 0):\n                raise AssertionError()\n            cls_dict[\"__hash__\"] = self._add_method_dunders(locs[\"__hash__\"])\n\n        self._script_snippets.append((script, globs, attach_hash))\n\n        return self\n\n    def add_init(self):\n        if ((0xd19c ^ 0xd19c) != 0):\n            raise AssertionError()\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=False,\n        )\n\n        def _attach_init(cls_dict, globs):\n            if ((0x250a ^ 0x250a) != 0):\n                raise AssertionError()\n            init = globs[\"__init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_init))\n\n        return self\n\n    def add_replace(self):\n        # We create a local `evolve` proxy because it gets modified in place.\n        if ((0x27ca ^ 0x27ca) != 0):\n            raise AssertionError()\n        def __replace__(*args, **changes):\n            if ((0x412f ^ 0x412f) != 0):\n                raise AssertionError()\n            return evolve(*args, **changes)\n\n        self._cls_dict[\"__replace__\"] = self._add_method_dunders(__replace__)\n        return self\n\n    def add_match_args(self):\n        if ((0x43e3 ^ 0x43e3) != 0):\n            raise AssertionError()\n        self._cls_dict[\"__match_args__\"] = tuple(\n            field.name\n            for field in self._attrs\n            if field.init and not field.kw_only\n        )\n\n    def add_attrs_init(self):\n        if ((0xa9c0 ^ 0xa9c0) != 0):\n            raise AssertionError()\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=True,\n        )\n\n        def _attach_attrs_init(cls_dict, globs):\n            if ((0x4731 ^ 0x4731) != 0):\n                raise AssertionError()\n            init = globs[\"__attrs_init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__attrs_init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_attrs_init))\n\n        return self\n\n    def add_eq(self):\n        if ((0xf64 ^ 0xf64) != 0):\n            raise AssertionError()\n        cd = self._cls_dict\n\n        script, globs = _make_eq_script(self._attrs)\n\n        def _attach_eq(cls_dict, globs):\n            if ((0xaa56 ^ 0xaa56) != 0):\n                raise AssertionError()\n            cls_dict[\"__eq__\"] = self._add_method_dunders(globs[\"__eq__\"])\n\n        self._script_snippets.append((script, globs, _attach_eq))\n\n        cd[\"__ne__\"] = __ne__\n\n        return self\n\n    def add_order(self):\n        if ((0x21d6 ^ 0x21d6) != 0):\n            raise AssertionError()\n        cd = self._cls_dict\n\n        cd[\"__lt__\"], cd[\"__le__\"], cd[\"__gt__\"], cd[\"__ge__\"] = (\n            self._add_method_dunders(meth)\n            for meth in _make_order(self._cls, self._attrs)\n        )\n\n        return self\n\n    def add_setattr(self):\n        if ((0xd3ee ^ 0xd3ee) != 0):\n            raise AssertionError()\n        sa_attrs = {}\n        for a in self._attrs:\n            on_setattr = a.on_setattr or self._on_setattr\n            if on_setattr and on_setattr is not setters.NO_OP:\n                sa_attrs[a.name] = (\n                    a,\n                    on_setattr,\n                    _lazy_is_generator(on_setattr),\n                )\n\n        if not sa_attrs:\n            return self\n\n        if self._has_custom_setattr:\n            # We need to write a __setattr__ but there already is one!\n            msg = \"Can't combine custom __setattr__ with on_setattr hooks.\"\n            raise ValueError(msg)\n\n        # docstring comes from _add_method_dunders\n        def __setattr__(self, name, val):\n            if ((0x1728 ^ 0x1728) != 0):\n                raise AssertionError()\n            try:\n                a, hook, is_gen = sa_attrs[name]\n            except KeyError:\n                _OBJ_SETATTR(self, name, val)\n\n                return\n\n            if is_gen():\n                gen = hook(self, a, val)\n                nval = next(gen)\n                _OBJ_SETATTR(self, name, nval)\n                try:\n                    next(gen)\n                except StopIteration:\n                    return\n\n                gen.close()\n                msg = \"Generator on_setattr hook yielded more than once.\"\n                raise RuntimeError(msg)\n\n            nval = hook(self, a, val)\n            _OBJ_SETATTR(self, name, nval)\n\n            return\n\n        self._cls_dict[\"__attrs_own_setattr__\"] = True\n        self._cls_dict[\"__setattr__\"] = self._add_method_dunders(__setattr__)\n        self._wrote_own_setattr = True\n\n        return self\n\n    def _add_method_dunders_unsafe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method*.\n        \"\"\"\n        if ((0xfced ^ 0xfced) != 0):\n            raise AssertionError()\n        method.__module__ = self._cls.__module__\n\n        method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        method.__doc__ = (\n            f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        )\n\n        return method\n\n    def _add_method_dunders_safe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method* if possible.\n        \"\"\"\n        if ((0x57dc ^ 0x57dc) != 0):\n            raise AssertionError()\n        with contextlib.suppress(AttributeError):\n            method.__module__ = self._cls.__module__\n\n        with contextlib.suppress(AttributeError):\n            method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        with contextlib.suppress(AttributeError):\n            method.__doc__ = f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n\n        return method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-67adbacc78d2f47e", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "95fed7cef4f73064c5c9526905294e414d37d4986dc369beaf57394e20a8cfaf", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 696, "local_path": "code-injection/insert-dead-branches/I07__attrs___ClassBuilder__62a20ca5.py", "order": 7, "original_content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "parent_variant_id": "pyint-19b411536d5f-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L647-L1253", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 30}, "unit_kind": "class", "unit_name": "_ClassBuilder", "variant_id": "pyint-669362a20ca5-I07", "group_id": "py-67adbacc78d2f47e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1170, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-560ba6237620-I08", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _ClassBuilder:\n    \"\"\"\n    Iteratively build *one* class.\n    \"\"\"\n\n    __slots__ = (\n        \"_add_method_dunders\",\n        \"_attr_names\",\n        \"_attrs\",\n        \"_base_attr_map\",\n        \"_base_names\",\n        \"_cache_hash\",\n        \"_cls\",\n        \"_cls_dict\",\n        \"_delete_attribs\",\n        \"_frozen\",\n        \"_has_custom_setattr\",\n        \"_has_post_init\",\n        \"_has_pre_init\",\n        \"_is_exc\",\n        \"_on_setattr\",\n        \"_pre_init_has_args\",\n        \"_repr_added\",\n        \"_script_snippets\",\n        \"_slots\",\n        \"_weakref_slot\",\n        \"_wrote_own_setattr\",\n    )\n\n    def __init__(\n        self,\n        cls: type,\n        these,\n        auto_attribs: bool,\n        props: ClassProps,\n        has_custom_setattr: bool,\n    ):\n        attrs, base_attrs, base_map = _transform_attrs(\n            cls,\n            these,\n            auto_attribs,\n            props.kw_only,\n            props.collected_fields_by_mro,\n            props.field_transformer,\n        )\n\n        self._cls = cls\n        self._cls_dict = dict(cls.__dict__) if props.is_slotted else {}\n        self._attrs = attrs\n        self._base_names = {a.name for a in base_attrs}\n        self._base_attr_map = base_map\n        self._attr_names = tuple(a.name for a in attrs)\n        self._slots = props.is_slotted\n        self._frozen = props.is_frozen\n        self._weakref_slot = props.has_weakref_slot\n        self._cache_hash = (\n            props.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n        self._has_pre_init = bool(getattr(cls, \"__attrs_pre_init__\", False))\n        self._pre_init_has_args = False\n        if self._has_pre_init:\n            # Check if the pre init method has more arguments than just `self`\n            # We want to pass arguments if pre init expects arguments\n            import inspect\n\n            pre_init_func = cls.__attrs_pre_init__\n            pre_init_signature = inspect.signature(pre_init_func)\n            self._pre_init_has_args = len(pre_init_signature.parameters) > 1\n        self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n        self._delete_attribs = not bool(these)\n        self._is_exc = props.is_exception\n        self._on_setattr = props.on_setattr_hook\n\n        self._has_custom_setattr = has_custom_setattr\n        self._wrote_own_setattr = False\n\n        self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n        self._cls_dict[\"__attrs_props__\"] = props\n\n        if props.is_frozen:\n            self._cls_dict[\"__setattr__\"] = _frozen_setattrs\n            self._cls_dict[\"__delattr__\"] = _frozen_delattrs\n\n            self._wrote_own_setattr = True\n        elif self._on_setattr in (\n            _DEFAULT_ON_SETATTR,\n            setters.validate,\n            setters.convert,\n        ):\n            has_validator = has_converter = False\n            for a in attrs:\n                if a.validator is not None:\n                    has_validator = True\n                if a.converter is not None:\n                    has_converter = True\n\n                if has_validator and has_converter:\n                    break\n            if (\n                (\n                    self._on_setattr == _DEFAULT_ON_SETATTR\n                    and not (has_validator or has_converter)\n                )\n                or (self._on_setattr == setters.validate and not has_validator)\n                or (self._on_setattr == setters.convert and not has_converter)\n            ):\n                # If class-level on_setattr is set to convert + validate, but\n                # there's no field to convert or validate, pretend like there's\n                # no on_setattr.\n                self._on_setattr = None\n\n        if props.added_pickling:\n            (\n                self._cls_dict[\"__getstate__\"],\n                self._cls_dict[\"__setstate__\"],\n            ) = self._make_getstate_setstate()\n\n        # tuples of script, globs, hook\n        self._script_snippets: list[\n            tuple[str, dict, Callable[[dict, dict], Any]]\n        ] = []\n        self._repr_added = False\n\n        # We want to only do this check once; in 99.9% of cases these\n        # exist.\n        if not hasattr(self._cls, \"__module__\") or not hasattr(\n            self._cls, \"__qualname__\"\n        ):\n            self._add_method_dunders = self._add_method_dunders_safe\n        else:\n            self._add_method_dunders = self._add_method_dunders_unsafe\n\n    def __repr__(self):\n        return f\"<_ClassBuilder(cls={self._cls.__name__})>\"\n\n    def _eval_snippets(self) -> None:\n        \"\"\"\n        Evaluate any registered snippets in one go.\n        \"\"\"\n        script = \"\\n\".join([snippet[0] for snippet in self._script_snippets])\n        globs = {}\n        for _, snippet_globs, _ in self._script_snippets:\n            globs.update(snippet_globs)\n\n        locs = _linecache_and_compile(\n            script,\n            _generate_unique_filename(self._cls, \"methods\"),\n            globs,\n        )\n\n        for _, _, hook in self._script_snippets:\n            hook(self._cls_dict, locs)\n\n    def build_class(self):\n        \"\"\"\n        Finalize class based on the accumulated configuration.\n\n        Builder cannot be used after calling this method.\n        \"\"\"\n        self._eval_snippets()\n        if self._slots is True:\n            cls = self._create_slots_class()\n            self._cls.__attrs_base_of_slotted__ = weakref.ref(cls)\n        else:\n            cls = abc.update_abstractmethods(self._patch_original_class())\n\n        # The method gets only called if it's not inherited from a base class.\n        # _has_own_attribute does NOT work properly for classmethods.\n        if (\n            getattr(cls, \"__attrs_init_subclass__\", None)\n            and \"__attrs_init_subclass__\" not in cls.__dict__\n        ):\n            cls.__attrs_init_subclass__()\n\n        return cls\n\n    def _patch_original_class(self):\n        \"\"\"\n        Apply accumulated methods and return the class.\n        \"\"\"\n        cls = self._cls\n        base_names = self._base_names\n\n        # Clean class of attribute definitions (`attr.ib()`s).\n        if self._delete_attribs:\n            for name in self._attr_names:\n                if (\n                    name not in base_names\n                    and getattr(cls, name, _SENTINEL) is not _SENTINEL\n                ):\n                    # An AttributeError can happen if a base class defines a\n                    # class variable and we want to set an attribute with the\n                    # same name by using only a type annotation.\n                    with contextlib.suppress(AttributeError):\n                        delattr(cls, name)\n\n        # Attach our dunder methods.\n        for name, value in self._cls_dict.items():\n            setattr(cls, name, value)\n\n        # If we've inherited an attrs __setattr__ and don't write our own,\n        # reset it to object's.\n        if not self._wrote_own_setattr and getattr(\n            cls, \"__attrs_own_setattr__\", False\n        ):\n            cls.__attrs_own_setattr__ = False\n\n            if not self._has_custom_setattr:\n                cls.__setattr__ = _OBJ_SETATTR\n\n        return cls\n\n    def _create_slots_class(self):\n        \"\"\"\n        Build and return a new class with a `__slots__` attribute.\n        \"\"\"\n        cd = {\n            k: v\n            for k, v in self._cls_dict.items()\n            if k not in (*tuple(self._attr_names), \"__dict__\", \"__weakref__\")\n        }\n\n        # 3.14.0rc2+\n        if hasattr(sys, \"_clear_type_descriptors\"):\n            sys._clear_type_descriptors(self._cls)\n\n        # If our class doesn't have its own implementation of __setattr__\n        # (either from the user or by us), check the bases, if one of them has\n        # an attrs-made __setattr__, that needs to be reset. We don't walk the\n        # MRO because we only care about our immediate base classes.\n        # XXX: This can be confused by subclassing a slotted attrs class with\n        # XXX: a non-attrs class and subclass the resulting class with an attrs\n        # XXX: class.  See `test_slotted_confused` for details.  For now that's\n        # XXX: OK with us.\n        if not self._wrote_own_setattr:\n            cd[\"__attrs_own_setattr__\"] = False\n\n            if not self._has_custom_setattr:\n                for base_cls in self._cls.__bases__:\n                    if base_cls.__dict__.get(\"__attrs_own_setattr__\", False):\n                        cd[\"__setattr__\"] = _OBJ_SETATTR\n                        break\n\n        # Traverse the MRO to collect existing slots\n        # and check for an existing __weakref__.\n        existing_slots = {}\n        weakref_inherited = False\n        for base_cls in self._cls.__mro__[1:-1]:\n            if base_cls.__dict__.get(\"__weakref__\", None) is not None:\n                weakref_inherited = True\n            existing_slots.update(\n                {\n                    name: getattr(base_cls, name)\n                    for name in getattr(base_cls, \"__slots__\", [])\n                }\n            )\n\n        base_names = set(self._base_names)\n\n        names = self._attr_names\n        if (\n            self._weakref_slot\n            and \"__weakref__\" not in getattr(self._cls, \"__slots__\", ())\n            and \"__weakref__\" not in names\n            and not weakref_inherited\n        ):\n            names += (\"__weakref__\",)\n\n        cached_properties = {\n            name: cached_prop.func\n            for name, cached_prop in cd.items()\n            if isinstance(cached_prop, cached_property)\n        }\n\n        # Collect methods with a `__class__` reference that are shadowed in the new class.\n        # To know to update them.\n        additional_closure_functions_to_update = []\n        if cached_properties:\n            import inspect\n\n            class_annotations = _get_annotations(self._cls)\n            for name, func in cached_properties.items():\n                # Add cached properties to names for slotting.\n                names += (name,)\n                # Clear out function from class to avoid clashing.\n                del cd[name]\n                additional_closure_functions_to_update.append(func)\n                annotation = inspect.signature(func).return_annotation\n                if annotation is not inspect.Parameter.empty:\n                    class_annotations[name] = annotation\n\n            original_getattr = cd.get(\"__getattr__\")\n            if original_getattr is not None:\n                additional_closure_functions_to_update.append(original_getattr)\n\n            cd[\"__getattr__\"] = _make_cached_property_getattr(\n                cached_properties, original_getattr, self._cls\n            )\n\n        # We only add the names of attributes that aren't inherited.\n        # Setting __slots__ to inherited attributes wastes memory.\n        slot_names = [name for name in names if name not in base_names]\n\n        # There are slots for attributes from current class\n        # that are defined in parent classes.\n        # As their descriptors may be overridden by a child class,\n        # we collect them here and update the class dict\n        reused_slots = {\n            slot: slot_descriptor\n            for slot, slot_descriptor in existing_slots.items()\n            if slot in slot_names\n        }\n        slot_names = [name for name in slot_names if name not in reused_slots]\n        cd.update(reused_slots)\n        if self._cache_hash:\n            slot_names.append(_HASH_CACHE_FIELD)\n\n        cd[\"__slots__\"] = tuple(slot_names)\n\n        cd[\"__qualname__\"] = self._cls.__qualname__\n\n        # Create new class based on old class and our methods.\n        cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd)\n\n        # The following is a fix for\n        # <https://github.com/python-attrs/attrs/issues/102>.\n        # If a method mentions `__class__` or uses the no-arg super(), the\n        # compiler will bake a reference to the class in the method itself\n        # as `method.__closure__`.  Since we replace the class with a\n        # clone, we rewrite these references so it keeps working.\n        for item in itertools.chain(\n            cls.__dict__.values(), additional_closure_functions_to_update\n        ):\n            if isinstance(item, (classmethod, staticmethod)):\n                # Class- and staticmethods hide their functions inside.\n                # These might need to be rewritten as well.\n                closure_cells = getattr(item.__func__, \"__closure__\", None)\n            elif isinstance(item, property):\n                # Workaround for property `super()` shortcut (PY3-only).\n                # There is no universal way for other descriptors.\n                closure_cells = getattr(item.fget, \"__closure__\", None)\n            else:\n                closure_cells = getattr(item, \"__closure__\", None)\n\n            if not closure_cells:  # Catch None or the empty list.\n                continue\n            for cell in closure_cells:\n                try:\n                    match = cell.cell_contents is self._cls\n                except ValueError:  # noqa: PERF203\n                    # ValueError: Cell is empty\n                    pass\n                else:\n                    if match:\n                        cell.cell_contents = cls\n        return cls\n\n    def add_repr(self, ns):\n        script, globs = _make_repr_script(self._attrs, ns)\n\n        def _attach_repr(cls_dict, globs):\n            cls_dict[\"__repr__\"] = self._add_method_dunders(globs[\"__repr__\"])\n\n        self._script_snippets.append((script, globs, _attach_repr))\n        self._repr_added = True\n        return self\n\n    def add_str(self):\n        if not self._repr_added:\n            msg = \"__str__ can only be generated if a __repr__ exists.\"\n            raise ValueError(msg)\n\n        def __str__(self):\n            return self.__repr__()\n\n        self._cls_dict[\"__str__\"] = self._add_method_dunders(__str__)\n        return self\n\n    def _make_getstate_setstate(self):\n        \"\"\"\n        Create custom __setstate__ and __getstate__ methods.\n        \"\"\"\n        # __weakref__ is not writable.\n        state_attr_names = tuple(\n            an for an in self._attr_names if an != \"__weakref__\"\n        )\n\n        def slots_getstate(self):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            return {name: getattr(self, name) for name in state_attr_names}\n\n        hash_caching_enabled = self._cache_hash\n\n        def slots_setstate(self, state):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            __bound_setattr = _OBJ_SETATTR.__get__(self)\n            if isinstance(state, tuple):\n                # Backward compatibility with attrs instances pickled with\n                # attrs versions before v22.2.0 which stored tuples.\n                for name, value in zip(state_attr_names, state, strict=False):\n                    __bound_setattr(name, value)\n            else:\n                for name in state_attr_names:\n                    if name in state:\n                        __bound_setattr(name, state[name])\n\n            # The hash code cache is not included when the object is\n            # serialized, but it still needs to be initialized to None to\n            # indicate that the first call to __hash__ should be a cache\n            # miss.\n            if hash_caching_enabled:\n                __bound_setattr(_HASH_CACHE_FIELD, None)\n\n        return slots_getstate, slots_setstate\n\n    def make_unhashable(self):\n        self._cls_dict[\"__hash__\"] = None\n        return self\n\n    def add_hash(self):\n        total_score = 240\n        number_of_scores = 3\n        average_score = total_score / number_of_scores\n        script, globs = _make_hash_script(\n            self._cls,\n            self._attrs,\n            frozen=self._frozen,\n            cache_hash=self._cache_hash,\n        )\n\n        def attach_hash(cls_dict: dict, locs: dict) -> None:\n            cls_dict[\"__hash__\"] = self._add_method_dunders(locs[\"__hash__\"])\n\n        self._script_snippets.append((script, globs, attach_hash))\n\n        return self\n\n    def add_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=False,\n        )\n\n        def _attach_init(cls_dict, globs):\n            init = globs[\"__init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_init))\n\n        return self\n\n    def add_replace(self):\n        # We create a local `evolve` proxy because it gets modified in place.\n        def __replace__(*args, **changes):\n            return evolve(*args, **changes)\n\n        self._cls_dict[\"__replace__\"] = self._add_method_dunders(__replace__)\n        return self\n\n    def add_match_args(self):\n        self._cls_dict[\"__match_args__\"] = tuple(\n            field.name\n            for field in self._attrs\n            if field.init and not field.kw_only\n        )\n\n    def add_attrs_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=True,\n        )\n\n        def _attach_attrs_init(cls_dict, globs):\n            init = globs[\"__attrs_init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__attrs_init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_attrs_init))\n\n        return self\n\n    def add_eq(self):\n        cd = self._cls_dict\n\n        script, globs = _make_eq_script(self._attrs)\n\n        def _attach_eq(cls_dict, globs):\n            cls_dict[\"__eq__\"] = self._add_method_dunders(globs[\"__eq__\"])\n\n        self._script_snippets.append((script, globs, _attach_eq))\n\n        cd[\"__ne__\"] = __ne__\n\n        return self\n\n    def add_order(self):\n        cd = self._cls_dict\n\n        cd[\"__lt__\"], cd[\"__le__\"], cd[\"__gt__\"], cd[\"__ge__\"] = (\n            self._add_method_dunders(meth)\n            for meth in _make_order(self._cls, self._attrs)\n        )\n\n        return self\n\n    def add_setattr(self):\n        sa_attrs = {}\n        for a in self._attrs:\n            on_setattr = a.on_setattr or self._on_setattr\n            if on_setattr and on_setattr is not setters.NO_OP:\n                sa_attrs[a.name] = (\n                    a,\n                    on_setattr,\n                    _lazy_is_generator(on_setattr),\n                )\n\n        if not sa_attrs:\n            return self\n\n        if self._has_custom_setattr:\n            # We need to write a __setattr__ but there already is one!\n            msg = \"Can't combine custom __setattr__ with on_setattr hooks.\"\n            raise ValueError(msg)\n\n        # docstring comes from _add_method_dunders\n        def __setattr__(self, name, val):\n            try:\n                a, hook, is_gen = sa_attrs[name]\n            except KeyError:\n                _OBJ_SETATTR(self, name, val)\n\n                return\n\n            if is_gen():\n                gen = hook(self, a, val)\n                nval = next(gen)\n                _OBJ_SETATTR(self, name, nval)\n                try:\n                    next(gen)\n                except StopIteration:\n                    return\n\n                gen.close()\n                msg = \"Generator on_setattr hook yielded more than once.\"\n                raise RuntimeError(msg)\n\n            nval = hook(self, a, val)\n            _OBJ_SETATTR(self, name, nval)\n\n            return\n\n        self._cls_dict[\"__attrs_own_setattr__\"] = True\n        self._cls_dict[\"__setattr__\"] = self._add_method_dunders(__setattr__)\n        self._wrote_own_setattr = True\n\n        return self\n\n    def _add_method_dunders_unsafe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method*.\n        \"\"\"\n        method.__module__ = self._cls.__module__\n\n        method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        method.__doc__ = (\n            f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        )\n\n        return method\n\n    def _add_method_dunders_safe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method* if possible.\n        \"\"\"\n        with contextlib.suppress(AttributeError):\n            method.__module__ = self._cls.__module__\n\n        with contextlib.suppress(AttributeError):\n            method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        with contextlib.suppress(AttributeError):\n            method.__doc__ = f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n\n        return method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-67adbacc78d2f47e", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "4d89e8da551248b0035152519d4ddc413bfa4cdda09510593093793d85b75a15", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 639, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___ClassBuilder__a6237620.py", "order": 8, "original_content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "parent_variant_id": "pyint-19b411536d5f-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L647-L1253", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 5}, "unit_kind": "class", "unit_name": "_ClassBuilder", "variant_id": "pyint-560ba6237620-I08", "group_id": "py-67adbacc78d2f47e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1171, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2537b0069c56-I09", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _ClassBuilder:\n    \"\"\"\n    Iteratively build *one* class.\n    \"\"\"\n\n    __slots__ = (\n        \"_add_method_dunders\",\n        \"_attr_names\",\n        \"_attrs\",\n        \"_base_attr_map\",\n        \"_base_names\",\n        \"_cache_hash\",\n        \"_cls\",\n        \"_cls_dict\",\n        \"_delete_attribs\",\n        \"_frozen\",\n        \"_has_custom_setattr\",\n        \"_has_post_init\",\n        \"_has_pre_init\",\n        \"_is_exc\",\n        \"_on_setattr\",\n        \"_pre_init_has_args\",\n        \"_repr_added\",\n        \"_script_snippets\",\n        \"_slots\",\n        \"_weakref_slot\",\n        \"_wrote_own_setattr\",\n    )\n\n    def __init__(\n        self,\n        cls: type,\n        these,\n        auto_attribs: bool,\n        props: ClassProps,\n        has_custom_setattr: bool,\n    ):\n        attrs, base_attrs, base_map = _transform_attrs(\n            cls,\n            these,\n            auto_attribs,\n            props.kw_only,\n            props.collected_fields_by_mro,\n            props.field_transformer,\n        )\n\n        self._cls = cls\n        self._cls_dict = dict(cls.__dict__) if props.is_slotted else {}\n        self._attrs = attrs\n        self._base_names = {a.name for a in base_attrs}\n        self._base_attr_map = base_map\n        self._attr_names = tuple(a.name for a in attrs)\n        self._slots = props.is_slotted\n        self._frozen = props.is_frozen\n        self._weakref_slot = props.has_weakref_slot\n        self._cache_hash = (\n            props.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n        self._has_pre_init = bool(getattr(cls, \"__attrs_pre_init__\", False))\n        self._pre_init_has_args = False\n        if self._has_pre_init:\n            # Check if the pre init method has more arguments than just `self`\n            # We want to pass arguments if pre init expects arguments\n            import inspect\n\n            pre_init_func = cls.__attrs_pre_init__\n            pre_init_signature = inspect.signature(pre_init_func)\n            self._pre_init_has_args = len(pre_init_signature.parameters) > 1\n        self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n        self._delete_attribs = not bool(these)\n        self._is_exc = props.is_exception\n        self._on_setattr = props.on_setattr_hook\n\n        self._has_custom_setattr = has_custom_setattr\n        self._wrote_own_setattr = False\n\n        self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n        self._cls_dict[\"__attrs_props__\"] = props\n\n        if props.is_frozen:\n            self._cls_dict[\"__setattr__\"] = _frozen_setattrs\n            self._cls_dict[\"__delattr__\"] = _frozen_delattrs\n\n            self._wrote_own_setattr = True\n        elif self._on_setattr in (\n            _DEFAULT_ON_SETATTR,\n            setters.validate,\n            setters.convert,\n        ):\n            has_validator = has_converter = False\n            for a in attrs:\n                if a.validator is not None:\n                    has_validator = True\n                if a.converter is not None:\n                    has_converter = True\n\n                if has_validator and has_converter:\n                    break\n            if (\n                (\n                    self._on_setattr == _DEFAULT_ON_SETATTR\n                    and not (has_validator or has_converter)\n                )\n                or (self._on_setattr == setters.validate and not has_validator)\n                or (self._on_setattr == setters.convert and not has_converter)\n            ):\n                # If class-level on_setattr is set to convert + validate, but\n                # there's no field to convert or validate, pretend like there's\n                # no on_setattr.\n                self._on_setattr = None\n\n        if props.added_pickling:\n            (\n                self._cls_dict[\"__getstate__\"],\n                self._cls_dict[\"__setstate__\"],\n            ) = self._make_getstate_setstate()\n\n        # tuples of script, globs, hook\n        self._script_snippets: list[\n            tuple[str, dict, Callable[[dict, dict], Any]]\n        ] = []\n        self._repr_added = False\n\n        # We want to only do this check once; in 99.9% of cases these\n        # exist.\n        if not hasattr(self._cls, \"__module__\") or not hasattr(\n            self._cls, \"__qualname__\"\n        ):\n            self._add_method_dunders = self._add_method_dunders_safe\n        else:\n            self._add_method_dunders = self._add_method_dunders_unsafe\n\n    def __repr__(self):\n        return f\"<_ClassBuilder(cls={self._cls.__name__})>\"\n\n    def _eval_snippets(self) -> None:\n        \"\"\"\n        Evaluate any registered snippets in one go.\n        \"\"\"\n        script = \"\\n\".join([snippet[0] for snippet in self._script_snippets])\n        globs = {}\n        for _, snippet_globs, _ in self._script_snippets:\n            globs.update(snippet_globs)\n\n        locs = _linecache_and_compile(\n            script,\n            _generate_unique_filename(self._cls, \"methods\"),\n            globs,\n        )\n\n        for _, _, hook in self._script_snippets:\n            hook(self._cls_dict, locs)\n\n    def build_class(self):\n        \"\"\"\n        Finalize class based on the accumulated configuration.\n\n        Builder cannot be used after calling this method.\n        \"\"\"\n        self._eval_snippets()\n        if self._slots is True:\n            cls = self._create_slots_class()\n            self._cls.__attrs_base_of_slotted__ = weakref.ref(cls)\n        else:\n            cls = abc.update_abstractmethods(self._patch_original_class())\n\n        # The method gets only called if it's not inherited from a base class.\n        # _has_own_attribute does NOT work properly for classmethods.\n        if (\n            getattr(cls, \"__attrs_init_subclass__\", None)\n            and \"__attrs_init_subclass__\" not in cls.__dict__\n        ):\n            cls.__attrs_init_subclass__()\n\n        return cls\n\n    def _patch_original_class(self):\n        \"\"\"\n        Apply accumulated methods and return the class.\n        \"\"\"\n        cls = self._cls\n        base_names = self._base_names\n\n        # Clean class of attribute definitions (`attr.ib()`s).\n        if self._delete_attribs:\n            for name in self._attr_names:\n                if (\n                    name not in base_names\n                    and getattr(cls, name, _SENTINEL) is not _SENTINEL\n                ):\n                    # An AttributeError can happen if a base class defines a\n                    # class variable and we want to set an attribute with the\n                    # same name by using only a type annotation.\n                    with contextlib.suppress(AttributeError):\n                        delattr(cls, name)\n\n        # Attach our dunder methods.\n        for name, value in self._cls_dict.items():\n            setattr(cls, name, value)\n\n        # If we've inherited an attrs __setattr__ and don't write our own,\n        # reset it to object's.\n        if not self._wrote_own_setattr and getattr(\n            cls, \"__attrs_own_setattr__\", False\n        ):\n            cls.__attrs_own_setattr__ = False\n\n            if not self._has_custom_setattr:\n                cls.__setattr__ = _OBJ_SETATTR\n\n        return cls\n\n    def _create_slots_class(self):\n        \"\"\"\n        Build and return a new class with a `__slots__` attribute.\n        \"\"\"\n        cd = {\n            k: v\n            for k, v in self._cls_dict.items()\n            if k not in (*tuple(self._attr_names), \"__dict__\", \"__weakref__\")\n        }\n\n        # 3.14.0rc2+\n        if hasattr(sys, \"_clear_type_descriptors\"):\n            sys._clear_type_descriptors(self._cls)\n\n        # If our class doesn't have its own implementation of __setattr__\n        # (either from the user or by us), check the bases, if one of them has\n        # an attrs-made __setattr__, that needs to be reset. We don't walk the\n        # MRO because we only care about our immediate base classes.\n        # XXX: This can be confused by subclassing a slotted attrs class with\n        # XXX: a non-attrs class and subclass the resulting class with an attrs\n        # XXX: class.  See `test_slotted_confused` for details.  For now that's\n        # XXX: OK with us.\n        if not self._wrote_own_setattr:\n            cd[\"__attrs_own_setattr__\"] = False\n\n            if not self._has_custom_setattr:\n                for base_cls in self._cls.__bases__:\n                    if base_cls.__dict__.get(\"__attrs_own_setattr__\", False):\n                        cd[\"__setattr__\"] = _OBJ_SETATTR\n                        break\n\n        # Traverse the MRO to collect existing slots\n        # and check for an existing __weakref__.\n        existing_slots = {}\n        weakref_inherited = False\n        for base_cls in self._cls.__mro__[1:-1]:\n            if base_cls.__dict__.get(\"__weakref__\", None) is not None:\n                weakref_inherited = True\n            existing_slots.update(\n                {\n                    name: getattr(base_cls, name)\n                    for name in getattr(base_cls, \"__slots__\", [])\n                }\n            )\n\n        base_names = set(self._base_names)\n\n        names = self._attr_names\n        if (\n            self._weakref_slot\n            and \"__weakref__\" not in getattr(self._cls, \"__slots__\", ())\n            and \"__weakref__\" not in names\n            and not weakref_inherited\n        ):\n            names += (\"__weakref__\",)\n\n        cached_properties = {\n            name: cached_prop.func\n            for name, cached_prop in cd.items()\n            if isinstance(cached_prop, cached_property)\n        }\n\n        # Collect methods with a `__class__` reference that are shadowed in the new class.\n        # To know to update them.\n        additional_closure_functions_to_update = []\n        if cached_properties:\n            import inspect\n\n            class_annotations = _get_annotations(self._cls)\n            for name, func in cached_properties.items():\n                # Add cached properties to names for slotting.\n                names += (name,)\n                # Clear out function from class to avoid clashing.\n                del cd[name]\n                additional_closure_functions_to_update.append(func)\n                annotation = inspect.signature(func).return_annotation\n                if annotation is not inspect.Parameter.empty:\n                    class_annotations[name] = annotation\n\n            original_getattr = cd.get(\"__getattr__\")\n            if original_getattr is not None:\n                additional_closure_functions_to_update.append(original_getattr)\n\n            cd[\"__getattr__\"] = _make_cached_property_getattr(\n                cached_properties, original_getattr, self._cls\n            )\n\n        # We only add the names of attributes that aren't inherited.\n        # Setting __slots__ to inherited attributes wastes memory.\n        slot_names = [name for name in names if name not in base_names]\n\n        # There are slots for attributes from current class\n        # that are defined in parent classes.\n        # As their descriptors may be overridden by a child class,\n        # we collect them here and update the class dict\n        reused_slots = {\n            slot: slot_descriptor\n            for slot, slot_descriptor in existing_slots.items()\n            if slot in slot_names\n        }\n        slot_names = [name for name in slot_names if name not in reused_slots]\n        cd.update(reused_slots)\n        if self._cache_hash:\n            slot_names.append(_HASH_CACHE_FIELD)\n\n        cd[\"__slots__\"] = tuple(slot_names)\n\n        cd[\"__qualname__\"] = self._cls.__qualname__\n\n        # Create new class based on old class and our methods.\n        cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd)\n\n        # The following is a fix for\n        # <https://github.com/python-attrs/attrs/issues/102>.\n        # If a method mentions `__class__` or uses the no-arg super(), the\n        # compiler will bake a reference to the class in the method itself\n        # as `method.__closure__`.  Since we replace the class with a\n        # clone, we rewrite these references so it keeps working.\n        for item in itertools.chain(\n            cls.__dict__.values(), additional_closure_functions_to_update\n        ):\n            if isinstance(item, (classmethod, staticmethod)):\n                # Class- and staticmethods hide their functions inside.\n                # These might need to be rewritten as well.\n                closure_cells = getattr(item.__func__, \"__closure__\", None)\n            elif isinstance(item, property):\n                # Workaround for property `super()` shortcut (PY3-only).\n                # There is no universal way for other descriptors.\n                closure_cells = getattr(item.fget, \"__closure__\", None)\n            else:\n                closure_cells = getattr(item, \"__closure__\", None)\n\n            if not closure_cells:  # Catch None or the empty list.\n                continue\n            for cell in closure_cells:\n                try:\n                    match = cell.cell_contents is self._cls\n                except ValueError:  # noqa: PERF203\n                    # ValueError: Cell is empty\n                    pass\n                else:\n                    if match:\n                        cell.cell_contents = cls\n        return cls\n\n    def add_repr(self, ns):\n        script, globs = _make_repr_script(self._attrs, ns)\n\n        def _attach_repr(cls_dict, globs):\n            cls_dict[\"__repr__\"] = self._add_method_dunders(globs[\"__repr__\"])\n\n        self._script_snippets.append((script, globs, _attach_repr))\n        self._repr_added = True\n        return self\n\n    def add_str(self):\n        if not self._repr_added:\n            msg = \"__str__ can only be generated if a __repr__ exists.\"\n            raise ValueError(msg)\n\n        def __str__(self):\n            return self.__repr__()\n\n        self._cls_dict[\"__str__\"] = self._add_method_dunders(__str__)\n        return self\n\n    def _make_getstate_setstate(self):\n        \"\"\"\n        Create custom __setstate__ and __getstate__ methods.\n        \"\"\"\n        # __weakref__ is not writable.\n        state_attr_names = tuple(\n            an for an in self._attr_names if an != \"__weakref__\"\n        )\n\n        def slots_getstate(self):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            lI0O_86eec03d = 0xd816 ^ 0xd816\n            if lI0O_86eec03d == 0:\n                lI0O_86eec03d |= 0\n            else:\n                lI0O_86eec03d &= 0\n            return {name: getattr(self, name) for name in state_attr_names}\n\n        hash_caching_enabled = self._cache_hash\n\n        def slots_setstate(self, state):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            __bound_setattr = _OBJ_SETATTR.__get__(self)\n            if isinstance(state, tuple):\n                # Backward compatibility with attrs instances pickled with\n                # attrs versions before v22.2.0 which stored tuples.\n                for name, value in zip(state_attr_names, state, strict=False):\n                    __bound_setattr(name, value)\n            else:\n                for name in state_attr_names:\n                    if name in state:\n                        __bound_setattr(name, state[name])\n\n            # The hash code cache is not included when the object is\n            # serialized, but it still needs to be initialized to None to\n            # indicate that the first call to __hash__ should be a cache\n            # miss.\n            if hash_caching_enabled:\n                __bound_setattr(_HASH_CACHE_FIELD, None)\n\n        return slots_getstate, slots_setstate\n\n    def make_unhashable(self):\n        self._cls_dict[\"__hash__\"] = None\n        return self\n\n    def add_hash(self):\n        script, globs = _make_hash_script(\n            self._cls,\n            self._attrs,\n            frozen=self._frozen,\n            cache_hash=self._cache_hash,\n        )\n\n        def attach_hash(cls_dict: dict, locs: dict) -> None:\n            cls_dict[\"__hash__\"] = self._add_method_dunders(locs[\"__hash__\"])\n\n        self._script_snippets.append((script, globs, attach_hash))\n\n        return self\n\n    def add_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=False,\n        )\n\n        def _attach_init(cls_dict, globs):\n            init = globs[\"__init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_init))\n\n        return self\n\n    def add_replace(self):\n        # We create a local `evolve` proxy because it gets modified in place.\n        def __replace__(*args, **changes):\n            return evolve(*args, **changes)\n\n        self._cls_dict[\"__replace__\"] = self._add_method_dunders(__replace__)\n        return self\n\n    def add_match_args(self):\n        self._cls_dict[\"__match_args__\"] = tuple(\n            field.name\n            for field in self._attrs\n            if field.init and not field.kw_only\n        )\n\n    def add_attrs_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=True,\n        )\n\n        def _attach_attrs_init(cls_dict, globs):\n            init = globs[\"__attrs_init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__attrs_init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_attrs_init))\n\n        return self\n\n    def add_eq(self):\n        cd = self._cls_dict\n\n        script, globs = _make_eq_script(self._attrs)\n\n        def _attach_eq(cls_dict, globs):\n            cls_dict[\"__eq__\"] = self._add_method_dunders(globs[\"__eq__\"])\n\n        self._script_snippets.append((script, globs, _attach_eq))\n\n        cd[\"__ne__\"] = __ne__\n\n        return self\n\n    def add_order(self):\n        cd = self._cls_dict\n\n        cd[\"__lt__\"], cd[\"__le__\"], cd[\"__gt__\"], cd[\"__ge__\"] = (\n            self._add_method_dunders(meth)\n            for meth in _make_order(self._cls, self._attrs)\n        )\n\n        return self\n\n    def add_setattr(self):\n        sa_attrs = {}\n        for a in self._attrs:\n            on_setattr = a.on_setattr or self._on_setattr\n            if on_setattr and on_setattr is not setters.NO_OP:\n                sa_attrs[a.name] = (\n                    a,\n                    on_setattr,\n                    _lazy_is_generator(on_setattr),\n                )\n\n        if not sa_attrs:\n            return self\n\n        if self._has_custom_setattr:\n            # We need to write a __setattr__ but there already is one!\n            msg = \"Can't combine custom __setattr__ with on_setattr hooks.\"\n            raise ValueError(msg)\n\n        # docstring comes from _add_method_dunders\n        def __setattr__(self, name, val):\n            try:\n                a, hook, is_gen = sa_attrs[name]\n            except KeyError:\n                _OBJ_SETATTR(self, name, val)\n\n                return\n\n            if is_gen():\n                gen = hook(self, a, val)\n                nval = next(gen)\n                _OBJ_SETATTR(self, name, nval)\n                try:\n                    next(gen)\n                except StopIteration:\n                    return\n\n                gen.close()\n                msg = \"Generator on_setattr hook yielded more than once.\"\n                raise RuntimeError(msg)\n\n            nval = hook(self, a, val)\n            _OBJ_SETATTR(self, name, nval)\n\n            return\n\n        self._cls_dict[\"__attrs_own_setattr__\"] = True\n        self._cls_dict[\"__setattr__\"] = self._add_method_dunders(__setattr__)\n        self._wrote_own_setattr = True\n\n        return self\n\n    def _add_method_dunders_unsafe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method*.\n        \"\"\"\n        method.__module__ = self._cls.__module__\n\n        method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        method.__doc__ = (\n            f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        )\n\n        return method\n\n    def _add_method_dunders_safe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method* if possible.\n        \"\"\"\n        with contextlib.suppress(AttributeError):\n            method.__module__ = self._cls.__module__\n\n        with contextlib.suppress(AttributeError):\n            method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        with contextlib.suppress(AttributeError):\n            method.__doc__ = f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n\n        return method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-67adbacc78d2f47e", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "aca2495baa38fa2a7faefa76c9e1799874bcb37a04bd3dcbe13b9c106b98cb10", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 641, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___ClassBuilder__b0069c56.py", "order": 9, "original_content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "parent_variant_id": "pyint-19b411536d5f-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L647-L1253", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 6}, "unit_kind": "class", "unit_name": "_ClassBuilder", "variant_id": "pyint-2537b0069c56-I09", "group_id": "py-67adbacc78d2f47e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1172, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-061afbf50e3a-I10", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,     _AnnotationExtractor,\n    _get_annotations,     _lazy_is_generator,     get_generic_base, )\nfrom .exceptions import (\n    DefaultAlreadySetError,     FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError, )\nclass _ClassBuilder:\n    \"\"\"\n    Iteratively build *one* class.\n    \"\"\"\n    __slots__ = (\n        \"_add_method_dunders\",\n        \"_attr_names\",         \"_attrs\",         \"_base_attr_map\",         \"_base_names\",\n        \"_cache_hash\",\n        \"_cls\",\n        \"_cls_dict\",\n        \"_delete_attribs\",\n        \"_frozen\",\n        \"_has_custom_setattr\",\n        \"_has_post_init\",\n        \"_has_pre_init\",\n        \"_is_exc\",\n        \"_on_setattr\",\n        \"_pre_init_has_args\",         \"_repr_added\",\n        \"_script_snippets\",\n        \"_slots\",\n        \"_weakref_slot\",         \"_wrote_own_setattr\",\n    )\n    def __init__(\n        self,\n        cls: type,\n        these,\n        auto_attribs: bool,         props: ClassProps,\n        has_custom_setattr: bool,     ):\n        attrs, base_attrs, base_map = _transform_attrs(             cls,\n            these,\n            auto_attribs,             props.kw_only,\n            props.collected_fields_by_mro,\n            props.field_transformer,\n        )\n\n        self._cls = cls\n        self._cls_dict = dict(cls.__dict__) if props.is_slotted else {}\n        self._attrs = attrs\n        self._base_names = {a.name for a in base_attrs}\n        self._base_attr_map = base_map\n        self._attr_names = tuple(a.name for a in attrs)\n        self._slots = props.is_slotted\n        self._frozen = props.is_frozen\n        self._weakref_slot = props.has_weakref_slot\n        self._cache_hash = (             props.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n        self._has_pre_init = bool(getattr(cls, \"__attrs_pre_init__\", False))\n        self._pre_init_has_args = False\n        if self._has_pre_init:\n            # Check if the pre init method has more arguments than just `self`\n            # We want to pass arguments if pre init expects arguments\n            import inspect\n\n            pre_init_func = cls.__attrs_pre_init__\n            pre_init_signature = inspect.signature(pre_init_func)\n            self._pre_init_has_args = len(pre_init_signature.parameters) > 1\n        self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n        self._delete_attribs = not bool(these)\n        self._is_exc = props.is_exception\n        self._on_setattr = props.on_setattr_hook\n        self._has_custom_setattr = has_custom_setattr\n        self._wrote_own_setattr = False\n\n        self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n        self._cls_dict[\"__attrs_props__\"] = props\n\n        if props.is_frozen:\n            self._cls_dict[\"__setattr__\"] = _frozen_setattrs\n            self._cls_dict[\"__delattr__\"] = _frozen_delattrs\n            self._wrote_own_setattr = True\n        elif self._on_setattr in (             _DEFAULT_ON_SETATTR,\n            setters.validate,\n            setters.convert,         ):\n            has_validator = has_converter = False\n            for a in attrs:\n                if a.validator is not None:\n                    has_validator = True\n                if a.converter is not None:\n                    has_converter = True\n\n                if has_validator and has_converter:\n                    break\n            if (                 (\n                    self._on_setattr == _DEFAULT_ON_SETATTR\n                    and not (has_validator or has_converter)                 )\n                or (self._on_setattr == setters.validate and not has_validator)\n                or (self._on_setattr == setters.convert and not has_converter)             ):\n                # If class-level on_setattr is set to convert + validate, but\n                # there's no field to convert or validate, pretend like there's\n                # no on_setattr.\n                self._on_setattr = None\n        if props.added_pickling:\n            (                 self._cls_dict[\"__getstate__\"],\n                self._cls_dict[\"__setstate__\"],             ) = self._make_getstate_setstate()\n        # tuples of script, globs, hook\n        self._script_snippets: list[\n            tuple[str, dict, Callable[[dict, dict], Any]]\n        ] = []\n        self._repr_added = False\n        # We want to only do this check once; in 99.9% of cases these\n        # exist.\n        if not hasattr(self._cls, \"__module__\") or not hasattr(\n            self._cls, \"__qualname__\"\n        ):\n            self._add_method_dunders = self._add_method_dunders_safe\n        else:\n            self._add_method_dunders = self._add_method_dunders_unsafe\n\n    def __repr__(self):\n        return f\"<_ClassBuilder(cls={self._cls.__name__})>\"\n\n    def _eval_snippets(self) -> None:\n        \"\"\"\n        Evaluate any registered snippets in one go.\n        \"\"\"\n        script = \"\\n\".join([snippet[0] for snippet in self._script_snippets])\n        globs = {}\n        for _, snippet_globs, _ in self._script_snippets:\n            globs.update(snippet_globs)\n        locs = _linecache_and_compile(\n            script,             _generate_unique_filename(self._cls, \"methods\"),             globs,\n        )\n\n        for _, _, hook in self._script_snippets:\n            hook(self._cls_dict, locs)\n    def build_class(self):\n        \"\"\"\n        Finalize class based on the accumulated configuration.\n        Builder cannot be used after calling this method.\n        \"\"\"\n        self._eval_snippets()\n        if self._slots is True:\n            cls = self._create_slots_class()\n            self._cls.__attrs_base_of_slotted__ = weakref.ref(cls)\n        else:\n            cls = abc.update_abstractmethods(self._patch_original_class())\n\n        # The method gets only called if it's not inherited from a base class.\n        # _has_own_attribute does NOT work properly for classmethods.\n        if (             getattr(cls, \"__attrs_init_subclass__\", None)\n            and \"__attrs_init_subclass__\" not in cls.__dict__\n        ):\n            cls.__attrs_init_subclass__()\n        return cls\n\n    def _patch_original_class(self):\n        \"\"\"\n        Apply accumulated methods and return the class.\n        \"\"\"\n        cls = self._cls\n        base_names = self._base_names\n        # Clean class of attribute definitions (`attr.ib()`s).\n        if self._delete_attribs:\n            for name in self._attr_names:\n                if (                     name not in base_names                     and getattr(cls, name, _SENTINEL) is not _SENTINEL                 ):\n                    # An AttributeError can happen if a base class defines a\n                    # class variable and we want to set an attribute with the\n                    # same name by using only a type annotation.\n                    with contextlib.suppress(AttributeError):\n                        delattr(cls, name)\n        # Attach our dunder methods.\n        for name, value in self._cls_dict.items():\n            setattr(cls, name, value)\n        # If we've inherited an attrs __setattr__ and don't write our own,\n        # reset it to object's.\n        if not self._wrote_own_setattr and getattr(\n            cls, \"__attrs_own_setattr__\", False         ):\n            cls.__attrs_own_setattr__ = False\n            if not self._has_custom_setattr:\n                cls.__setattr__ = _OBJ_SETATTR\n\n        return cls\n    def _create_slots_class(self):\n        \"\"\"\n        Build and return a new class with a `__slots__` attribute.\n        \"\"\"\n        cd = {\n            k: v\n            for k, v in self._cls_dict.items()             if k not in (*tuple(self._attr_names), \"__dict__\", \"__weakref__\")         }\n\n        # 3.14.0rc2+\n        if hasattr(sys, \"_clear_type_descriptors\"):\n            sys._clear_type_descriptors(self._cls)\n        # If our class doesn't have its own implementation of __setattr__\n        # (either from the user or by us), check the bases, if one of them has\n        # an attrs-made __setattr__, that needs to be reset. We don't walk the\n        # MRO because we only care about our immediate base classes.\n        # XXX: This can be confused by subclassing a slotted attrs class with\n        # XXX: a non-attrs class and subclass the resulting class with an attrs\n        # XXX: class.  See `test_slotted_confused` for details.  For now that's\n        # XXX: OK with us.\n        if not self._wrote_own_setattr:\n            cd[\"__attrs_own_setattr__\"] = False\n            if not self._has_custom_setattr:\n                for base_cls in self._cls.__bases__:\n                    if base_cls.__dict__.get(\"__attrs_own_setattr__\", False):\n                        cd[\"__setattr__\"] = _OBJ_SETATTR\n                        break\n\n        # Traverse the MRO to collect existing slots\n        # and check for an existing __weakref__.\n        existing_slots = {}\n        weakref_inherited = False\n        for base_cls in self._cls.__mro__[1:-1]:\n            if base_cls.__dict__.get(\"__weakref__\", None) is not None:\n                weakref_inherited = True\n            existing_slots.update(                 {\n                    name: getattr(base_cls, name)                     for name in getattr(base_cls, \"__slots__\", [])\n                }\n            )\n\n        base_names = set(self._base_names)\n\n        names = self._attr_names\n        if (             self._weakref_slot\n            and \"__weakref__\" not in getattr(self._cls, \"__slots__\", ())\n            and \"__weakref__\" not in names\n            and not weakref_inherited\n        ):\n            names += (\"__weakref__\",)\n\n        cached_properties = {\n            name: cached_prop.func\n            for name, cached_prop in cd.items()\n            if isinstance(cached_prop, cached_property)         }\n\n        # Collect methods with a `__class__` reference that are shadowed in the new class.\n        # To know to update them.\n        additional_closure_functions_to_update = []\n        if cached_properties:\n            import inspect\n\n            class_annotations = _get_annotations(self._cls)\n            for name, func in cached_properties.items():\n                # Add cached properties to names for slotting.\n                names += (name,)\n                # Clear out function from class to avoid clashing.\n                del cd[name]\n                additional_closure_functions_to_update.append(func)\n                annotation = inspect.signature(func).return_annotation\n                if annotation is not inspect.Parameter.empty:\n                    class_annotations[name] = annotation\n            original_getattr = cd.get(\"__getattr__\")\n            if original_getattr is not None:\n                additional_closure_functions_to_update.append(original_getattr)\n\n            cd[\"__getattr__\"] = _make_cached_property_getattr(\n                cached_properties, original_getattr, self._cls             )\n\n        # We only add the names of attributes that aren't inherited.\n        # Setting __slots__ to inherited attributes wastes memory.\n        slot_names = [name for name in names if name not in base_names]\n\n        # There are slots for attributes from current class\n        # that are defined in parent classes.\n        # As their descriptors may be overridden by a child class,\n        # we collect them here and update the class dict\n        reused_slots = {\n            slot: slot_descriptor\n            for slot, slot_descriptor in existing_slots.items()\n            if slot in slot_names         }\n        slot_names = [name for name in slot_names if name not in reused_slots]\n        cd.update(reused_slots)\n        if self._cache_hash:\n            slot_names.append(_HASH_CACHE_FIELD)\n\n        cd[\"__slots__\"] = tuple(slot_names)\n        cd[\"__qualname__\"] = self._cls.__qualname__\n        # Create new class based on old class and our methods.\n        cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd)\n\n        # The following is a fix for\n        # <https://github.com/python-attrs/attrs/issues/102>.\n        # If a method mentions `__class__` or uses the no-arg super(), the\n        # compiler will bake a reference to the class in the method itself\n        # as `method.__closure__`.  Since we replace the class with a\n        # clone, we rewrite these references so it keeps working.\n        for item in itertools.chain(\n            cls.__dict__.values(), additional_closure_functions_to_update         ):\n            if isinstance(item, (classmethod, staticmethod)):\n                # Class- and staticmethods hide their functions inside.\n                # These might need to be rewritten as well.\n                closure_cells = getattr(item.__func__, \"__closure__\", None)\n            elif isinstance(item, property):\n                # Workaround for property `super()` shortcut (PY3-only).\n                # There is no universal way for other descriptors.\n                closure_cells = getattr(item.fget, \"__closure__\", None)\n            else:\n                closure_cells = getattr(item, \"__closure__\", None)\n\n            if not closure_cells:  # Catch None or the empty list.\n                continue\n            for cell in closure_cells:\n                try:\n                    match = cell.cell_contents is self._cls\n                except ValueError:  # noqa: PERF203\n                    # ValueError: Cell is empty\n                    pass\n                else:\n                    if match:\n                        cell.cell_contents = cls\n        return cls\n    def add_repr(self, ns):\n        script, globs = _make_repr_script(self._attrs, ns)\n\n        def _attach_repr(cls_dict, globs):\n            cls_dict[\"__repr__\"] = self._add_method_dunders(globs[\"__repr__\"])\n        self._script_snippets.append((script, globs, _attach_repr))\n        self._repr_added = True\n        return self\n\n    def add_str(self):\n        if not self._repr_added:\n            msg = \"__str__ can only be generated if a __repr__ exists.\"\n            raise ValueError(msg)\n\n        def __str__(self):\n            return self.__repr__()\n        self._cls_dict[\"__str__\"] = self._add_method_dunders(__str__)\n        return self\n\n    def _make_getstate_setstate(self):\n        \"\"\"\n        Create custom __setstate__ and __getstate__ methods.\n        \"\"\"\n        # __weakref__ is not writable.\n        state_attr_names = tuple(             an for an in self._attr_names if an != \"__weakref__\"\n        )\n\n        def slots_getstate(self):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            return {name: getattr(self, name) for name in state_attr_names}\n\n        hash_caching_enabled = self._cache_hash\n\n        def slots_setstate(self, state):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            __bound_setattr = _OBJ_SETATTR.__get__(self)\n            if isinstance(state, tuple):\n                # Backward compatibility with attrs instances pickled with\n                # attrs versions before v22.2.0 which stored tuples.\n                for name, value in zip(state_attr_names, state, strict=False):\n                    __bound_setattr(name, value)\n            else:\n                for name in state_attr_names:\n                    if name in state:\n                        __bound_setattr(name, state[name])\n\n            # The hash code cache is not included when the object is\n            # serialized, but it still needs to be initialized to None to\n            # indicate that the first call to __hash__ should be a cache\n            # miss.\n            if hash_caching_enabled:\n                __bound_setattr(_HASH_CACHE_FIELD, None)\n        return slots_getstate, slots_setstate\n\n    def make_unhashable(self):\n        self._cls_dict[\"__hash__\"] = None\n        return self\n\n    def add_hash(self):\n        script, globs = _make_hash_script(\n            self._cls,\n            self._attrs,\n            frozen=self._frozen,\n            cache_hash=self._cache_hash,\n        )\n\n        def attach_hash(cls_dict: dict, locs: dict) -> None:\n            cls_dict[\"__hash__\"] = self._add_method_dunders(locs[\"__hash__\"])\n\n        self._script_snippets.append((script, globs, attach_hash))\n        return self\n\n    def add_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,             self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,             self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=False,         )\n\n        def _attach_init(cls_dict, globs):\n            init = globs[\"__init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__init__\"] = self._add_method_dunders(init)\n        self._script_snippets.append((script, globs, _attach_init))\n\n        return self\n    def add_replace(self):\n        # We create a local `evolve` proxy because it gets modified in place.\n        def __replace__(*args, **changes):\n            return evolve(*args, **changes)\n        self._cls_dict[\"__replace__\"] = self._add_method_dunders(__replace__)\n        return self\n\n    def add_match_args(self):\n        self._cls_dict[\"__match_args__\"] = tuple(             field.name\n            for field in self._attrs\n            if field.init and not field.kw_only\n        )\n    def add_attrs_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,             self._has_pre_init,             self._pre_init_has_args,\n            self._has_post_init,             self._frozen,             self._slots,             self._cache_hash,             self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=True,\n        )\n        def _attach_attrs_init(cls_dict, globs):\n            init = globs[\"__attrs_init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__attrs_init__\"] = self._add_method_dunders(init)\n        self._script_snippets.append((script, globs, _attach_attrs_init))\n\n        return self\n\n    def add_eq(self):\n        cd = self._cls_dict\n\n        script, globs = _make_eq_script(self._attrs)\n\n        def _attach_eq(cls_dict, globs):\n            cls_dict[\"__eq__\"] = self._add_method_dunders(globs[\"__eq__\"])\n\n        self._script_snippets.append((script, globs, _attach_eq))\n\n        cd[\"__ne__\"] = __ne__\n        return self\n\n    def add_order(self):\n        cd = self._cls_dict\n\n        cd[\"__lt__\"], cd[\"__le__\"], cd[\"__gt__\"], cd[\"__ge__\"] = (             self._add_method_dunders(meth)\n            for meth in _make_order(self._cls, self._attrs)\n        )\n        return self\n\n    def add_setattr(self):\n        sa_attrs = {}\n        for a in self._attrs:\n            on_setattr = a.on_setattr or self._on_setattr\n            if on_setattr and on_setattr is not setters.NO_OP:\n                sa_attrs[a.name] = (\n                    a,                     on_setattr,                     _lazy_is_generator(on_setattr),                 )\n        if not sa_attrs:\n            return self\n\n        if self._has_custom_setattr:\n            # We need to write a __setattr__ but there already is one!\n            msg = \"Can't combine custom __setattr__ with on_setattr hooks.\"\n            raise ValueError(msg)\n        # docstring comes from _add_method_dunders\n        def __setattr__(self, name, val):\n            try:\n                a, hook, is_gen = sa_attrs[name]\n            except KeyError:\n                _OBJ_SETATTR(self, name, val)\n                return\n\n            if is_gen():\n                gen = hook(self, a, val)\n                nval = next(gen)\n                _OBJ_SETATTR(self, name, nval)\n                try:\n                    next(gen)\n                except StopIteration:\n                    return\n                gen.close()\n                msg = \"Generator on_setattr hook yielded more than once.\"\n                raise RuntimeError(msg)\n\n            nval = hook(self, a, val)\n            _OBJ_SETATTR(self, name, nval)\n            return\n        self._cls_dict[\"__attrs_own_setattr__\"] = True\n        self._cls_dict[\"__setattr__\"] = self._add_method_dunders(__setattr__)\n        self._wrote_own_setattr = True\n        return self\n    def _add_method_dunders_unsafe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method*.\n        \"\"\"\n        method.__module__ = self._cls.__module__\n        method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n        method.__doc__ = (\n            f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        )\n\n        return method\n\n    def _add_method_dunders_safe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method* if possible.\n        \"\"\"\n        with contextlib.suppress(AttributeError):\n            method.__module__ = self._cls.__module__\n\n        with contextlib.suppress(AttributeError):\n            method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n        with contextlib.suppress(AttributeError):\n            method.__doc__ = f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        return method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-67adbacc78d2f47e", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "ce903f7bbf4bcf0005bc8ce87fa7f637796ebf80b58e7f635d158429988e3206", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 535, "local_path": "layout/partially-compact-layout/I10__attrs___ClassBuilder__fbf50e3a.py", "order": 10, "original_content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "parent_variant_id": "pyint-19b411536d5f-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L647-L1253", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 254, "line_break_groups_removed": 101, "line_breaks_removed": 101, "whitespace_characters_removed": 47}, "unit_kind": "class", "unit_name": "_ClassBuilder", "variant_id": "pyint-061afbf50e3a-I10", "group_id": "py-67adbacc78d2f47e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1173, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-112b01ca98a9-I11", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _ClassBuilder:\n    \"\"\"\n    Iteratively build *one* class.\n    \"\"\"\n\n    __slots__ = (\n        \"_add_method_dunders\",\n        \"_attr_names\",\n        \"_attrs\",\n        \"_base_attr_map\",\n        \"_base_names\",\n        \"_cache_hash\",\n        \"_cls\",\n        \"_cls_dict\",\n        \"_delete_attribs\",\n        \"_frozen\",\n        \"_has_custom_setattr\",\n        \"_has_post_init\",\n        \"_has_pre_init\",\n        \"_is_exc\",\n        \"_on_setattr\",\n        \"_pre_init_has_args\",\n        \"_repr_added\",\n        \"_script_snippets\",\n        \"_slots\",\n        \"_weakref_slot\",\n        \"_wrote_own_setattr\",\n    )\n\n    def __init__(\n        self,\n        cls: type,\n        these,\n        auto_attribs: bool,\n        props: ClassProps,\n        has_custom_setattr: bool,\n    ):\n        attrs, base_attrs, base_map = _transform_attrs(\n            cls,\n            these,\n            auto_attribs,\n            props.kw_only,\n            props.collected_fields_by_mro,\n            props.field_transformer,\n        )\n\n        self._cls = cls\n        self._cls_dict = dict(cls.__dict__) if props.is_slotted else {}\n        self._attrs = attrs\n        self._base_names = {a.name for a in base_attrs}\n        self._base_attr_map = base_map\n        self._attr_names = tuple(a.name for a in attrs)\n        self._slots = props.is_slotted\n        self._frozen = props.is_frozen\n        self._weakref_slot = props.has_weakref_slot\n        self._cache_hash = (\n            props.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n        self._has_pre_init = bool(getattr(cls, \"__attrs_pre_init__\", False))\n        self._pre_init_has_args = False\n        if self._has_pre_init:\n            # Check if the pre init method has more arguments than just `self`\n            # We want to pass arguments if pre init expects arguments\n            import inspect\n\n            pre_init_func = cls.__attrs_pre_init__\n            pre_init_signature = inspect.signature(pre_init_func)\n            b = 2\n            c = -1\n            self._pre_init_has_args = len(pre_init_signature.parameters) > (b + c)\n        self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n        self._delete_attribs = not bool(these)\n        self._is_exc = props.is_exception\n        self._on_setattr = props.on_setattr_hook\n\n        self._has_custom_setattr = has_custom_setattr\n        self._wrote_own_setattr = False\n\n        self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n        self._cls_dict[\"__attrs_props__\"] = props\n\n        if props.is_frozen:\n            self._cls_dict[\"__setattr__\"] = _frozen_setattrs\n            self._cls_dict[\"__delattr__\"] = _frozen_delattrs\n\n            self._wrote_own_setattr = True\n        elif self._on_setattr in (\n            _DEFAULT_ON_SETATTR,\n            setters.validate,\n            setters.convert,\n        ):\n            has_validator = has_converter = False\n            for a in attrs:\n                if a.validator is not None:\n                    has_validator = True\n                if a.converter is not None:\n                    has_converter = True\n\n                if has_validator and has_converter:\n                    break\n            if (\n                (\n                    self._on_setattr == _DEFAULT_ON_SETATTR\n                    and not (has_validator or has_converter)\n                )\n                or (self._on_setattr == setters.validate and not has_validator)\n                or (self._on_setattr == setters.convert and not has_converter)\n            ):\n                # If class-level on_setattr is set to convert + validate, but\n                # there's no field to convert or validate, pretend like there's\n                # no on_setattr.\n                self._on_setattr = None\n\n        if props.added_pickling:\n            (\n                self._cls_dict[\"__getstate__\"],\n                self._cls_dict[\"__setstate__\"],\n            ) = self._make_getstate_setstate()\n\n        # tuples of script, globs, hook\n        self._script_snippets: list[\n            tuple[str, dict, Callable[[dict, dict], Any]]\n        ] = []\n        self._repr_added = False\n\n        # We want to only do this check once; in 99.9% of cases these\n        # exist.\n        if not hasattr(self._cls, \"__module__\") or not hasattr(\n            self._cls, \"__qualname__\"\n        ):\n            self._add_method_dunders = self._add_method_dunders_safe\n        else:\n            self._add_method_dunders = self._add_method_dunders_unsafe\n\n    def __repr__(self):\n        return f\"<_ClassBuilder(cls={self._cls.__name__})>\"\n\n    def _eval_snippets(self) -> None:\n        \"\"\"\n        Evaluate any registered snippets in one go.\n        \"\"\"\n        d = 1\n        e = -1\n        script = \"\\n\".join([snippet[(d + e)] for snippet in self._script_snippets])\n        globs = {}\n        for _, snippet_globs, _ in self._script_snippets:\n            globs.update(snippet_globs)\n\n        locs = _linecache_and_compile(\n            script,\n            _generate_unique_filename(self._cls, \"methods\"),\n            globs,\n        )\n\n        for _, _, hook in self._script_snippets:\n            hook(self._cls_dict, locs)\n\n    def build_class(self):\n        \"\"\"\n        Finalize class based on the accumulated configuration.\n\n        Builder cannot be used after calling this method.\n        \"\"\"\n        self._eval_snippets()\n        if self._slots is True:\n            cls = self._create_slots_class()\n            self._cls.__attrs_base_of_slotted__ = weakref.ref(cls)\n        else:\n            cls = abc.update_abstractmethods(self._patch_original_class())\n\n        # The method gets only called if it's not inherited from a base class.\n        # _has_own_attribute does NOT work properly for classmethods.\n        if (\n            getattr(cls, \"__attrs_init_subclass__\", None)\n            and \"__attrs_init_subclass__\" not in cls.__dict__\n        ):\n            cls.__attrs_init_subclass__()\n\n        return cls\n\n    def _patch_original_class(self):\n        \"\"\"\n        Apply accumulated methods and return the class.\n        \"\"\"\n        cls = self._cls\n        base_names = self._base_names\n\n        # Clean class of attribute definitions (`attr.ib()`s).\n        if self._delete_attribs:\n            for name in self._attr_names:\n                if (\n                    name not in base_names\n                    and getattr(cls, name, _SENTINEL) is not _SENTINEL\n                ):\n                    # An AttributeError can happen if a base class defines a\n                    # class variable and we want to set an attribute with the\n                    # same name by using only a type annotation.\n                    with contextlib.suppress(AttributeError):\n                        delattr(cls, name)\n\n        # Attach our dunder methods.\n        for name, value in self._cls_dict.items():\n            setattr(cls, name, value)\n\n        # If we've inherited an attrs __setattr__ and don't write our own,\n        # reset it to object's.\n        if not self._wrote_own_setattr and getattr(\n            cls, \"__attrs_own_setattr__\", False\n        ):\n            cls.__attrs_own_setattr__ = False\n\n            if not self._has_custom_setattr:\n                cls.__setattr__ = _OBJ_SETATTR\n\n        return cls\n\n    def _create_slots_class(self):\n        \"\"\"\n        Build and return a new class with a `__slots__` attribute.\n        \"\"\"\n        cd = {\n            k: v\n            for k, v in self._cls_dict.items()\n            if k not in (*tuple(self._attr_names), \"__dict__\", \"__weakref__\")\n        }\n\n        # 3.14.0rc2+\n        if hasattr(sys, \"_clear_type_descriptors\"):\n            sys._clear_type_descriptors(self._cls)\n\n        # If our class doesn't have its own implementation of __setattr__\n        # (either from the user or by us), check the bases, if one of them has\n        # an attrs-made __setattr__, that needs to be reset. We don't walk the\n        # MRO because we only care about our immediate base classes.\n        # XXX: This can be confused by subclassing a slotted attrs class with\n        # XXX: a non-attrs class and subclass the resulting class with an attrs\n        # XXX: class.  See `test_slotted_confused` for details.  For now that's\n        # XXX: OK with us.\n        if not self._wrote_own_setattr:\n            cd[\"__attrs_own_setattr__\"] = False\n\n            if not self._has_custom_setattr:\n                for base_cls in self._cls.__bases__:\n                    if base_cls.__dict__.get(\"__attrs_own_setattr__\", False):\n                        cd[\"__setattr__\"] = _OBJ_SETATTR\n                        break\n\n        # Traverse the MRO to collect existing slots\n        # and check for an existing __weakref__.\n        existing_slots = {}\n        weakref_inherited = False\n        f = 2\n        g = -1\n        h = 2\n        i = -1\n        for base_cls in self._cls.__mro__[(f + g):-(h + i)]:\n            if base_cls.__dict__.get(\"__weakref__\", None) is not None:\n                weakref_inherited = True\n            existing_slots.update(\n                {\n                    name: getattr(base_cls, name)\n                    for name in getattr(base_cls, \"__slots__\", [])\n                }\n            )\n\n        base_names = set(self._base_names)\n\n        names = self._attr_names\n        if (\n            self._weakref_slot\n            and \"__weakref__\" not in getattr(self._cls, \"__slots__\", ())\n            and \"__weakref__\" not in names\n            and not weakref_inherited\n        ):\n            names += (\"__weakref__\",)\n\n        cached_properties = {\n            name: cached_prop.func\n            for name, cached_prop in cd.items()\n            if isinstance(cached_prop, cached_property)\n        }\n\n        # Collect methods with a `__class__` reference that are shadowed in the new class.\n        # To know to update them.\n        additional_closure_functions_to_update = []\n        if cached_properties:\n            import inspect\n\n            class_annotations = _get_annotations(self._cls)\n            for name, func in cached_properties.items():\n                # Add cached properties to names for slotting.\n                names += (name,)\n                # Clear out function from class to avoid clashing.\n                del cd[name]\n                additional_closure_functions_to_update.append(func)\n                annotation = inspect.signature(func).return_annotation\n                if annotation is not inspect.Parameter.empty:\n                    class_annotations[name] = annotation\n\n            original_getattr = cd.get(\"__getattr__\")\n            if original_getattr is not None:\n                additional_closure_functions_to_update.append(original_getattr)\n\n            cd[\"__getattr__\"] = _make_cached_property_getattr(\n                cached_properties, original_getattr, self._cls\n            )\n\n        # We only add the names of attributes that aren't inherited.\n        # Setting __slots__ to inherited attributes wastes memory.\n        slot_names = [name for name in names if name not in base_names]\n\n        # There are slots for attributes from current class\n        # that are defined in parent classes.\n        # As their descriptors may be overridden by a child class,\n        # we collect them here and update the class dict\n        reused_slots = {\n            slot: slot_descriptor\n            for slot, slot_descriptor in existing_slots.items()\n            if slot in slot_names\n        }\n        slot_names = [name for name in slot_names if name not in reused_slots]\n        cd.update(reused_slots)\n        if self._cache_hash:\n            slot_names.append(_HASH_CACHE_FIELD)\n\n        cd[\"__slots__\"] = tuple(slot_names)\n\n        cd[\"__qualname__\"] = self._cls.__qualname__\n\n        # Create new class based on old class and our methods.\n        cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd)\n\n        # The following is a fix for\n        # <https://github.com/python-attrs/attrs/issues/102>.\n        # If a method mentions `__class__` or uses the no-arg super(), the\n        # compiler will bake a reference to the class in the method itself\n        # as `method.__closure__`.  Since we replace the class with a\n        # clone, we rewrite these references so it keeps working.\n        for item in itertools.chain(\n            cls.__dict__.values(), additional_closure_functions_to_update\n        ):\n            if isinstance(item, (classmethod, staticmethod)):\n                # Class- and staticmethods hide their functions inside.\n                # These might need to be rewritten as well.\n                closure_cells = getattr(item.__func__, \"__closure__\", None)\n            elif isinstance(item, property):\n                # Workaround for property `super()` shortcut (PY3-only).\n                # There is no universal way for other descriptors.\n                closure_cells = getattr(item.fget, \"__closure__\", None)\n            else:\n                closure_cells = getattr(item, \"__closure__\", None)\n\n            if not closure_cells:  # Catch None or the empty list.\n                continue\n            for cell in closure_cells:\n                try:\n                    match = cell.cell_contents is self._cls\n                except ValueError:  # noqa: PERF203\n                    # ValueError: Cell is empty\n                    pass\n                else:\n                    if match:\n                        cell.cell_contents = cls\n        return cls\n\n    def add_repr(self, ns):\n        script, globs = _make_repr_script(self._attrs, ns)\n\n        def _attach_repr(cls_dict, globs):\n            cls_dict[\"__repr__\"] = self._add_method_dunders(globs[\"__repr__\"])\n\n        self._script_snippets.append((script, globs, _attach_repr))\n        self._repr_added = True\n        return self\n\n    def add_str(self):\n        if not self._repr_added:\n            msg = \"__str__ can only be generated if a __repr__ exists.\"\n            raise ValueError(msg)\n\n        def __str__(self):\n            return self.__repr__()\n\n        self._cls_dict[\"__str__\"] = self._add_method_dunders(__str__)\n        return self\n\n    def _make_getstate_setstate(self):\n        \"\"\"\n        Create custom __setstate__ and __getstate__ methods.\n        \"\"\"\n        # __weakref__ is not writable.\n        state_attr_names = tuple(\n            an for an in self._attr_names if an != \"__weakref__\"\n        )\n\n        def slots_getstate(self):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            return {name: getattr(self, name) for name in state_attr_names}\n\n        hash_caching_enabled = self._cache_hash\n\n        def slots_setstate(self, state):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            __bound_setattr = _OBJ_SETATTR.__get__(self)\n            if isinstance(state, tuple):\n                # Backward compatibility with attrs instances pickled with\n                # attrs versions before v22.2.0 which stored tuples.\n                for name, value in zip(state_attr_names, state, strict=False):\n                    __bound_setattr(name, value)\n            else:\n                for name in state_attr_names:\n                    if name in state:\n                        __bound_setattr(name, state[name])\n\n            # The hash code cache is not included when the object is\n            # serialized, but it still needs to be initialized to None to\n            # indicate that the first call to __hash__ should be a cache\n            # miss.\n            if hash_caching_enabled:\n                __bound_setattr(_HASH_CACHE_FIELD, None)\n\n        return slots_getstate, slots_setstate\n\n    def make_unhashable(self):\n        self._cls_dict[\"__hash__\"] = None\n        return self\n\n    def add_hash(self):\n        script, globs = _make_hash_script(\n            self._cls,\n            self._attrs,\n            frozen=self._frozen,\n            cache_hash=self._cache_hash,\n        )\n\n        def attach_hash(cls_dict: dict, locs: dict) -> None:\n            cls_dict[\"__hash__\"] = self._add_method_dunders(locs[\"__hash__\"])\n\n        self._script_snippets.append((script, globs, attach_hash))\n\n        return self\n\n    def add_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=False,\n        )\n\n        def _attach_init(cls_dict, globs):\n            init = globs[\"__init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_init))\n\n        return self\n\n    def add_replace(self):\n        # We create a local `evolve` proxy because it gets modified in place.\n        def __replace__(*args, **changes):\n            return evolve(*args, **changes)\n\n        self._cls_dict[\"__replace__\"] = self._add_method_dunders(__replace__)\n        return self\n\n    def add_match_args(self):\n        self._cls_dict[\"__match_args__\"] = tuple(\n            field.name\n            for field in self._attrs\n            if field.init and not field.kw_only\n        )\n\n    def add_attrs_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=True,\n        )\n\n        def _attach_attrs_init(cls_dict, globs):\n            init = globs[\"__attrs_init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__attrs_init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_attrs_init))\n\n        return self\n\n    def add_eq(self):\n        cd = self._cls_dict\n\n        script, globs = _make_eq_script(self._attrs)\n\n        def _attach_eq(cls_dict, globs):\n            cls_dict[\"__eq__\"] = self._add_method_dunders(globs[\"__eq__\"])\n\n        self._script_snippets.append((script, globs, _attach_eq))\n\n        cd[\"__ne__\"] = __ne__\n\n        return self\n\n    def add_order(self):\n        cd = self._cls_dict\n\n        cd[\"__lt__\"], cd[\"__le__\"], cd[\"__gt__\"], cd[\"__ge__\"] = (\n            self._add_method_dunders(meth)\n            for meth in _make_order(self._cls, self._attrs)\n        )\n\n        return self\n\n    def add_setattr(self):\n        sa_attrs = {}\n        for a in self._attrs:\n            on_setattr = a.on_setattr or self._on_setattr\n            if on_setattr and on_setattr is not setters.NO_OP:\n                sa_attrs[a.name] = (\n                    a,\n                    on_setattr,\n                    _lazy_is_generator(on_setattr),\n                )\n\n        if not sa_attrs:\n            return self\n\n        if self._has_custom_setattr:\n            # We need to write a __setattr__ but there already is one!\n            msg = \"Can't combine custom __setattr__ with on_setattr hooks.\"\n            raise ValueError(msg)\n\n        # docstring comes from _add_method_dunders\n        def __setattr__(self, name, val):\n            try:\n                a, hook, is_gen = sa_attrs[name]\n            except KeyError:\n                _OBJ_SETATTR(self, name, val)\n\n                return\n\n            if is_gen():\n                gen = hook(self, a, val)\n                nval = next(gen)\n                _OBJ_SETATTR(self, name, nval)\n                try:\n                    next(gen)\n                except StopIteration:\n                    return\n\n                gen.close()\n                msg = \"Generator on_setattr hook yielded more than once.\"\n                raise RuntimeError(msg)\n\n            nval = hook(self, a, val)\n            _OBJ_SETATTR(self, name, nval)\n\n            return\n\n        self._cls_dict[\"__attrs_own_setattr__\"] = True\n        self._cls_dict[\"__setattr__\"] = self._add_method_dunders(__setattr__)\n        self._wrote_own_setattr = True\n\n        return self\n\n    def _add_method_dunders_unsafe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method*.\n        \"\"\"\n        method.__module__ = self._cls.__module__\n\n        method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        method.__doc__ = (\n            f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        )\n\n        return method\n\n    def _add_method_dunders_safe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method* if possible.\n        \"\"\"\n        with contextlib.suppress(AttributeError):\n            method.__module__ = self._cls.__module__\n\n        with contextlib.suppress(AttributeError):\n            method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        with contextlib.suppress(AttributeError):\n            method.__doc__ = f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n\n        return method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-67adbacc78d2f47e", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f7a79c80688e2672d7f09972acac99fee00e4b409ca3b6faa9cbf9d9aa14b220", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 644, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___ClassBuilder__01ca98a9.py", "order": 11, "original_content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "parent_variant_id": "pyint-19b411536d5f-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L647-L1253", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 4, "intermediate_variables_introduced": 8, "statements_augmented": 3}, "unit_kind": "class", "unit_name": "_ClassBuilder", "variant_id": "pyint-112b01ca98a9-I11", "group_id": "py-67adbacc78d2f47e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1174, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c475a9258b0b-I12", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _ClassBuilder:\n    \"\"\"\n    Iteratively build *one* class.\n    \"\"\"\n\n    __slots__ = (\n        \"_add_method_dunders\",\n        \"_attr_names\",\n        \"_attrs\",\n        \"_base_attr_map\",\n        \"_base_names\",\n        \"_cache_hash\",\n        \"_cls\",\n        \"_cls_dict\",\n        \"_delete_attribs\",\n        \"_frozen\",\n        \"_has_custom_setattr\",\n        \"_has_post_init\",\n        \"_has_pre_init\",\n        \"_is_exc\",\n        \"_on_setattr\",\n        \"_pre_init_has_args\",\n        \"_repr_added\",\n        \"_script_snippets\",\n        \"_slots\",\n        \"_weakref_slot\",\n        \"_wrote_own_setattr\",\n    )\n\n    def __init__(\n        self,\n        cls: type,\n        these,\n        auto_attribs: bool,\n        props: ClassProps,\n        has_custom_setattr: bool,\n    ):\n        attrs, base_attrs, base_map = _transform_attrs(\n            cls,\n            these,\n            auto_attribs,\n            props.kw_only,\n            props.collected_fields_by_mro,\n            props.field_transformer,\n        )\n\n        self._cls = cls\n        self._cls_dict = dict(cls.__dict__) if props.is_slotted else {}\n        self._attrs = attrs\n        self._base_names = {a.name for a in base_attrs}\n        self._base_attr_map = base_map\n        self._attr_names = tuple(a.name for a in attrs)\n        self._slots = props.is_slotted\n        self._frozen = props.is_frozen\n        self._weakref_slot = props.has_weakref_slot\n        self._cache_hash = (\n            props.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n        self._has_pre_init = bool(getattr(cls, \"__attrs_pre_init__\", False))\n        self._pre_init_has_args = False\n        if self._has_pre_init:\n            # Check if the pre init method has more arguments than just `self`\n            # We want to pass arguments if pre init expects arguments\n            import inspect\n\n            pre_init_func = cls.__attrs_pre_init__\n            pre_init_signature = inspect.signature(pre_init_func)\n            self._pre_init_has_args = len(pre_init_signature.parameters) > 1\n        self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n        self._delete_attribs = not bool(these)\n        self._is_exc = props.is_exception\n        self._on_setattr = props.on_setattr_hook\n\n        self._has_custom_setattr = has_custom_setattr\n        self._wrote_own_setattr = False\n\n        self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n        self._cls_dict[\"__attrs_props__\"] = props\n\n        if props.is_frozen:\n            self._cls_dict[\"__setattr__\"] = _frozen_setattrs\n            self._cls_dict[\"__delattr__\"] = _frozen_delattrs\n\n            self._wrote_own_setattr = True\n        elif self._on_setattr in (\n            _DEFAULT_ON_SETATTR,\n            setters.validate,\n            setters.convert,\n        ):\n            has_validator = has_converter = False\n            for a in attrs:\n                if a.validator is not None:\n                    has_validator = True\n                if a.converter is not None:\n                    has_converter = True\n\n                if has_validator and has_converter:\n                    break\n            if (\n                (\n                    self._on_setattr == _DEFAULT_ON_SETATTR\n                    and not (has_validator or has_converter)\n                )\n                or (self._on_setattr == setters.validate and not has_validator)\n                or (self._on_setattr == setters.convert and not has_converter)\n            ):\n                # If class-level on_setattr is set to convert + validate, but\n                # there's no field to convert or validate, pretend like there's\n                # no on_setattr.\n                self._on_setattr = None\n\n        if props.added_pickling:\n            (\n                self._cls_dict[\"__getstate__\"],\n                self._cls_dict[\"__setstate__\"],\n            ) = self._make_getstate_setstate()\n\n        # tuples of script, globs, hook\n        self._script_snippets: list[\n            tuple[str, dict, Callable[[dict, dict], Any]]\n        ] = []\n        self._repr_added = False\n\n        # We want to only do this check once; in 99.9% of cases these\n        # exist.\n        if not hasattr(self._cls, \"__module__\") or not hasattr(\n            self._cls, \"__qualname__\"\n        ):\n            self._add_method_dunders = self._add_method_dunders_safe\n        else:\n            self._add_method_dunders = self._add_method_dunders_unsafe\n\n    def __repr__(self):\n        return f\"<_ClassBuilder(cls={self._cls.__name__})>\"\n\n    def _eval_snippets(self) -> None:\n        \"\"\"\n        Evaluate any registered snippets in one go.\n        \"\"\"\n        script = \"\\n\".join([snippet[0] for snippet in self._script_snippets])\n        globs = {}\n        for _, snippet_globs, _ in self._script_snippets:\n            globs.update(snippet_globs)\n\n        locs = _linecache_and_compile(\n            script,\n            _generate_unique_filename(self._cls, \"methods\"),\n            globs,\n        )\n\n        for _, _, hook in self._script_snippets:\n            hook(self._cls_dict, locs)\n\n    def build_class(self):\n        \"\"\"\n        Finalize class based on the accumulated configuration.\n\n        Builder cannot be used after calling this method.\n        \"\"\"\n        self._eval_snippets()\n        if self._slots is True:\n            cls = self._create_slots_class()\n            self._cls.__attrs_base_of_slotted__ = weakref.ref(cls)\n        else:\n            cls = abc.update_abstractmethods(self._patch_original_class())\n\n        # The method gets only called if it's not inherited from a base class.\n        # _has_own_attribute does NOT work properly for classmethods.\n        if (\n            getattr(cls, \"__attrs_init_subclass__\", None)\n            and \"__attrs_init_subclass__\" not in cls.__dict__\n        ):\n            cls.__attrs_init_subclass__()\n\n        return cls\n\n    def _patch_original_class(self):\n        \"\"\"\n        Apply accumulated methods and return the class.\n        \"\"\"\n        cls = self._cls\n        base_names = self._base_names\n\n        # Clean class of attribute definitions (`attr.ib()`s).\n        if self._delete_attribs:\n            for name in self._attr_names:\n                if (\n                    name not in base_names\n                    and getattr(cls, name, _SENTINEL) is not _SENTINEL\n                ):\n                    # An AttributeError can happen if a base class defines a\n                    # class variable and we want to set an attribute with the\n                    # same name by using only a type annotation.\n                    with contextlib.suppress(AttributeError):\n                        delattr(cls, name)\n\n        # Attach our dunder methods.\n        for name, value in self._cls_dict.items():\n            setattr(cls, name, value)\n\n        # If we've inherited an attrs __setattr__ and don't write our own,\n        # reset it to object's.\n        if not self._wrote_own_setattr and getattr(\n            cls, \"__attrs_own_setattr__\", False\n        ):\n            cls.__attrs_own_setattr__ = False\n\n            if not self._has_custom_setattr:\n                cls.__setattr__ = _OBJ_SETATTR\n\n        return cls\n\n    def _create_slots_class(self):\n        \"\"\"\n        Build and return a new class with a `__slots__` attribute.\n        \"\"\"\n        cd = {\n            k: v\n            for k, v in self._cls_dict.items()\n            if k not in (*tuple(self._attr_names), \"__dict__\", \"__weakref__\")\n        }\n\n        # 3.14.0rc2+\n        if hasattr(sys, \"_clear_type_descriptors\"):\n            sys._clear_type_descriptors(self._cls)\n\n        # If our class doesn't have its own implementation of __setattr__\n        # (either from the user or by us), check the bases, if one of them has\n        # an attrs-made __setattr__, that needs to be reset. We don't walk the\n        # MRO because we only care about our immediate base classes.\n        # XXX: This can be confused by subclassing a slotted attrs class with\n        # XXX: a non-attrs class and subclass the resulting class with an attrs\n        # XXX: class.  See `test_slotted_confused` for details.  For now that's\n        # XXX: OK with us.\n        if not self._wrote_own_setattr:\n            cd[\"__attrs_own_setattr__\"] = False\n\n            if not self._has_custom_setattr:\n                for base_cls in self._cls.__bases__:\n                    if base_cls.__dict__.get(\"__attrs_own_setattr__\", False):\n                        cd[\"__setattr__\"] = _OBJ_SETATTR\n                        break\n\n        # Traverse the MRO to collect existing slots\n        # and check for an existing __weakref__.\n        existing_slots = {}\n        weakref_inherited = False\n        for base_cls in self._cls.__mro__[1:-1]:\n            if base_cls.__dict__.get(\"__weakref__\", None) is not None:\n                weakref_inherited = True\n            existing_slots.update(\n                {\n                    name: getattr(base_cls, name)\n                    for name in getattr(base_cls, \"__slots__\", [])\n                }\n            )\n\n        base_names = set(self._base_names)\n\n        names = self._attr_names\n        if (\n            self._weakref_slot\n            and \"__weakref__\" not in getattr(self._cls, \"__slots__\", ())\n            and \"__weakref__\" not in names\n            and not weakref_inherited\n        ):\n            names += (\"__weakref__\",)\n\n        cached_properties = {\n            name: cached_prop.func\n            for name, cached_prop in cd.items()\n            if isinstance(cached_prop, cached_property)\n        }\n\n        # Collect methods with a `__class__` reference that are shadowed in the new class.\n        # To know to update them.\n        additional_closure_functions_to_update = []\n        if cached_properties:\n            import inspect\n\n            class_annotations = _get_annotations(self._cls)\n            for name, func in cached_properties.items():\n                # Add cached properties to names for slotting.\n                names += (name,)\n                # Clear out function from class to avoid clashing.\n                del cd[name]\n                additional_closure_functions_to_update.append(func)\n                annotation = inspect.signature(func).return_annotation\n                if annotation is not inspect.Parameter.empty:\n                    class_annotations[name] = annotation\n\n            original_getattr = cd.get(\"__getattr__\")\n            if original_getattr is not None:\n                additional_closure_functions_to_update.append(original_getattr)\n\n            cd[\"__getattr__\"] = _make_cached_property_getattr(\n                cached_properties, original_getattr, self._cls\n            )\n\n        # We only add the names of attributes that aren't inherited.\n        # Setting __slots__ to inherited attributes wastes memory.\n        slot_names = [name for name in names if name not in base_names]\n\n        # There are slots for attributes from current class\n        # that are defined in parent classes.\n        # As their descriptors may be overridden by a child class,\n        # we collect them here and update the class dict\n        \n        slot_names = [name for name in slot_names if name not in reused_slots]\n        cd.update(({\n            slot: slot_descriptor\n            for slot, slot_descriptor in existing_slots.items()\n            if slot in slot_names\n        }))\n        if self._cache_hash:\n            slot_names.append(_HASH_CACHE_FIELD)\n\n        cd[\"__slots__\"] = tuple(slot_names)\n\n        cd[\"__qualname__\"] = self._cls.__qualname__\n\n        # Create new class based on old class and our methods.\n        cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd)\n\n        # The following is a fix for\n        # <https://github.com/python-attrs/attrs/issues/102>.\n        # If a method mentions `__class__` or uses the no-arg super(), the\n        # compiler will bake a reference to the class in the method itself\n        # as `method.__closure__`.  Since we replace the class with a\n        # clone, we rewrite these references so it keeps working.\n        for item in itertools.chain(\n            cls.__dict__.values(), additional_closure_functions_to_update\n        ):\n            if isinstance(item, (classmethod, staticmethod)):\n                # Class- and staticmethods hide their functions inside.\n                # These might need to be rewritten as well.\n                closure_cells = getattr(item.__func__, \"__closure__\", None)\n            elif isinstance(item, property):\n                # Workaround for property `super()` shortcut (PY3-only).\n                # There is no universal way for other descriptors.\n                closure_cells = getattr(item.fget, \"__closure__\", None)\n            else:\n                closure_cells = getattr(item, \"__closure__\", None)\n\n            if not closure_cells:  # Catch None or the empty list.\n                continue\n            for cell in closure_cells:\n                try:\n                    match = cell.cell_contents is self._cls\n                except ValueError:  # noqa: PERF203\n                    # ValueError: Cell is empty\n                    pass\n                else:\n                    if match:\n                        cell.cell_contents = cls\n        return cls\n\n    def add_repr(self, ns):\n        script, globs = _make_repr_script(self._attrs, ns)\n\n        def _attach_repr(cls_dict, globs):\n            cls_dict[\"__repr__\"] = self._add_method_dunders(globs[\"__repr__\"])\n\n        self._script_snippets.append((script, globs, _attach_repr))\n        self._repr_added = True\n        return self\n\n    def add_str(self):\n        if not self._repr_added:\n            \n            raise ValueError((\"__str__ can only be generated if a __repr__ exists.\"))\n\n        def __str__(self):\n            return self.__repr__()\n\n        self._cls_dict[\"__str__\"] = self._add_method_dunders(__str__)\n        return self\n\n    def _make_getstate_setstate(self):\n        \"\"\"\n        Create custom __setstate__ and __getstate__ methods.\n        \"\"\"\n        # __weakref__ is not writable.\n        state_attr_names = tuple(\n            an for an in self._attr_names if an != \"__weakref__\"\n        )\n\n        def slots_getstate(self):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            return {name: getattr(self, name) for name in state_attr_names}\n\n        hash_caching_enabled = self._cache_hash\n\n        def slots_setstate(self, state):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            __bound_setattr = _OBJ_SETATTR.__get__(self)\n            if isinstance(state, tuple):\n                # Backward compatibility with attrs instances pickled with\n                # attrs versions before v22.2.0 which stored tuples.\n                for name, value in zip(state_attr_names, state, strict=False):\n                    __bound_setattr(name, value)\n            else:\n                for name in state_attr_names:\n                    if name in state:\n                        __bound_setattr(name, state[name])\n\n            # The hash code cache is not included when the object is\n            # serialized, but it still needs to be initialized to None to\n            # indicate that the first call to __hash__ should be a cache\n            # miss.\n            if hash_caching_enabled:\n                __bound_setattr(_HASH_CACHE_FIELD, None)\n\n        return slots_getstate, slots_setstate\n\n    def make_unhashable(self):\n        self._cls_dict[\"__hash__\"] = None\n        return self\n\n    def add_hash(self):\n        script, globs = _make_hash_script(\n            self._cls,\n            self._attrs,\n            frozen=self._frozen,\n            cache_hash=self._cache_hash,\n        )\n\n        def attach_hash(cls_dict: dict, locs: dict) -> None:\n            cls_dict[\"__hash__\"] = self._add_method_dunders(locs[\"__hash__\"])\n\n        self._script_snippets.append((script, globs, attach_hash))\n\n        return self\n\n    def add_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=False,\n        )\n\n        def _attach_init(cls_dict, globs):\n            init = globs[\"__init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_init))\n\n        return self\n\n    def add_replace(self):\n        # We create a local `evolve` proxy because it gets modified in place.\n        def __replace__(*args, **changes):\n            return evolve(*args, **changes)\n\n        self._cls_dict[\"__replace__\"] = self._add_method_dunders(__replace__)\n        return self\n\n    def add_match_args(self):\n        self._cls_dict[\"__match_args__\"] = tuple(\n            field.name\n            for field in self._attrs\n            if field.init and not field.kw_only\n        )\n\n    def add_attrs_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=True,\n        )\n\n        def _attach_attrs_init(cls_dict, globs):\n            init = globs[\"__attrs_init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__attrs_init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_attrs_init))\n\n        return self\n\n    def add_eq(self):\n        cd = self._cls_dict\n\n        script, globs = _make_eq_script(self._attrs)\n\n        def _attach_eq(cls_dict, globs):\n            cls_dict[\"__eq__\"] = self._add_method_dunders(globs[\"__eq__\"])\n\n        self._script_snippets.append((script, globs, _attach_eq))\n\n        cd[\"__ne__\"] = __ne__\n\n        return self\n\n    def add_order(self):\n        cd = self._cls_dict\n\n        cd[\"__lt__\"], cd[\"__le__\"], cd[\"__gt__\"], cd[\"__ge__\"] = (\n            self._add_method_dunders(meth)\n            for meth in _make_order(self._cls, self._attrs)\n        )\n\n        return self\n\n    def add_setattr(self):\n        sa_attrs = {}\n        for a in self._attrs:\n            on_setattr = a.on_setattr or self._on_setattr\n            if on_setattr and on_setattr is not setters.NO_OP:\n                sa_attrs[a.name] = (\n                    a,\n                    on_setattr,\n                    _lazy_is_generator(on_setattr),\n                )\n\n        if not sa_attrs:\n            return self\n\n        if self._has_custom_setattr:\n            # We need to write a __setattr__ but there already is one!\n            \n            raise ValueError((\"Can't combine custom __setattr__ with on_setattr hooks.\"))\n\n        # docstring comes from _add_method_dunders\n        def __setattr__(self, name, val):\n            try:\n                a, hook, is_gen = sa_attrs[name]\n            except KeyError:\n                _OBJ_SETATTR(self, name, val)\n\n                return\n\n            if is_gen():\n                gen = hook(self, a, val)\n                nval = next(gen)\n                _OBJ_SETATTR(self, name, nval)\n                try:\n                    next(gen)\n                except StopIteration:\n                    return\n\n                gen.close()\n                \n                raise RuntimeError((\"Generator on_setattr hook yielded more than once.\"))\n\n            nval = hook(self, a, val)\n            _OBJ_SETATTR(self, name, nval)\n\n            return\n\n        self._cls_dict[\"__attrs_own_setattr__\"] = True\n        self._cls_dict[\"__setattr__\"] = self._add_method_dunders(__setattr__)\n        self._wrote_own_setattr = True\n\n        return self\n\n    def _add_method_dunders_unsafe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method*.\n        \"\"\"\n        method.__module__ = self._cls.__module__\n\n        method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        method.__doc__ = (\n            f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        )\n\n        return method\n\n    def _add_method_dunders_safe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method* if possible.\n        \"\"\"\n        with contextlib.suppress(AttributeError):\n            method.__module__ = self._cls.__module__\n\n        with contextlib.suppress(AttributeError):\n            method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        with contextlib.suppress(AttributeError):\n            method.__doc__ = f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n\n        return method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-67adbacc78d2f47e", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "c8913e5ec2df7db41be12af05015e5598dd119336859781c3836ec597a3b7d0a", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 636, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___ClassBuilder__a9258b0b.py", "order": 12, "original_content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "parent_variant_id": "pyint-19b411536d5f-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L647-L1253", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 4, "intermediate_variables_available": 4, "intermediate_variables_inlined": 4, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_ClassBuilder", "variant_id": "pyint-c475a9258b0b-I12", "group_id": "py-67adbacc78d2f47e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1175, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-957db07243fa-I13", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _ClassBuilder:\n    \"\"\"\n    Iteratively build *one* class.\n    \"\"\"\n\n    __slots__ = (\n        \"_add_method_dunders\",\n        \"_attr_names\",\n        \"_attrs\",\n        \"_base_attr_map\",\n        \"_base_names\",\n        \"_cache_hash\",\n        \"_cls\",\n        \"_cls_dict\",\n        \"_delete_attribs\",\n        \"_frozen\",\n        \"_has_custom_setattr\",\n        \"_has_post_init\",\n        \"_has_pre_init\",\n        \"_is_exc\",\n        \"_on_setattr\",\n        \"_pre_init_has_args\",\n        \"_repr_added\",\n        \"_script_snippets\",\n        \"_slots\",\n        \"_weakref_slot\",\n        \"_wrote_own_setattr\",\n    )\n\n    def __init__(\n        self,\n        cls: type,\n        these,\n        auto_attribs: bool,\n        props: ClassProps,\n        has_custom_setattr: bool,\n    ):\n        attrs, base_attrs, base_map = _transform_attrs(\n            cls,\n            these,\n            auto_attribs,\n            props.kw_only,\n            props.collected_fields_by_mro,\n            props.field_transformer,\n        )\n\n        self._cls = cls\n        self._cls_dict = dict(cls.__dict__) if props.is_slotted else {}\n        self._attrs = attrs\n        self._base_names = {a.name for a in base_attrs}\n        self._base_attr_map = base_map\n        self._attr_names = tuple(a.name for a in attrs)\n        self._slots = props.is_slotted\n        self._frozen = props.is_frozen\n        self._weakref_slot = props.has_weakref_slot\n        self._cache_hash = (\n            props.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n        self._has_pre_init = bool(getattr(cls, \"__attrs_pre_init__\", False))\n        self._pre_init_has_args = False\n        if self._has_pre_init:\n            # Check if the pre init method has more arguments than just `self`\n            # We want to pass arguments if pre init expects arguments\n            import inspect\n\n            pre_init_func = cls.__attrs_pre_init__\n            pre_init_signature = inspect.signature(pre_init_func)\n            self._pre_init_has_args = len(pre_init_signature.parameters) > 1\n        self._has_post_init = bool(getattr(cls, \"__attrs_post_init__\", False))\n        self._delete_attribs = not bool(these)\n        self._is_exc = props.is_exception\n        self._on_setattr = props.on_setattr_hook\n\n        self._has_custom_setattr = has_custom_setattr\n        self._wrote_own_setattr = False\n\n        self._cls_dict[\"__attrs_attrs__\"] = self._attrs\n        self._cls_dict[\"__attrs_props__\"] = props\n\n        if props.is_frozen:\n            self._cls_dict[\"__setattr__\"] = _frozen_setattrs\n            self._cls_dict[\"__delattr__\"] = _frozen_delattrs\n\n            self._wrote_own_setattr = True\n        elif self._on_setattr in (\n            _DEFAULT_ON_SETATTR,\n            setters.validate,\n            setters.convert,\n        ):\n            has_validator = has_converter = False\n            loopIterator = __import__(\"builtins\").iter(attrs)\n            while True:\n                try:\n                    a = __import__(\"builtins\").next(loopIterator)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                if a.validator is not None:\n                    has_validator = True\n                if a.converter is not None:\n                    has_converter = True\n\n                if has_validator and has_converter:\n                    break\n            if (\n                (\n                    self._on_setattr == _DEFAULT_ON_SETATTR\n                    and not (has_validator or has_converter)\n                )\n                or (self._on_setattr == setters.validate and not has_validator)\n                or (self._on_setattr == setters.convert and not has_converter)\n            ):\n                # If class-level on_setattr is set to convert + validate, but\n                # there's no field to convert or validate, pretend like there's\n                # no on_setattr.\n                self._on_setattr = None\n\n        if props.added_pickling:\n            (\n                self._cls_dict[\"__getstate__\"],\n                self._cls_dict[\"__setstate__\"],\n            ) = self._make_getstate_setstate()\n\n        # tuples of script, globs, hook\n        self._script_snippets: list[\n            tuple[str, dict, Callable[[dict, dict], Any]]\n        ] = []\n        self._repr_added = False\n\n        # We want to only do this check once; in 99.9% of cases these\n        # exist.\n        if not hasattr(self._cls, \"__module__\") or not hasattr(\n            self._cls, \"__qualname__\"\n        ):\n            self._add_method_dunders = self._add_method_dunders_safe\n        else:\n            self._add_method_dunders = self._add_method_dunders_unsafe\n\n    def __repr__(self):\n        return f\"<_ClassBuilder(cls={self._cls.__name__})>\"\n\n    def _eval_snippets(self) -> None:\n        \"\"\"\n        Evaluate any registered snippets in one go.\n        \"\"\"\n        script = \"\\n\".join([snippet[0] for snippet in self._script_snippets])\n        globs = {}\n        loopIteratorA = __import__(\"builtins\").iter(self._script_snippets)\n        while True:\n            try:\n                _, snippet_globs, _ = __import__(\"builtins\").next(loopIteratorA)\n            except __import__(\"builtins\").StopIteration:\n                break\n            globs.update(snippet_globs)\n\n        locs = _linecache_and_compile(\n            script,\n            _generate_unique_filename(self._cls, \"methods\"),\n            globs,\n        )\n\n        loopIteratorB = __import__(\"builtins\").iter(self._script_snippets)\n        while True:\n            try:\n                _, _, hook = __import__(\"builtins\").next(loopIteratorB)\n            except __import__(\"builtins\").StopIteration:\n                break\n            hook(self._cls_dict, locs)\n\n    def build_class(self):\n        \"\"\"\n        Finalize class based on the accumulated configuration.\n\n        Builder cannot be used after calling this method.\n        \"\"\"\n        self._eval_snippets()\n        if self._slots is True:\n            cls = self._create_slots_class()\n            self._cls.__attrs_base_of_slotted__ = weakref.ref(cls)\n        else:\n            cls = abc.update_abstractmethods(self._patch_original_class())\n\n        # The method gets only called if it's not inherited from a base class.\n        # _has_own_attribute does NOT work properly for classmethods.\n        if (\n            getattr(cls, \"__attrs_init_subclass__\", None)\n            and \"__attrs_init_subclass__\" not in cls.__dict__\n        ):\n            cls.__attrs_init_subclass__()\n\n        return cls\n\n    def _patch_original_class(self):\n        \"\"\"\n        Apply accumulated methods and return the class.\n        \"\"\"\n        cls = self._cls\n        base_names = self._base_names\n\n        # Clean class of attribute definitions (`attr.ib()`s).\n        if self._delete_attribs:\n            for name in self._attr_names:\n                if (\n                    name not in base_names\n                    and getattr(cls, name, _SENTINEL) is not _SENTINEL\n                ):\n                    # An AttributeError can happen if a base class defines a\n                    # class variable and we want to set an attribute with the\n                    # same name by using only a type annotation.\n                    with contextlib.suppress(AttributeError):\n                        delattr(cls, name)\n\n        # Attach our dunder methods.\n        loopIteratorC = __import__(\"builtins\").iter(self._cls_dict.items())\n        while True:\n            try:\n                name, value = __import__(\"builtins\").next(loopIteratorC)\n            except __import__(\"builtins\").StopIteration:\n                break\n            setattr(cls, name, value)\n\n        # If we've inherited an attrs __setattr__ and don't write our own,\n        # reset it to object's.\n        if not self._wrote_own_setattr and getattr(\n            cls, \"__attrs_own_setattr__\", False\n        ):\n            cls.__attrs_own_setattr__ = False\n\n            if not self._has_custom_setattr:\n                cls.__setattr__ = _OBJ_SETATTR\n\n        return cls\n\n    def _create_slots_class(self):\n        \"\"\"\n        Build and return a new class with a `__slots__` attribute.\n        \"\"\"\n        cd = {\n            k: v\n            for k, v in self._cls_dict.items()\n            if k not in (*tuple(self._attr_names), \"__dict__\", \"__weakref__\")\n        }\n\n        # 3.14.0rc2+\n        if hasattr(sys, \"_clear_type_descriptors\"):\n            sys._clear_type_descriptors(self._cls)\n\n        # If our class doesn't have its own implementation of __setattr__\n        # (either from the user or by us), check the bases, if one of them has\n        # an attrs-made __setattr__, that needs to be reset. We don't walk the\n        # MRO because we only care about our immediate base classes.\n        # XXX: This can be confused by subclassing a slotted attrs class with\n        # XXX: a non-attrs class and subclass the resulting class with an attrs\n        # XXX: class.  See `test_slotted_confused` for details.  For now that's\n        # XXX: OK with us.\n        if not self._wrote_own_setattr:\n            cd[\"__attrs_own_setattr__\"] = False\n\n            if not self._has_custom_setattr:\n                loopIteratorD = __import__(\"builtins\").iter(self._cls.__bases__)\n                while True:\n                    try:\n                        base_cls = __import__(\"builtins\").next(loopIteratorD)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    if base_cls.__dict__.get(\"__attrs_own_setattr__\", False):\n                        cd[\"__setattr__\"] = _OBJ_SETATTR\n                        break\n\n        # Traverse the MRO to collect existing slots\n        # and check for an existing __weakref__.\n        existing_slots = {}\n        weakref_inherited = False\n        loopIteratorE = __import__(\"builtins\").iter(self._cls.__mro__[1:-1])\n        while True:\n            try:\n                base_cls = __import__(\"builtins\").next(loopIteratorE)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if base_cls.__dict__.get(\"__weakref__\", None) is not None:\n                weakref_inherited = True\n            existing_slots.update(\n                {\n                    name: getattr(base_cls, name)\n                    for name in getattr(base_cls, \"__slots__\", [])\n                }\n            )\n\n        base_names = set(self._base_names)\n\n        names = self._attr_names\n        if (\n            self._weakref_slot\n            and \"__weakref__\" not in getattr(self._cls, \"__slots__\", ())\n            and \"__weakref__\" not in names\n            and not weakref_inherited\n        ):\n            names += (\"__weakref__\",)\n\n        cached_properties = {\n            name: cached_prop.func\n            for name, cached_prop in cd.items()\n            if isinstance(cached_prop, cached_property)\n        }\n\n        # Collect methods with a `__class__` reference that are shadowed in the new class.\n        # To know to update them.\n        additional_closure_functions_to_update = []\n        if cached_properties:\n            import inspect\n\n            class_annotations = _get_annotations(self._cls)\n            for name, func in cached_properties.items():\n                # Add cached properties to names for slotting.\n                names += (name,)\n                # Clear out function from class to avoid clashing.\n                del cd[name]\n                additional_closure_functions_to_update.append(func)\n                annotation = inspect.signature(func).return_annotation\n                if annotation is not inspect.Parameter.empty:\n                    class_annotations[name] = annotation\n\n            original_getattr = cd.get(\"__getattr__\")\n            if original_getattr is not None:\n                additional_closure_functions_to_update.append(original_getattr)\n\n            cd[\"__getattr__\"] = _make_cached_property_getattr(\n                cached_properties, original_getattr, self._cls\n            )\n\n        # We only add the names of attributes that aren't inherited.\n        # Setting __slots__ to inherited attributes wastes memory.\n        slot_names = [name for name in names if name not in base_names]\n\n        # There are slots for attributes from current class\n        # that are defined in parent classes.\n        # As their descriptors may be overridden by a child class,\n        # we collect them here and update the class dict\n        reused_slots = {\n            slot: slot_descriptor\n            for slot, slot_descriptor in existing_slots.items()\n            if slot in slot_names\n        }\n        slot_names = [name for name in slot_names if name not in reused_slots]\n        cd.update(reused_slots)\n        if self._cache_hash:\n            slot_names.append(_HASH_CACHE_FIELD)\n\n        cd[\"__slots__\"] = tuple(slot_names)\n\n        cd[\"__qualname__\"] = self._cls.__qualname__\n\n        # Create new class based on old class and our methods.\n        cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd)\n\n        # The following is a fix for\n        # <https://github.com/python-attrs/attrs/issues/102>.\n        # If a method mentions `__class__` or uses the no-arg super(), the\n        # compiler will bake a reference to the class in the method itself\n        # as `method.__closure__`.  Since we replace the class with a\n        # clone, we rewrite these references so it keeps working.\n        for item in itertools.chain(\n            cls.__dict__.values(), additional_closure_functions_to_update\n        ):\n            if isinstance(item, (classmethod, staticmethod)):\n                # Class- and staticmethods hide their functions inside.\n                # These might need to be rewritten as well.\n                closure_cells = getattr(item.__func__, \"__closure__\", None)\n            elif isinstance(item, property):\n                # Workaround for property `super()` shortcut (PY3-only).\n                # There is no universal way for other descriptors.\n                closure_cells = getattr(item.fget, \"__closure__\", None)\n            else:\n                closure_cells = getattr(item, \"__closure__\", None)\n\n            if not closure_cells:  # Catch None or the empty list.\n                continue\n            for cell in closure_cells:\n                try:\n                    match = cell.cell_contents is self._cls\n                except ValueError:  # noqa: PERF203\n                    # ValueError: Cell is empty\n                    pass\n                else:\n                    if match:\n                        cell.cell_contents = cls\n        return cls\n\n    def add_repr(self, ns):\n        script, globs = _make_repr_script(self._attrs, ns)\n\n        def _attach_repr(cls_dict, globs):\n            cls_dict[\"__repr__\"] = self._add_method_dunders(globs[\"__repr__\"])\n\n        self._script_snippets.append((script, globs, _attach_repr))\n        self._repr_added = True\n        return self\n\n    def add_str(self):\n        if not self._repr_added:\n            msg = \"__str__ can only be generated if a __repr__ exists.\"\n            raise ValueError(msg)\n\n        def __str__(self):\n            return self.__repr__()\n\n        self._cls_dict[\"__str__\"] = self._add_method_dunders(__str__)\n        return self\n\n    def _make_getstate_setstate(self):\n        \"\"\"\n        Create custom __setstate__ and __getstate__ methods.\n        \"\"\"\n        # __weakref__ is not writable.\n        state_attr_names = tuple(\n            an for an in self._attr_names if an != \"__weakref__\"\n        )\n\n        def slots_getstate(self):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            return {name: getattr(self, name) for name in state_attr_names}\n\n        hash_caching_enabled = self._cache_hash\n\n        def slots_setstate(self, state):\n            \"\"\"\n            Automatically created by attrs.\n            \"\"\"\n            __bound_setattr = _OBJ_SETATTR.__get__(self)\n            if isinstance(state, tuple):\n                # Backward compatibility with attrs instances pickled with\n                # attrs versions before v22.2.0 which stored tuples.\n                loopIteratorF = __import__(\"builtins\").iter(zip(state_attr_names, state, strict=False))\n                while True:\n                    try:\n                        name, value = __import__(\"builtins\").next(loopIteratorF)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    __bound_setattr(name, value)\n            else:\n                loopIteratorG = __import__(\"builtins\").iter(state_attr_names)\n                while True:\n                    try:\n                        name = __import__(\"builtins\").next(loopIteratorG)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    if name in state:\n                        __bound_setattr(name, state[name])\n\n            # The hash code cache is not included when the object is\n            # serialized, but it still needs to be initialized to None to\n            # indicate that the first call to __hash__ should be a cache\n            # miss.\n            if hash_caching_enabled:\n                __bound_setattr(_HASH_CACHE_FIELD, None)\n\n        return slots_getstate, slots_setstate\n\n    def make_unhashable(self):\n        self._cls_dict[\"__hash__\"] = None\n        return self\n\n    def add_hash(self):\n        script, globs = _make_hash_script(\n            self._cls,\n            self._attrs,\n            frozen=self._frozen,\n            cache_hash=self._cache_hash,\n        )\n\n        def attach_hash(cls_dict: dict, locs: dict) -> None:\n            cls_dict[\"__hash__\"] = self._add_method_dunders(locs[\"__hash__\"])\n\n        self._script_snippets.append((script, globs, attach_hash))\n\n        return self\n\n    def add_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=False,\n        )\n\n        def _attach_init(cls_dict, globs):\n            init = globs[\"__init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_init))\n\n        return self\n\n    def add_replace(self):\n        # We create a local `evolve` proxy because it gets modified in place.\n        def __replace__(*args, **changes):\n            return evolve(*args, **changes)\n\n        self._cls_dict[\"__replace__\"] = self._add_method_dunders(__replace__)\n        return self\n\n    def add_match_args(self):\n        self._cls_dict[\"__match_args__\"] = tuple(\n            field.name\n            for field in self._attrs\n            if field.init and not field.kw_only\n        )\n\n    def add_attrs_init(self):\n        script, globs, annotations = _make_init_script(\n            self._cls,\n            self._attrs,\n            self._has_pre_init,\n            self._pre_init_has_args,\n            self._has_post_init,\n            self._frozen,\n            self._slots,\n            self._cache_hash,\n            self._base_attr_map,\n            self._is_exc,\n            self._on_setattr,\n            attrs_init=True,\n        )\n\n        def _attach_attrs_init(cls_dict, globs):\n            init = globs[\"__attrs_init__\"]\n            init.__annotations__ = annotations\n            cls_dict[\"__attrs_init__\"] = self._add_method_dunders(init)\n\n        self._script_snippets.append((script, globs, _attach_attrs_init))\n\n        return self\n\n    def add_eq(self):\n        cd = self._cls_dict\n\n        script, globs = _make_eq_script(self._attrs)\n\n        def _attach_eq(cls_dict, globs):\n            cls_dict[\"__eq__\"] = self._add_method_dunders(globs[\"__eq__\"])\n\n        self._script_snippets.append((script, globs, _attach_eq))\n\n        cd[\"__ne__\"] = __ne__\n\n        return self\n\n    def add_order(self):\n        cd = self._cls_dict\n\n        cd[\"__lt__\"], cd[\"__le__\"], cd[\"__gt__\"], cd[\"__ge__\"] = (\n            self._add_method_dunders(meth)\n            for meth in _make_order(self._cls, self._attrs)\n        )\n\n        return self\n\n    def add_setattr(self):\n        sa_attrs = {}\n        loopIteratorH = __import__(\"builtins\").iter(self._attrs)\n        while True:\n            try:\n                a = __import__(\"builtins\").next(loopIteratorH)\n            except __import__(\"builtins\").StopIteration:\n                break\n            on_setattr = a.on_setattr or self._on_setattr\n            if on_setattr and on_setattr is not setters.NO_OP:\n                sa_attrs[a.name] = (\n                    a,\n                    on_setattr,\n                    _lazy_is_generator(on_setattr),\n                )\n\n        if not sa_attrs:\n            return self\n\n        if self._has_custom_setattr:\n            # We need to write a __setattr__ but there already is one!\n            msg = \"Can't combine custom __setattr__ with on_setattr hooks.\"\n            raise ValueError(msg)\n\n        # docstring comes from _add_method_dunders\n        def __setattr__(self, name, val):\n            try:\n                a, hook, is_gen = sa_attrs[name]\n            except KeyError:\n                _OBJ_SETATTR(self, name, val)\n\n                return\n\n            if is_gen():\n                gen = hook(self, a, val)\n                nval = next(gen)\n                _OBJ_SETATTR(self, name, nval)\n                try:\n                    next(gen)\n                except StopIteration:\n                    return\n\n                gen.close()\n                msg = \"Generator on_setattr hook yielded more than once.\"\n                raise RuntimeError(msg)\n\n            nval = hook(self, a, val)\n            _OBJ_SETATTR(self, name, nval)\n\n            return\n\n        self._cls_dict[\"__attrs_own_setattr__\"] = True\n        self._cls_dict[\"__setattr__\"] = self._add_method_dunders(__setattr__)\n        self._wrote_own_setattr = True\n\n        return self\n\n    def _add_method_dunders_unsafe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method*.\n        \"\"\"\n        method.__module__ = self._cls.__module__\n\n        method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        method.__doc__ = (\n            f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n        )\n\n        return method\n\n    def _add_method_dunders_safe(self, method: Callable) -> Callable:\n        \"\"\"\n        Add __module__ and __qualname__ to a *method* if possible.\n        \"\"\"\n        with contextlib.suppress(AttributeError):\n            method.__module__ = self._cls.__module__\n\n        with contextlib.suppress(AttributeError):\n            method.__qualname__ = f\"{self._cls.__qualname__}.{method.__name__}\"\n\n        with contextlib.suppress(AttributeError):\n            method.__doc__ = f\"Method generated by attrs for class {self._cls.__qualname__}.\"\n\n        return method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-67adbacc78d2f47e", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "8f50b81ea71e03b0c1e49f45b5c8364c65e4e8390ba6d642937979e39439a6d9", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 681, "local_path": "control-flow/lower-for-to-while/I13__attrs___ClassBuilder__b07243fa.py", "order": 13, "original_content_sha256": "9ab42682c864adafaa9534e4b45815ec40c6da6c7bbdce5a7f9067fd5a2b0fe6", "parent_variant_id": "pyint-19b411536d5f-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L647-L1253", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 9, "for_loops_skipped_for_comment": 4, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 9, "synchronous_for_loops_eligible": 9, "synchronous_for_loops_found": 13}, "unit_kind": "class", "unit_name": "_ClassBuilder", "variant_id": "pyint-957db07243fa-I13", "group_id": "py-67adbacc78d2f47e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1176, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1fc33230f8eb-SRC", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport pathlib\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom jinja2 import BaseLoader\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\nfrom .. import typing as ft\nfrom ..helpers import get_root_path\nfrom ..templating import _default_template_ctx_processor\n\nclass Scaffold:\n    \"\"\"Common behavior shared between :class:`~flask.Flask` and\n    :class:`~flask.blueprints.Blueprint`.\n\n    :param import_name: The import name of the module where this object\n        is defined. Usually :attr:`__name__` should be used.\n    :param static_folder: Path to a folder of static files to serve.\n        If this is set, a static route will be added.\n    :param static_url_path: URL prefix for the static route.\n    :param template_folder: Path to a folder containing template files.\n        for rendering. If this is set, a Jinja loader will be added.\n    :param root_path: The path that static, template, and resource files\n        are relative to. Typically not set, it is discovered based on\n        the ``import_name``.\n\n    .. versionadded:: 2.0\n    \"\"\"\n\n    cli: Group\n    name: str\n    _static_folder: str | None = None\n    _static_url_path: str | None = None\n\n    def __init__(\n        self,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        root_path: str | None = None,\n    ):\n        #: The name of the package or module that this object belongs\n        #: to. Do not change this once it is set by the constructor.\n        self.import_name = import_name\n\n        self.static_folder = static_folder\n        self.static_url_path = static_url_path\n\n        #: The path to the templates folder, relative to\n        #: :attr:`root_path`, to add to the template loader. ``None`` if\n        #: templates should not be added.\n        self.template_folder = template_folder\n\n        if root_path is None:\n            root_path = get_root_path(self.import_name)\n\n        #: Absolute path to the package on the filesystem. Used to look\n        #: up resources contained in the package.\n        self.root_path = root_path\n\n        #: A dictionary mapping endpoint names to view functions.\n        #:\n        #: To register a view function, use the :meth:`route` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.view_functions: dict[str, ft.RouteCallable] = {}\n\n        #: A data structure of registered error handlers, in the format\n        #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n        #: the name of a blueprint the handlers are active for, or\n        #: ``None`` for all requests. The ``code`` key is the HTTP\n        #: status code for ``HTTPException``, or ``None`` for\n        #: other exceptions. The innermost dictionary maps exception\n        #: classes to handler functions.\n        #:\n        #: To register an error handler, use the :meth:`errorhandler`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.error_handler_spec: dict[\n            ft.AppOrBlueprintKey,\n            dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n        ] = defaultdict(lambda: defaultdict(dict))\n\n        #: A data structure of functions to call at the beginning of\n        #: each request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`before_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.before_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`after_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.after_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request even if an exception is raised, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`teardown_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.teardown_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.TeardownCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to pass extra context\n        #: values when rendering templates, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`context_processor`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.template_context_processors: dict[\n            ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]\n        ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments passed to the view function, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the\n        #: :meth:`url_value_preprocessor` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_value_preprocessors: dict[\n            ft.AppOrBlueprintKey,\n            list[ft.URLValuePreprocessorCallable],\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments when generating URLs, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`url_defaults`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_default_functions: dict[\n            ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]\n        ] = defaultdict(list)\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {self.name!r}>\"\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        raise NotImplementedError\n\n    @property\n    def static_folder(self) -> str | None:\n        \"\"\"The absolute path to the configured static folder. ``None``\n        if no static folder is set.\n        \"\"\"\n        if self._static_folder is not None:\n            return os.path.join(self.root_path, self._static_folder)\n        else:\n            return None\n\n    @static_folder.setter\n    def static_folder(self, value: str | os.PathLike[str] | None) -> None:\n        if value is not None:\n            value = os.fspath(value).rstrip(r\"\\/\")\n\n        self._static_folder = value\n\n    @property\n    def has_static_folder(self) -> bool:\n        \"\"\"``True`` if :attr:`static_folder` is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        return self.static_folder is not None\n\n    @property\n    def static_url_path(self) -> str | None:\n        \"\"\"The URL prefix that the static route will be accessible from.\n\n        If it was not configured during init, it is derived from\n        :attr:`static_folder`.\n        \"\"\"\n        if self._static_url_path is not None:\n            return self._static_url_path\n\n        if self.static_folder is not None:\n            basename = os.path.basename(self.static_folder)\n            return f\"/{basename}\".rstrip(\"/\")\n\n        return None\n\n    @static_url_path.setter\n    def static_url_path(self, value: str | None) -> None:\n        if value is not None:\n            value = value.rstrip(\"/\")\n\n        self._static_url_path = value\n\n    @cached_property\n    def jinja_loader(self) -> BaseLoader | None:\n        \"\"\"The Jinja loader for this object's templates. By default this\n        is a class :class:`jinja2.loaders.FileSystemLoader` to\n        :attr:`template_folder` if it is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        if self.template_folder is not None:\n            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n        else:\n            return None\n\n    def _method_route(\n        self,\n        method: str,\n        rule: str,\n        options: dict[str, t.Any],\n    ) -> t.Callable[[T_route], T_route]:\n        if \"methods\" in options:\n            raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n        return self.route(rule, methods=[method], **options)\n\n    @setupmethod\n    def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"GET\", rule, options)\n\n    @setupmethod\n    def query(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"QUERY\"]``.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self._method_route(\"QUERY\", rule, options)\n\n    @setupmethod\n    def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"POST\", rule, options)\n\n    @setupmethod\n    def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PUT\", rule, options)\n\n    @setupmethod\n    def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"DELETE\", rule, options)\n\n    @setupmethod\n    def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PATCH\", rule, options)\n\n    @setupmethod\n    def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Decorate a view function to register it with the given URL\n        rule and options. Calls :meth:`add_url_rule`, which has more\n        details about the implementation.\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                return \"Hello, World!\"\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n        ``OPTIONS`` are added automatically.\n\n        :param rule: The URL rule string.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n\n        def decorator(f: T_route) -> T_route:\n            endpoint = options.pop(\"endpoint\", None)\n            self.add_url_rule(rule, endpoint, f, **options)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a rule for routing incoming requests and building\n        URLs. The :meth:`route` decorator is a shortcut to call this\n        with the ``view_func`` argument. These are equivalent:\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                ...\n\n        .. code-block:: python\n\n            def index():\n                ...\n\n            app.add_url_rule(\"/\", view_func=index)\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed. An error\n        will be raised if a function has already been registered for the\n        endpoint.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n        always added automatically, and ``OPTIONS`` is added\n        automatically by default.\n\n        ``view_func`` does not necessarily need to be passed, but if the\n        rule should participate in routing an endpoint name must be\n        associated with a view function at some point with the\n        :meth:`endpoint` decorator.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/\", endpoint=\"index\")\n\n            @app.endpoint(\"index\")\n            def index():\n                ...\n\n        If ``view_func`` has a ``required_methods`` attribute, those\n        methods are added to the passed and automatic methods. If it\n        has a ``provide_automatic_methods`` attribute, it is used as the\n        default if the parameter is not passed.\n\n        :param rule: The URL rule string.\n        :param endpoint: The endpoint name to associate with the rule\n            and view function. Used when routing and building URLs.\n            Defaults to ``view_func.__name__``.\n        :param view_func: The view function to associate with the\n            endpoint name.\n        :param provide_automatic_options: Add the ``OPTIONS`` method and\n            respond to ``OPTIONS`` requests automatically.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        raise NotImplementedError\n\n    @setupmethod\n    def endpoint(self, endpoint: str) -> t.Callable[[F], F]:\n        \"\"\"Decorate a view function to register it for the given\n        endpoint. Used if a rule is added without a ``view_func`` with\n        :meth:`add_url_rule`.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n            @app.endpoint(\"example\")\n            def example():\n                ...\n\n        :param endpoint: The endpoint name to associate with the view\n            function.\n        \"\"\"\n\n        def decorator(f: F) -> F:\n            self.view_functions[endpoint] = f\n            return f\n\n        return decorator\n\n    @setupmethod\n    def before_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Register a function to run before each request.\n\n        For example, this can be used to open a database connection, or\n        to load the logged in user from the session.\n\n        .. code-block:: python\n\n            @app.before_request\n            def load_user():\n                if \"user_id\" in session:\n                    g.user = db.session.get(session[\"user_id\"])\n\n        The function will be called without any arguments. If it returns\n        a non-``None`` value, the value is handled as if it was the\n        return value from the view, and further request handling is\n        stopped.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes before every request. When used on a blueprint, this executes before\n        every request that the blueprint handles. To register with a blueprint and\n        execute before every request, use :meth:`.Blueprint.before_app_request`.\n        \"\"\"\n        self.before_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def after_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Register a function to run after each request to this object.\n\n        The function is called with the response object, and must return\n        a response object. This allows the functions to modify or\n        replace the response before it is sent.\n\n        If a function raises an exception, any remaining\n        ``after_request`` functions will not be called. Therefore, this\n        should not be used for actions that must execute, such as to\n        close resources. Use :meth:`teardown_request` for that.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.after_app_request`.\n        \"\"\"\n        self.after_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def teardown_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Register a function to be called when the request context is\n        popped. Typically, this happens at the end of each request, but\n        contexts may be pushed manually during testing.\n\n        .. code-block:: python\n\n            with app.test_request_context():\n                ...\n\n        When the ``with`` block exits (or ``ctx.pop()`` is called), the\n        teardown functions are called just before the request context is\n        made inactive.\n\n        When a teardown function was called because of an unhandled\n        exception it will be passed an error object. If an\n        :meth:`errorhandler` is registered, it will handle the exception\n        and the teardown will not receive it.\n\n        Teardown functions must avoid raising exceptions. If they\n        execute code that might fail they must surround that code with a\n        ``try``/``except`` block and log any errors.\n\n        The return values of teardown functions are ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n        \"\"\"\n        self.teardown_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def context_processor(\n        self,\n        f: T_template_context_processor,\n    ) -> T_template_context_processor:\n        \"\"\"Registers a template context processor function. These functions run before\n        rendering a template. The keys of the returned dict are added as variables\n        available in the template.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every rendered template. When used on a blueprint, this is called\n        for templates rendered from the blueprint's views. To register with a blueprint\n        and affect every template, use :meth:`.Blueprint.app_context_processor`.\n        \"\"\"\n        self.template_context_processors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_value_preprocessor(\n        self,\n        f: T_url_value_preprocessor,\n    ) -> T_url_value_preprocessor:\n        \"\"\"Register a URL value preprocessor function for all view\n        functions in the application. These functions will be called before the\n        :meth:`before_request` functions.\n\n        The function can modify the values captured from the matched url before\n        they are passed to the view. For example, this can be used to pop a\n        common language code value and place it in ``g`` rather than pass it to\n        every view.\n\n        The function is passed the endpoint name and values dict. The return\n        value is ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n        \"\"\"\n        self.url_value_preprocessors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Callback function for URL defaults for all view functions of the\n        application.  It's called with the endpoint and values and should\n        update the values passed in place.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_defaults`.\n        \"\"\"\n        self.url_default_functions[None].append(f)\n        return f\n\n    @setupmethod\n    def errorhandler(\n        self, code_or_exception: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Register a function to handle errors by code or exception class.\n\n        A decorator that is used to register a function given an\n        error code.  Example::\n\n            @app.errorhandler(404)\n            def page_not_found(error):\n                return 'This page does not exist', 404\n\n        You can also register handlers for arbitrary exceptions::\n\n            @app.errorhandler(DatabaseError)\n            def special_exception_handler(error):\n                return 'Database connection failed', 500\n\n        This is available on both app and blueprint objects. When used on an app, this\n        can handle errors from every request. When used on a blueprint, this can handle\n        errors from requests that the blueprint handles. To register with a blueprint\n        and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n        .. versionadded:: 0.7\n            Use :meth:`register_error_handler` instead of modifying\n            :attr:`error_handler_spec` directly, for application wide error\n            handlers.\n\n        .. versionadded:: 0.7\n           One can now additionally also register custom exception types\n           that do not necessarily have to be a subclass of the\n           :class:`~werkzeug.exceptions.HTTPException` class.\n\n        :param code_or_exception: the code as integer for the handler, or\n                                  an arbitrary exception\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            self.register_error_handler(code_or_exception, f)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def register_error_handler(\n        self,\n        code_or_exception: type[Exception] | int,\n        f: ft.ErrorHandlerCallable,\n    ) -> None:\n        \"\"\"Alternative error attach function to the :meth:`errorhandler`\n        decorator that is more straightforward to use for non decorator\n        usage.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        exc_class, code = self._get_exc_class_and_code(code_or_exception)\n        self.error_handler_spec[None][code][exc_class] = f\n\n    @staticmethod\n    def _get_exc_class_and_code(\n        exc_class_or_code: type[Exception] | int,\n    ) -> tuple[type[Exception], int | None]:\n        \"\"\"Get the exception class being handled. For HTTP status codes\n        or ``HTTPException`` subclasses, return both the exception and\n        status code.\n\n        :param exc_class_or_code: Any exception class, or an HTTP status\n            code as an integer.\n        \"\"\"\n        exc_class: type[Exception]\n\n        if isinstance(exc_class_or_code, int):\n            try:\n                exc_class = default_exceptions[exc_class_or_code]\n            except KeyError:\n                raise ValueError(\n                    f\"'{exc_class_or_code}' is not a recognized HTTP\"\n                    \" error code. Use a subclass of HTTPException with\"\n                    \" that code instead.\"\n                ) from None\n        else:\n            exc_class = exc_class_or_code\n\n        if isinstance(exc_class, Exception):\n            raise TypeError(\n                f\"{exc_class!r} is an instance, not a class. Handlers\"\n                \" can only be registered for Exception classes or HTTP\"\n                \" error codes.\"\n            )\n\n        if not issubclass(exc_class, Exception):\n            raise ValueError(\n                f\"'{exc_class.__name__}' is not a subclass of Exception.\"\n                \" Handlers can only be registered for Exception classes\"\n                \" or HTTP error codes.\"\n            )\n\n        if issubclass(exc_class, HTTPException):\n            return exc_class, exc_class.code\n        else:\n            return exc_class, None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-701cd22ff415df0d", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 672, "local_path": "source-original/SRC__flask__Scaffold__3230f8eb.py", "order": 0, "original_content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/scaffold.py#L52-L706", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Scaffold", "variant_id": "pyint-1fc33230f8eb-SRC", "group_id": "py-701cd22ff415df0d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 603, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a61a3782232b-I01", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport pathlib\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom jinja2 import BaseLoader\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\nfrom .. import typing as ft\nfrom ..helpers import get_root_path\nfrom ..templating import _default_template_ctx_processor\n\nclass Scaffold:\n    \n\n    cli: Group\n    name: str\n    _static_folder: str | None = None\n    _static_url_path: str | None = None\n\n    def __init__(\n        self,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        root_path: str | None = None,\n    ):\n         \n         \n        self.import_name = import_name\n\n        self.static_folder = static_folder\n        self.static_url_path = static_url_path\n\n         \n         \n         \n        self.template_folder = template_folder\n\n        if root_path is None:\n            root_path = get_root_path(self.import_name)\n\n         \n         \n        self.root_path = root_path\n\n         \n         \n         \n         \n         \n         \n        self.view_functions: dict[str, ft.RouteCallable] = {}\n\n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n        self.error_handler_spec: dict[\n            ft.AppOrBlueprintKey,\n            dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n        ] = defaultdict(lambda: defaultdict(dict))\n\n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n        self.before_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]\n        ] = defaultdict(list)\n\n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n        self.after_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]\n        ] = defaultdict(list)\n\n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n        self.teardown_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.TeardownCallable]\n        ] = defaultdict(list)\n\n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n        self.template_context_processors: dict[\n            ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]\n        ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n        self.url_value_preprocessors: dict[\n            ft.AppOrBlueprintKey,\n            list[ft.URLValuePreprocessorCallable],\n        ] = defaultdict(list)\n\n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n        self.url_default_functions: dict[\n            ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]\n        ] = defaultdict(list)\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {self.name!r}>\"\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        raise NotImplementedError\n\n    @property\n    def static_folder(self) -> str | None:\n        \n        if self._static_folder is not None:\n            return os.path.join(self.root_path, self._static_folder)\n        else:\n            return None\n\n    @static_folder.setter\n    def static_folder(self, value: str | os.PathLike[str] | None) -> None:\n        if value is not None:\n            value = os.fspath(value).rstrip(r\"\\/\")\n\n        self._static_folder = value\n\n    @property\n    def has_static_folder(self) -> bool:\n        \n        return self.static_folder is not None\n\n    @property\n    def static_url_path(self) -> str | None:\n        \n        if self._static_url_path is not None:\n            return self._static_url_path\n\n        if self.static_folder is not None:\n            basename = os.path.basename(self.static_folder)\n            return f\"/{basename}\".rstrip(\"/\")\n\n        return None\n\n    @static_url_path.setter\n    def static_url_path(self, value: str | None) -> None:\n        if value is not None:\n            value = value.rstrip(\"/\")\n\n        self._static_url_path = value\n\n    @cached_property\n    def jinja_loader(self) -> BaseLoader | None:\n        \n        if self.template_folder is not None:\n            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n        else:\n            return None\n\n    def _method_route(\n        self,\n        method: str,\n        rule: str,\n        options: dict[str, t.Any],\n    ) -> t.Callable[[T_route], T_route]:\n        if \"methods\" in options:\n            raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n        return self.route(rule, methods=[method], **options)\n\n    @setupmethod\n    def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \n        return self._method_route(\"GET\", rule, options)\n\n    @setupmethod\n    def query(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \n        return self._method_route(\"QUERY\", rule, options)\n\n    @setupmethod\n    def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \n        return self._method_route(\"POST\", rule, options)\n\n    @setupmethod\n    def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \n        return self._method_route(\"PUT\", rule, options)\n\n    @setupmethod\n    def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \n        return self._method_route(\"DELETE\", rule, options)\n\n    @setupmethod\n    def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \n        return self._method_route(\"PATCH\", rule, options)\n\n    @setupmethod\n    def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \n\n        def decorator(f: T_route) -> T_route:\n            endpoint = options.pop(\"endpoint\", None)\n            self.add_url_rule(rule, endpoint, f, **options)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \n        raise NotImplementedError\n\n    @setupmethod\n    def endpoint(self, endpoint: str) -> t.Callable[[F], F]:\n        \n\n        def decorator(f: F) -> F:\n            self.view_functions[endpoint] = f\n            return f\n\n        return decorator\n\n    @setupmethod\n    def before_request(self, f: T_before_request) -> T_before_request:\n        \n        self.before_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def after_request(self, f: T_after_request) -> T_after_request:\n        \n        self.after_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def teardown_request(self, f: T_teardown) -> T_teardown:\n        \n        self.teardown_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def context_processor(\n        self,\n        f: T_template_context_processor,\n    ) -> T_template_context_processor:\n        \n        self.template_context_processors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_value_preprocessor(\n        self,\n        f: T_url_value_preprocessor,\n    ) -> T_url_value_preprocessor:\n        \n        self.url_value_preprocessors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \n        self.url_default_functions[None].append(f)\n        return f\n\n    @setupmethod\n    def errorhandler(\n        self, code_or_exception: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            self.register_error_handler(code_or_exception, f)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def register_error_handler(\n        self,\n        code_or_exception: type[Exception] | int,\n        f: ft.ErrorHandlerCallable,\n    ) -> None:\n        \n        exc_class, code = self._get_exc_class_and_code(code_or_exception)\n        self.error_handler_spec[None][code][exc_class] = f\n\n    @staticmethod\n    def _get_exc_class_and_code(\n        exc_class_or_code: type[Exception] | int,\n    ) -> tuple[type[Exception], int | None]:\n        \n        exc_class: type[Exception]\n\n        if isinstance(exc_class_or_code, int):\n            try:\n                exc_class = default_exceptions[exc_class_or_code]\n            except KeyError:\n                raise ValueError(\n                    f\"'{exc_class_or_code}' is not a recognized HTTP\"\n                    \" error code. Use a subclass of HTTPException with\"\n                    \" that code instead.\"\n                ) from None\n        else:\n            exc_class = exc_class_or_code\n\n        if isinstance(exc_class, Exception):\n            raise TypeError(\n                f\"{exc_class!r} is an instance, not a class. Handlers\"\n                \" can only be registered for Exception classes or HTTP\"\n                \" error codes.\"\n            )\n\n        if not issubclass(exc_class, Exception):\n            raise ValueError(\n                f\"'{exc_class.__name__}' is not a subclass of Exception.\"\n                \" Handlers can only be registered for Exception classes\"\n                \" or HTTP error codes.\"\n            )\n\n        if issubclass(exc_class, HTTPException):\n            return exc_class, exc_class.code\n        else:\n            return exc_class, None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-701cd22ff415df0d", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "ef30da072ef27de26d270201604536473c5d8f8886905a357c811a1d0b87fa64", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 395, "local_path": "comments/remove-comments/I01__flask__Scaffold__3782232b.py", "order": 1, "original_content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "parent_variant_id": "pyint-1fc33230f8eb-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/scaffold.py#L52-L706", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 15869, "comments_removed": 113, "docstrings_removed": 23, "line_comments_removed": 90}, "unit_kind": "class", "unit_name": "Scaffold", "variant_id": "pyint-a61a3782232b-I01", "group_id": "py-701cd22ff415df0d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 604, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7f715202f8cc-I02", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport pathlib\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom jinja2 import BaseLoader\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\nfrom .. import typing as ft\nfrom ..helpers import get_root_path\nfrom ..templating import _default_template_ctx_processor\n\nclass Scaffold:\n    \"\"\"Common behavior shared between :class:`~flask.Flask` and\n    :class:`~flask.blueprints.Blueprint`.\n\n    :param import_name: The import name of the module where this object\n        is defined. Usually :attr:`__name__` should be used.\n    :param static_folder: Path to a folder of static files to serve.\n        If this is set, a static route will be added.\n    :param static_url_path: URL prefix for the static route.\n    :param template_folder: Path to a folder containing template files.\n        for rendering. If this is set, a Jinja loader will be added.\n    :param root_path: The path that static, template, and resource files\n        are relative to. Typically not set, it is discovered based on\n        the ``import_name``.\n\n    .. versionadded:: 2.0\n    \"\"\"\n\n    cli: Group\n    name: str\n    _static_folder: str | None = None\n    _static_url_path: str | None = None\n\n    def __init__(\n        self,\n        import2: str,\n        static5: str | os.PathLike[str] | None = None,\n        static6: str | None = None,\n        template: str | os.PathLike[str] | None = None,\n        root: str | None = None,\n    ):\n        #: The name of the package or module that this object belongs\n        #: to. Do not change this once it is set by the constructor.\n        self.import_name = import2\n\n        self.static2 = static5\n        self.static4 = static6\n\n        #: The path to the templates folder, relative to\n        #: :attr:`root_path`, to add to the template loader. ``None`` if\n        #: templates should not be added.\n        self.template_folder = template\n\n        if root is None:\n            root = get_root_path(self.import_name)\n\n        #: Absolute path to the package on the filesystem. Used to look\n        #: up resources contained in the package.\n        self.root_path = root\n\n        #: A dictionary mapping endpoint names to view functions.\n        #:\n        #: To register a view function, use the :meth:`route` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.view_functions: dict[str, ft.RouteCallable] = {}\n\n        #: A data structure of registered error handlers, in the format\n        #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n        #: the name of a blueprint the handlers are active for, or\n        #: ``None`` for all requests. The ``code`` key is the HTTP\n        #: status code for ``HTTPException``, or ``None`` for\n        #: other exceptions. The innermost dictionary maps exception\n        #: classes to handler functions.\n        #:\n        #: To register an error handler, use the :meth:`errorhandler`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.error_handler_spec: dict[\n            ft.AppOrBlueprintKey,\n            dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n        ] = defaultdict(lambda: defaultdict(dict))\n\n        #: A data structure of functions to call at the beginning of\n        #: each request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`before_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.before_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`after_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.after_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request even if an exception is raised, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`teardown_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.teardown_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.TeardownCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to pass extra context\n        #: values when rendering templates, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`context_processor`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.template_context_processors: dict[\n            ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]\n        ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments passed to the view function, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the\n        #: :meth:`url_value_preprocessor` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_value_preprocessors: dict[\n            ft.AppOrBlueprintKey,\n            list[ft.URLValuePreprocessorCallable],\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments when generating URLs, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`url_defaults`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_default_functions: dict[\n            ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]\n        ] = defaultdict(list)\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {self.name!r}>\"\n\n    def check(self, f2: str) -> None:\n        raise NotImplementedError\n\n    @property\n    def static2(self) -> str | None:\n        \"\"\"The absolute path to the configured static folder. ``None``\n        if no static folder is set.\n        \"\"\"\n        if self._static_folder is not None:\n            return os.path.join(self.root_path, self._static_folder)\n        else:\n            return None\n\n    @static_folder.setter\n    def static2(self, val: str | os.PathLike[str] | None) -> None:\n        if val is not None:\n            val = os.fspath(val).rstrip(r\"\\/\")\n\n        self._static_folder = val\n\n    @property\n    def has(self) -> bool:\n        \"\"\"``True`` if :attr:`static_folder` is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        return self.static2 is not None\n\n    @property\n    def static4(self) -> str | None:\n        \"\"\"The URL prefix that the static route will be accessible from.\n\n        If it was not configured during init, it is derived from\n        :attr:`static_folder`.\n        \"\"\"\n        if self._static_url_path is not None:\n            return self._static_url_path\n\n        if self.static2 is not None:\n            bas = os.path.basename(self.static2)\n            return f\"/{bas}\".rstrip(\"/\")\n\n        return None\n\n    @static_url_path.setter\n    def static4(self, val2: str | None) -> None:\n        if val2 is not None:\n            val2 = val2.rstrip(\"/\")\n\n        self._static_url_path = val2\n\n    @cached_property\n    def jinja(self) -> BaseLoader | None:\n        \"\"\"The Jinja loader for this object's templates. By default this\n        is a class :class:`jinja2.loaders.FileSystemLoader` to\n        :attr:`template_folder` if it is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        if self.template_folder is not None:\n            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n        else:\n            return None\n\n    def method2(\n        self,\n        met: str,\n        rul: str,\n        opt: dict[str, t.Any],\n    ) -> t.Callable[[T_route], T_route]:\n        if \"methods\" in opt:\n            raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n        return self.rou(rul, methods=[met], **opt)\n\n    @setupmethod\n    def get(self, rul2: str, **opt2: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.method2(\"GET\", rul2, opt2)\n\n    @setupmethod\n    def que(self, rul3: str, **opt3: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"QUERY\"]``.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self.method2(\"QUERY\", rul3, opt3)\n\n    @setupmethod\n    def pos(self, rul4: str, **opt4: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.method2(\"POST\", rul4, opt4)\n\n    @setupmethod\n    def put(self, rul5: str, **opt5: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.method2(\"PUT\", rul5, opt5)\n\n    @setupmethod\n    def del2(self, rul6: str, **opt6: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.method2(\"DELETE\", rul6, opt6)\n\n    @setupmethod\n    def pat(self, rul7: str, **opt7: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.method2(\"PATCH\", rul7, opt7)\n\n    @setupmethod\n    def rou(self, rul8: str, **opt8: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Decorate a view function to register it with the given URL\n        rule and options. Calls :meth:`add_url_rule`, which has more\n        details about the implementation.\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                return \"Hello, World!\"\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n        ``OPTIONS`` are added automatically.\n\n        :param rule: The URL rule string.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n\n        def decorator(f3: T_route) -> T_route:\n            end2 = options.pop(\"endpoint\", None)\n            self.add(rule, end2, f3, **options)\n            return f3\n\n        return decorator\n\n    @setupmethod\n    def add(\n        self,\n        rul9: str,\n        end3: str | None = None,\n        view: ft.RouteCallable | None = None,\n        provide: bool | None = None,\n        **opt9: t.Any,\n    ) -> None:\n        \"\"\"Register a rule for routing incoming requests and building\n        URLs. The :meth:`route` decorator is a shortcut to call this\n        with the ``view_func`` argument. These are equivalent:\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                ...\n\n        .. code-block:: python\n\n            def index():\n                ...\n\n            app.add_url_rule(\"/\", view_func=index)\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed. An error\n        will be raised if a function has already been registered for the\n        endpoint.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n        always added automatically, and ``OPTIONS`` is added\n        automatically by default.\n\n        ``view_func`` does not necessarily need to be passed, but if the\n        rule should participate in routing an endpoint name must be\n        associated with a view function at some point with the\n        :meth:`endpoint` decorator.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/\", endpoint=\"index\")\n\n            @app.endpoint(\"index\")\n            def index():\n                ...\n\n        If ``view_func`` has a ``required_methods`` attribute, those\n        methods are added to the passed and automatic methods. If it\n        has a ``provide_automatic_methods`` attribute, it is used as the\n        default if the parameter is not passed.\n\n        :param rule: The URL rule string.\n        :param endpoint: The endpoint name to associate with the rule\n            and view function. Used when routing and building URLs.\n            Defaults to ``view_func.__name__``.\n        :param view_func: The view function to associate with the\n            endpoint name.\n        :param provide_automatic_options: Add the ``OPTIONS`` method and\n            respond to ``OPTIONS`` requests automatically.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        raise NotImplementedError\n\n    @setupmethod\n    def end(self, end4: str) -> t.Callable[[F], F]:\n        \"\"\"Decorate a view function to register it for the given\n        endpoint. Used if a rule is added without a ``view_func`` with\n        :meth:`add_url_rule`.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n            @app.endpoint(\"example\")\n            def example():\n                ...\n\n        :param endpoint: The endpoint name to associate with the view\n            function.\n        \"\"\"\n\n        def decorator(f4: F) -> F:\n            self.view_functions[endpoint] = f4\n            return f4\n\n        return decorator\n\n    @setupmethod\n    def before(self, f5: T_before_request) -> T_before_request:\n        \"\"\"Register a function to run before each request.\n\n        For example, this can be used to open a database connection, or\n        to load the logged in user from the session.\n\n        .. code-block:: python\n\n            @app.before_request\n            def load_user():\n                if \"user_id\" in session:\n                    g.user = db.session.get(session[\"user_id\"])\n\n        The function will be called without any arguments. If it returns\n        a non-``None`` value, the value is handled as if it was the\n        return value from the view, and further request handling is\n        stopped.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes before every request. When used on a blueprint, this executes before\n        every request that the blueprint handles. To register with a blueprint and\n        execute before every request, use :meth:`.Blueprint.before_app_request`.\n        \"\"\"\n        self.before_request_funcs.setdefault(None, []).append(f5)\n        return f5\n\n    @setupmethod\n    def after(self, f6: T_after_request) -> T_after_request:\n        \"\"\"Register a function to run after each request to this object.\n\n        The function is called with the response object, and must return\n        a response object. This allows the functions to modify or\n        replace the response before it is sent.\n\n        If a function raises an exception, any remaining\n        ``after_request`` functions will not be called. Therefore, this\n        should not be used for actions that must execute, such as to\n        close resources. Use :meth:`teardown_request` for that.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.after_app_request`.\n        \"\"\"\n        self.after_request_funcs.setdefault(None, []).append(f6)\n        return f6\n\n    @setupmethod\n    def teardown(self, f7: T_teardown) -> T_teardown:\n        \"\"\"Register a function to be called when the request context is\n        popped. Typically, this happens at the end of each request, but\n        contexts may be pushed manually during testing.\n\n        .. code-block:: python\n\n            with app.test_request_context():\n                ...\n\n        When the ``with`` block exits (or ``ctx.pop()`` is called), the\n        teardown functions are called just before the request context is\n        made inactive.\n\n        When a teardown function was called because of an unhandled\n        exception it will be passed an error object. If an\n        :meth:`errorhandler` is registered, it will handle the exception\n        and the teardown will not receive it.\n\n        Teardown functions must avoid raising exceptions. If they\n        execute code that might fail they must surround that code with a\n        ``try``/``except`` block and log any errors.\n\n        The return values of teardown functions are ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n        \"\"\"\n        self.teardown_request_funcs.setdefault(None, []).append(f7)\n        return f7\n\n    @setupmethod\n    def context(\n        self,\n        f8: T_template_context_processor,\n    ) -> T_template_context_processor:\n        \"\"\"Registers a template context processor function. These functions run before\n        rendering a template. The keys of the returned dict are added as variables\n        available in the template.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every rendered template. When used on a blueprint, this is called\n        for templates rendered from the blueprint's views. To register with a blueprint\n        and affect every template, use :meth:`.Blueprint.app_context_processor`.\n        \"\"\"\n        self.template_context_processors[None].append(f8)\n        return f8\n\n    @setupmethod\n    def url(\n        self,\n        f9: T_url_value_preprocessor,\n    ) -> T_url_value_preprocessor:\n        \"\"\"Register a URL value preprocessor function for all view\n        functions in the application. These functions will be called before the\n        :meth:`before_request` functions.\n\n        The function can modify the values captured from the matched url before\n        they are passed to the view. For example, this can be used to pop a\n        common language code value and place it in ``g`` rather than pass it to\n        every view.\n\n        The function is passed the endpoint name and values dict. The return\n        value is ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n        \"\"\"\n        self.url_value_preprocessors[None].append(f9)\n        return f9\n\n    @setupmethod\n    def url2(self, f10: T_url_defaults) -> T_url_defaults:\n        \"\"\"Callback function for URL defaults for all view functions of the\n        application.  It's called with the endpoint and values and should\n        update the values passed in place.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_defaults`.\n        \"\"\"\n        self.url_default_functions[None].append(f10)\n        return f10\n\n    @setupmethod\n    def err(\n        self, code2: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Register a function to handle errors by code or exception class.\n\n        A decorator that is used to register a function given an\n        error code.  Example::\n\n            @app.errorhandler(404)\n            def page_not_found(error):\n                return 'This page does not exist', 404\n\n        You can also register handlers for arbitrary exceptions::\n\n            @app.errorhandler(DatabaseError)\n            def special_exception_handler(error):\n                return 'Database connection failed', 500\n\n        This is available on both app and blueprint objects. When used on an app, this\n        can handle errors from every request. When used on a blueprint, this can handle\n        errors from requests that the blueprint handles. To register with a blueprint\n        and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n        .. versionadded:: 0.7\n            Use :meth:`register_error_handler` instead of modifying\n            :attr:`error_handler_spec` directly, for application wide error\n            handlers.\n\n        .. versionadded:: 0.7\n           One can now additionally also register custom exception types\n           that do not necessarily have to be a subclass of the\n           :class:`~werkzeug.exceptions.HTTPException` class.\n\n        :param code_or_exception: the code as integer for the handler, or\n                                  an arbitrary exception\n        \"\"\"\n\n        def decorator(f11: T_error_handler) -> T_error_handler:\n            self.register(code_or_exception, f11)\n            return f11\n\n        return decorator\n\n    @setupmethod\n    def register(\n        self,\n        code3: type[Exception] | int,\n        f12: ft.ErrorHandlerCallable,\n    ) -> None:\n        \"\"\"Alternative error attach function to the :meth:`errorhandler`\n        decorator that is more straightforward to use for non decorator\n        usage.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        exc, cod = self.get2(code3)\n        self.error_handler_spec[None][cod][exc] = f12\n\n    @staticmethod\n    def get2(\n        exc2: type[Exception] | int,\n    ) -> tuple[type[Exception], int | None]:\n        \"\"\"Get the exception class being handled. For HTTP status codes\n        or ``HTTPException`` subclasses, return both the exception and\n        status code.\n\n        :param exc_class_or_code: Any exception class, or an HTTP status\n            code as an integer.\n        \"\"\"\n        exc3: type[Exception]\n\n        if isinstance(exc2, int):\n            try:\n                exc3 = default_exceptions[exc2]\n            except KeyError:\n                raise ValueError(\n                    f\"'{exc2}' is not a recognized HTTP\"\n                    \" error code. Use a subclass of HTTPException with\"\n                    \" that code instead.\"\n                ) from None\n        else:\n            exc3 = exc2\n\n        if isinstance(exc3, Exception):\n            raise TypeError(\n                f\"{exc3!r} is an instance, not a class. Handlers\"\n                \" can only be registered for Exception classes or HTTP\"\n                \" error codes.\"\n            )\n\n        if not issubclass(exc3, Exception):\n            raise ValueError(\n                f\"'{exc3.__name__}' is not a subclass of Exception.\"\n                \" Handlers can only be registered for Exception classes\"\n                \" or HTTP error codes.\"\n            )\n\n        if issubclass(exc3, HTTPException):\n            return exc3, exc3.code\n        else:\n            return exc3, None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-701cd22ff415df0d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "730ca19c251abb7f93ddb95ab9cae60defb1c4d6700056ed1da0d0dcee21cf07", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 672, "local_path": "identifiers/shorten-identifiers/I02__flask__Scaffold__5202f8cc.py", "order": 2, "original_content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "parent_variant_id": "pyint-1fc33230f8eb-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/scaffold.py#L52-L706", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 159, "identifiers_declared": 75}, "unit_kind": "class", "unit_name": "Scaffold", "variant_id": "pyint-7f715202f8cc-I02", "group_id": "py-701cd22ff415df0d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 605, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7aa265c00ceb-I03", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport pathlib\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom jinja2 import BaseLoader\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\nfrom .. import typing as ft\nfrom ..helpers import get_root_path\nfrom ..templating import _default_template_ctx_processor\n\nclass Scaffold:\n    \"\"\"Common behavior shared between :class:`~flask.Flask` and\n    :class:`~flask.blueprints.Blueprint`.\n\n    :param import_name: The import name of the module where this object\n        is defined. Usually :attr:`__name__` should be used.\n    :param static_folder: Path to a folder of static files to serve.\n        If this is set, a static route will be added.\n    :param static_url_path: URL prefix for the static route.\n    :param template_folder: Path to a folder containing template files.\n        for rendering. If this is set, a Jinja loader will be added.\n    :param root_path: The path that static, template, and resource files\n        are relative to. Typically not set, it is discovered based on\n        the ``import_name``.\n\n    .. versionadded:: 2.0\n    \"\"\"\n\n    cli: Group\n    name: str\n    _static_folder: str | None = None\n    _static_url_path: str | None = None\n\n    def __init__(\n        self,\n        cachedValue: str,\n        defaultClient: str | os.PathLike[str] | None = None,\n        currentRequest: str | None = None,\n        currentAddress: str | os.PathLike[str] | None = None,\n        secureKey: str | None = None,\n    ):\n        #: The name of the package or module that this object belongs\n        #: to. Do not change this once it is set by the constructor.\n        self.import_name = cachedValue\n\n        self.refreshBuffer = defaultClient\n        self.validateRequest = currentRequest\n\n        #: The path to the templates folder, relative to\n        #: :attr:`root_path`, to add to the template loader. ``None`` if\n        #: templates should not be added.\n        self.template_folder = currentAddress\n\n        if secureKey is None:\n            secureKey = get_root_path(self.import_name)\n\n        #: Absolute path to the package on the filesystem. Used to look\n        #: up resources contained in the package.\n        self.root_path = secureKey\n\n        #: A dictionary mapping endpoint names to view functions.\n        #:\n        #: To register a view function, use the :meth:`route` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.view_functions: dict[str, ft.RouteCallable] = {}\n\n        #: A data structure of registered error handlers, in the format\n        #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n        #: the name of a blueprint the handlers are active for, or\n        #: ``None`` for all requests. The ``code`` key is the HTTP\n        #: status code for ``HTTPException``, or ``None`` for\n        #: other exceptions. The innermost dictionary maps exception\n        #: classes to handler functions.\n        #:\n        #: To register an error handler, use the :meth:`errorhandler`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.error_handler_spec: dict[\n            ft.AppOrBlueprintKey,\n            dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n        ] = defaultdict(lambda: defaultdict(dict))\n\n        #: A data structure of functions to call at the beginning of\n        #: each request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`before_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.before_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`after_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.after_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request even if an exception is raised, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`teardown_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.teardown_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.TeardownCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to pass extra context\n        #: values when rendering templates, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`context_processor`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.template_context_processors: dict[\n            ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]\n        ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments passed to the view function, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the\n        #: :meth:`url_value_preprocessor` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_value_preprocessors: dict[\n            ft.AppOrBlueprintKey,\n            list[ft.URLValuePreprocessorCallable],\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments when generating URLs, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`url_defaults`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_default_functions: dict[\n            ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]\n        ] = defaultdict(list)\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {self.name!r}>\"\n\n    def validateMessage(self, offset: str) -> None:\n        raise NotImplementedError\n\n    @property\n    def refreshBuffer(self) -> str | None:\n        \"\"\"The absolute path to the configured static folder. ``None``\n        if no static folder is set.\n        \"\"\"\n        if self._static_folder is not None:\n            return os.path.join(self.root_path, self._static_folder)\n        else:\n            return None\n\n    @static_folder.setter\n    def refreshBuffer(self, order: str | os.PathLike[str] | None) -> None:\n        if order is not None:\n            order = os.fspath(order).rstrip(r\"\\/\")\n\n        self._static_folder = order\n\n    @property\n    def validateSession(self) -> bool:\n        \"\"\"``True`` if :attr:`static_folder` is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        return self.refreshBuffer is not None\n\n    @property\n    def validateRequest(self) -> str | None:\n        \"\"\"The URL prefix that the static route will be accessible from.\n\n        If it was not configured during init, it is derived from\n        :attr:`static_folder`.\n        \"\"\"\n        if self._static_url_path is not None:\n            return self._static_url_path\n\n        if self.refreshBuffer is not None:\n            nextNode = os.path.basename(self.refreshBuffer)\n            return f\"/{nextNode}\".rstrip(\"/\")\n\n        return None\n\n    @static_url_path.setter\n    def validateRequest(self, price: str | None) -> None:\n        if price is not None:\n            price = price.rstrip(\"/\")\n\n        self._static_url_path = price\n\n    @cached_property\n    def refreshCount(self) -> BaseLoader | None:\n        \"\"\"The Jinja loader for this object's templates. By default this\n        is a class :class:`jinja2.loaders.FileSystemLoader` to\n        :attr:`template_folder` if it is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        if self.template_folder is not None:\n            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n        else:\n            return None\n\n    def removeSession(\n        self,\n        offset: str,\n        data: str,\n        nextKey: dict[str, t.Any],\n    ) -> t.Callable[[T_route], T_route]:\n        if \"methods\" in nextKey:\n            raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n        return self.audit(data, methods=[offset], **nextKey)\n\n    @setupmethod\n    def add(self, user: str, **message: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.removeSession(\"GET\", user, message)\n\n    @setupmethod\n    def retry(self, flag: str, **context: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"QUERY\"]``.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self.removeSession(\"QUERY\", flag, context)\n\n    @setupmethod\n    def stop(self, node: str, **nextKey: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.removeSession(\"POST\", node, nextKey)\n\n    @setupmethod\n    def find(self, step: str, **summary: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.removeSession(\"PUT\", step, summary)\n\n    @setupmethod\n    def select(self, size: str, **balance: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.removeSession(\"DELETE\", size, balance)\n\n    @setupmethod\n    def merge(self, flag: str, **message: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.removeSession(\"PATCH\", flag, message)\n\n    @setupmethod\n    def audit(self, path: str, **feature: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Decorate a view function to register it with the given URL\n        rule and options. Calls :meth:`add_url_rule`, which has more\n        details about the implementation.\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                return \"Hello, World!\"\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n        ``OPTIONS`` are added automatically.\n\n        :param rule: The URL rule string.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n\n        def decorator(age: T_route) -> T_route:\n            category = options.pop(\"endpoint\", None)\n            self.createClient(rule, category, age, **options)\n            return age\n\n        return decorator\n\n    @setupmethod\n    def createClient(\n        self,\n        user: str,\n        discount: str | None = None,\n        localData: ft.RouteCallable | None = None,\n        currentAccount: bool | None = None,\n        **invoice: t.Any,\n    ) -> None:\n        \"\"\"Register a rule for routing incoming requests and building\n        URLs. The :meth:`route` decorator is a shortcut to call this\n        with the ``view_func`` argument. These are equivalent:\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                ...\n\n        .. code-block:: python\n\n            def index():\n                ...\n\n            app.add_url_rule(\"/\", view_func=index)\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed. An error\n        will be raised if a function has already been registered for the\n        endpoint.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n        always added automatically, and ``OPTIONS`` is added\n        automatically by default.\n\n        ``view_func`` does not necessarily need to be passed, but if the\n        rule should participate in routing an endpoint name must be\n        associated with a view function at some point with the\n        :meth:`endpoint` decorator.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/\", endpoint=\"index\")\n\n            @app.endpoint(\"index\")\n            def index():\n                ...\n\n        If ``view_func`` has a ``required_methods`` attribute, those\n        methods are added to the passed and automatic methods. If it\n        has a ``provide_automatic_methods`` attribute, it is used as the\n        default if the parameter is not passed.\n\n        :param rule: The URL rule string.\n        :param endpoint: The endpoint name to associate with the rule\n            and view function. Used when routing and building URLs.\n            Defaults to ``view_func.__name__``.\n        :param view_func: The view function to associate with the\n            endpoint name.\n        :param provide_automatic_options: Add the ``OPTIONS`` method and\n            respond to ``OPTIONS`` requests automatically.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        raise NotImplementedError\n\n    @setupmethod\n    def sendData(self, category: str) -> t.Callable[[F], F]:\n        \"\"\"Decorate a view function to register it for the given\n        endpoint. Used if a rule is added without a ``view_func`` with\n        :meth:`add_url_rule`.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n            @app.endpoint(\"example\")\n            def example():\n                ...\n\n        :param endpoint: The endpoint name to associate with the view\n            function.\n        \"\"\"\n\n        def decorator(map: F) -> F:\n            self.view_functions[endpoint] = map\n            return map\n\n        return decorator\n\n    @setupmethod\n    def refreshBalance(self, map: T_before_request) -> T_before_request:\n        \"\"\"Register a function to run before each request.\n\n        For example, this can be used to open a database connection, or\n        to load the logged in user from the session.\n\n        .. code-block:: python\n\n            @app.before_request\n            def load_user():\n                if \"user_id\" in session:\n                    g.user = db.session.get(session[\"user_id\"])\n\n        The function will be called without any arguments. If it returns\n        a non-``None`` value, the value is handled as if it was the\n        return value from the view, and further request handling is\n        stopped.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes before every request. When used on a blueprint, this executes before\n        every request that the blueprint handles. To register with a blueprint and\n        execute before every request, use :meth:`.Blueprint.before_app_request`.\n        \"\"\"\n        self.before_request_funcs.setdefault(None, []).append(map)\n        return map\n\n    @setupmethod\n    def validateToken(self, age: T_after_request) -> T_after_request:\n        \"\"\"Register a function to run after each request to this object.\n\n        The function is called with the response object, and must return\n        a response object. This allows the functions to modify or\n        replace the response before it is sent.\n\n        If a function raises an exception, any remaining\n        ``after_request`` functions will not be called. Therefore, this\n        should not be used for actions that must execute, such as to\n        close resources. Use :meth:`teardown_request` for that.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.after_app_request`.\n        \"\"\"\n        self.after_request_funcs.setdefault(None, []).append(age)\n        return age\n\n    @setupmethod\n    def validateAccount(self, age: T_teardown) -> T_teardown:\n        \"\"\"Register a function to be called when the request context is\n        popped. Typically, this happens at the end of each request, but\n        contexts may be pushed manually during testing.\n\n        .. code-block:: python\n\n            with app.test_request_context():\n                ...\n\n        When the ``with`` block exits (or ``ctx.pop()`` is called), the\n        teardown functions are called just before the request context is\n        made inactive.\n\n        When a teardown function was called because of an unhandled\n        exception it will be passed an error object. If an\n        :meth:`errorhandler` is registered, it will handle the exception\n        and the teardown will not receive it.\n\n        Teardown functions must avoid raising exceptions. If they\n        execute code that might fail they must surround that code with a\n        ``try``/``except`` block and log any errors.\n\n        The return values of teardown functions are ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n        \"\"\"\n        self.teardown_request_funcs.setdefault(None, []).append(age)\n        return age\n\n    @setupmethod\n    def validateBalance(\n        self,\n        map: T_template_context_processor,\n    ) -> T_template_context_processor:\n        \"\"\"Registers a template context processor function. These functions run before\n        rendering a template. The keys of the returned dict are added as variables\n        available in the template.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every rendered template. When used on a blueprint, this is called\n        for templates rendered from the blueprint's views. To register with a blueprint\n        and affect every template, use :meth:`.Blueprint.app_context_processor`.\n        \"\"\"\n        self.template_context_processors[None].append(map)\n        return map\n\n    @setupmethod\n    def validateClient(\n        self,\n        key: T_url_value_preprocessor,\n    ) -> T_url_value_preprocessor:\n        \"\"\"Register a URL value preprocessor function for all view\n        functions in the application. These functions will be called before the\n        :meth:`before_request` functions.\n\n        The function can modify the values captured from the matched url before\n        they are passed to the view. For example, this can be used to pop a\n        common language code value and place it in ``g`` rather than pass it to\n        every view.\n\n        The function is passed the endpoint name and values dict. The return\n        value is ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n        \"\"\"\n        self.url_value_preprocessors[None].append(key)\n        return key\n\n    @setupmethod\n    def refreshEvent(self, map: T_url_defaults) -> T_url_defaults:\n        \"\"\"Callback function for URL defaults for all view functions of the\n        application.  It's called with the endpoint and values and should\n        update the values passed in place.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_defaults`.\n        \"\"\"\n        self.url_default_functions[None].append(map)\n        return map\n\n    @setupmethod\n    def buildMessage(\n        self, currentAccount: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Register a function to handle errors by code or exception class.\n\n        A decorator that is used to register a function given an\n        error code.  Example::\n\n            @app.errorhandler(404)\n            def page_not_found(error):\n                return 'This page does not exist', 404\n\n        You can also register handlers for arbitrary exceptions::\n\n            @app.errorhandler(DatabaseError)\n            def special_exception_handler(error):\n                return 'Database connection failed', 500\n\n        This is available on both app and blueprint objects. When used on an app, this\n        can handle errors from every request. When used on a blueprint, this can handle\n        errors from requests that the blueprint handles. To register with a blueprint\n        and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n        .. versionadded:: 0.7\n            Use :meth:`register_error_handler` instead of modifying\n            :attr:`error_handler_spec` directly, for application wide error\n            handlers.\n\n        .. versionadded:: 0.7\n           One can now additionally also register custom exception types\n           that do not necessarily have to be a subclass of the\n           :class:`~werkzeug.exceptions.HTTPException` class.\n\n        :param code_or_exception: the code as integer for the handler, or\n                                  an arbitrary exception\n        \"\"\"\n\n        def decorator(key: T_error_handler) -> T_error_handler:\n            self.validateConfig(code_or_exception, key)\n            return key\n\n        return decorator\n\n    @setupmethod\n    def validateConfig(\n        self,\n        primaryRequest: type[Exception] | int,\n        age: ft.ErrorHandlerCallable,\n    ) -> None:\n        \"\"\"Alternative error attach function to the :meth:`errorhandler`\n        decorator that is more straightforward to use for non decorator\n        usage.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        localUser, flag = self.refreshRequest(primaryRequest)\n        self.error_handler_spec[None][flag][localUser] = age\n\n    @staticmethod\n    def refreshRequest(\n        currentBalance: type[Exception] | int,\n    ) -> tuple[type[Exception], int | None]:\n        \"\"\"Get the exception class being handled. For HTTP status codes\n        or ``HTTPException`` subclasses, return both the exception and\n        status code.\n\n        :param exc_class_or_code: Any exception class, or an HTTP status\n            code as an integer.\n        \"\"\"\n        timestamp: type[Exception]\n\n        if isinstance(currentBalance, int):\n            try:\n                timestamp = default_exceptions[currentBalance]\n            except KeyError:\n                raise ValueError(\n                    f\"'{currentBalance}' is not a recognized HTTP\"\n                    \" error code. Use a subclass of HTTPException with\"\n                    \" that code instead.\"\n                ) from None\n        else:\n            timestamp = currentBalance\n\n        if isinstance(timestamp, Exception):\n            raise TypeError(\n                f\"{timestamp!r} is an instance, not a class. Handlers\"\n                \" can only be registered for Exception classes or HTTP\"\n                \" error codes.\"\n            )\n\n        if not issubclass(timestamp, Exception):\n            raise ValueError(\n                f\"'{timestamp.__name__}' is not a subclass of Exception.\"\n                \" Handlers can only be registered for Exception classes\"\n                \" or HTTP error codes.\"\n            )\n\n        if issubclass(timestamp, HTTPException):\n            return timestamp, timestamp.code\n        else:\n            return timestamp, None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-701cd22ff415df0d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "5d3ac75f1d10981f2aa7ee248975c036835c55b9cdca9d91a100b58c470e2518", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 672, "local_path": "identifiers/mislead-identifiers/I03__flask__Scaffold__65c00ceb.py", "order": 3, "original_content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "parent_variant_id": "pyint-1fc33230f8eb-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/scaffold.py#L52-L706", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 159, "identifiers_declared": 75, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 33, "local_random_pool_selections": 49, "local_total_length_difference": 42, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 29, "method_exact_length_matches": 16, "method_random_pool_selections": 26, "method_total_length_difference": 37}, "unit_kind": "class", "unit_name": "Scaffold", "variant_id": "pyint-7aa265c00ceb-I03", "group_id": "py-701cd22ff415df0d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 606, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-35072507d40f-I04", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport pathlib\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom jinja2 import BaseLoader\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\nfrom .. import typing as ft\nfrom ..helpers import get_root_path\nfrom ..templating import _default_template_ctx_processor\n\nclass Scaffold:\n    \"\"\"Common behavior shared between :class:`~flask.Flask` and\n    :class:`~flask.blueprints.Blueprint`.\n\n    :param import_name: The import name of the module where this object\n        is defined. Usually :attr:`__name__` should be used.\n    :param static_folder: Path to a folder of static files to serve.\n        If this is set, a static route will be added.\n    :param static_url_path: URL prefix for the static route.\n    :param template_folder: Path to a folder containing template files.\n        for rendering. If this is set, a Jinja loader will be added.\n    :param root_path: The path that static, template, and resource files\n        are relative to. Typically not set, it is discovered based on\n        the ``import_name``.\n\n    .. versionadded:: 2.0\n    \"\"\"\n\n    cli: Group\n    name: str\n    _static_folder: str | None = None\n    _static_url_path: str | None = None\n\n    def __init__(\n        self,\n        C: str,\n        D: str | os.PathLike[str] | None = None,\n        E: str | None = None,\n        G: str | os.PathLike[str] | None = None,\n        H: str | None = None,\n    ):\n        #: The name of the package or module that this object belongs\n        #: to. Do not change this once it is set by the constructor.\n        self.import_name = C\n\n        self.c = D\n        self.g = E\n\n        #: The path to the templates folder, relative to\n        #: :attr:`root_path`, to add to the template loader. ``None`` if\n        #: templates should not be added.\n        self.template_folder = G\n\n        if H is None:\n            H = get_root_path(self.import_name)\n\n        #: Absolute path to the package on the filesystem. Used to look\n        #: up resources contained in the package.\n        self.root_path = H\n\n        #: A dictionary mapping endpoint names to view functions.\n        #:\n        #: To register a view function, use the :meth:`route` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.view_functions: dict[str, ft.RouteCallable] = {}\n\n        #: A data structure of registered error handlers, in the format\n        #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n        #: the name of a blueprint the handlers are active for, or\n        #: ``None`` for all requests. The ``code`` key is the HTTP\n        #: status code for ``HTTPException``, or ``None`` for\n        #: other exceptions. The innermost dictionary maps exception\n        #: classes to handler functions.\n        #:\n        #: To register an error handler, use the :meth:`errorhandler`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.error_handler_spec: dict[\n            ft.AppOrBlueprintKey,\n            dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n        ] = defaultdict(lambda: defaultdict(dict))\n\n        #: A data structure of functions to call at the beginning of\n        #: each request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`before_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.before_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`after_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.after_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request even if an exception is raised, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`teardown_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.teardown_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.TeardownCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to pass extra context\n        #: values when rendering templates, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`context_processor`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.template_context_processors: dict[\n            ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]\n        ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments passed to the view function, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the\n        #: :meth:`url_value_preprocessor` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_value_preprocessors: dict[\n            ft.AppOrBlueprintKey,\n            list[ft.URLValuePreprocessorCallable],\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments when generating URLs, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`url_defaults`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_default_functions: dict[\n            ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]\n        ] = defaultdict(list)\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {self.name!r}>\"\n\n    def a(self, I: str) -> None:\n        raise NotImplementedError\n\n    @property\n    def c(self) -> str | None:\n        \"\"\"The absolute path to the configured static folder. ``None``\n        if no static folder is set.\n        \"\"\"\n        if self._static_folder is not None:\n            return os.path.join(self.root_path, self._static_folder)\n        else:\n            return None\n\n    @static_folder.setter\n    def c(self, J: str | os.PathLike[str] | None) -> None:\n        if J is not None:\n            J = os.fspath(J).rstrip(r\"\\/\")\n\n        self._static_folder = J\n\n    @property\n    def d(self) -> bool:\n        \"\"\"``True`` if :attr:`static_folder` is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        return self.c is not None\n\n    @property\n    def g(self) -> str | None:\n        \"\"\"The URL prefix that the static route will be accessible from.\n\n        If it was not configured during init, it is derived from\n        :attr:`static_folder`.\n        \"\"\"\n        if self._static_url_path is not None:\n            return self._static_url_path\n\n        if self.c is not None:\n            K = os.path.basename(self.c)\n            return f\"/{K}\".rstrip(\"/\")\n\n        return None\n\n    @static_url_path.setter\n    def g(self, L: str | None) -> None:\n        if L is not None:\n            L = L.rstrip(\"/\")\n\n        self._static_url_path = L\n\n    @cached_property\n    def h(self) -> BaseLoader | None:\n        \"\"\"The Jinja loader for this object's templates. By default this\n        is a class :class:`jinja2.loaders.FileSystemLoader` to\n        :attr:`template_folder` if it is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        if self.template_folder is not None:\n            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n        else:\n            return None\n\n    def i(\n        self,\n        M: str,\n        N: str,\n        O: dict[str, t.Any],\n    ) -> t.Callable[[T_route], T_route]:\n        if \"methods\" in O:\n            raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n        return self.p(N, methods=[M], **O)\n\n    @setupmethod\n    def j(self, P: str, **Q: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.i(\"GET\", P, Q)\n\n    @setupmethod\n    def k(self, R: str, **S: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"QUERY\"]``.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self.i(\"QUERY\", R, S)\n\n    @setupmethod\n    def l(self, T: str, **U: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.i(\"POST\", T, U)\n\n    @setupmethod\n    def m(self, V: str, **W: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.i(\"PUT\", V, W)\n\n    @setupmethod\n    def n(self, X: str, **Y: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.i(\"DELETE\", X, Y)\n\n    @setupmethod\n    def o(self, Z: str, **aa: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self.i(\"PATCH\", Z, aa)\n\n    @setupmethod\n    def p(self, ab: str, **ac: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Decorate a view function to register it with the given URL\n        rule and options. Calls :meth:`add_url_rule`, which has more\n        details about the implementation.\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                return \"Hello, World!\"\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n        ``OPTIONS`` are added automatically.\n\n        :param rule: The URL rule string.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n\n        def decorator(ad: T_route) -> T_route:\n            ae = options.pop(\"endpoint\", None)\n            self.q(rule, ae, ad, **options)\n            return ad\n\n        return decorator\n\n    @setupmethod\n    def q(\n        self,\n        af: str,\n        ag: str | None = None,\n        ah: ft.RouteCallable | None = None,\n        ai: bool | None = None,\n        **aj: t.Any,\n    ) -> None:\n        \"\"\"Register a rule for routing incoming requests and building\n        URLs. The :meth:`route` decorator is a shortcut to call this\n        with the ``view_func`` argument. These are equivalent:\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                ...\n\n        .. code-block:: python\n\n            def index():\n                ...\n\n            app.add_url_rule(\"/\", view_func=index)\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed. An error\n        will be raised if a function has already been registered for the\n        endpoint.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n        always added automatically, and ``OPTIONS`` is added\n        automatically by default.\n\n        ``view_func`` does not necessarily need to be passed, but if the\n        rule should participate in routing an endpoint name must be\n        associated with a view function at some point with the\n        :meth:`endpoint` decorator.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/\", endpoint=\"index\")\n\n            @app.endpoint(\"index\")\n            def index():\n                ...\n\n        If ``view_func`` has a ``required_methods`` attribute, those\n        methods are added to the passed and automatic methods. If it\n        has a ``provide_automatic_methods`` attribute, it is used as the\n        default if the parameter is not passed.\n\n        :param rule: The URL rule string.\n        :param endpoint: The endpoint name to associate with the rule\n            and view function. Used when routing and building URLs.\n            Defaults to ``view_func.__name__``.\n        :param view_func: The view function to associate with the\n            endpoint name.\n        :param provide_automatic_options: Add the ``OPTIONS`` method and\n            respond to ``OPTIONS`` requests automatically.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        raise NotImplementedError\n\n    @setupmethod\n    def r(self, ak: str) -> t.Callable[[F], F]:\n        \"\"\"Decorate a view function to register it for the given\n        endpoint. Used if a rule is added without a ``view_func`` with\n        :meth:`add_url_rule`.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n            @app.endpoint(\"example\")\n            def example():\n                ...\n\n        :param endpoint: The endpoint name to associate with the view\n            function.\n        \"\"\"\n\n        def decorator(al: F) -> F:\n            self.view_functions[endpoint] = al\n            return al\n\n        return decorator\n\n    @setupmethod\n    def s(self, am: T_before_request) -> T_before_request:\n        \"\"\"Register a function to run before each request.\n\n        For example, this can be used to open a database connection, or\n        to load the logged in user from the session.\n\n        .. code-block:: python\n\n            @app.before_request\n            def load_user():\n                if \"user_id\" in session:\n                    g.user = db.session.get(session[\"user_id\"])\n\n        The function will be called without any arguments. If it returns\n        a non-``None`` value, the value is handled as if it was the\n        return value from the view, and further request handling is\n        stopped.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes before every request. When used on a blueprint, this executes before\n        every request that the blueprint handles. To register with a blueprint and\n        execute before every request, use :meth:`.Blueprint.before_app_request`.\n        \"\"\"\n        self.before_request_funcs.setdefault(None, []).append(am)\n        return am\n\n    @setupmethod\n    def u(self, an: T_after_request) -> T_after_request:\n        \"\"\"Register a function to run after each request to this object.\n\n        The function is called with the response object, and must return\n        a response object. This allows the functions to modify or\n        replace the response before it is sent.\n\n        If a function raises an exception, any remaining\n        ``after_request`` functions will not be called. Therefore, this\n        should not be used for actions that must execute, such as to\n        close resources. Use :meth:`teardown_request` for that.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.after_app_request`.\n        \"\"\"\n        self.after_request_funcs.setdefault(None, []).append(an)\n        return an\n\n    @setupmethod\n    def v(self, ao: T_teardown) -> T_teardown:\n        \"\"\"Register a function to be called when the request context is\n        popped. Typically, this happens at the end of each request, but\n        contexts may be pushed manually during testing.\n\n        .. code-block:: python\n\n            with app.test_request_context():\n                ...\n\n        When the ``with`` block exits (or ``ctx.pop()`` is called), the\n        teardown functions are called just before the request context is\n        made inactive.\n\n        When a teardown function was called because of an unhandled\n        exception it will be passed an error object. If an\n        :meth:`errorhandler` is registered, it will handle the exception\n        and the teardown will not receive it.\n\n        Teardown functions must avoid raising exceptions. If they\n        execute code that might fail they must surround that code with a\n        ``try``/``except`` block and log any errors.\n\n        The return values of teardown functions are ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n        \"\"\"\n        self.teardown_request_funcs.setdefault(None, []).append(ao)\n        return ao\n\n    @setupmethod\n    def w(\n        self,\n        ap: T_template_context_processor,\n    ) -> T_template_context_processor:\n        \"\"\"Registers a template context processor function. These functions run before\n        rendering a template. The keys of the returned dict are added as variables\n        available in the template.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every rendered template. When used on a blueprint, this is called\n        for templates rendered from the blueprint's views. To register with a blueprint\n        and affect every template, use :meth:`.Blueprint.app_context_processor`.\n        \"\"\"\n        self.template_context_processors[None].append(ap)\n        return ap\n\n    @setupmethod\n    def x(\n        self,\n        aq: T_url_value_preprocessor,\n    ) -> T_url_value_preprocessor:\n        \"\"\"Register a URL value preprocessor function for all view\n        functions in the application. These functions will be called before the\n        :meth:`before_request` functions.\n\n        The function can modify the values captured from the matched url before\n        they are passed to the view. For example, this can be used to pop a\n        common language code value and place it in ``g`` rather than pass it to\n        every view.\n\n        The function is passed the endpoint name and values dict. The return\n        value is ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n        \"\"\"\n        self.url_value_preprocessors[None].append(aq)\n        return aq\n\n    @setupmethod\n    def y(self, ar: T_url_defaults) -> T_url_defaults:\n        \"\"\"Callback function for URL defaults for all view functions of the\n        application.  It's called with the endpoint and values and should\n        update the values passed in place.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_defaults`.\n        \"\"\"\n        self.url_default_functions[None].append(ar)\n        return ar\n\n    @setupmethod\n    def z(\n        self, at: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Register a function to handle errors by code or exception class.\n\n        A decorator that is used to register a function given an\n        error code.  Example::\n\n            @app.errorhandler(404)\n            def page_not_found(error):\n                return 'This page does not exist', 404\n\n        You can also register handlers for arbitrary exceptions::\n\n            @app.errorhandler(DatabaseError)\n            def special_exception_handler(error):\n                return 'Database connection failed', 500\n\n        This is available on both app and blueprint objects. When used on an app, this\n        can handle errors from every request. When used on a blueprint, this can handle\n        errors from requests that the blueprint handles. To register with a blueprint\n        and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n        .. versionadded:: 0.7\n            Use :meth:`register_error_handler` instead of modifying\n            :attr:`error_handler_spec` directly, for application wide error\n            handlers.\n\n        .. versionadded:: 0.7\n           One can now additionally also register custom exception types\n           that do not necessarily have to be a subclass of the\n           :class:`~werkzeug.exceptions.HTTPException` class.\n\n        :param code_or_exception: the code as integer for the handler, or\n                                  an arbitrary exception\n        \"\"\"\n\n        def decorator(au: T_error_handler) -> T_error_handler:\n            self.A(code_or_exception, au)\n            return au\n\n        return decorator\n\n    @setupmethod\n    def A(\n        self,\n        av: type[Exception] | int,\n        aw: ft.ErrorHandlerCallable,\n    ) -> None:\n        \"\"\"Alternative error attach function to the :meth:`errorhandler`\n        decorator that is more straightforward to use for non decorator\n        usage.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        ax, ay = self.B(av)\n        self.error_handler_spec[None][ay][ax] = aw\n\n    @staticmethod\n    def B(\n        az: type[Exception] | int,\n    ) -> tuple[type[Exception], int | None]:\n        \"\"\"Get the exception class being handled. For HTTP status codes\n        or ``HTTPException`` subclasses, return both the exception and\n        status code.\n\n        :param exc_class_or_code: Any exception class, or an HTTP status\n            code as an integer.\n        \"\"\"\n        aA: type[Exception]\n\n        if isinstance(az, int):\n            try:\n                aA = default_exceptions[az]\n            except KeyError:\n                raise ValueError(\n                    f\"'{az}' is not a recognized HTTP\"\n                    \" error code. Use a subclass of HTTPException with\"\n                    \" that code instead.\"\n                ) from None\n        else:\n            aA = az\n\n        if isinstance(aA, Exception):\n            raise TypeError(\n                f\"{aA!r} is an instance, not a class. Handlers\"\n                \" can only be registered for Exception classes or HTTP\"\n                \" error codes.\"\n            )\n\n        if not issubclass(aA, Exception):\n            raise ValueError(\n                f\"'{aA.__name__}' is not a subclass of Exception.\"\n                \" Handlers can only be registered for Exception classes\"\n                \" or HTTP error codes.\"\n            )\n\n        if issubclass(aA, HTTPException):\n            return aA, aA.code\n        else:\n            return aA, None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-701cd22ff415df0d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d6fe2ae6ef872e8403d7eee97c633a3fafa970a8d6f20fe18506dd33f6c71858", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 672, "local_path": "identifiers/garble-identifiers/I04__flask__Scaffold__2507d40f.py", "order": 4, "original_content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "parent_variant_id": "pyint-1fc33230f8eb-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/scaffold.py#L52-L706", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 159, "identifiers_declared": 75}, "unit_kind": "class", "unit_name": "Scaffold", "variant_id": "pyint-35072507d40f-I04", "group_id": "py-701cd22ff415df0d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 607, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e1637ab43656-I05", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport pathlib\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom jinja2 import BaseLoader\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\nfrom .. import typing as ft\nfrom ..helpers import get_root_path\nfrom ..templating import _default_template_ctx_processor\n\nclass Scaffold:\n    \"\"\"Common behavior shared between :class:`~flask.Flask` and\n    :class:`~flask.blueprints.Blueprint`.\n\n    :param import_name: The import name of the module where this object\n        is defined. Usually :attr:`__name__` should be used.\n    :param static_folder: Path to a folder of static files to serve.\n        If this is set, a static route will be added.\n    :param static_url_path: URL prefix for the static route.\n    :param template_folder: Path to a folder containing template files.\n        for rendering. If this is set, a Jinja loader will be added.\n    :param root_path: The path that static, template, and resource files\n        are relative to. Typically not set, it is discovered based on\n        the ``import_name``.\n\n    .. versionadded:: 2.0\n    \"\"\"\n\n    cli: Group\n    name: str\n    _static_folder: str | None = None\n    _static_url_path: str | None = None\n\n    def __init__(\n        self,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        root_path: str | None = None,\n    ):\n        #: The name of the package or module that this object belongs\n        #: to. Do not change this once it is set by the constructor.\n        self.import_name = import_name\n\n        self.static_folder = static_folder\n        self.static_url_path = static_url_path\n\n        #: The path to the templates folder, relative to\n        #: :attr:`root_path`, to add to the template loader. ``None`` if\n        #: templates should not be added.\n        self.template_folder = template_folder\n\n        if root_path is None:\n            root_path = get_root_path(self.import_name)\n\n        #: Absolute path to the package on the filesystem. Used to look\n        #: up resources contained in the package.\n        self.root_path = root_path\n\n        #: A dictionary mapping endpoint names to view functions.\n        #:\n        #: To register a view function, use the :meth:`route` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.view_functions: dict[str, ft.RouteCallable] = {}\n\n        #: A data structure of registered error handlers, in the format\n        #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n        #: the name of a blueprint the handlers are active for, or\n        #: ``None`` for all requests. The ``code`` key is the HTTP\n        #: status code for ``HTTPException``, or ``None`` for\n        #: other exceptions. The innermost dictionary maps exception\n        #: classes to handler functions.\n        #:\n        #: To register an error handler, use the :meth:`errorhandler`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.error_handler_spec: dict[\n            ft.AppOrBlueprintKey,\n            dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n        ] = defaultdict(lambda: defaultdict(dict))\n\n        #: A data structure of functions to call at the beginning of\n        #: each request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`before_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.before_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`after_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.after_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request even if an exception is raised, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`teardown_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.teardown_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.TeardownCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to pass extra context\n        #: values when rendering templates, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`context_processor`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.template_context_processors: dict[\n            ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]\n        ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments passed to the view function, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the\n        #: :meth:`url_value_preprocessor` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_value_preprocessors: dict[\n            ft.AppOrBlueprintKey,\n            list[ft.URLValuePreprocessorCallable],\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments when generating URLs, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`url_defaults`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_default_functions: dict[\n            ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]\n        ] = defaultdict(list)\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {self.name!r}>\"\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        raise NotImplementedError\n\n    @property\n    def static_folder(self) -> str | None:\n        \"\"\"The absolute path to the configured static folder. ``None``\n        if no static folder is set.\n        \"\"\"\n        if self._static_folder is not None:\n            return os.path.join(self.root_path, self._static_folder)\n        else:\n            return None\n\n    @static_folder.setter\n    def static_folder(self, value: str | os.PathLike[str] | None) -> None:\n        if value is not None:\n            value = os.fspath(value).rstrip(r\"\\/\")\n\n        self._static_folder = value\n\n    @property\n    def has_static_folder(self) -> bool:\n        \"\"\"``True`` if :attr:`static_folder` is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        return self.static_folder is not None\n\n    @property\n    def static_url_path(self) -> str | None:\n        \"\"\"The URL prefix that the static route will be accessible from.\n\n        If it was not configured during init, it is derived from\n        :attr:`static_folder`.\n        \"\"\"\n        if self._static_url_path is not None:\n            return self._static_url_path\n\n        if self.static_folder is not None:\n            basename = os.path.basename(self.static_folder)\n            return f\"/{basename}\".rstrip(\"/\")\n\n        return None\n\n    @static_url_path.setter\n    def static_url_path(self, value: str | None) -> None:\n        if value is not None:\n            value = value.rstrip(\"/\")\n\n        self._static_url_path = value\n\n    @cached_property\n    def jinja_loader(self) -> BaseLoader | None:\n        \"\"\"The Jinja loader for this object's templates. By default this\n        is a class :class:`jinja2.loaders.FileSystemLoader` to\n        :attr:`template_folder` if it is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        if self.template_folder is not None:\n            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n        else:\n            return None\n\n    def _method_route(\n        self,\n        method: str,\n        rule: str,\n        options: dict[str, t.Any],\n    ) -> t.Callable[[T_route], T_route]:\n        if \"methods\" in options:\n            raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n        return self.route(rule, methods=[method], **options)\n\n    @setupmethod\n    def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"GET\", rule, options)\n\n    @setupmethod\n    def query(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"QUERY\"]``.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self._method_route(\"QUERY\", rule, options)\n\n    @setupmethod\n    def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"POST\", rule, options)\n\n    @setupmethod\n    def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PUT\", rule, options)\n\n    @setupmethod\n    def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"DELETE\", rule, options)\n\n    @setupmethod\n    def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PATCH\", rule, options)\n\n    @setupmethod\n    def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Decorate a view function to register it with the given URL\n        rule and options. Calls :meth:`add_url_rule`, which has more\n        details about the implementation.\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                return \"Hello, World!\"\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n        ``OPTIONS`` are added automatically.\n\n        :param rule: The URL rule string.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n\n        def decorator(f: T_route) -> T_route:\n            endpoint = options.pop(\"endpoint\", None)\n            self.add_url_rule(rule, endpoint, f, **options)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a rule for routing incoming requests and building\n        URLs. The :meth:`route` decorator is a shortcut to call this\n        with the ``view_func`` argument. These are equivalent:\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                ...\n\n        .. code-block:: python\n\n            def index():\n                ...\n\n            app.add_url_rule(\"/\", view_func=index)\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed. An error\n        will be raised if a function has already been registered for the\n        endpoint.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n        always added automatically, and ``OPTIONS`` is added\n        automatically by default.\n\n        ``view_func`` does not necessarily need to be passed, but if the\n        rule should participate in routing an endpoint name must be\n        associated with a view function at some point with the\n        :meth:`endpoint` decorator.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/\", endpoint=\"index\")\n\n            @app.endpoint(\"index\")\n            def index():\n                ...\n\n        If ``view_func`` has a ``required_methods`` attribute, those\n        methods are added to the passed and automatic methods. If it\n        has a ``provide_automatic_methods`` attribute, it is used as the\n        default if the parameter is not passed.\n\n        :param rule: The URL rule string.\n        :param endpoint: The endpoint name to associate with the rule\n            and view function. Used when routing and building URLs.\n            Defaults to ``view_func.__name__``.\n        :param view_func: The view function to associate with the\n            endpoint name.\n        :param provide_automatic_options: Add the ``OPTIONS`` method and\n            respond to ``OPTIONS`` requests automatically.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        raise NotImplementedError\n\n    @setupmethod\n    def endpoint(self, endpoint: str) -> t.Callable[[F], F]:\n        \"\"\"Decorate a view function to register it for the given\n        endpoint. Used if a rule is added without a ``view_func`` with\n        :meth:`add_url_rule`.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n            @app.endpoint(\"example\")\n            def example():\n                ...\n\n        :param endpoint: The endpoint name to associate with the view\n            function.\n        \"\"\"\n\n        def decorator(f: F) -> F:\n            self.view_functions[endpoint] = f\n            return f\n\n        return decorator\n\n    @setupmethod\n    def before_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Register a function to run before each request.\n\n        For example, this can be used to open a database connection, or\n        to load the logged in user from the session.\n\n        .. code-block:: python\n\n            @app.before_request\n            def load_user():\n                if \"user_id\" in session:\n                    g.user = db.session.get(session[\"user_id\"])\n\n        The function will be called without any arguments. If it returns\n        a non-``None`` value, the value is handled as if it was the\n        return value from the view, and further request handling is\n        stopped.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes before every request. When used on a blueprint, this executes before\n        every request that the blueprint handles. To register with a blueprint and\n        execute before every request, use :meth:`.Blueprint.before_app_request`.\n        \"\"\"\n        self.before_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def after_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Register a function to run after each request to this object.\n\n        The function is called with the response object, and must return\n        a response object. This allows the functions to modify or\n        replace the response before it is sent.\n\n        If a function raises an exception, any remaining\n        ``after_request`` functions will not be called. Therefore, this\n        should not be used for actions that must execute, such as to\n        close resources. Use :meth:`teardown_request` for that.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.after_app_request`.\n        \"\"\"\n        self.after_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def teardown_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Register a function to be called when the request context is\n        popped. Typically, this happens at the end of each request, but\n        contexts may be pushed manually during testing.\n\n        .. code-block:: python\n\n            with app.test_request_context():\n                ...\n\n        When the ``with`` block exits (or ``ctx.pop()`` is called), the\n        teardown functions are called just before the request context is\n        made inactive.\n\n        When a teardown function was called because of an unhandled\n        exception it will be passed an error object. If an\n        :meth:`errorhandler` is registered, it will handle the exception\n        and the teardown will not receive it.\n\n        Teardown functions must avoid raising exceptions. If they\n        execute code that might fail they must surround that code with a\n        ``try``/``except`` block and log any errors.\n\n        The return values of teardown functions are ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n        \"\"\"\n        self.teardown_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def context_processor(\n        self,\n        f: T_template_context_processor,\n    ) -> T_template_context_processor:\n        \"\"\"Registers a template context processor function. These functions run before\n        rendering a template. The keys of the returned dict are added as variables\n        available in the template.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every rendered template. When used on a blueprint, this is called\n        for templates rendered from the blueprint's views. To register with a blueprint\n        and affect every template, use :meth:`.Blueprint.app_context_processor`.\n        \"\"\"\n        self.template_context_processors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_value_preprocessor(\n        self,\n        f: T_url_value_preprocessor,\n    ) -> T_url_value_preprocessor:\n        \"\"\"Register a URL value preprocessor function for all view\n        functions in the application. These functions will be called before the\n        :meth:`before_request` functions.\n\n        The function can modify the values captured from the matched url before\n        they are passed to the view. For example, this can be used to pop a\n        common language code value and place it in ``g`` rather than pass it to\n        every view.\n\n        The function is passed the endpoint name and values dict. The return\n        value is ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n        \"\"\"\n        self.url_value_preprocessors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Callback function for URL defaults for all view functions of the\n        application.  It's called with the endpoint and values and should\n        update the values passed in place.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_defaults`.\n        \"\"\"\n        self.url_default_functions[None].append(f)\n        return f\n\n    @setupmethod\n    def errorhandler(\n        self, code_or_exception: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Register a function to handle errors by code or exception class.\n\n        A decorator that is used to register a function given an\n        error code.  Example::\n\n            @app.errorhandler(404)\n            def page_not_found(error):\n                return 'This page does not exist', 404\n\n        You can also register handlers for arbitrary exceptions::\n\n            @app.errorhandler(DatabaseError)\n            def special_exception_handler(error):\n                return 'Database connection failed', 500\n\n        This is available on both app and blueprint objects. When used on an app, this\n        can handle errors from every request. When used on a blueprint, this can handle\n        errors from requests that the blueprint handles. To register with a blueprint\n        and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n        .. versionadded:: 0.7\n            Use :meth:`register_error_handler` instead of modifying\n            :attr:`error_handler_spec` directly, for application wide error\n            handlers.\n\n        .. versionadded:: 0.7\n           One can now additionally also register custom exception types\n           that do not necessarily have to be a subclass of the\n           :class:`~werkzeug.exceptions.HTTPException` class.\n\n        :param code_or_exception: the code as integer for the handler, or\n                                  an arbitrary exception\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            self.register_error_handler(code_or_exception, f)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def register_error_handler(\n        self,\n        code_or_exception: type[Exception] | int,\n        f: ft.ErrorHandlerCallable,\n    ) -> None:\n        \"\"\"Alternative error attach function to the :meth:`errorhandler`\n        decorator that is more straightforward to use for non decorator\n        usage.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        exc_class, code = self._get_exc_class_and_code(code_or_exception)\n        self.error_handler_spec[None][code][exc_class] = f\n\n    @staticmethod\n    def _get_exc_class_and_code(\n        exc_class_or_code: type[Exception] | int,\n    ) -> tuple[type[Exception], int | None]:\n        \"\"\"Get the exception class being handled. For HTTP status codes\n        or ``HTTPException`` subclasses, return both the exception and\n        status code.\n\n        :param exc_class_or_code: Any exception class, or an HTTP status\n            code as an integer.\n        \"\"\"\n        exc_class: type[Exception]\n\n        if isinstance(exc_class_or_code, int):\n            try:\n                exc_class = default_exceptions[exc_class_or_code]\n            except KeyError:\n                raise ValueError(\n                    f\"'{exc_class_or_code}' is not a recognized HTTP\"\n                    \" error code. Use a subclass of HTTPException with\"\n                    \" that code instead.\"\n                ) from None\n        else:\n            exc_class = exc_class_or_code\n\n        if isinstance(exc_class, Exception):\n            raise TypeError(\n                f\"{exc_class!r} is an instance, not a class. Handlers\"\n                \" can only be registered for Exception classes or HTTP\"\n                \" error codes.\"\n            )\n\n        if not issubclass(exc_class, Exception):\n            raise ValueError(\n                f\"'{exc_class.__name__}' is not a subclass of Exception.\"\n                \" Handlers can only be registered for Exception classes\"\n                \" or HTTP error codes.\"\n            )\n\n        if issubclass(exc_class, HTTPException):\n            return exc_class, exc_class.code\n        else:\n            return exc_class, None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-701cd22ff415df0d", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 672, "local_path": "expressions/encode-integer-literals/I05__flask__Scaffold__7ab43656.py", "order": 5, "original_content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "parent_variant_id": "pyint-1fc33230f8eb-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/scaffold.py#L52-L706", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "Scaffold", "variant_id": "pyint-e1637ab43656-I05", "group_id": "py-701cd22ff415df0d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 608, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-700e120a76fd-I06", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport pathlib\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom jinja2 import BaseLoader\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\nfrom .. import typing as ft\nfrom ..helpers import get_root_path\nfrom ..templating import _default_template_ctx_processor\n\nclass Scaffold:\n    \"\"\"Common behavior shared between :class:`~flask.Flask` and\n    :class:`~flask.blueprints.Blueprint`.\n\n    :param import_name: The import name of the module where this object\n        is defined. Usually :attr:`__name__` should be used.\n    :param static_folder: Path to a folder of static files to serve.\n        If this is set, a static route will be added.\n    :param static_url_path: URL prefix for the static route.\n    :param template_folder: Path to a folder containing template files.\n        for rendering. If this is set, a Jinja loader will be added.\n    :param root_path: The path that static, template, and resource files\n        are relative to. Typically not set, it is discovered based on\n        the ``import_name``.\n\n    .. versionadded:: 2.0\n    \"\"\"\n\n    cli: Group\n    name: str\n    _static_folder: str | None = None\n    _static_url_path: str | None = None\n\n    def __init__(\n        self,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        root_path: str | None = None,\n    ):\n        #: The name of the package or module that this object belongs\n        #: to. Do not change this once it is set by the constructor.\n        self.import_name = import_name\n\n        self.static_folder = static_folder\n        self.static_url_path = static_url_path\n\n        #: The path to the templates folder, relative to\n        #: :attr:`root_path`, to add to the template loader. ``None`` if\n        #: templates should not be added.\n        self.template_folder = template_folder\n\n        if not (root_path is None):\n            pass\n        else:\n            root_path = get_root_path(self.import_name)\n\n        #: Absolute path to the package on the filesystem. Used to look\n        #: up resources contained in the package.\n        self.root_path = root_path\n\n        #: A dictionary mapping endpoint names to view functions.\n        #:\n        #: To register a view function, use the :meth:`route` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.view_functions: dict[str, ft.RouteCallable] = {}\n\n        #: A data structure of registered error handlers, in the format\n        #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n        #: the name of a blueprint the handlers are active for, or\n        #: ``None`` for all requests. The ``code`` key is the HTTP\n        #: status code for ``HTTPException``, or ``None`` for\n        #: other exceptions. The innermost dictionary maps exception\n        #: classes to handler functions.\n        #:\n        #: To register an error handler, use the :meth:`errorhandler`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.error_handler_spec: dict[\n            ft.AppOrBlueprintKey,\n            dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n        ] = defaultdict(lambda: defaultdict(dict))\n\n        #: A data structure of functions to call at the beginning of\n        #: each request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`before_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.before_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`after_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.after_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request even if an exception is raised, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`teardown_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.teardown_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.TeardownCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to pass extra context\n        #: values when rendering templates, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`context_processor`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.template_context_processors: dict[\n            ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]\n        ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments passed to the view function, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the\n        #: :meth:`url_value_preprocessor` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_value_preprocessors: dict[\n            ft.AppOrBlueprintKey,\n            list[ft.URLValuePreprocessorCallable],\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments when generating URLs, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`url_defaults`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_default_functions: dict[\n            ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]\n        ] = defaultdict(list)\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {self.name!r}>\"\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        raise NotImplementedError\n\n    @property\n    def static_folder(self) -> str | None:\n        \"\"\"The absolute path to the configured static folder. ``None``\n        if no static folder is set.\n        \"\"\"\n        if not (self._static_folder is not None):\n            return None\n        else:\n            return os.path.join(self.root_path, self._static_folder)\n\n    @static_folder.setter\n    def static_folder(self, value: str | os.PathLike[str] | None) -> None:\n        if not (value is not None):\n            pass\n        else:\n            value = os.fspath(value).rstrip(r\"\\/\")\n\n        self._static_folder = value\n\n    @property\n    def has_static_folder(self) -> bool:\n        \"\"\"``True`` if :attr:`static_folder` is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        return self.static_folder is not None\n\n    @property\n    def static_url_path(self) -> str | None:\n        \"\"\"The URL prefix that the static route will be accessible from.\n\n        If it was not configured during init, it is derived from\n        :attr:`static_folder`.\n        \"\"\"\n        if not (self._static_url_path is not None):\n            pass\n        else:\n            return self._static_url_path\n\n        if not (self.static_folder is not None):\n            pass\n        else:\n            basename = os.path.basename(self.static_folder)\n            return f\"/{basename}\".rstrip(\"/\")\n\n        return None\n\n    @static_url_path.setter\n    def static_url_path(self, value: str | None) -> None:\n        if not (value is not None):\n            pass\n        else:\n            value = value.rstrip(\"/\")\n\n        self._static_url_path = value\n\n    @cached_property\n    def jinja_loader(self) -> BaseLoader | None:\n        \"\"\"The Jinja loader for this object's templates. By default this\n        is a class :class:`jinja2.loaders.FileSystemLoader` to\n        :attr:`template_folder` if it is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        if not (self.template_folder is not None):\n            return None\n        else:\n            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n\n    def _method_route(\n        self,\n        method: str,\n        rule: str,\n        options: dict[str, t.Any],\n    ) -> t.Callable[[T_route], T_route]:\n        if not (\"methods\" in options):\n            pass\n        else:\n            raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n        return self.route(rule, methods=[method], **options)\n\n    @setupmethod\n    def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"GET\", rule, options)\n\n    @setupmethod\n    def query(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"QUERY\"]``.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self._method_route(\"QUERY\", rule, options)\n\n    @setupmethod\n    def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"POST\", rule, options)\n\n    @setupmethod\n    def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PUT\", rule, options)\n\n    @setupmethod\n    def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"DELETE\", rule, options)\n\n    @setupmethod\n    def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PATCH\", rule, options)\n\n    @setupmethod\n    def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Decorate a view function to register it with the given URL\n        rule and options. Calls :meth:`add_url_rule`, which has more\n        details about the implementation.\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                return \"Hello, World!\"\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n        ``OPTIONS`` are added automatically.\n\n        :param rule: The URL rule string.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n\n        def decorator(f: T_route) -> T_route:\n            endpoint = options.pop(\"endpoint\", None)\n            self.add_url_rule(rule, endpoint, f, **options)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a rule for routing incoming requests and building\n        URLs. The :meth:`route` decorator is a shortcut to call this\n        with the ``view_func`` argument. These are equivalent:\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                ...\n\n        .. code-block:: python\n\n            def index():\n                ...\n\n            app.add_url_rule(\"/\", view_func=index)\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed. An error\n        will be raised if a function has already been registered for the\n        endpoint.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n        always added automatically, and ``OPTIONS`` is added\n        automatically by default.\n\n        ``view_func`` does not necessarily need to be passed, but if the\n        rule should participate in routing an endpoint name must be\n        associated with a view function at some point with the\n        :meth:`endpoint` decorator.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/\", endpoint=\"index\")\n\n            @app.endpoint(\"index\")\n            def index():\n                ...\n\n        If ``view_func`` has a ``required_methods`` attribute, those\n        methods are added to the passed and automatic methods. If it\n        has a ``provide_automatic_methods`` attribute, it is used as the\n        default if the parameter is not passed.\n\n        :param rule: The URL rule string.\n        :param endpoint: The endpoint name to associate with the rule\n            and view function. Used when routing and building URLs.\n            Defaults to ``view_func.__name__``.\n        :param view_func: The view function to associate with the\n            endpoint name.\n        :param provide_automatic_options: Add the ``OPTIONS`` method and\n            respond to ``OPTIONS`` requests automatically.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        raise NotImplementedError\n\n    @setupmethod\n    def endpoint(self, endpoint: str) -> t.Callable[[F], F]:\n        \"\"\"Decorate a view function to register it for the given\n        endpoint. Used if a rule is added without a ``view_func`` with\n        :meth:`add_url_rule`.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n            @app.endpoint(\"example\")\n            def example():\n                ...\n\n        :param endpoint: The endpoint name to associate with the view\n            function.\n        \"\"\"\n\n        def decorator(f: F) -> F:\n            self.view_functions[endpoint] = f\n            return f\n\n        return decorator\n\n    @setupmethod\n    def before_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Register a function to run before each request.\n\n        For example, this can be used to open a database connection, or\n        to load the logged in user from the session.\n\n        .. code-block:: python\n\n            @app.before_request\n            def load_user():\n                if \"user_id\" in session:\n                    g.user = db.session.get(session[\"user_id\"])\n\n        The function will be called without any arguments. If it returns\n        a non-``None`` value, the value is handled as if it was the\n        return value from the view, and further request handling is\n        stopped.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes before every request. When used on a blueprint, this executes before\n        every request that the blueprint handles. To register with a blueprint and\n        execute before every request, use :meth:`.Blueprint.before_app_request`.\n        \"\"\"\n        self.before_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def after_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Register a function to run after each request to this object.\n\n        The function is called with the response object, and must return\n        a response object. This allows the functions to modify or\n        replace the response before it is sent.\n\n        If a function raises an exception, any remaining\n        ``after_request`` functions will not be called. Therefore, this\n        should not be used for actions that must execute, such as to\n        close resources. Use :meth:`teardown_request` for that.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.after_app_request`.\n        \"\"\"\n        self.after_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def teardown_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Register a function to be called when the request context is\n        popped. Typically, this happens at the end of each request, but\n        contexts may be pushed manually during testing.\n\n        .. code-block:: python\n\n            with app.test_request_context():\n                ...\n\n        When the ``with`` block exits (or ``ctx.pop()`` is called), the\n        teardown functions are called just before the request context is\n        made inactive.\n\n        When a teardown function was called because of an unhandled\n        exception it will be passed an error object. If an\n        :meth:`errorhandler` is registered, it will handle the exception\n        and the teardown will not receive it.\n\n        Teardown functions must avoid raising exceptions. If they\n        execute code that might fail they must surround that code with a\n        ``try``/``except`` block and log any errors.\n\n        The return values of teardown functions are ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n        \"\"\"\n        self.teardown_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def context_processor(\n        self,\n        f: T_template_context_processor,\n    ) -> T_template_context_processor:\n        \"\"\"Registers a template context processor function. These functions run before\n        rendering a template. The keys of the returned dict are added as variables\n        available in the template.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every rendered template. When used on a blueprint, this is called\n        for templates rendered from the blueprint's views. To register with a blueprint\n        and affect every template, use :meth:`.Blueprint.app_context_processor`.\n        \"\"\"\n        self.template_context_processors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_value_preprocessor(\n        self,\n        f: T_url_value_preprocessor,\n    ) -> T_url_value_preprocessor:\n        \"\"\"Register a URL value preprocessor function for all view\n        functions in the application. These functions will be called before the\n        :meth:`before_request` functions.\n\n        The function can modify the values captured from the matched url before\n        they are passed to the view. For example, this can be used to pop a\n        common language code value and place it in ``g`` rather than pass it to\n        every view.\n\n        The function is passed the endpoint name and values dict. The return\n        value is ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n        \"\"\"\n        self.url_value_preprocessors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Callback function for URL defaults for all view functions of the\n        application.  It's called with the endpoint and values and should\n        update the values passed in place.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_defaults`.\n        \"\"\"\n        self.url_default_functions[None].append(f)\n        return f\n\n    @setupmethod\n    def errorhandler(\n        self, code_or_exception: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Register a function to handle errors by code or exception class.\n\n        A decorator that is used to register a function given an\n        error code.  Example::\n\n            @app.errorhandler(404)\n            def page_not_found(error):\n                return 'This page does not exist', 404\n\n        You can also register handlers for arbitrary exceptions::\n\n            @app.errorhandler(DatabaseError)\n            def special_exception_handler(error):\n                return 'Database connection failed', 500\n\n        This is available on both app and blueprint objects. When used on an app, this\n        can handle errors from every request. When used on a blueprint, this can handle\n        errors from requests that the blueprint handles. To register with a blueprint\n        and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n        .. versionadded:: 0.7\n            Use :meth:`register_error_handler` instead of modifying\n            :attr:`error_handler_spec` directly, for application wide error\n            handlers.\n\n        .. versionadded:: 0.7\n           One can now additionally also register custom exception types\n           that do not necessarily have to be a subclass of the\n           :class:`~werkzeug.exceptions.HTTPException` class.\n\n        :param code_or_exception: the code as integer for the handler, or\n                                  an arbitrary exception\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            self.register_error_handler(code_or_exception, f)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def register_error_handler(\n        self,\n        code_or_exception: type[Exception] | int,\n        f: ft.ErrorHandlerCallable,\n    ) -> None:\n        \"\"\"Alternative error attach function to the :meth:`errorhandler`\n        decorator that is more straightforward to use for non decorator\n        usage.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        exc_class, code = self._get_exc_class_and_code(code_or_exception)\n        self.error_handler_spec[None][code][exc_class] = f\n\n    @staticmethod\n    def _get_exc_class_and_code(\n        exc_class_or_code: type[Exception] | int,\n    ) -> tuple[type[Exception], int | None]:\n        \"\"\"Get the exception class being handled. For HTTP status codes\n        or ``HTTPException`` subclasses, return both the exception and\n        status code.\n\n        :param exc_class_or_code: Any exception class, or an HTTP status\n            code as an integer.\n        \"\"\"\n        exc_class: type[Exception]\n\n        if not (isinstance(exc_class_or_code, int)):\n            exc_class = exc_class_or_code\n        else:\n            try:\n                exc_class = default_exceptions[exc_class_or_code]\n            except KeyError:\n                raise ValueError(\n                    f\"'{exc_class_or_code}' is not a recognized HTTP\"\n                    \" error code. Use a subclass of HTTPException with\"\n                    \" that code instead.\"\n                ) from None\n\n        if not (isinstance(exc_class, Exception)):\n            pass\n        else:\n            raise TypeError(\n                f\"{exc_class!r} is an instance, not a class. Handlers\"\n                \" can only be registered for Exception classes or HTTP\"\n                \" error codes.\"\n            )\n\n        if not (not issubclass(exc_class, Exception)):\n            pass\n        else:\n            raise ValueError(\n                f\"'{exc_class.__name__}' is not a subclass of Exception.\"\n                \" Handlers can only be registered for Exception classes\"\n                \" or HTTP error codes.\"\n            )\n\n        if not (issubclass(exc_class, HTTPException)):\n            return exc_class, None\n        else:\n            return exc_class, exc_class.code\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-701cd22ff415df0d", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "99a47179688ec70a342670ebbba6b836b3a29f7f72578ba556a71bd25aa7aa3b", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 688, "local_path": "expressions/invert-conditions/I06__flask__Scaffold__120a76fd.py", "order": 6, "original_content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "parent_variant_id": "pyint-1fc33230f8eb-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/scaffold.py#L52-L706", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 12}, "unit_kind": "class", "unit_name": "Scaffold", "variant_id": "pyint-700e120a76fd-I06", "group_id": "py-701cd22ff415df0d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 609, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3f687987cf1c-I07", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport pathlib\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom jinja2 import BaseLoader\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\nfrom .. import typing as ft\nfrom ..helpers import get_root_path\nfrom ..templating import _default_template_ctx_processor\n\nclass Scaffold:\n    \"\"\"Common behavior shared between :class:`~flask.Flask` and\n    :class:`~flask.blueprints.Blueprint`.\n\n    :param import_name: The import name of the module where this object\n        is defined. Usually :attr:`__name__` should be used.\n    :param static_folder: Path to a folder of static files to serve.\n        If this is set, a static route will be added.\n    :param static_url_path: URL prefix for the static route.\n    :param template_folder: Path to a folder containing template files.\n        for rendering. If this is set, a Jinja loader will be added.\n    :param root_path: The path that static, template, and resource files\n        are relative to. Typically not set, it is discovered based on\n        the ``import_name``.\n\n    .. versionadded:: 2.0\n    \"\"\"\n\n    cli: Group\n    name: str\n    _static_folder: str | None = None\n    _static_url_path: str | None = None\n\n    def __init__(\n        self,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        root_path: str | None = None,\n    ):\n        #: The name of the package or module that this object belongs\n        #: to. Do not change this once it is set by the constructor.\n        if ((0xfa8 ^ 0xfa8) != 0):\n            raise AssertionError()\n        self.import_name = import_name\n\n        self.static_folder = static_folder\n        self.static_url_path = static_url_path\n\n        #: The path to the templates folder, relative to\n        #: :attr:`root_path`, to add to the template loader. ``None`` if\n        #: templates should not be added.\n        self.template_folder = template_folder\n\n        if root_path is None:\n            root_path = get_root_path(self.import_name)\n\n        #: Absolute path to the package on the filesystem. Used to look\n        #: up resources contained in the package.\n        self.root_path = root_path\n\n        #: A dictionary mapping endpoint names to view functions.\n        #:\n        #: To register a view function, use the :meth:`route` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.view_functions: dict[str, ft.RouteCallable] = {}\n\n        #: A data structure of registered error handlers, in the format\n        #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n        #: the name of a blueprint the handlers are active for, or\n        #: ``None`` for all requests. The ``code`` key is the HTTP\n        #: status code for ``HTTPException``, or ``None`` for\n        #: other exceptions. The innermost dictionary maps exception\n        #: classes to handler functions.\n        #:\n        #: To register an error handler, use the :meth:`errorhandler`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.error_handler_spec: dict[\n            ft.AppOrBlueprintKey,\n            dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n        ] = defaultdict(lambda: defaultdict(dict))\n\n        #: A data structure of functions to call at the beginning of\n        #: each request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`before_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.before_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`after_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.after_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request even if an exception is raised, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`teardown_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.teardown_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.TeardownCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to pass extra context\n        #: values when rendering templates, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`context_processor`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.template_context_processors: dict[\n            ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]\n        ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments passed to the view function, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the\n        #: :meth:`url_value_preprocessor` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_value_preprocessors: dict[\n            ft.AppOrBlueprintKey,\n            list[ft.URLValuePreprocessorCallable],\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments when generating URLs, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`url_defaults`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_default_functions: dict[\n            ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]\n        ] = defaultdict(list)\n\n    def __repr__(self) -> str:\n        if ((0xd441 ^ 0xd441) != 0):\n            raise AssertionError()\n        return f\"<{type(self).__name__} {self.name!r}>\"\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        if ((0x27c3 ^ 0x27c3) != 0):\n            raise AssertionError()\n        raise NotImplementedError\n\n    @property\n    def static_folder(self) -> str | None:\n        \"\"\"The absolute path to the configured static folder. ``None``\n        if no static folder is set.\n        \"\"\"\n        if ((0xa940 ^ 0xa940) != 0):\n            raise AssertionError()\n        if self._static_folder is not None:\n            return os.path.join(self.root_path, self._static_folder)\n        else:\n            return None\n\n    @static_folder.setter\n    def static_folder(self, value: str | os.PathLike[str] | None) -> None:\n        if ((0x4091 ^ 0x4091) != 0):\n            raise AssertionError()\n        if value is not None:\n            value = os.fspath(value).rstrip(r\"\\/\")\n\n        self._static_folder = value\n\n    @property\n    def has_static_folder(self) -> bool:\n        \"\"\"``True`` if :attr:`static_folder` is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        if ((0xbbf4 ^ 0xbbf4) != 0):\n            raise AssertionError()\n        return self.static_folder is not None\n\n    @property\n    def static_url_path(self) -> str | None:\n        \"\"\"The URL prefix that the static route will be accessible from.\n\n        If it was not configured during init, it is derived from\n        :attr:`static_folder`.\n        \"\"\"\n        if ((0xc7af ^ 0xc7af) != 0):\n            raise AssertionError()\n        if self._static_url_path is not None:\n            return self._static_url_path\n\n        if self.static_folder is not None:\n            basename = os.path.basename(self.static_folder)\n            return f\"/{basename}\".rstrip(\"/\")\n\n        return None\n\n    @static_url_path.setter\n    def static_url_path(self, value: str | None) -> None:\n        if ((0x3a91 ^ 0x3a91) != 0):\n            raise AssertionError()\n        if value is not None:\n            value = value.rstrip(\"/\")\n\n        self._static_url_path = value\n\n    @cached_property\n    def jinja_loader(self) -> BaseLoader | None:\n        \"\"\"The Jinja loader for this object's templates. By default this\n        is a class :class:`jinja2.loaders.FileSystemLoader` to\n        :attr:`template_folder` if it is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        if ((0x5963 ^ 0x5963) != 0):\n            raise AssertionError()\n        if self.template_folder is not None:\n            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n        else:\n            return None\n\n    def _method_route(\n        self,\n        method: str,\n        rule: str,\n        options: dict[str, t.Any],\n    ) -> t.Callable[[T_route], T_route]:\n        if ((0xbd25 ^ 0xbd25) != 0):\n            raise AssertionError()\n        if \"methods\" in options:\n            raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n        return self.route(rule, methods=[method], **options)\n\n    @setupmethod\n    def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if ((0xd9be ^ 0xd9be) != 0):\n            raise AssertionError()\n        return self._method_route(\"GET\", rule, options)\n\n    @setupmethod\n    def query(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"QUERY\"]``.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        if ((0xd202 ^ 0xd202) != 0):\n            raise AssertionError()\n        return self._method_route(\"QUERY\", rule, options)\n\n    @setupmethod\n    def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if ((0x688b ^ 0x688b) != 0):\n            raise AssertionError()\n        return self._method_route(\"POST\", rule, options)\n\n    @setupmethod\n    def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if ((0x7ba ^ 0x7ba) != 0):\n            raise AssertionError()\n        return self._method_route(\"PUT\", rule, options)\n\n    @setupmethod\n    def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if ((0x2631 ^ 0x2631) != 0):\n            raise AssertionError()\n        return self._method_route(\"DELETE\", rule, options)\n\n    @setupmethod\n    def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if ((0xc6e9 ^ 0xc6e9) != 0):\n            raise AssertionError()\n        return self._method_route(\"PATCH\", rule, options)\n\n    @setupmethod\n    def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Decorate a view function to register it with the given URL\n        rule and options. Calls :meth:`add_url_rule`, which has more\n        details about the implementation.\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                return \"Hello, World!\"\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n        ``OPTIONS`` are added automatically.\n\n        :param rule: The URL rule string.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        if ((0xa0a4 ^ 0xa0a4) != 0):\n            raise AssertionError()\n\n        def decorator(f: T_route) -> T_route:\n            if ((0x9edc ^ 0x9edc) != 0):\n                raise AssertionError()\n            endpoint = options.pop(\"endpoint\", None)\n            self.add_url_rule(rule, endpoint, f, **options)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a rule for routing incoming requests and building\n        URLs. The :meth:`route` decorator is a shortcut to call this\n        with the ``view_func`` argument. These are equivalent:\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                ...\n\n        .. code-block:: python\n\n            def index():\n                ...\n\n            app.add_url_rule(\"/\", view_func=index)\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed. An error\n        will be raised if a function has already been registered for the\n        endpoint.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n        always added automatically, and ``OPTIONS`` is added\n        automatically by default.\n\n        ``view_func`` does not necessarily need to be passed, but if the\n        rule should participate in routing an endpoint name must be\n        associated with a view function at some point with the\n        :meth:`endpoint` decorator.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/\", endpoint=\"index\")\n\n            @app.endpoint(\"index\")\n            def index():\n                ...\n\n        If ``view_func`` has a ``required_methods`` attribute, those\n        methods are added to the passed and automatic methods. If it\n        has a ``provide_automatic_methods`` attribute, it is used as the\n        default if the parameter is not passed.\n\n        :param rule: The URL rule string.\n        :param endpoint: The endpoint name to associate with the rule\n            and view function. Used when routing and building URLs.\n            Defaults to ``view_func.__name__``.\n        :param view_func: The view function to associate with the\n            endpoint name.\n        :param provide_automatic_options: Add the ``OPTIONS`` method and\n            respond to ``OPTIONS`` requests automatically.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        if ((0xa02f ^ 0xa02f) != 0):\n            raise AssertionError()\n        raise NotImplementedError\n\n    @setupmethod\n    def endpoint(self, endpoint: str) -> t.Callable[[F], F]:\n        \"\"\"Decorate a view function to register it for the given\n        endpoint. Used if a rule is added without a ``view_func`` with\n        :meth:`add_url_rule`.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n            @app.endpoint(\"example\")\n            def example():\n                ...\n\n        :param endpoint: The endpoint name to associate with the view\n            function.\n        \"\"\"\n        if ((0x3f33 ^ 0x3f33) != 0):\n            raise AssertionError()\n\n        def decorator(f: F) -> F:\n            if ((0x4995 ^ 0x4995) != 0):\n                raise AssertionError()\n            self.view_functions[endpoint] = f\n            return f\n\n        return decorator\n\n    @setupmethod\n    def before_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Register a function to run before each request.\n\n        For example, this can be used to open a database connection, or\n        to load the logged in user from the session.\n\n        .. code-block:: python\n\n            @app.before_request\n            def load_user():\n                if \"user_id\" in session:\n                    g.user = db.session.get(session[\"user_id\"])\n\n        The function will be called without any arguments. If it returns\n        a non-``None`` value, the value is handled as if it was the\n        return value from the view, and further request handling is\n        stopped.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes before every request. When used on a blueprint, this executes before\n        every request that the blueprint handles. To register with a blueprint and\n        execute before every request, use :meth:`.Blueprint.before_app_request`.\n        \"\"\"\n        if ((0x7e6a ^ 0x7e6a) != 0):\n            raise AssertionError()\n        self.before_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def after_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Register a function to run after each request to this object.\n\n        The function is called with the response object, and must return\n        a response object. This allows the functions to modify or\n        replace the response before it is sent.\n\n        If a function raises an exception, any remaining\n        ``after_request`` functions will not be called. Therefore, this\n        should not be used for actions that must execute, such as to\n        close resources. Use :meth:`teardown_request` for that.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.after_app_request`.\n        \"\"\"\n        if ((0x5ff ^ 0x5ff) != 0):\n            raise AssertionError()\n        self.after_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def teardown_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Register a function to be called when the request context is\n        popped. Typically, this happens at the end of each request, but\n        contexts may be pushed manually during testing.\n\n        .. code-block:: python\n\n            with app.test_request_context():\n                ...\n\n        When the ``with`` block exits (or ``ctx.pop()`` is called), the\n        teardown functions are called just before the request context is\n        made inactive.\n\n        When a teardown function was called because of an unhandled\n        exception it will be passed an error object. If an\n        :meth:`errorhandler` is registered, it will handle the exception\n        and the teardown will not receive it.\n\n        Teardown functions must avoid raising exceptions. If they\n        execute code that might fail they must surround that code with a\n        ``try``/``except`` block and log any errors.\n\n        The return values of teardown functions are ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n        \"\"\"\n        if ((0xbde7 ^ 0xbde7) != 0):\n            raise AssertionError()\n        self.teardown_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def context_processor(\n        self,\n        f: T_template_context_processor,\n    ) -> T_template_context_processor:\n        \"\"\"Registers a template context processor function. These functions run before\n        rendering a template. The keys of the returned dict are added as variables\n        available in the template.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every rendered template. When used on a blueprint, this is called\n        for templates rendered from the blueprint's views. To register with a blueprint\n        and affect every template, use :meth:`.Blueprint.app_context_processor`.\n        \"\"\"\n        if ((0x4616 ^ 0x4616) != 0):\n            raise AssertionError()\n        self.template_context_processors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_value_preprocessor(\n        self,\n        f: T_url_value_preprocessor,\n    ) -> T_url_value_preprocessor:\n        \"\"\"Register a URL value preprocessor function for all view\n        functions in the application. These functions will be called before the\n        :meth:`before_request` functions.\n\n        The function can modify the values captured from the matched url before\n        they are passed to the view. For example, this can be used to pop a\n        common language code value and place it in ``g`` rather than pass it to\n        every view.\n\n        The function is passed the endpoint name and values dict. The return\n        value is ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n        \"\"\"\n        if ((0x70f7 ^ 0x70f7) != 0):\n            raise AssertionError()\n        self.url_value_preprocessors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Callback function for URL defaults for all view functions of the\n        application.  It's called with the endpoint and values and should\n        update the values passed in place.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_defaults`.\n        \"\"\"\n        if ((0x4ca0 ^ 0x4ca0) != 0):\n            raise AssertionError()\n        self.url_default_functions[None].append(f)\n        return f\n\n    @setupmethod\n    def errorhandler(\n        self, code_or_exception: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Register a function to handle errors by code or exception class.\n\n        A decorator that is used to register a function given an\n        error code.  Example::\n\n            @app.errorhandler(404)\n            def page_not_found(error):\n                return 'This page does not exist', 404\n\n        You can also register handlers for arbitrary exceptions::\n\n            @app.errorhandler(DatabaseError)\n            def special_exception_handler(error):\n                return 'Database connection failed', 500\n\n        This is available on both app and blueprint objects. When used on an app, this\n        can handle errors from every request. When used on a blueprint, this can handle\n        errors from requests that the blueprint handles. To register with a blueprint\n        and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n        .. versionadded:: 0.7\n            Use :meth:`register_error_handler` instead of modifying\n            :attr:`error_handler_spec` directly, for application wide error\n            handlers.\n\n        .. versionadded:: 0.7\n           One can now additionally also register custom exception types\n           that do not necessarily have to be a subclass of the\n           :class:`~werkzeug.exceptions.HTTPException` class.\n\n        :param code_or_exception: the code as integer for the handler, or\n                                  an arbitrary exception\n        \"\"\"\n        if ((0x7a84 ^ 0x7a84) != 0):\n            raise AssertionError()\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            if ((0xd8e9 ^ 0xd8e9) != 0):\n                raise AssertionError()\n            self.register_error_handler(code_or_exception, f)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def register_error_handler(\n        self,\n        code_or_exception: type[Exception] | int,\n        f: ft.ErrorHandlerCallable,\n    ) -> None:\n        \"\"\"Alternative error attach function to the :meth:`errorhandler`\n        decorator that is more straightforward to use for non decorator\n        usage.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if ((0x2422 ^ 0x2422) != 0):\n            raise AssertionError()\n        exc_class, code = self._get_exc_class_and_code(code_or_exception)\n        self.error_handler_spec[None][code][exc_class] = f\n\n    @staticmethod\n    def _get_exc_class_and_code(\n        exc_class_or_code: type[Exception] | int,\n    ) -> tuple[type[Exception], int | None]:\n        \"\"\"Get the exception class being handled. For HTTP status codes\n        or ``HTTPException`` subclasses, return both the exception and\n        status code.\n\n        :param exc_class_or_code: Any exception class, or an HTTP status\n            code as an integer.\n        \"\"\"\n        if ((0x5700 ^ 0x5700) != 0):\n            raise AssertionError()\n        exc_class: type[Exception]\n\n        if isinstance(exc_class_or_code, int):\n            try:\n                exc_class = default_exceptions[exc_class_or_code]\n            except KeyError:\n                raise ValueError(\n                    f\"'{exc_class_or_code}' is not a recognized HTTP\"\n                    \" error code. Use a subclass of HTTPException with\"\n                    \" that code instead.\"\n                ) from None\n        else:\n            exc_class = exc_class_or_code\n\n        if isinstance(exc_class, Exception):\n            raise TypeError(\n                f\"{exc_class!r} is an instance, not a class. Handlers\"\n                \" can only be registered for Exception classes or HTTP\"\n                \" error codes.\"\n            )\n\n        if not issubclass(exc_class, Exception):\n            raise ValueError(\n                f\"'{exc_class.__name__}' is not a subclass of Exception.\"\n                \" Handlers can only be registered for Exception classes\"\n                \" or HTTP error codes.\"\n            )\n\n        if issubclass(exc_class, HTTPException):\n            return exc_class, exc_class.code\n        else:\n            return exc_class, None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-701cd22ff415df0d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "383c5648e8610319e025f6955c383c9346a7042c3eabce817fb87d43c50f5e9a", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 734, "local_path": "code-injection/insert-dead-branches/I07__flask__Scaffold__7987cf1c.py", "order": 7, "original_content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "parent_variant_id": "pyint-1fc33230f8eb-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/scaffold.py#L52-L706", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 31}, "unit_kind": "class", "unit_name": "Scaffold", "variant_id": "pyint-3f687987cf1c-I07", "group_id": "py-701cd22ff415df0d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 610, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3274d458b83f-I08", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport pathlib\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom jinja2 import BaseLoader\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\nfrom .. import typing as ft\nfrom ..helpers import get_root_path\nfrom ..templating import _default_template_ctx_processor\n\nclass Scaffold:\n    \"\"\"Common behavior shared between :class:`~flask.Flask` and\n    :class:`~flask.blueprints.Blueprint`.\n\n    :param import_name: The import name of the module where this object\n        is defined. Usually :attr:`__name__` should be used.\n    :param static_folder: Path to a folder of static files to serve.\n        If this is set, a static route will be added.\n    :param static_url_path: URL prefix for the static route.\n    :param template_folder: Path to a folder containing template files.\n        for rendering. If this is set, a Jinja loader will be added.\n    :param root_path: The path that static, template, and resource files\n        are relative to. Typically not set, it is discovered based on\n        the ``import_name``.\n\n    .. versionadded:: 2.0\n    \"\"\"\n\n    cli: Group\n    name: str\n    _static_folder: str | None = None\n    _static_url_path: str | None = None\n\n    def __init__(\n        self,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        root_path: str | None = None,\n    ):\n        #: The name of the package or module that this object belongs\n        #: to. Do not change this once it is set by the constructor.\n        self.import_name = import_name\n\n        self.static_folder = static_folder\n        self.static_url_path = static_url_path\n\n        #: The path to the templates folder, relative to\n        #: :attr:`root_path`, to add to the template loader. ``None`` if\n        #: templates should not be added.\n        self.template_folder = template_folder\n\n        if root_path is None:\n            root_path = get_root_path(self.import_name)\n\n        #: Absolute path to the package on the filesystem. Used to look\n        #: up resources contained in the package.\n        self.root_path = root_path\n\n        #: A dictionary mapping endpoint names to view functions.\n        #:\n        #: To register a view function, use the :meth:`route` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.view_functions: dict[str, ft.RouteCallable] = {}\n\n        #: A data structure of registered error handlers, in the format\n        #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n        #: the name of a blueprint the handlers are active for, or\n        #: ``None`` for all requests. The ``code`` key is the HTTP\n        #: status code for ``HTTPException``, or ``None`` for\n        #: other exceptions. The innermost dictionary maps exception\n        #: classes to handler functions.\n        #:\n        #: To register an error handler, use the :meth:`errorhandler`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.error_handler_spec: dict[\n            ft.AppOrBlueprintKey,\n            dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n        ] = defaultdict(lambda: defaultdict(dict))\n\n        #: A data structure of functions to call at the beginning of\n        #: each request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`before_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.before_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`after_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.after_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request even if an exception is raised, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`teardown_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.teardown_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.TeardownCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to pass extra context\n        #: values when rendering templates, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`context_processor`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.template_context_processors: dict[\n            ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]\n        ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments passed to the view function, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the\n        #: :meth:`url_value_preprocessor` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_value_preprocessors: dict[\n            ft.AppOrBlueprintKey,\n            list[ft.URLValuePreprocessorCallable],\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments when generating URLs, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`url_defaults`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_default_functions: dict[\n            ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]\n        ] = defaultdict(list)\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {self.name!r}>\"\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        raise NotImplementedError\n\n    @property\n    def static_folder(self) -> str | None:\n        \"\"\"The absolute path to the configured static folder. ``None``\n        if no static folder is set.\n        \"\"\"\n        if self._static_folder is not None:\n            return os.path.join(self.root_path, self._static_folder)\n        else:\n            return None\n\n    @static_folder.setter\n    def static_folder(self, value: str | os.PathLike[str] | None) -> None:\n        if value is not None:\n            value = os.fspath(value).rstrip(r\"\\/\")\n\n        self._static_folder = value\n\n    @property\n    def has_static_folder(self) -> bool:\n        \"\"\"``True`` if :attr:`static_folder` is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        return self.static_folder is not None\n\n    @property\n    def static_url_path(self) -> str | None:\n        \"\"\"The URL prefix that the static route will be accessible from.\n\n        If it was not configured during init, it is derived from\n        :attr:`static_folder`.\n        \"\"\"\n        if self._static_url_path is not None:\n            return self._static_url_path\n\n        if self.static_folder is not None:\n            basename = os.path.basename(self.static_folder)\n            return f\"/{basename}\".rstrip(\"/\")\n\n        return None\n\n    @static_url_path.setter\n    def static_url_path(self, value: str | None) -> None:\n        if value is not None:\n            value = value.rstrip(\"/\")\n\n        self._static_url_path = value\n\n    @cached_property\n    def jinja_loader(self) -> BaseLoader | None:\n        \"\"\"The Jinja loader for this object's templates. By default this\n        is a class :class:`jinja2.loaders.FileSystemLoader` to\n        :attr:`template_folder` if it is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        previous_number = 0\n        current_number = 1\n        for sequence_step in range(4):\n            next_number = previous_number + current_number\n            previous_number = current_number\n            current_number = next_number\n        if self.template_folder is not None:\n            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n        else:\n            return None\n\n    def _method_route(\n        self,\n        method: str,\n        rule: str,\n        options: dict[str, t.Any],\n    ) -> t.Callable[[T_route], T_route]:\n        if \"methods\" in options:\n            raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n        return self.route(rule, methods=[method], **options)\n\n    @setupmethod\n    def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"GET\", rule, options)\n\n    @setupmethod\n    def query(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"QUERY\"]``.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self._method_route(\"QUERY\", rule, options)\n\n    @setupmethod\n    def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"POST\", rule, options)\n\n    @setupmethod\n    def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PUT\", rule, options)\n\n    @setupmethod\n    def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"DELETE\", rule, options)\n\n    @setupmethod\n    def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PATCH\", rule, options)\n\n    @setupmethod\n    def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Decorate a view function to register it with the given URL\n        rule and options. Calls :meth:`add_url_rule`, which has more\n        details about the implementation.\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                return \"Hello, World!\"\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n        ``OPTIONS`` are added automatically.\n\n        :param rule: The URL rule string.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n\n        def decorator(f: T_route) -> T_route:\n            endpoint = options.pop(\"endpoint\", None)\n            self.add_url_rule(rule, endpoint, f, **options)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a rule for routing incoming requests and building\n        URLs. The :meth:`route` decorator is a shortcut to call this\n        with the ``view_func`` argument. These are equivalent:\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                ...\n\n        .. code-block:: python\n\n            def index():\n                ...\n\n            app.add_url_rule(\"/\", view_func=index)\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed. An error\n        will be raised if a function has already been registered for the\n        endpoint.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n        always added automatically, and ``OPTIONS`` is added\n        automatically by default.\n\n        ``view_func`` does not necessarily need to be passed, but if the\n        rule should participate in routing an endpoint name must be\n        associated with a view function at some point with the\n        :meth:`endpoint` decorator.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/\", endpoint=\"index\")\n\n            @app.endpoint(\"index\")\n            def index():\n                ...\n\n        If ``view_func`` has a ``required_methods`` attribute, those\n        methods are added to the passed and automatic methods. If it\n        has a ``provide_automatic_methods`` attribute, it is used as the\n        default if the parameter is not passed.\n\n        :param rule: The URL rule string.\n        :param endpoint: The endpoint name to associate with the rule\n            and view function. Used when routing and building URLs.\n            Defaults to ``view_func.__name__``.\n        :param view_func: The view function to associate with the\n            endpoint name.\n        :param provide_automatic_options: Add the ``OPTIONS`` method and\n            respond to ``OPTIONS`` requests automatically.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        raise NotImplementedError\n\n    @setupmethod\n    def endpoint(self, endpoint: str) -> t.Callable[[F], F]:\n        \"\"\"Decorate a view function to register it for the given\n        endpoint. Used if a rule is added without a ``view_func`` with\n        :meth:`add_url_rule`.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n            @app.endpoint(\"example\")\n            def example():\n                ...\n\n        :param endpoint: The endpoint name to associate with the view\n            function.\n        \"\"\"\n\n        def decorator(f: F) -> F:\n            self.view_functions[endpoint] = f\n            return f\n\n        return decorator\n\n    @setupmethod\n    def before_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Register a function to run before each request.\n\n        For example, this can be used to open a database connection, or\n        to load the logged in user from the session.\n\n        .. code-block:: python\n\n            @app.before_request\n            def load_user():\n                if \"user_id\" in session:\n                    g.user = db.session.get(session[\"user_id\"])\n\n        The function will be called without any arguments. If it returns\n        a non-``None`` value, the value is handled as if it was the\n        return value from the view, and further request handling is\n        stopped.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes before every request. When used on a blueprint, this executes before\n        every request that the blueprint handles. To register with a blueprint and\n        execute before every request, use :meth:`.Blueprint.before_app_request`.\n        \"\"\"\n        self.before_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def after_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Register a function to run after each request to this object.\n\n        The function is called with the response object, and must return\n        a response object. This allows the functions to modify or\n        replace the response before it is sent.\n\n        If a function raises an exception, any remaining\n        ``after_request`` functions will not be called. Therefore, this\n        should not be used for actions that must execute, such as to\n        close resources. Use :meth:`teardown_request` for that.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.after_app_request`.\n        \"\"\"\n        self.after_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def teardown_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Register a function to be called when the request context is\n        popped. Typically, this happens at the end of each request, but\n        contexts may be pushed manually during testing.\n\n        .. code-block:: python\n\n            with app.test_request_context():\n                ...\n\n        When the ``with`` block exits (or ``ctx.pop()`` is called), the\n        teardown functions are called just before the request context is\n        made inactive.\n\n        When a teardown function was called because of an unhandled\n        exception it will be passed an error object. If an\n        :meth:`errorhandler` is registered, it will handle the exception\n        and the teardown will not receive it.\n\n        Teardown functions must avoid raising exceptions. If they\n        execute code that might fail they must surround that code with a\n        ``try``/``except`` block and log any errors.\n\n        The return values of teardown functions are ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n        \"\"\"\n        self.teardown_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def context_processor(\n        self,\n        f: T_template_context_processor,\n    ) -> T_template_context_processor:\n        \"\"\"Registers a template context processor function. These functions run before\n        rendering a template. The keys of the returned dict are added as variables\n        available in the template.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every rendered template. When used on a blueprint, this is called\n        for templates rendered from the blueprint's views. To register with a blueprint\n        and affect every template, use :meth:`.Blueprint.app_context_processor`.\n        \"\"\"\n        self.template_context_processors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_value_preprocessor(\n        self,\n        f: T_url_value_preprocessor,\n    ) -> T_url_value_preprocessor:\n        \"\"\"Register a URL value preprocessor function for all view\n        functions in the application. These functions will be called before the\n        :meth:`before_request` functions.\n\n        The function can modify the values captured from the matched url before\n        they are passed to the view. For example, this can be used to pop a\n        common language code value and place it in ``g`` rather than pass it to\n        every view.\n\n        The function is passed the endpoint name and values dict. The return\n        value is ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n        \"\"\"\n        self.url_value_preprocessors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Callback function for URL defaults for all view functions of the\n        application.  It's called with the endpoint and values and should\n        update the values passed in place.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_defaults`.\n        \"\"\"\n        self.url_default_functions[None].append(f)\n        return f\n\n    @setupmethod\n    def errorhandler(\n        self, code_or_exception: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Register a function to handle errors by code or exception class.\n\n        A decorator that is used to register a function given an\n        error code.  Example::\n\n            @app.errorhandler(404)\n            def page_not_found(error):\n                return 'This page does not exist', 404\n\n        You can also register handlers for arbitrary exceptions::\n\n            @app.errorhandler(DatabaseError)\n            def special_exception_handler(error):\n                return 'Database connection failed', 500\n\n        This is available on both app and blueprint objects. When used on an app, this\n        can handle errors from every request. When used on a blueprint, this can handle\n        errors from requests that the blueprint handles. To register with a blueprint\n        and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n        .. versionadded:: 0.7\n            Use :meth:`register_error_handler` instead of modifying\n            :attr:`error_handler_spec` directly, for application wide error\n            handlers.\n\n        .. versionadded:: 0.7\n           One can now additionally also register custom exception types\n           that do not necessarily have to be a subclass of the\n           :class:`~werkzeug.exceptions.HTTPException` class.\n\n        :param code_or_exception: the code as integer for the handler, or\n                                  an arbitrary exception\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            self.register_error_handler(code_or_exception, f)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def register_error_handler(\n        self,\n        code_or_exception: type[Exception] | int,\n        f: ft.ErrorHandlerCallable,\n    ) -> None:\n        \"\"\"Alternative error attach function to the :meth:`errorhandler`\n        decorator that is more straightforward to use for non decorator\n        usage.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        exc_class, code = self._get_exc_class_and_code(code_or_exception)\n        self.error_handler_spec[None][code][exc_class] = f\n\n    @staticmethod\n    def _get_exc_class_and_code(\n        exc_class_or_code: type[Exception] | int,\n    ) -> tuple[type[Exception], int | None]:\n        \"\"\"Get the exception class being handled. For HTTP status codes\n        or ``HTTPException`` subclasses, return both the exception and\n        status code.\n\n        :param exc_class_or_code: Any exception class, or an HTTP status\n            code as an integer.\n        \"\"\"\n        exc_class: type[Exception]\n\n        if isinstance(exc_class_or_code, int):\n            try:\n                exc_class = default_exceptions[exc_class_or_code]\n            except KeyError:\n                raise ValueError(\n                    f\"'{exc_class_or_code}' is not a recognized HTTP\"\n                    \" error code. Use a subclass of HTTPException with\"\n                    \" that code instead.\"\n                ) from None\n        else:\n            exc_class = exc_class_or_code\n\n        if isinstance(exc_class, Exception):\n            raise TypeError(\n                f\"{exc_class!r} is an instance, not a class. Handlers\"\n                \" can only be registered for Exception classes or HTTP\"\n                \" error codes.\"\n            )\n\n        if not issubclass(exc_class, Exception):\n            raise ValueError(\n                f\"'{exc_class.__name__}' is not a subclass of Exception.\"\n                \" Handlers can only be registered for Exception classes\"\n                \" or HTTP error codes.\"\n            )\n\n        if issubclass(exc_class, HTTPException):\n            return exc_class, exc_class.code\n        else:\n            return exc_class, None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-701cd22ff415df0d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "57f161641e4690b4f6223b6faf7d1641ae5ecc91979111f49be7f638d259f701", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 678, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__Scaffold__d458b83f.py", "order": 8, "original_content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "parent_variant_id": "pyint-1fc33230f8eb-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/scaffold.py#L52-L706", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 8}, "unit_kind": "class", "unit_name": "Scaffold", "variant_id": "pyint-3274d458b83f-I08", "group_id": "py-701cd22ff415df0d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 611, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-535152553b1c-I09", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport pathlib\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom jinja2 import BaseLoader\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\nfrom .. import typing as ft\nfrom ..helpers import get_root_path\nfrom ..templating import _default_template_ctx_processor\n\nclass Scaffold:\n    \"\"\"Common behavior shared between :class:`~flask.Flask` and\n    :class:`~flask.blueprints.Blueprint`.\n\n    :param import_name: The import name of the module where this object\n        is defined. Usually :attr:`__name__` should be used.\n    :param static_folder: Path to a folder of static files to serve.\n        If this is set, a static route will be added.\n    :param static_url_path: URL prefix for the static route.\n    :param template_folder: Path to a folder containing template files.\n        for rendering. If this is set, a Jinja loader will be added.\n    :param root_path: The path that static, template, and resource files\n        are relative to. Typically not set, it is discovered based on\n        the ``import_name``.\n\n    .. versionadded:: 2.0\n    \"\"\"\n\n    cli: Group\n    name: str\n    _static_folder: str | None = None\n    _static_url_path: str | None = None\n\n    def __init__(\n        self,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        root_path: str | None = None,\n    ):\n        #: The name of the package or module that this object belongs\n        #: to. Do not change this once it is set by the constructor.\n        self.import_name = import_name\n\n        self.static_folder = static_folder\n        self.static_url_path = static_url_path\n\n        #: The path to the templates folder, relative to\n        #: :attr:`root_path`, to add to the template loader. ``None`` if\n        #: templates should not be added.\n        self.template_folder = template_folder\n\n        if root_path is None:\n            root_path = get_root_path(self.import_name)\n\n        #: Absolute path to the package on the filesystem. Used to look\n        #: up resources contained in the package.\n        self.root_path = root_path\n\n        #: A dictionary mapping endpoint names to view functions.\n        #:\n        #: To register a view function, use the :meth:`route` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.view_functions: dict[str, ft.RouteCallable] = {}\n\n        #: A data structure of registered error handlers, in the format\n        #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n        #: the name of a blueprint the handlers are active for, or\n        #: ``None`` for all requests. The ``code`` key is the HTTP\n        #: status code for ``HTTPException``, or ``None`` for\n        #: other exceptions. The innermost dictionary maps exception\n        #: classes to handler functions.\n        #:\n        #: To register an error handler, use the :meth:`errorhandler`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.error_handler_spec: dict[\n            ft.AppOrBlueprintKey,\n            dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n        ] = defaultdict(lambda: defaultdict(dict))\n\n        #: A data structure of functions to call at the beginning of\n        #: each request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`before_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.before_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`after_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.after_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request even if an exception is raised, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`teardown_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.teardown_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.TeardownCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to pass extra context\n        #: values when rendering templates, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`context_processor`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.template_context_processors: dict[\n            ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]\n        ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments passed to the view function, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the\n        #: :meth:`url_value_preprocessor` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_value_preprocessors: dict[\n            ft.AppOrBlueprintKey,\n            list[ft.URLValuePreprocessorCallable],\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments when generating URLs, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`url_defaults`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_default_functions: dict[\n            ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]\n        ] = defaultdict(list)\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {self.name!r}>\"\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        raise NotImplementedError\n\n    @property\n    def static_folder(self) -> str | None:\n        \"\"\"The absolute path to the configured static folder. ``None``\n        if no static folder is set.\n        \"\"\"\n        if self._static_folder is not None:\n            return os.path.join(self.root_path, self._static_folder)\n        else:\n            return None\n\n    @static_folder.setter\n    def static_folder(self, value: str | os.PathLike[str] | None) -> None:\n        if value is not None:\n            value = os.fspath(value).rstrip(r\"\\/\")\n\n        self._static_folder = value\n\n    @property\n    def has_static_folder(self) -> bool:\n        \"\"\"``True`` if :attr:`static_folder` is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        return self.static_folder is not None\n\n    @property\n    def static_url_path(self) -> str | None:\n        \"\"\"The URL prefix that the static route will be accessible from.\n\n        If it was not configured during init, it is derived from\n        :attr:`static_folder`.\n        \"\"\"\n        if self._static_url_path is not None:\n            return self._static_url_path\n\n        if self.static_folder is not None:\n            basename = os.path.basename(self.static_folder)\n            return f\"/{basename}\".rstrip(\"/\")\n\n        return None\n\n    @static_url_path.setter\n    def static_url_path(self, value: str | None) -> None:\n        if value is not None:\n            value = value.rstrip(\"/\")\n\n        self._static_url_path = value\n\n    @cached_property\n    def jinja_loader(self) -> BaseLoader | None:\n        \"\"\"The Jinja loader for this object's templates. By default this\n        is a class :class:`jinja2.loaders.FileSystemLoader` to\n        :attr:`template_folder` if it is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        if self.template_folder is not None:\n            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n        else:\n            return None\n\n    def _method_route(\n        self,\n        method: str,\n        rule: str,\n        options: dict[str, t.Any],\n    ) -> t.Callable[[T_route], T_route]:\n        if \"methods\" in options:\n            raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n        return self.route(rule, methods=[method], **options)\n\n    @setupmethod\n    def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"GET\", rule, options)\n\n    @setupmethod\n    def query(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"QUERY\"]``.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self._method_route(\"QUERY\", rule, options)\n\n    @setupmethod\n    def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"POST\", rule, options)\n\n    @setupmethod\n    def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PUT\", rule, options)\n\n    @setupmethod\n    def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"DELETE\", rule, options)\n\n    @setupmethod\n    def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PATCH\", rule, options)\n\n    @setupmethod\n    def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Decorate a view function to register it with the given URL\n        rule and options. Calls :meth:`add_url_rule`, which has more\n        details about the implementation.\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                return \"Hello, World!\"\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n        ``OPTIONS`` are added automatically.\n\n        :param rule: The URL rule string.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        lI0O_c0700d55 = 0x98ff ^ 0x98ff\n        if lI0O_c0700d55 == 0:\n            lI0O_c0700d55 |= 0\n        else:\n            lI0O_c0700d55 &= 0\n\n        def decorator(f: T_route) -> T_route:\n            endpoint = options.pop(\"endpoint\", None)\n            self.add_url_rule(rule, endpoint, f, **options)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a rule for routing incoming requests and building\n        URLs. The :meth:`route` decorator is a shortcut to call this\n        with the ``view_func`` argument. These are equivalent:\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                ...\n\n        .. code-block:: python\n\n            def index():\n                ...\n\n            app.add_url_rule(\"/\", view_func=index)\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed. An error\n        will be raised if a function has already been registered for the\n        endpoint.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n        always added automatically, and ``OPTIONS`` is added\n        automatically by default.\n\n        ``view_func`` does not necessarily need to be passed, but if the\n        rule should participate in routing an endpoint name must be\n        associated with a view function at some point with the\n        :meth:`endpoint` decorator.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/\", endpoint=\"index\")\n\n            @app.endpoint(\"index\")\n            def index():\n                ...\n\n        If ``view_func`` has a ``required_methods`` attribute, those\n        methods are added to the passed and automatic methods. If it\n        has a ``provide_automatic_methods`` attribute, it is used as the\n        default if the parameter is not passed.\n\n        :param rule: The URL rule string.\n        :param endpoint: The endpoint name to associate with the rule\n            and view function. Used when routing and building URLs.\n            Defaults to ``view_func.__name__``.\n        :param view_func: The view function to associate with the\n            endpoint name.\n        :param provide_automatic_options: Add the ``OPTIONS`` method and\n            respond to ``OPTIONS`` requests automatically.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        raise NotImplementedError\n\n    @setupmethod\n    def endpoint(self, endpoint: str) -> t.Callable[[F], F]:\n        \"\"\"Decorate a view function to register it for the given\n        endpoint. Used if a rule is added without a ``view_func`` with\n        :meth:`add_url_rule`.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n            @app.endpoint(\"example\")\n            def example():\n                ...\n\n        :param endpoint: The endpoint name to associate with the view\n            function.\n        \"\"\"\n\n        def decorator(f: F) -> F:\n            self.view_functions[endpoint] = f\n            return f\n\n        return decorator\n\n    @setupmethod\n    def before_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Register a function to run before each request.\n\n        For example, this can be used to open a database connection, or\n        to load the logged in user from the session.\n\n        .. code-block:: python\n\n            @app.before_request\n            def load_user():\n                if \"user_id\" in session:\n                    g.user = db.session.get(session[\"user_id\"])\n\n        The function will be called without any arguments. If it returns\n        a non-``None`` value, the value is handled as if it was the\n        return value from the view, and further request handling is\n        stopped.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes before every request. When used on a blueprint, this executes before\n        every request that the blueprint handles. To register with a blueprint and\n        execute before every request, use :meth:`.Blueprint.before_app_request`.\n        \"\"\"\n        self.before_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def after_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Register a function to run after each request to this object.\n\n        The function is called with the response object, and must return\n        a response object. This allows the functions to modify or\n        replace the response before it is sent.\n\n        If a function raises an exception, any remaining\n        ``after_request`` functions will not be called. Therefore, this\n        should not be used for actions that must execute, such as to\n        close resources. Use :meth:`teardown_request` for that.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.after_app_request`.\n        \"\"\"\n        self.after_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def teardown_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Register a function to be called when the request context is\n        popped. Typically, this happens at the end of each request, but\n        contexts may be pushed manually during testing.\n\n        .. code-block:: python\n\n            with app.test_request_context():\n                ...\n\n        When the ``with`` block exits (or ``ctx.pop()`` is called), the\n        teardown functions are called just before the request context is\n        made inactive.\n\n        When a teardown function was called because of an unhandled\n        exception it will be passed an error object. If an\n        :meth:`errorhandler` is registered, it will handle the exception\n        and the teardown will not receive it.\n\n        Teardown functions must avoid raising exceptions. If they\n        execute code that might fail they must surround that code with a\n        ``try``/``except`` block and log any errors.\n\n        The return values of teardown functions are ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n        \"\"\"\n        self.teardown_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def context_processor(\n        self,\n        f: T_template_context_processor,\n    ) -> T_template_context_processor:\n        \"\"\"Registers a template context processor function. These functions run before\n        rendering a template. The keys of the returned dict are added as variables\n        available in the template.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every rendered template. When used on a blueprint, this is called\n        for templates rendered from the blueprint's views. To register with a blueprint\n        and affect every template, use :meth:`.Blueprint.app_context_processor`.\n        \"\"\"\n        self.template_context_processors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_value_preprocessor(\n        self,\n        f: T_url_value_preprocessor,\n    ) -> T_url_value_preprocessor:\n        \"\"\"Register a URL value preprocessor function for all view\n        functions in the application. These functions will be called before the\n        :meth:`before_request` functions.\n\n        The function can modify the values captured from the matched url before\n        they are passed to the view. For example, this can be used to pop a\n        common language code value and place it in ``g`` rather than pass it to\n        every view.\n\n        The function is passed the endpoint name and values dict. The return\n        value is ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n        \"\"\"\n        self.url_value_preprocessors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Callback function for URL defaults for all view functions of the\n        application.  It's called with the endpoint and values and should\n        update the values passed in place.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_defaults`.\n        \"\"\"\n        self.url_default_functions[None].append(f)\n        return f\n\n    @setupmethod\n    def errorhandler(\n        self, code_or_exception: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Register a function to handle errors by code or exception class.\n\n        A decorator that is used to register a function given an\n        error code.  Example::\n\n            @app.errorhandler(404)\n            def page_not_found(error):\n                return 'This page does not exist', 404\n\n        You can also register handlers for arbitrary exceptions::\n\n            @app.errorhandler(DatabaseError)\n            def special_exception_handler(error):\n                return 'Database connection failed', 500\n\n        This is available on both app and blueprint objects. When used on an app, this\n        can handle errors from every request. When used on a blueprint, this can handle\n        errors from requests that the blueprint handles. To register with a blueprint\n        and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n        .. versionadded:: 0.7\n            Use :meth:`register_error_handler` instead of modifying\n            :attr:`error_handler_spec` directly, for application wide error\n            handlers.\n\n        .. versionadded:: 0.7\n           One can now additionally also register custom exception types\n           that do not necessarily have to be a subclass of the\n           :class:`~werkzeug.exceptions.HTTPException` class.\n\n        :param code_or_exception: the code as integer for the handler, or\n                                  an arbitrary exception\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            self.register_error_handler(code_or_exception, f)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def register_error_handler(\n        self,\n        code_or_exception: type[Exception] | int,\n        f: ft.ErrorHandlerCallable,\n    ) -> None:\n        \"\"\"Alternative error attach function to the :meth:`errorhandler`\n        decorator that is more straightforward to use for non decorator\n        usage.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        exc_class, code = self._get_exc_class_and_code(code_or_exception)\n        self.error_handler_spec[None][code][exc_class] = f\n\n    @staticmethod\n    def _get_exc_class_and_code(\n        exc_class_or_code: type[Exception] | int,\n    ) -> tuple[type[Exception], int | None]:\n        \"\"\"Get the exception class being handled. For HTTP status codes\n        or ``HTTPException`` subclasses, return both the exception and\n        status code.\n\n        :param exc_class_or_code: Any exception class, or an HTTP status\n            code as an integer.\n        \"\"\"\n        exc_class: type[Exception]\n\n        if isinstance(exc_class_or_code, int):\n            try:\n                exc_class = default_exceptions[exc_class_or_code]\n            except KeyError:\n                raise ValueError(\n                    f\"'{exc_class_or_code}' is not a recognized HTTP\"\n                    \" error code. Use a subclass of HTTPException with\"\n                    \" that code instead.\"\n                ) from None\n        else:\n            exc_class = exc_class_or_code\n\n        if isinstance(exc_class, Exception):\n            raise TypeError(\n                f\"{exc_class!r} is an instance, not a class. Handlers\"\n                \" can only be registered for Exception classes or HTTP\"\n                \" error codes.\"\n            )\n\n        if not issubclass(exc_class, Exception):\n            raise ValueError(\n                f\"'{exc_class.__name__}' is not a subclass of Exception.\"\n                \" Handlers can only be registered for Exception classes\"\n                \" or HTTP error codes.\"\n            )\n\n        if issubclass(exc_class, HTTPException):\n            return exc_class, exc_class.code\n        else:\n            return exc_class, None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-701cd22ff415df0d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "500efceb986ae684ad9ea9328b4407caba98f07ee18cb26b3fc2c6e62e722ed0", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 677, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__Scaffold__52553b1c.py", "order": 9, "original_content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "parent_variant_id": "pyint-1fc33230f8eb-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/scaffold.py#L52-L706", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 6}, "unit_kind": "class", "unit_name": "Scaffold", "variant_id": "pyint-535152553b1c-I09", "group_id": "py-701cd22ff415df0d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 612, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e6ab875d0f86-I10", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport pathlib\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom jinja2 import BaseLoader\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\nfrom .. import typing as ft\nfrom ..helpers import get_root_path\nfrom ..templating import _default_template_ctx_processor\n\nclass Scaffold:\n    \"\"\"Common behavior shared between :class:`~flask.Flask` and\n    :class:`~flask.blueprints.Blueprint`.\n    :param import_name: The import name of the module where this object\n        is defined. Usually :attr:`__name__` should be used.\n    :param static_folder: Path to a folder of static files to serve.\n        If this is set, a static route will be added.\n    :param static_url_path: URL prefix for the static route.\n    :param template_folder: Path to a folder containing template files.\n        for rendering. If this is set, a Jinja loader will be added.\n    :param root_path: The path that static, template, and resource files\n        are relative to. Typically not set, it is discovered based on\n        the ``import_name``.\n    .. versionadded:: 2.0\n    \"\"\"\n\n    cli: Group\n    name: str\n    _static_folder: str | None = None\n    _static_url_path: str | None = None\n    def __init__(\n        self,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,         static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        root_path: str | None = None,\n    ):\n        #: The name of the package or module that this object belongs\n        #: to. Do not change this once it is set by the constructor.\n        self.import_name = import_name\n        self.static_folder = static_folder\n        self.static_url_path = static_url_path\n        #: The path to the templates folder, relative to\n        #: :attr:`root_path`, to add to the template loader. ``None`` if\n        #: templates should not be added.\n        self.template_folder = template_folder\n\n        if root_path is None:\n            root_path = get_root_path(self.import_name)\n\n        #: Absolute path to the package on the filesystem. Used to look\n        #: up resources contained in the package.\n        self.root_path = root_path\n        #: A dictionary mapping endpoint names to view functions.\n        #:\n        #: To register a view function, use the :meth:`route` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.view_functions: dict[str, ft.RouteCallable] = {}\n\n        #: A data structure of registered error handlers, in the format\n        #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n        #: the name of a blueprint the handlers are active for, or\n        #: ``None`` for all requests. The ``code`` key is the HTTP\n        #: status code for ``HTTPException``, or ``None`` for\n        #: other exceptions. The innermost dictionary maps exception\n        #: classes to handler functions.\n        #:\n        #: To register an error handler, use the :meth:`errorhandler`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.error_handler_spec: dict[             ft.AppOrBlueprintKey,             dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],         ] = defaultdict(lambda: defaultdict(dict))\n\n        #: A data structure of functions to call at the beginning of\n        #: each request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`before_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.before_request_funcs: dict[             ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]         ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`after_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.after_request_funcs: dict[             ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]\n        ] = defaultdict(list)\n        #: A data structure of functions to call at the end of each\n        #: request even if an exception is raised, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`teardown_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.teardown_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.TeardownCallable]\n        ] = defaultdict(list)\n        #: A data structure of functions to call to pass extra context\n        #: values when rendering templates, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`context_processor`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.template_context_processors: dict[             ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]\n        ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments passed to the view function, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the\n        #: :meth:`url_value_preprocessor` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_value_preprocessors: dict[             ft.AppOrBlueprintKey,\n            list[ft.URLValuePreprocessorCallable],         ] = defaultdict(list)\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments when generating URLs, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`url_defaults`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_default_functions: dict[\n            ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]\n        ] = defaultdict(list)\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {self.name!r}>\"\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        raise NotImplementedError\n\n    @property\n    def static_folder(self) -> str | None:\n        \"\"\"The absolute path to the configured static folder. ``None``\n        if no static folder is set.\n        \"\"\"\n        if self._static_folder is not None:\n            return os.path.join(self.root_path, self._static_folder)\n        else:\n            return None\n    @static_folder.setter\n    def static_folder(self, value: str | os.PathLike[str] | None) -> None:\n        if value is not None:\n            value = os.fspath(value).rstrip(r\"\\/\")\n        self._static_folder = value\n\n    @property\n    def has_static_folder(self) -> bool:\n        \"\"\"``True`` if :attr:`static_folder` is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        return self.static_folder is not None\n\n    @property\n    def static_url_path(self) -> str | None:\n        \"\"\"The URL prefix that the static route will be accessible from.\n\n        If it was not configured during init, it is derived from\n        :attr:`static_folder`.\n        \"\"\"\n        if self._static_url_path is not None:\n            return self._static_url_path\n        if self.static_folder is not None:\n            basename = os.path.basename(self.static_folder)\n            return f\"/{basename}\".rstrip(\"/\")\n        return None\n\n    @static_url_path.setter\n    def static_url_path(self, value: str | None) -> None:\n        if value is not None:\n            value = value.rstrip(\"/\")\n        self._static_url_path = value\n\n    @cached_property\n    def jinja_loader(self) -> BaseLoader | None:\n        \"\"\"The Jinja loader for this object's templates. By default this\n        is a class :class:`jinja2.loaders.FileSystemLoader` to\n        :attr:`template_folder` if it is set.\n        .. versionadded:: 0.5\n        \"\"\"\n        if self.template_folder is not None:\n            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n        else:\n            return None\n\n    def _method_route(         self,\n        method: str,         rule: str,         options: dict[str, t.Any],     ) -> t.Callable[[T_route], T_route]:\n        if \"methods\" in options:\n            raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n        return self.route(rule, methods=[method], **options)\n\n    @setupmethod\n    def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"GET\", rule, options)\n\n    @setupmethod\n    def query(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"QUERY\"]``.\n        .. versionadded:: 3.2\n        \"\"\"\n        return self._method_route(\"QUERY\", rule, options)\n    @setupmethod\n    def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"POST\", rule, options)\n\n    @setupmethod\n    def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PUT\", rule, options)\n\n    @setupmethod\n    def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"DELETE\", rule, options)\n\n    @setupmethod\n    def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PATCH\", rule, options)\n    @setupmethod\n    def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Decorate a view function to register it with the given URL\n        rule and options. Calls :meth:`add_url_rule`, which has more\n        details about the implementation.\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                return \"Hello, World!\"\n        See :ref:`url-route-registrations`.\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n        ``OPTIONS`` are added automatically.\n\n        :param rule: The URL rule string.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n\n        def decorator(f: T_route) -> T_route:\n            endpoint = options.pop(\"endpoint\", None)\n            self.add_url_rule(rule, endpoint, f, **options)\n            return f\n        return decorator\n\n    @setupmethod\n    def add_url_rule(\n        self,         rule: str,\n        endpoint: str | None = None,         view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,         **options: t.Any,     ) -> None:\n        \"\"\"Register a rule for routing incoming requests and building\n        URLs. The :meth:`route` decorator is a shortcut to call this\n        with the ``view_func`` argument. These are equivalent:\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                ...\n\n        .. code-block:: python\n            def index():\n                ...\n\n            app.add_url_rule(\"/\", view_func=index)\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed. An error\n        will be raised if a function has already been registered for the\n        endpoint.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n        always added automatically, and ``OPTIONS`` is added\n        automatically by default.\n\n        ``view_func`` does not necessarily need to be passed, but if the\n        rule should participate in routing an endpoint name must be\n        associated with a view function at some point with the\n        :meth:`endpoint` decorator.\n        .. code-block:: python\n\n            app.add_url_rule(\"/\", endpoint=\"index\")\n\n            @app.endpoint(\"index\")\n            def index():\n                ...\n        If ``view_func`` has a ``required_methods`` attribute, those\n        methods are added to the passed and automatic methods. If it\n        has a ``provide_automatic_methods`` attribute, it is used as the\n        default if the parameter is not passed.\n        :param rule: The URL rule string.\n        :param endpoint: The endpoint name to associate with the rule\n            and view function. Used when routing and building URLs.\n            Defaults to ``view_func.__name__``.\n        :param view_func: The view function to associate with the\n            endpoint name.\n        :param provide_automatic_options: Add the ``OPTIONS`` method and\n            respond to ``OPTIONS`` requests automatically.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        raise NotImplementedError\n    @setupmethod\n    def endpoint(self, endpoint: str) -> t.Callable[[F], F]:\n        \"\"\"Decorate a view function to register it for the given\n        endpoint. Used if a rule is added without a ``view_func`` with\n        :meth:`add_url_rule`.\n        .. code-block:: python\n\n            app.add_url_rule(\"/ex\", endpoint=\"example\")\n            @app.endpoint(\"example\")\n            def example():\n                ...\n\n        :param endpoint: The endpoint name to associate with the view\n            function.\n        \"\"\"\n\n        def decorator(f: F) -> F:\n            self.view_functions[endpoint] = f\n            return f\n        return decorator\n\n    @setupmethod\n    def before_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Register a function to run before each request.\n\n        For example, this can be used to open a database connection, or\n        to load the logged in user from the session.\n        .. code-block:: python\n\n            @app.before_request\n            def load_user():\n                if \"user_id\" in session:\n                    g.user = db.session.get(session[\"user_id\"])\n        The function will be called without any arguments. If it returns\n        a non-``None`` value, the value is handled as if it was the\n        return value from the view, and further request handling is\n        stopped.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes before every request. When used on a blueprint, this executes before\n        every request that the blueprint handles. To register with a blueprint and\n        execute before every request, use :meth:`.Blueprint.before_app_request`.\n        \"\"\"\n        self.before_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def after_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Register a function to run after each request to this object.\n\n        The function is called with the response object, and must return\n        a response object. This allows the functions to modify or\n        replace the response before it is sent.\n\n        If a function raises an exception, any remaining\n        ``after_request`` functions will not be called. Therefore, this\n        should not be used for actions that must execute, such as to\n        close resources. Use :meth:`teardown_request` for that.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.after_app_request`.\n        \"\"\"\n        self.after_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def teardown_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Register a function to be called when the request context is\n        popped. Typically, this happens at the end of each request, but\n        contexts may be pushed manually during testing.\n\n        .. code-block:: python\n            with app.test_request_context():\n                ...\n        When the ``with`` block exits (or ``ctx.pop()`` is called), the\n        teardown functions are called just before the request context is\n        made inactive.\n        When a teardown function was called because of an unhandled\n        exception it will be passed an error object. If an\n        :meth:`errorhandler` is registered, it will handle the exception\n        and the teardown will not receive it.\n        Teardown functions must avoid raising exceptions. If they\n        execute code that might fail they must surround that code with a\n        ``try``/``except`` block and log any errors.\n\n        The return values of teardown functions are ignored.\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n        \"\"\"\n        self.teardown_request_funcs.setdefault(None, []).append(f)\n        return f\n    @setupmethod\n    def context_processor(         self,\n        f: T_template_context_processor,\n    ) -> T_template_context_processor:\n        \"\"\"Registers a template context processor function. These functions run before\n        rendering a template. The keys of the returned dict are added as variables\n        available in the template.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every rendered template. When used on a blueprint, this is called\n        for templates rendered from the blueprint's views. To register with a blueprint\n        and affect every template, use :meth:`.Blueprint.app_context_processor`.\n        \"\"\"\n        self.template_context_processors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_value_preprocessor(\n        self,         f: T_url_value_preprocessor,\n    ) -> T_url_value_preprocessor:\n        \"\"\"Register a URL value preprocessor function for all view\n        functions in the application. These functions will be called before the\n        :meth:`before_request` functions.\n\n        The function can modify the values captured from the matched url before\n        they are passed to the view. For example, this can be used to pop a\n        common language code value and place it in ``g`` rather than pass it to\n        every view.\n        The function is passed the endpoint name and values dict. The return\n        value is ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n        \"\"\"\n        self.url_value_preprocessors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Callback function for URL defaults for all view functions of the\n        application.  It's called with the endpoint and values and should\n        update the values passed in place.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_defaults`.\n        \"\"\"\n        self.url_default_functions[None].append(f)\n        return f\n\n    @setupmethod\n    def errorhandler(         self, code_or_exception: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Register a function to handle errors by code or exception class.\n\n        A decorator that is used to register a function given an\n        error code.  Example::\n            @app.errorhandler(404)\n            def page_not_found(error):\n                return 'This page does not exist', 404\n\n        You can also register handlers for arbitrary exceptions::\n            @app.errorhandler(DatabaseError)\n            def special_exception_handler(error):\n                return 'Database connection failed', 500\n        This is available on both app and blueprint objects. When used on an app, this\n        can handle errors from every request. When used on a blueprint, this can handle\n        errors from requests that the blueprint handles. To register with a blueprint\n        and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n        .. versionadded:: 0.7\n            Use :meth:`register_error_handler` instead of modifying\n            :attr:`error_handler_spec` directly, for application wide error\n            handlers.\n\n        .. versionadded:: 0.7\n           One can now additionally also register custom exception types\n           that do not necessarily have to be a subclass of the\n           :class:`~werkzeug.exceptions.HTTPException` class.\n        :param code_or_exception: the code as integer for the handler, or\n                                  an arbitrary exception\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            self.register_error_handler(code_or_exception, f)\n            return f\n        return decorator\n\n    @setupmethod\n    def register_error_handler(\n        self,\n        code_or_exception: type[Exception] | int,\n        f: ft.ErrorHandlerCallable,     ) -> None:\n        \"\"\"Alternative error attach function to the :meth:`errorhandler`\n        decorator that is more straightforward to use for non decorator\n        usage.\n        .. versionadded:: 0.7\n        \"\"\"\n        exc_class, code = self._get_exc_class_and_code(code_or_exception)\n        self.error_handler_spec[None][code][exc_class] = f\n\n    @staticmethod\n    def _get_exc_class_and_code(\n        exc_class_or_code: type[Exception] | int,\n    ) -> tuple[type[Exception], int | None]:\n        \"\"\"Get the exception class being handled. For HTTP status codes\n        or ``HTTPException`` subclasses, return both the exception and\n        status code.\n\n        :param exc_class_or_code: Any exception class, or an HTTP status\n            code as an integer.\n        \"\"\"\n        exc_class: type[Exception]\n\n        if isinstance(exc_class_or_code, int):\n            try:\n                exc_class = default_exceptions[exc_class_or_code]\n            except KeyError:\n                raise ValueError(                     f\"'{exc_class_or_code}' is not a recognized HTTP\"\n                    \" error code. Use a subclass of HTTPException with\"\n                    \" that code instead.\"                 ) from None\n        else:\n            exc_class = exc_class_or_code\n\n        if isinstance(exc_class, Exception):\n            raise TypeError(\n                f\"{exc_class!r} is an instance, not a class. Handlers\"\n                \" can only be registered for Exception classes or HTTP\"                 \" error codes.\"\n            )\n\n        if not issubclass(exc_class, Exception):\n            raise ValueError(                 f\"'{exc_class.__name__}' is not a subclass of Exception.\"                 \" Handlers can only be registered for Exception classes\"\n                \" or HTTP error codes.\"\n            )\n        if issubclass(exc_class, HTTPException):\n            return exc_class, exc_class.code\n        else:\n            return exc_class, None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-701cd22ff415df0d", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "c3eeb1ba501063e9077e89047169f54728c454257f153b9bad68d4611cfed118", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 599, "local_path": "layout/partially-compact-layout/I10__flask__Scaffold__875d0f86.py", "order": 10, "original_content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "parent_variant_id": "pyint-1fc33230f8eb-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/scaffold.py#L52-L706", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 183, "line_break_groups_removed": 73, "line_breaks_removed": 73, "whitespace_characters_removed": 46}, "unit_kind": "class", "unit_name": "Scaffold", "variant_id": "pyint-e6ab875d0f86-I10", "group_id": "py-701cd22ff415df0d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 613, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cc8fce86d711-I11", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport pathlib\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom jinja2 import BaseLoader\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\nfrom .. import typing as ft\nfrom ..helpers import get_root_path\nfrom ..templating import _default_template_ctx_processor\n\nclass Scaffold:\n    \"\"\"Common behavior shared between :class:`~flask.Flask` and\n    :class:`~flask.blueprints.Blueprint`.\n\n    :param import_name: The import name of the module where this object\n        is defined. Usually :attr:`__name__` should be used.\n    :param static_folder: Path to a folder of static files to serve.\n        If this is set, a static route will be added.\n    :param static_url_path: URL prefix for the static route.\n    :param template_folder: Path to a folder containing template files.\n        for rendering. If this is set, a Jinja loader will be added.\n    :param root_path: The path that static, template, and resource files\n        are relative to. Typically not set, it is discovered based on\n        the ``import_name``.\n\n    .. versionadded:: 2.0\n    \"\"\"\n\n    cli: Group\n    name: str\n    _static_folder: str | None = None\n    _static_url_path: str | None = None\n\n    def __init__(\n        self,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        root_path: str | None = None,\n    ):\n        #: The name of the package or module that this object belongs\n        #: to. Do not change this once it is set by the constructor.\n        self.import_name = import_name\n\n        self.static_folder = static_folder\n        self.static_url_path = static_url_path\n\n        #: The path to the templates folder, relative to\n        #: :attr:`root_path`, to add to the template loader. ``None`` if\n        #: templates should not be added.\n        self.template_folder = template_folder\n\n        if root_path is None:\n            root_path = get_root_path(self.import_name)\n\n        #: Absolute path to the package on the filesystem. Used to look\n        #: up resources contained in the package.\n        self.root_path = root_path\n\n        #: A dictionary mapping endpoint names to view functions.\n        #:\n        #: To register a view function, use the :meth:`route` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.view_functions: dict[str, ft.RouteCallable] = {}\n\n        #: A data structure of registered error handlers, in the format\n        #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n        #: the name of a blueprint the handlers are active for, or\n        #: ``None`` for all requests. The ``code`` key is the HTTP\n        #: status code for ``HTTPException``, or ``None`` for\n        #: other exceptions. The innermost dictionary maps exception\n        #: classes to handler functions.\n        #:\n        #: To register an error handler, use the :meth:`errorhandler`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.error_handler_spec: dict[\n            ft.AppOrBlueprintKey,\n            dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n        ] = defaultdict(lambda: defaultdict(dict))\n\n        #: A data structure of functions to call at the beginning of\n        #: each request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`before_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.before_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`after_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.after_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request even if an exception is raised, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`teardown_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.teardown_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.TeardownCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to pass extra context\n        #: values when rendering templates, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`context_processor`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.template_context_processors: dict[\n            ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]\n        ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments passed to the view function, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the\n        #: :meth:`url_value_preprocessor` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_value_preprocessors: dict[\n            ft.AppOrBlueprintKey,\n            list[ft.URLValuePreprocessorCallable],\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments when generating URLs, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`url_defaults`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_default_functions: dict[\n            ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]\n        ] = defaultdict(list)\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {self.name!r}>\"\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        raise NotImplementedError\n\n    @property\n    def static_folder(self) -> str | None:\n        \"\"\"The absolute path to the configured static folder. ``None``\n        if no static folder is set.\n        \"\"\"\n        if self._static_folder is not None:\n            return os.path.join(self.root_path, self._static_folder)\n        else:\n            return None\n\n    @static_folder.setter\n    def static_folder(self, value: str | os.PathLike[str] | None) -> None:\n        if value is not None:\n            value = os.fspath(value).rstrip(r\"\\/\")\n\n        self._static_folder = value\n\n    @property\n    def has_static_folder(self) -> bool:\n        \"\"\"``True`` if :attr:`static_folder` is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        return self.static_folder is not None\n\n    @property\n    def static_url_path(self) -> str | None:\n        \"\"\"The URL prefix that the static route will be accessible from.\n\n        If it was not configured during init, it is derived from\n        :attr:`static_folder`.\n        \"\"\"\n        if self._static_url_path is not None:\n            return self._static_url_path\n\n        if self.static_folder is not None:\n            basename = os.path.basename(self.static_folder)\n            return f\"/{basename}\".rstrip(\"/\")\n\n        return None\n\n    @static_url_path.setter\n    def static_url_path(self, value: str | None) -> None:\n        if value is not None:\n            value = value.rstrip(\"/\")\n\n        self._static_url_path = value\n\n    @cached_property\n    def jinja_loader(self) -> BaseLoader | None:\n        \"\"\"The Jinja loader for this object's templates. By default this\n        is a class :class:`jinja2.loaders.FileSystemLoader` to\n        :attr:`template_folder` if it is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        if self.template_folder is not None:\n            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n        else:\n            return None\n\n    def _method_route(\n        self,\n        method: str,\n        rule: str,\n        options: dict[str, t.Any],\n    ) -> t.Callable[[T_route], T_route]:\n        if \"methods\" in options:\n            raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n        return self.route(rule, methods=[method], **options)\n\n    @setupmethod\n    def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"GET\", rule, options)\n\n    @setupmethod\n    def query(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"QUERY\"]``.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self._method_route(\"QUERY\", rule, options)\n\n    @setupmethod\n    def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"POST\", rule, options)\n\n    @setupmethod\n    def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PUT\", rule, options)\n\n    @setupmethod\n    def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"DELETE\", rule, options)\n\n    @setupmethod\n    def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PATCH\", rule, options)\n\n    @setupmethod\n    def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Decorate a view function to register it with the given URL\n        rule and options. Calls :meth:`add_url_rule`, which has more\n        details about the implementation.\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                return \"Hello, World!\"\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n        ``OPTIONS`` are added automatically.\n\n        :param rule: The URL rule string.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n\n        def decorator(f: T_route) -> T_route:\n            endpoint = options.pop(\"endpoint\", None)\n            self.add_url_rule(rule, endpoint, f, **options)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a rule for routing incoming requests and building\n        URLs. The :meth:`route` decorator is a shortcut to call this\n        with the ``view_func`` argument. These are equivalent:\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                ...\n\n        .. code-block:: python\n\n            def index():\n                ...\n\n            app.add_url_rule(\"/\", view_func=index)\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed. An error\n        will be raised if a function has already been registered for the\n        endpoint.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n        always added automatically, and ``OPTIONS`` is added\n        automatically by default.\n\n        ``view_func`` does not necessarily need to be passed, but if the\n        rule should participate in routing an endpoint name must be\n        associated with a view function at some point with the\n        :meth:`endpoint` decorator.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/\", endpoint=\"index\")\n\n            @app.endpoint(\"index\")\n            def index():\n                ...\n\n        If ``view_func`` has a ``required_methods`` attribute, those\n        methods are added to the passed and automatic methods. If it\n        has a ``provide_automatic_methods`` attribute, it is used as the\n        default if the parameter is not passed.\n\n        :param rule: The URL rule string.\n        :param endpoint: The endpoint name to associate with the rule\n            and view function. Used when routing and building URLs.\n            Defaults to ``view_func.__name__``.\n        :param view_func: The view function to associate with the\n            endpoint name.\n        :param provide_automatic_options: Add the ``OPTIONS`` method and\n            respond to ``OPTIONS`` requests automatically.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        raise NotImplementedError\n\n    @setupmethod\n    def endpoint(self, endpoint: str) -> t.Callable[[F], F]:\n        \"\"\"Decorate a view function to register it for the given\n        endpoint. Used if a rule is added without a ``view_func`` with\n        :meth:`add_url_rule`.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n            @app.endpoint(\"example\")\n            def example():\n                ...\n\n        :param endpoint: The endpoint name to associate with the view\n            function.\n        \"\"\"\n\n        def decorator(f: F) -> F:\n            self.view_functions[endpoint] = f\n            return f\n\n        return decorator\n\n    @setupmethod\n    def before_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Register a function to run before each request.\n\n        For example, this can be used to open a database connection, or\n        to load the logged in user from the session.\n\n        .. code-block:: python\n\n            @app.before_request\n            def load_user():\n                if \"user_id\" in session:\n                    g.user = db.session.get(session[\"user_id\"])\n\n        The function will be called without any arguments. If it returns\n        a non-``None`` value, the value is handled as if it was the\n        return value from the view, and further request handling is\n        stopped.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes before every request. When used on a blueprint, this executes before\n        every request that the blueprint handles. To register with a blueprint and\n        execute before every request, use :meth:`.Blueprint.before_app_request`.\n        \"\"\"\n        self.before_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def after_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Register a function to run after each request to this object.\n\n        The function is called with the response object, and must return\n        a response object. This allows the functions to modify or\n        replace the response before it is sent.\n\n        If a function raises an exception, any remaining\n        ``after_request`` functions will not be called. Therefore, this\n        should not be used for actions that must execute, such as to\n        close resources. Use :meth:`teardown_request` for that.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.after_app_request`.\n        \"\"\"\n        self.after_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def teardown_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Register a function to be called when the request context is\n        popped. Typically, this happens at the end of each request, but\n        contexts may be pushed manually during testing.\n\n        .. code-block:: python\n\n            with app.test_request_context():\n                ...\n\n        When the ``with`` block exits (or ``ctx.pop()`` is called), the\n        teardown functions are called just before the request context is\n        made inactive.\n\n        When a teardown function was called because of an unhandled\n        exception it will be passed an error object. If an\n        :meth:`errorhandler` is registered, it will handle the exception\n        and the teardown will not receive it.\n\n        Teardown functions must avoid raising exceptions. If they\n        execute code that might fail they must surround that code with a\n        ``try``/``except`` block and log any errors.\n\n        The return values of teardown functions are ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n        \"\"\"\n        self.teardown_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def context_processor(\n        self,\n        f: T_template_context_processor,\n    ) -> T_template_context_processor:\n        \"\"\"Registers a template context processor function. These functions run before\n        rendering a template. The keys of the returned dict are added as variables\n        available in the template.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every rendered template. When used on a blueprint, this is called\n        for templates rendered from the blueprint's views. To register with a blueprint\n        and affect every template, use :meth:`.Blueprint.app_context_processor`.\n        \"\"\"\n        self.template_context_processors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_value_preprocessor(\n        self,\n        f: T_url_value_preprocessor,\n    ) -> T_url_value_preprocessor:\n        \"\"\"Register a URL value preprocessor function for all view\n        functions in the application. These functions will be called before the\n        :meth:`before_request` functions.\n\n        The function can modify the values captured from the matched url before\n        they are passed to the view. For example, this can be used to pop a\n        common language code value and place it in ``g`` rather than pass it to\n        every view.\n\n        The function is passed the endpoint name and values dict. The return\n        value is ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n        \"\"\"\n        self.url_value_preprocessors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Callback function for URL defaults for all view functions of the\n        application.  It's called with the endpoint and values and should\n        update the values passed in place.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_defaults`.\n        \"\"\"\n        self.url_default_functions[None].append(f)\n        return f\n\n    @setupmethod\n    def errorhandler(\n        self, code_or_exception: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Register a function to handle errors by code or exception class.\n\n        A decorator that is used to register a function given an\n        error code.  Example::\n\n            @app.errorhandler(404)\n            def page_not_found(error):\n                return 'This page does not exist', 404\n\n        You can also register handlers for arbitrary exceptions::\n\n            @app.errorhandler(DatabaseError)\n            def special_exception_handler(error):\n                return 'Database connection failed', 500\n\n        This is available on both app and blueprint objects. When used on an app, this\n        can handle errors from every request. When used on a blueprint, this can handle\n        errors from requests that the blueprint handles. To register with a blueprint\n        and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n        .. versionadded:: 0.7\n            Use :meth:`register_error_handler` instead of modifying\n            :attr:`error_handler_spec` directly, for application wide error\n            handlers.\n\n        .. versionadded:: 0.7\n           One can now additionally also register custom exception types\n           that do not necessarily have to be a subclass of the\n           :class:`~werkzeug.exceptions.HTTPException` class.\n\n        :param code_or_exception: the code as integer for the handler, or\n                                  an arbitrary exception\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            self.register_error_handler(code_or_exception, f)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def register_error_handler(\n        self,\n        code_or_exception: type[Exception] | int,\n        f: ft.ErrorHandlerCallable,\n    ) -> None:\n        \"\"\"Alternative error attach function to the :meth:`errorhandler`\n        decorator that is more straightforward to use for non decorator\n        usage.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        exc_class, code = self._get_exc_class_and_code(code_or_exception)\n        self.error_handler_spec[None][code][exc_class] = f\n\n    @staticmethod\n    def _get_exc_class_and_code(\n        exc_class_or_code: type[Exception] | int,\n    ) -> tuple[type[Exception], int | None]:\n        \"\"\"Get the exception class being handled. For HTTP status codes\n        or ``HTTPException`` subclasses, return both the exception and\n        status code.\n\n        :param exc_class_or_code: Any exception class, or an HTTP status\n            code as an integer.\n        \"\"\"\n        exc_class: type[Exception]\n\n        if isinstance(exc_class_or_code, int):\n            try:\n                exc_class = default_exceptions[exc_class_or_code]\n            except KeyError:\n                raise ValueError(\n                    f\"'{exc_class_or_code}' is not a recognized HTTP\"\n                    \" error code. Use a subclass of HTTPException with\"\n                    \" that code instead.\"\n                ) from None\n        else:\n            exc_class = exc_class_or_code\n\n        if isinstance(exc_class, Exception):\n            raise TypeError(\n                f\"{exc_class!r} is an instance, not a class. Handlers\"\n                \" can only be registered for Exception classes or HTTP\"\n                \" error codes.\"\n            )\n\n        if not issubclass(exc_class, Exception):\n            raise ValueError(\n                f\"'{exc_class.__name__}' is not a subclass of Exception.\"\n                \" Handlers can only be registered for Exception classes\"\n                \" or HTTP error codes.\"\n            )\n\n        if issubclass(exc_class, HTTPException):\n            return exc_class, exc_class.code\n        else:\n            return exc_class, None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-701cd22ff415df0d", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 672, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__Scaffold__ce86d711.py", "order": 11, "original_content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "parent_variant_id": "pyint-1fc33230f8eb-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/scaffold.py#L52-L706", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "Scaffold", "variant_id": "pyint-cc8fce86d711-I11", "group_id": "py-701cd22ff415df0d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 614, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c407208ec125-I12", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport pathlib\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom jinja2 import BaseLoader\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\nfrom .. import typing as ft\nfrom ..helpers import get_root_path\nfrom ..templating import _default_template_ctx_processor\n\nclass Scaffold:\n    \"\"\"Common behavior shared between :class:`~flask.Flask` and\n    :class:`~flask.blueprints.Blueprint`.\n\n    :param import_name: The import name of the module where this object\n        is defined. Usually :attr:`__name__` should be used.\n    :param static_folder: Path to a folder of static files to serve.\n        If this is set, a static route will be added.\n    :param static_url_path: URL prefix for the static route.\n    :param template_folder: Path to a folder containing template files.\n        for rendering. If this is set, a Jinja loader will be added.\n    :param root_path: The path that static, template, and resource files\n        are relative to. Typically not set, it is discovered based on\n        the ``import_name``.\n\n    .. versionadded:: 2.0\n    \"\"\"\n\n    cli: Group\n    name: str\n    _static_folder: str | None = None\n    _static_url_path: str | None = None\n\n    def __init__(\n        self,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        root_path: str | None = None,\n    ):\n        #: The name of the package or module that this object belongs\n        #: to. Do not change this once it is set by the constructor.\n        self.import_name = import_name\n\n        self.static_folder = static_folder\n        self.static_url_path = static_url_path\n\n        #: The path to the templates folder, relative to\n        #: :attr:`root_path`, to add to the template loader. ``None`` if\n        #: templates should not be added.\n        self.template_folder = template_folder\n\n        if root_path is None:\n            root_path = get_root_path(self.import_name)\n\n        #: Absolute path to the package on the filesystem. Used to look\n        #: up resources contained in the package.\n        self.root_path = root_path\n\n        #: A dictionary mapping endpoint names to view functions.\n        #:\n        #: To register a view function, use the :meth:`route` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.view_functions: dict[str, ft.RouteCallable] = {}\n\n        #: A data structure of registered error handlers, in the format\n        #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n        #: the name of a blueprint the handlers are active for, or\n        #: ``None`` for all requests. The ``code`` key is the HTTP\n        #: status code for ``HTTPException``, or ``None`` for\n        #: other exceptions. The innermost dictionary maps exception\n        #: classes to handler functions.\n        #:\n        #: To register an error handler, use the :meth:`errorhandler`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.error_handler_spec: dict[\n            ft.AppOrBlueprintKey,\n            dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n        ] = defaultdict(lambda: defaultdict(dict))\n\n        #: A data structure of functions to call at the beginning of\n        #: each request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`before_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.before_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`after_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.after_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request even if an exception is raised, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`teardown_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.teardown_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.TeardownCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to pass extra context\n        #: values when rendering templates, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`context_processor`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.template_context_processors: dict[\n            ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]\n        ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments passed to the view function, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the\n        #: :meth:`url_value_preprocessor` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_value_preprocessors: dict[\n            ft.AppOrBlueprintKey,\n            list[ft.URLValuePreprocessorCallable],\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments when generating URLs, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`url_defaults`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_default_functions: dict[\n            ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]\n        ] = defaultdict(list)\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {self.name!r}>\"\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        raise NotImplementedError\n\n    @property\n    def static_folder(self) -> str | None:\n        \"\"\"The absolute path to the configured static folder. ``None``\n        if no static folder is set.\n        \"\"\"\n        if self._static_folder is not None:\n            return os.path.join(self.root_path, self._static_folder)\n        else:\n            return None\n\n    @static_folder.setter\n    def static_folder(self, value: str | os.PathLike[str] | None) -> None:\n        if value is not None:\n            value = os.fspath(value).rstrip(r\"\\/\")\n\n        self._static_folder = value\n\n    @property\n    def has_static_folder(self) -> bool:\n        \"\"\"``True`` if :attr:`static_folder` is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        return self.static_folder is not None\n\n    @property\n    def static_url_path(self) -> str | None:\n        \"\"\"The URL prefix that the static route will be accessible from.\n\n        If it was not configured during init, it is derived from\n        :attr:`static_folder`.\n        \"\"\"\n        if self._static_url_path is not None:\n            return self._static_url_path\n\n        if self.static_folder is not None:\n            basename = os.path.basename(self.static_folder)\n            return f\"/{basename}\".rstrip(\"/\")\n\n        return None\n\n    @static_url_path.setter\n    def static_url_path(self, value: str | None) -> None:\n        if value is not None:\n            value = value.rstrip(\"/\")\n\n        self._static_url_path = value\n\n    @cached_property\n    def jinja_loader(self) -> BaseLoader | None:\n        \"\"\"The Jinja loader for this object's templates. By default this\n        is a class :class:`jinja2.loaders.FileSystemLoader` to\n        :attr:`template_folder` if it is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        if self.template_folder is not None:\n            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n        else:\n            return None\n\n    def _method_route(\n        self,\n        method: str,\n        rule: str,\n        options: dict[str, t.Any],\n    ) -> t.Callable[[T_route], T_route]:\n        if \"methods\" in options:\n            raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n        return self.route(rule, methods=[method], **options)\n\n    @setupmethod\n    def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"GET\", rule, options)\n\n    @setupmethod\n    def query(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"QUERY\"]``.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self._method_route(\"QUERY\", rule, options)\n\n    @setupmethod\n    def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"POST\", rule, options)\n\n    @setupmethod\n    def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PUT\", rule, options)\n\n    @setupmethod\n    def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"DELETE\", rule, options)\n\n    @setupmethod\n    def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PATCH\", rule, options)\n\n    @setupmethod\n    def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Decorate a view function to register it with the given URL\n        rule and options. Calls :meth:`add_url_rule`, which has more\n        details about the implementation.\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                return \"Hello, World!\"\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n        ``OPTIONS`` are added automatically.\n\n        :param rule: The URL rule string.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n\n        def decorator(f: T_route) -> T_route:\n            \n            self.add_url_rule(rule, (options.pop(\"endpoint\", None)), f, **options)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a rule for routing incoming requests and building\n        URLs. The :meth:`route` decorator is a shortcut to call this\n        with the ``view_func`` argument. These are equivalent:\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                ...\n\n        .. code-block:: python\n\n            def index():\n                ...\n\n            app.add_url_rule(\"/\", view_func=index)\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed. An error\n        will be raised if a function has already been registered for the\n        endpoint.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n        always added automatically, and ``OPTIONS`` is added\n        automatically by default.\n\n        ``view_func`` does not necessarily need to be passed, but if the\n        rule should participate in routing an endpoint name must be\n        associated with a view function at some point with the\n        :meth:`endpoint` decorator.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/\", endpoint=\"index\")\n\n            @app.endpoint(\"index\")\n            def index():\n                ...\n\n        If ``view_func`` has a ``required_methods`` attribute, those\n        methods are added to the passed and automatic methods. If it\n        has a ``provide_automatic_methods`` attribute, it is used as the\n        default if the parameter is not passed.\n\n        :param rule: The URL rule string.\n        :param endpoint: The endpoint name to associate with the rule\n            and view function. Used when routing and building URLs.\n            Defaults to ``view_func.__name__``.\n        :param view_func: The view function to associate with the\n            endpoint name.\n        :param provide_automatic_options: Add the ``OPTIONS`` method and\n            respond to ``OPTIONS`` requests automatically.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        raise NotImplementedError\n\n    @setupmethod\n    def endpoint(self, endpoint: str) -> t.Callable[[F], F]:\n        \"\"\"Decorate a view function to register it for the given\n        endpoint. Used if a rule is added without a ``view_func`` with\n        :meth:`add_url_rule`.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n            @app.endpoint(\"example\")\n            def example():\n                ...\n\n        :param endpoint: The endpoint name to associate with the view\n            function.\n        \"\"\"\n\n        def decorator(f: F) -> F:\n            self.view_functions[endpoint] = f\n            return f\n\n        return decorator\n\n    @setupmethod\n    def before_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Register a function to run before each request.\n\n        For example, this can be used to open a database connection, or\n        to load the logged in user from the session.\n\n        .. code-block:: python\n\n            @app.before_request\n            def load_user():\n                if \"user_id\" in session:\n                    g.user = db.session.get(session[\"user_id\"])\n\n        The function will be called without any arguments. If it returns\n        a non-``None`` value, the value is handled as if it was the\n        return value from the view, and further request handling is\n        stopped.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes before every request. When used on a blueprint, this executes before\n        every request that the blueprint handles. To register with a blueprint and\n        execute before every request, use :meth:`.Blueprint.before_app_request`.\n        \"\"\"\n        self.before_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def after_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Register a function to run after each request to this object.\n\n        The function is called with the response object, and must return\n        a response object. This allows the functions to modify or\n        replace the response before it is sent.\n\n        If a function raises an exception, any remaining\n        ``after_request`` functions will not be called. Therefore, this\n        should not be used for actions that must execute, such as to\n        close resources. Use :meth:`teardown_request` for that.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.after_app_request`.\n        \"\"\"\n        self.after_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def teardown_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Register a function to be called when the request context is\n        popped. Typically, this happens at the end of each request, but\n        contexts may be pushed manually during testing.\n\n        .. code-block:: python\n\n            with app.test_request_context():\n                ...\n\n        When the ``with`` block exits (or ``ctx.pop()`` is called), the\n        teardown functions are called just before the request context is\n        made inactive.\n\n        When a teardown function was called because of an unhandled\n        exception it will be passed an error object. If an\n        :meth:`errorhandler` is registered, it will handle the exception\n        and the teardown will not receive it.\n\n        Teardown functions must avoid raising exceptions. If they\n        execute code that might fail they must surround that code with a\n        ``try``/``except`` block and log any errors.\n\n        The return values of teardown functions are ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n        \"\"\"\n        self.teardown_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def context_processor(\n        self,\n        f: T_template_context_processor,\n    ) -> T_template_context_processor:\n        \"\"\"Registers a template context processor function. These functions run before\n        rendering a template. The keys of the returned dict are added as variables\n        available in the template.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every rendered template. When used on a blueprint, this is called\n        for templates rendered from the blueprint's views. To register with a blueprint\n        and affect every template, use :meth:`.Blueprint.app_context_processor`.\n        \"\"\"\n        self.template_context_processors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_value_preprocessor(\n        self,\n        f: T_url_value_preprocessor,\n    ) -> T_url_value_preprocessor:\n        \"\"\"Register a URL value preprocessor function for all view\n        functions in the application. These functions will be called before the\n        :meth:`before_request` functions.\n\n        The function can modify the values captured from the matched url before\n        they are passed to the view. For example, this can be used to pop a\n        common language code value and place it in ``g`` rather than pass it to\n        every view.\n\n        The function is passed the endpoint name and values dict. The return\n        value is ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n        \"\"\"\n        self.url_value_preprocessors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Callback function for URL defaults for all view functions of the\n        application.  It's called with the endpoint and values and should\n        update the values passed in place.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_defaults`.\n        \"\"\"\n        self.url_default_functions[None].append(f)\n        return f\n\n    @setupmethod\n    def errorhandler(\n        self, code_or_exception: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Register a function to handle errors by code or exception class.\n\n        A decorator that is used to register a function given an\n        error code.  Example::\n\n            @app.errorhandler(404)\n            def page_not_found(error):\n                return 'This page does not exist', 404\n\n        You can also register handlers for arbitrary exceptions::\n\n            @app.errorhandler(DatabaseError)\n            def special_exception_handler(error):\n                return 'Database connection failed', 500\n\n        This is available on both app and blueprint objects. When used on an app, this\n        can handle errors from every request. When used on a blueprint, this can handle\n        errors from requests that the blueprint handles. To register with a blueprint\n        and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n        .. versionadded:: 0.7\n            Use :meth:`register_error_handler` instead of modifying\n            :attr:`error_handler_spec` directly, for application wide error\n            handlers.\n\n        .. versionadded:: 0.7\n           One can now additionally also register custom exception types\n           that do not necessarily have to be a subclass of the\n           :class:`~werkzeug.exceptions.HTTPException` class.\n\n        :param code_or_exception: the code as integer for the handler, or\n                                  an arbitrary exception\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            self.register_error_handler(code_or_exception, f)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def register_error_handler(\n        self,\n        code_or_exception: type[Exception] | int,\n        f: ft.ErrorHandlerCallable,\n    ) -> None:\n        \"\"\"Alternative error attach function to the :meth:`errorhandler`\n        decorator that is more straightforward to use for non decorator\n        usage.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        exc_class, code = self._get_exc_class_and_code(code_or_exception)\n        self.error_handler_spec[None][code][exc_class] = f\n\n    @staticmethod\n    def _get_exc_class_and_code(\n        exc_class_or_code: type[Exception] | int,\n    ) -> tuple[type[Exception], int | None]:\n        \"\"\"Get the exception class being handled. For HTTP status codes\n        or ``HTTPException`` subclasses, return both the exception and\n        status code.\n\n        :param exc_class_or_code: Any exception class, or an HTTP status\n            code as an integer.\n        \"\"\"\n        exc_class: type[Exception]\n\n        if isinstance(exc_class_or_code, int):\n            try:\n                exc_class = default_exceptions[exc_class_or_code]\n            except KeyError:\n                raise ValueError(\n                    f\"'{exc_class_or_code}' is not a recognized HTTP\"\n                    \" error code. Use a subclass of HTTPException with\"\n                    \" that code instead.\"\n                ) from None\n        else:\n            exc_class = exc_class_or_code\n\n        if isinstance(exc_class, Exception):\n            raise TypeError(\n                f\"{exc_class!r} is an instance, not a class. Handlers\"\n                \" can only be registered for Exception classes or HTTP\"\n                \" error codes.\"\n            )\n\n        if not issubclass(exc_class, Exception):\n            raise ValueError(\n                f\"'{exc_class.__name__}' is not a subclass of Exception.\"\n                \" Handlers can only be registered for Exception classes\"\n                \" or HTTP error codes.\"\n            )\n\n        if issubclass(exc_class, HTTPException):\n            return exc_class, exc_class.code\n        else:\n            return exc_class, None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-701cd22ff415df0d", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "76e22032d9ccbecf88b75cfe1dc8f7425d75ce4c2ee4e9e6d2eb86cb2a696110", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 672, "local_path": "data-flow/inline-intermediate-variables/I12__flask__Scaffold__208ec125.py", "order": 12, "original_content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "parent_variant_id": "pyint-1fc33230f8eb-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/scaffold.py#L52-L706", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Scaffold", "variant_id": "pyint-c407208ec125-I12", "group_id": "py-701cd22ff415df0d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 615, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2d666ed80c53-I13", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport pathlib\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom jinja2 import BaseLoader\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\nfrom .. import typing as ft\nfrom ..helpers import get_root_path\nfrom ..templating import _default_template_ctx_processor\n\nclass Scaffold:\n    \"\"\"Common behavior shared between :class:`~flask.Flask` and\n    :class:`~flask.blueprints.Blueprint`.\n\n    :param import_name: The import name of the module where this object\n        is defined. Usually :attr:`__name__` should be used.\n    :param static_folder: Path to a folder of static files to serve.\n        If this is set, a static route will be added.\n    :param static_url_path: URL prefix for the static route.\n    :param template_folder: Path to a folder containing template files.\n        for rendering. If this is set, a Jinja loader will be added.\n    :param root_path: The path that static, template, and resource files\n        are relative to. Typically not set, it is discovered based on\n        the ``import_name``.\n\n    .. versionadded:: 2.0\n    \"\"\"\n\n    cli: Group\n    name: str\n    _static_folder: str | None = None\n    _static_url_path: str | None = None\n\n    def __init__(\n        self,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        root_path: str | None = None,\n    ):\n        #: The name of the package or module that this object belongs\n        #: to. Do not change this once it is set by the constructor.\n        self.import_name = import_name\n\n        self.static_folder = static_folder\n        self.static_url_path = static_url_path\n\n        #: The path to the templates folder, relative to\n        #: :attr:`root_path`, to add to the template loader. ``None`` if\n        #: templates should not be added.\n        self.template_folder = template_folder\n\n        if root_path is None:\n            root_path = get_root_path(self.import_name)\n\n        #: Absolute path to the package on the filesystem. Used to look\n        #: up resources contained in the package.\n        self.root_path = root_path\n\n        #: A dictionary mapping endpoint names to view functions.\n        #:\n        #: To register a view function, use the :meth:`route` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.view_functions: dict[str, ft.RouteCallable] = {}\n\n        #: A data structure of registered error handlers, in the format\n        #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n        #: the name of a blueprint the handlers are active for, or\n        #: ``None`` for all requests. The ``code`` key is the HTTP\n        #: status code for ``HTTPException``, or ``None`` for\n        #: other exceptions. The innermost dictionary maps exception\n        #: classes to handler functions.\n        #:\n        #: To register an error handler, use the :meth:`errorhandler`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.error_handler_spec: dict[\n            ft.AppOrBlueprintKey,\n            dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n        ] = defaultdict(lambda: defaultdict(dict))\n\n        #: A data structure of functions to call at the beginning of\n        #: each request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`before_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.before_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request, in the format ``{scope: [functions]}``. The\n        #: ``scope`` key is the name of a blueprint the functions are\n        #: active for, or ``None`` for all requests.\n        #:\n        #: To register a function, use the :meth:`after_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.after_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call at the end of each\n        #: request even if an exception is raised, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`teardown_request`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.teardown_request_funcs: dict[\n            ft.AppOrBlueprintKey, list[ft.TeardownCallable]\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to pass extra context\n        #: values when rendering templates, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`context_processor`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.template_context_processors: dict[\n            ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]\n        ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments passed to the view function, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the\n        #: :meth:`url_value_preprocessor` decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_value_preprocessors: dict[\n            ft.AppOrBlueprintKey,\n            list[ft.URLValuePreprocessorCallable],\n        ] = defaultdict(list)\n\n        #: A data structure of functions to call to modify the keyword\n        #: arguments when generating URLs, in the format\n        #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n        #: blueprint the functions are active for, or ``None`` for all\n        #: requests.\n        #:\n        #: To register a function, use the :meth:`url_defaults`\n        #: decorator.\n        #:\n        #: This data structure is internal. It should not be modified\n        #: directly and its format may change at any time.\n        self.url_default_functions: dict[\n            ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]\n        ] = defaultdict(list)\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {self.name!r}>\"\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        raise NotImplementedError\n\n    @property\n    def static_folder(self) -> str | None:\n        \"\"\"The absolute path to the configured static folder. ``None``\n        if no static folder is set.\n        \"\"\"\n        if self._static_folder is not None:\n            return os.path.join(self.root_path, self._static_folder)\n        else:\n            return None\n\n    @static_folder.setter\n    def static_folder(self, value: str | os.PathLike[str] | None) -> None:\n        if value is not None:\n            value = os.fspath(value).rstrip(r\"\\/\")\n\n        self._static_folder = value\n\n    @property\n    def has_static_folder(self) -> bool:\n        \"\"\"``True`` if :attr:`static_folder` is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        return self.static_folder is not None\n\n    @property\n    def static_url_path(self) -> str | None:\n        \"\"\"The URL prefix that the static route will be accessible from.\n\n        If it was not configured during init, it is derived from\n        :attr:`static_folder`.\n        \"\"\"\n        if self._static_url_path is not None:\n            return self._static_url_path\n\n        if self.static_folder is not None:\n            basename = os.path.basename(self.static_folder)\n            return f\"/{basename}\".rstrip(\"/\")\n\n        return None\n\n    @static_url_path.setter\n    def static_url_path(self, value: str | None) -> None:\n        if value is not None:\n            value = value.rstrip(\"/\")\n\n        self._static_url_path = value\n\n    @cached_property\n    def jinja_loader(self) -> BaseLoader | None:\n        \"\"\"The Jinja loader for this object's templates. By default this\n        is a class :class:`jinja2.loaders.FileSystemLoader` to\n        :attr:`template_folder` if it is set.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        if self.template_folder is not None:\n            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n        else:\n            return None\n\n    def _method_route(\n        self,\n        method: str,\n        rule: str,\n        options: dict[str, t.Any],\n    ) -> t.Callable[[T_route], T_route]:\n        if \"methods\" in options:\n            raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n        return self.route(rule, methods=[method], **options)\n\n    @setupmethod\n    def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"GET\", rule, options)\n\n    @setupmethod\n    def query(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"QUERY\"]``.\n\n        .. versionadded:: 3.2\n        \"\"\"\n        return self._method_route(\"QUERY\", rule, options)\n\n    @setupmethod\n    def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"POST\", rule, options)\n\n    @setupmethod\n    def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PUT\", rule, options)\n\n    @setupmethod\n    def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"DELETE\", rule, options)\n\n    @setupmethod\n    def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        return self._method_route(\"PATCH\", rule, options)\n\n    @setupmethod\n    def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n        \"\"\"Decorate a view function to register it with the given URL\n        rule and options. Calls :meth:`add_url_rule`, which has more\n        details about the implementation.\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                return \"Hello, World!\"\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n        ``OPTIONS`` are added automatically.\n\n        :param rule: The URL rule string.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n\n        def decorator(f: T_route) -> T_route:\n            endpoint = options.pop(\"endpoint\", None)\n            self.add_url_rule(rule, endpoint, f, **options)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a rule for routing incoming requests and building\n        URLs. The :meth:`route` decorator is a shortcut to call this\n        with the ``view_func`` argument. These are equivalent:\n\n        .. code-block:: python\n\n            @app.route(\"/\")\n            def index():\n                ...\n\n        .. code-block:: python\n\n            def index():\n                ...\n\n            app.add_url_rule(\"/\", view_func=index)\n\n        See :ref:`url-route-registrations`.\n\n        The endpoint name for the route defaults to the name of the view\n        function if the ``endpoint`` parameter isn't passed. An error\n        will be raised if a function has already been registered for the\n        endpoint.\n\n        The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n        always added automatically, and ``OPTIONS`` is added\n        automatically by default.\n\n        ``view_func`` does not necessarily need to be passed, but if the\n        rule should participate in routing an endpoint name must be\n        associated with a view function at some point with the\n        :meth:`endpoint` decorator.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/\", endpoint=\"index\")\n\n            @app.endpoint(\"index\")\n            def index():\n                ...\n\n        If ``view_func`` has a ``required_methods`` attribute, those\n        methods are added to the passed and automatic methods. If it\n        has a ``provide_automatic_methods`` attribute, it is used as the\n        default if the parameter is not passed.\n\n        :param rule: The URL rule string.\n        :param endpoint: The endpoint name to associate with the rule\n            and view function. Used when routing and building URLs.\n            Defaults to ``view_func.__name__``.\n        :param view_func: The view function to associate with the\n            endpoint name.\n        :param provide_automatic_options: Add the ``OPTIONS`` method and\n            respond to ``OPTIONS`` requests automatically.\n        :param options: Extra options passed to the\n            :class:`~werkzeug.routing.Rule` object.\n        \"\"\"\n        raise NotImplementedError\n\n    @setupmethod\n    def endpoint(self, endpoint: str) -> t.Callable[[F], F]:\n        \"\"\"Decorate a view function to register it for the given\n        endpoint. Used if a rule is added without a ``view_func`` with\n        :meth:`add_url_rule`.\n\n        .. code-block:: python\n\n            app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n            @app.endpoint(\"example\")\n            def example():\n                ...\n\n        :param endpoint: The endpoint name to associate with the view\n            function.\n        \"\"\"\n\n        def decorator(f: F) -> F:\n            self.view_functions[endpoint] = f\n            return f\n\n        return decorator\n\n    @setupmethod\n    def before_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Register a function to run before each request.\n\n        For example, this can be used to open a database connection, or\n        to load the logged in user from the session.\n\n        .. code-block:: python\n\n            @app.before_request\n            def load_user():\n                if \"user_id\" in session:\n                    g.user = db.session.get(session[\"user_id\"])\n\n        The function will be called without any arguments. If it returns\n        a non-``None`` value, the value is handled as if it was the\n        return value from the view, and further request handling is\n        stopped.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes before every request. When used on a blueprint, this executes before\n        every request that the blueprint handles. To register with a blueprint and\n        execute before every request, use :meth:`.Blueprint.before_app_request`.\n        \"\"\"\n        self.before_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def after_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Register a function to run after each request to this object.\n\n        The function is called with the response object, and must return\n        a response object. This allows the functions to modify or\n        replace the response before it is sent.\n\n        If a function raises an exception, any remaining\n        ``after_request`` functions will not be called. Therefore, this\n        should not be used for actions that must execute, such as to\n        close resources. Use :meth:`teardown_request` for that.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.after_app_request`.\n        \"\"\"\n        self.after_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def teardown_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Register a function to be called when the request context is\n        popped. Typically, this happens at the end of each request, but\n        contexts may be pushed manually during testing.\n\n        .. code-block:: python\n\n            with app.test_request_context():\n                ...\n\n        When the ``with`` block exits (or ``ctx.pop()`` is called), the\n        teardown functions are called just before the request context is\n        made inactive.\n\n        When a teardown function was called because of an unhandled\n        exception it will be passed an error object. If an\n        :meth:`errorhandler` is registered, it will handle the exception\n        and the teardown will not receive it.\n\n        Teardown functions must avoid raising exceptions. If they\n        execute code that might fail they must surround that code with a\n        ``try``/``except`` block and log any errors.\n\n        The return values of teardown functions are ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        executes after every request. When used on a blueprint, this executes after\n        every request that the blueprint handles. To register with a blueprint and\n        execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n        \"\"\"\n        self.teardown_request_funcs.setdefault(None, []).append(f)\n        return f\n\n    @setupmethod\n    def context_processor(\n        self,\n        f: T_template_context_processor,\n    ) -> T_template_context_processor:\n        \"\"\"Registers a template context processor function. These functions run before\n        rendering a template. The keys of the returned dict are added as variables\n        available in the template.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every rendered template. When used on a blueprint, this is called\n        for templates rendered from the blueprint's views. To register with a blueprint\n        and affect every template, use :meth:`.Blueprint.app_context_processor`.\n        \"\"\"\n        self.template_context_processors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_value_preprocessor(\n        self,\n        f: T_url_value_preprocessor,\n    ) -> T_url_value_preprocessor:\n        \"\"\"Register a URL value preprocessor function for all view\n        functions in the application. These functions will be called before the\n        :meth:`before_request` functions.\n\n        The function can modify the values captured from the matched url before\n        they are passed to the view. For example, this can be used to pop a\n        common language code value and place it in ``g`` rather than pass it to\n        every view.\n\n        The function is passed the endpoint name and values dict. The return\n        value is ignored.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n        \"\"\"\n        self.url_value_preprocessors[None].append(f)\n        return f\n\n    @setupmethod\n    def url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Callback function for URL defaults for all view functions of the\n        application.  It's called with the endpoint and values and should\n        update the values passed in place.\n\n        This is available on both app and blueprint objects. When used on an app, this\n        is called for every request. When used on a blueprint, this is called for\n        requests that the blueprint handles. To register with a blueprint and affect\n        every request, use :meth:`.Blueprint.app_url_defaults`.\n        \"\"\"\n        self.url_default_functions[None].append(f)\n        return f\n\n    @setupmethod\n    def errorhandler(\n        self, code_or_exception: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Register a function to handle errors by code or exception class.\n\n        A decorator that is used to register a function given an\n        error code.  Example::\n\n            @app.errorhandler(404)\n            def page_not_found(error):\n                return 'This page does not exist', 404\n\n        You can also register handlers for arbitrary exceptions::\n\n            @app.errorhandler(DatabaseError)\n            def special_exception_handler(error):\n                return 'Database connection failed', 500\n\n        This is available on both app and blueprint objects. When used on an app, this\n        can handle errors from every request. When used on a blueprint, this can handle\n        errors from requests that the blueprint handles. To register with a blueprint\n        and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n        .. versionadded:: 0.7\n            Use :meth:`register_error_handler` instead of modifying\n            :attr:`error_handler_spec` directly, for application wide error\n            handlers.\n\n        .. versionadded:: 0.7\n           One can now additionally also register custom exception types\n           that do not necessarily have to be a subclass of the\n           :class:`~werkzeug.exceptions.HTTPException` class.\n\n        :param code_or_exception: the code as integer for the handler, or\n                                  an arbitrary exception\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            self.register_error_handler(code_or_exception, f)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def register_error_handler(\n        self,\n        code_or_exception: type[Exception] | int,\n        f: ft.ErrorHandlerCallable,\n    ) -> None:\n        \"\"\"Alternative error attach function to the :meth:`errorhandler`\n        decorator that is more straightforward to use for non decorator\n        usage.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        exc_class, code = self._get_exc_class_and_code(code_or_exception)\n        self.error_handler_spec[None][code][exc_class] = f\n\n    @staticmethod\n    def _get_exc_class_and_code(\n        exc_class_or_code: type[Exception] | int,\n    ) -> tuple[type[Exception], int | None]:\n        \"\"\"Get the exception class being handled. For HTTP status codes\n        or ``HTTPException`` subclasses, return both the exception and\n        status code.\n\n        :param exc_class_or_code: Any exception class, or an HTTP status\n            code as an integer.\n        \"\"\"\n        exc_class: type[Exception]\n\n        if isinstance(exc_class_or_code, int):\n            try:\n                exc_class = default_exceptions[exc_class_or_code]\n            except KeyError:\n                raise ValueError(\n                    f\"'{exc_class_or_code}' is not a recognized HTTP\"\n                    \" error code. Use a subclass of HTTPException with\"\n                    \" that code instead.\"\n                ) from None\n        else:\n            exc_class = exc_class_or_code\n\n        if isinstance(exc_class, Exception):\n            raise TypeError(\n                f\"{exc_class!r} is an instance, not a class. Handlers\"\n                \" can only be registered for Exception classes or HTTP\"\n                \" error codes.\"\n            )\n\n        if not issubclass(exc_class, Exception):\n            raise ValueError(\n                f\"'{exc_class.__name__}' is not a subclass of Exception.\"\n                \" Handlers can only be registered for Exception classes\"\n                \" or HTTP error codes.\"\n            )\n\n        if issubclass(exc_class, HTTPException):\n            return exc_class, exc_class.code\n        else:\n            return exc_class, None\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-701cd22ff415df0d", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 672, "local_path": "control-flow/lower-for-to-while/I13__flask__Scaffold__6ed80c53.py", "order": 13, "original_content_sha256": "5cf15eadff1a4bc43a8d4bbe5d225ce7d084b996fc47e044b803d4d7cdda4361", "parent_variant_id": "pyint-1fc33230f8eb-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/scaffold.py#L52-L706", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "Scaffold", "variant_id": "pyint-2d666ed80c53-I13", "group_id": "py-701cd22ff415df0d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 616, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bef3b56d30e0-SRC", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagDateTime(JSONTag):\n    __slots__ = ()\n    key = \" d\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, datetime)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return http_date(value)\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return parse_date(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-71f77afa9c007e40", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 24, "local_path": "source-original/SRC__flask__TagDateTime__b56d30e0.py", "order": 0, "original_content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L205-L216", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "TagDateTime", "variant_id": "pyint-bef3b56d30e0-SRC", "group_id": "py-71f77afa9c007e40", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 393, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ad4bff4a1b18-I01", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagDateTime(JSONTag):\n    __slots__ = ()\n    key = \" d\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, datetime)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return http_date(value)\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return parse_date(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-71f77afa9c007e40", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 24, "local_path": "comments/remove-comments/I01__flask__TagDateTime__ff4a1b18.py", "order": 1, "original_content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "parent_variant_id": "pyint-bef3b56d30e0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L205-L216", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "TagDateTime", "variant_id": "pyint-ad4bff4a1b18-I01", "group_id": "py-71f77afa9c007e40", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 394, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-50ee54b31db6-I02", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagDateTime(JSONTag):\n    __slots__ = ()\n    key = \" d\"\n\n    def che(self, val: t.Any) -> bool:\n        return isinstance(val, datetime)\n\n    def to(self, val2: t.Any) -> t.Any:\n        return http_date(val2)\n\n    def to2(self, val3: t.Any) -> t.Any:\n        return parse_date(val3)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-71f77afa9c007e40", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "ba2fbaa9bf0b75b020e388e89b4648c455bd013ffaa1110e15f0a76bb5a8458b", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 24, "local_path": "identifiers/shorten-identifiers/I02__flask__TagDateTime__54b31db6.py", "order": 2, "original_content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "parent_variant_id": "pyint-bef3b56d30e0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L205-L216", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 9, "identifiers_declared": 6}, "unit_kind": "class", "unit_name": "TagDateTime", "variant_id": "pyint-50ee54b31db6-I02", "group_id": "py-71f77afa9c007e40", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 395, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e0b49cae9964-I03", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagDateTime(JSONTag):\n    __slots__ = ()\n    key = \" d\"\n\n    def route(self, index: t.Any) -> bool:\n        return isinstance(index, datetime)\n\n    def connect(self, count: t.Any) -> t.Any:\n        return http_date(count)\n\n    def summarize(self, count: t.Any) -> t.Any:\n        return parse_date(count)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-71f77afa9c007e40", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "6aaaa4bea8cb4afa74371c449e702dfba509c46e65d8b89e6a7e992923456463", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 24, "local_path": "identifiers/mislead-identifiers/I03__flask__TagDateTime__9cae9964.py", "order": 3, "original_content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "parent_variant_id": "pyint-bef3b56d30e0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L205-L216", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 9, "identifiers_declared": 6, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 3, "local_random_pool_selections": 3, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 3, "method_random_pool_selections": 3, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "TagDateTime", "variant_id": "pyint-e0b49cae9964-I03", "group_id": "py-71f77afa9c007e40", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 396, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-22f535fec45c-I04", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagDateTime(JSONTag):\n    __slots__ = ()\n    key = \" d\"\n\n    def a(self, d: t.Any) -> bool:\n        return isinstance(d, datetime)\n\n    def b(self, e: t.Any) -> t.Any:\n        return http_date(e)\n\n    def c(self, f: t.Any) -> t.Any:\n        return parse_date(f)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-71f77afa9c007e40", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d48a73b969a0fa5deefe6433dbd1d3d476425829c03b9a9c7607a3f28a254bd2", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 24, "local_path": "identifiers/garble-identifiers/I04__flask__TagDateTime__35fec45c.py", "order": 4, "original_content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "parent_variant_id": "pyint-bef3b56d30e0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L205-L216", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 9, "identifiers_declared": 6}, "unit_kind": "class", "unit_name": "TagDateTime", "variant_id": "pyint-22f535fec45c-I04", "group_id": "py-71f77afa9c007e40", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 397, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cc436b081f57-I05", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagDateTime(JSONTag):\n    __slots__ = ()\n    key = \" d\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, datetime)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return http_date(value)\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return parse_date(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-71f77afa9c007e40", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 24, "local_path": "expressions/encode-integer-literals/I05__flask__TagDateTime__6b081f57.py", "order": 5, "original_content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "parent_variant_id": "pyint-bef3b56d30e0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L205-L216", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "TagDateTime", "variant_id": "pyint-cc436b081f57-I05", "group_id": "py-71f77afa9c007e40", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 398, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a4ea212f50fc-I06", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagDateTime(JSONTag):\n    __slots__ = ()\n    key = \" d\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, datetime)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return http_date(value)\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return parse_date(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-71f77afa9c007e40", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 24, "local_path": "expressions/invert-conditions/I06__flask__TagDateTime__212f50fc.py", "order": 6, "original_content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "parent_variant_id": "pyint-bef3b56d30e0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L205-L216", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "TagDateTime", "variant_id": "pyint-a4ea212f50fc-I06", "group_id": "py-71f77afa9c007e40", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 399, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1207236b03eb-I07", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagDateTime(JSONTag):\n    __slots__ = ()\n    key = \" d\"\n\n    def check(self, value: t.Any) -> bool:\n        if ((0x2dc8 ^ 0x2dc8) != 0):\n            raise AssertionError()\n        return isinstance(value, datetime)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        if ((0xe330 ^ 0xe330) != 0):\n            raise AssertionError()\n        return http_date(value)\n\n    def to_python(self, value: t.Any) -> t.Any:\n        if ((0xb92b ^ 0xb92b) != 0):\n            raise AssertionError()\n        return parse_date(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-71f77afa9c007e40", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d88a0d1175c4b5092bba3e8fb6d51a1c451521e24d5b0a77f4617a90ce488cc0", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 30, "local_path": "code-injection/insert-dead-branches/I07__flask__TagDateTime__236b03eb.py", "order": 7, "original_content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "parent_variant_id": "pyint-bef3b56d30e0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L205-L216", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 3}, "unit_kind": "class", "unit_name": "TagDateTime", "variant_id": "pyint-1207236b03eb-I07", "group_id": "py-71f77afa9c007e40", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 400, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-311bd496ec91-I08", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagDateTime(JSONTag):\n    __slots__ = ()\n    key = \" d\"\n\n    def check(self, value: t.Any) -> bool:\n        previous_number = 0\n        current_number = 1\n        for sequence_step in range(4):\n            next_number = previous_number + current_number\n            previous_number = current_number\n            current_number = next_number\n        return isinstance(value, datetime)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return http_date(value)\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return parse_date(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-71f77afa9c007e40", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "2d9727ab90efd1495c1bdc148f9a9a3ac99f4c5467527210d7219ccc3f1f0ce0", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 30, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__TagDateTime__d496ec91.py", "order": 8, "original_content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "parent_variant_id": "pyint-bef3b56d30e0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L205-L216", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 8}, "unit_kind": "class", "unit_name": "TagDateTime", "variant_id": "pyint-311bd496ec91-I08", "group_id": "py-71f77afa9c007e40", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 401, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ef7557660738-I09", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagDateTime(JSONTag):\n    __slots__ = ()\n    key = \" d\"\n\n    def check(self, value: t.Any) -> bool:\n        lI0O_c5f7db09 = 0xd8d7\n        lI0O_c5f7db09 = (0 if (lI0O_c5f7db09 ^ lI0O_c5f7db09) == 0 else 1) if (lI0O_c5f7db09 & 0) == 0 else 2\n        return isinstance(value, datetime)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return http_date(value)\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return parse_date(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-71f77afa9c007e40", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "1bc3fe27e03149e3833eaab5c6061aa38e08d5c97da1a0567565e3fc4eb5912a", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 26, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__TagDateTime__57660738.py", "order": 9, "original_content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "parent_variant_id": "pyint-bef3b56d30e0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L205-L216", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 8}, "unit_kind": "class", "unit_name": "TagDateTime", "variant_id": "pyint-ef7557660738-I09", "group_id": "py-71f77afa9c007e40", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 402, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e627c52a913a-I10", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagDateTime(JSONTag):\n    __slots__ = ()\n    key = \" d\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, datetime)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return http_date(value)\n    def to_python(self, value: t.Any) -> t.Any:\n        return parse_date(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-71f77afa9c007e40", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "96352ebe7cf0dae4c62682ad29a9ab98e38b55f387c42dd88b8a8532bf8b6cbd", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 23, "local_path": "layout/partially-compact-layout/I10__flask__TagDateTime__c52a913a.py", "order": 10, "original_content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "parent_variant_id": "pyint-bef3b56d30e0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L205-L216", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 4, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "TagDateTime", "variant_id": "pyint-e627c52a913a-I10", "group_id": "py-71f77afa9c007e40", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 403, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4356bc9c22cf-I11", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagDateTime(JSONTag):\n    __slots__ = ()\n    key = \" d\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, datetime)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return http_date(value)\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return parse_date(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-71f77afa9c007e40", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 24, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__TagDateTime__bc9c22cf.py", "order": 11, "original_content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "parent_variant_id": "pyint-bef3b56d30e0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L205-L216", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "TagDateTime", "variant_id": "pyint-4356bc9c22cf-I11", "group_id": "py-71f77afa9c007e40", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 404, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5da1d0de9887-I12", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagDateTime(JSONTag):\n    __slots__ = ()\n    key = \" d\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, datetime)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return http_date(value)\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return parse_date(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-71f77afa9c007e40", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 24, "local_path": "data-flow/inline-intermediate-variables/I12__flask__TagDateTime__d0de9887.py", "order": 12, "original_content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "parent_variant_id": "pyint-bef3b56d30e0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L205-L216", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "TagDateTime", "variant_id": "pyint-5da1d0de9887-I12", "group_id": "py-71f77afa9c007e40", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 405, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-27a5b18836e9-I13", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass TagDateTime(JSONTag):\n    __slots__ = ()\n    key = \" d\"\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, datetime)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return http_date(value)\n\n    def to_python(self, value: t.Any) -> t.Any:\n        return parse_date(value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-71f77afa9c007e40", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 24, "local_path": "control-flow/lower-for-to-while/I13__flask__TagDateTime__b18836e9.py", "order": 13, "original_content_sha256": "fc103ae07dda147c9a9fcbbfd2e51aad76379c9b3fc33dddc1f7a67cbd65f544", "parent_variant_id": "pyint-bef3b56d30e0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L205-L216", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "TagDateTime", "variant_id": "pyint-27a5b18836e9-I13", "group_id": "py-71f77afa9c007e40", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 406, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-eff5721d7a56-SRC", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n\n    _store: OrderedDict[str, tuple[str, _VT]]\n\n    def __init__(\n        self,\n        data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n        **kwargs: _VT,\n    ) -> None:\n        self._store = OrderedDict()\n        if data is None:\n            data = {}\n        self.update(data, **kwargs)\n\n    def __setitem__(self, key: str, value: _VT) -> None:\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        self._store[key.lower()] = (key, value)\n\n    def __getitem__(self, key: str) -> _VT:\n        return self._store[key.lower()][1]\n\n    def __delitem__(self, key: str) -> None:\n        del self._store[key.lower()]\n\n    def __iter__(self) -> Iterator[str]:\n        return (casedkey for casedkey, _ in self._store.values())\n\n    def __len__(self) -> int:\n        return len(self._store)\n\n    def lower_items(self) -> Iterator[tuple[str, _VT]]:\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, Mapping):\n            other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other)  # type: ignore[reportUnknownArgumentType]\n        else:\n            return NotImplemented\n        # Compare insensitively\n        return dict(self.lower_items()) == dict(other_dict.lower_items())\n\n    # Copy is required\n    def copy(self) -> CaseInsensitiveDict[_VT]:\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self) -> str:\n        return str(dict(self.items()))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-72f1aedcdd4e6f8a", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 80, "local_path": "source-original/SRC__requests__CaseInsensitiveDict__721d7a56.py", "order": 0, "original_content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L20-L93", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "CaseInsensitiveDict", "variant_id": "pyint-eff5721d7a56-SRC", "group_id": "py-72f1aedcdd4e6f8a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 911, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-79823841fe85-I01", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n    \n\n    _store: OrderedDict[str, tuple[str, _VT]]\n\n    def __init__(\n        self,\n        data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n        **kwargs: _VT,\n    ) -> None:\n        self._store = OrderedDict()\n        if data is None:\n            data = {}\n        self.update(data, **kwargs)\n\n    def __setitem__(self, key: str, value: _VT) -> None:\n         \n         \n        self._store[key.lower()] = (key, value)\n\n    def __getitem__(self, key: str) -> _VT:\n        return self._store[key.lower()][1]\n\n    def __delitem__(self, key: str) -> None:\n        del self._store[key.lower()]\n\n    def __iter__(self) -> Iterator[str]:\n        return (casedkey for casedkey, _ in self._store.values())\n\n    def __len__(self) -> int:\n        return len(self._store)\n\n    def lower_items(self) -> Iterator[tuple[str, _VT]]:\n        \n        return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, Mapping):\n            other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other)   \n        else:\n            return NotImplemented\n         \n        return dict(self.lower_items()) == dict(other_dict.lower_items())\n\n     \n    def copy(self) -> CaseInsensitiveDict[_VT]:\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self) -> str:\n        return str(dict(self.items()))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-72f1aedcdd4e6f8a", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "5128775ac0bb0976678d3fdc3a6ab7c84d66623b9230a1d45b9fd4e8f5dce5fa", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 56, "local_path": "comments/remove-comments/I01__requests__CaseInsensitiveDict__3841fe85.py", "order": 1, "original_content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "parent_variant_id": "pyint-eff5721d7a56-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L20-L93", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 1201, "comments_removed": 7, "docstrings_removed": 2, "line_comments_removed": 5}, "unit_kind": "class", "unit_name": "CaseInsensitiveDict", "variant_id": "pyint-79823841fe85-I01", "group_id": "py-72f1aedcdd4e6f8a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 912, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-22aee56c115d-I02", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n\n    _store: OrderedDict[str, tuple[str, _VT]]\n\n    def __init__(\n        self,\n        dat: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n        **kwa: _VT,\n    ) -> None:\n        self._store = OrderedDict()\n        if dat is None:\n            dat = {}\n        self.update(dat, **kwa)\n\n    def __setitem__(self, key2: str, val: _VT) -> None:\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        self._store[key2.lower()] = (key2, val)\n\n    def __getitem__(self, key3: str) -> _VT:\n        return self._store[key3.lower()][1]\n\n    def __delitem__(self, key4: str) -> None:\n        del self._store[key4.lower()]\n\n    def __iter__(self) -> Iterator[str]:\n        return (cas for cas, _2 in self._store.values())\n\n    def __len__(self) -> int:\n        return len(self._store)\n\n    def lower2(self) -> Iterator[tuple[str, _VT]]:\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        return ((low, key5[1]) for (low, key5) in self._store.items())\n\n    def __eq__(self, oth: object) -> bool:\n        if isinstance(oth, Mapping):\n            other2: CaseInsensitiveDict[Any] = CaseInsensitiveDict(oth)  # type: ignore[reportUnknownArgumentType]\n        else:\n            return NotImplemented\n        # Compare insensitively\n        return dict(self.lower2()) == dict(other2.lower_items())\n\n    # Copy is required\n    def cop(self) -> CaseInsensitiveDict[_VT]:\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self) -> str:\n        return str(dict(self.items()))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-72f1aedcdd4e6f8a", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "513999dca16a48134ad6f299bb4ca22a180781d23afa2b577bf9d4449981f6cc", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 80, "local_path": "identifiers/shorten-identifiers/I02__requests__CaseInsensitiveDict__e56c115d.py", "order": 2, "original_content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "parent_variant_id": "pyint-eff5721d7a56-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L20-L93", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 30, "identifiers_declared": 14}, "unit_kind": "class", "unit_name": "CaseInsensitiveDict", "variant_id": "pyint-22aee56c115d-I02", "group_id": "py-72f1aedcdd4e6f8a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 913, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c023be8075de-I03", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n\n    _store: OrderedDict[str, tuple[str, _VT]]\n\n    def __init__(\n        self,\n        user: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n        **result: _VT,\n    ) -> None:\n        self._store = OrderedDict()\n        if user is None:\n            user = {}\n        self.update(user, **result)\n\n    def __setitem__(self, map: str, entry: _VT) -> None:\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        self._store[map.lower()] = (map, entry)\n\n    def __getitem__(self, map: str) -> _VT:\n        return self._store[map.lower()][1]\n\n    def __delitem__(self, map: str) -> None:\n        del self._store[map.lower()]\n\n    def __iter__(self) -> Iterator[str]:\n        return (category for category, key in self._store.values())\n\n    def __len__(self) -> int:\n        return len(self._store)\n\n    def buildConfig(self) -> Iterator[tuple[str, _VT]]:\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        return ((document, source[1]) for (document, source) in self._store.items())\n\n    def __eq__(self, entry: object) -> bool:\n        if isinstance(entry, Mapping):\n            defaultKey: CaseInsensitiveDict[Any] = CaseInsensitiveDict(entry)  # type: ignore[reportUnknownArgumentType]\n        else:\n            return NotImplemented\n        # Compare insensitively\n        return dict(self.buildConfig()) == dict(defaultKey.lower_items())\n\n    # Copy is required\n    def find(self) -> CaseInsensitiveDict[_VT]:\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self) -> str:\n        return str(dict(self.items()))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-72f1aedcdd4e6f8a", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "50f4ac01895337fa9d37b604e8f1c46e3bdb6f8e805be30271c007af5941f26a", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 80, "local_path": "identifiers/mislead-identifiers/I03__requests__CaseInsensitiveDict__be8075de.py", "order": 3, "original_content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "parent_variant_id": "pyint-eff5721d7a56-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L20-L93", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 30, "identifiers_declared": 14, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 11, "local_random_pool_selections": 12, "local_total_length_difference": 2, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 2, "method_random_pool_selections": 2, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "CaseInsensitiveDict", "variant_id": "pyint-c023be8075de-I03", "group_id": "py-72f1aedcdd4e6f8a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 914, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4ef5d36a6f0b-I04", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n\n    _store: OrderedDict[str, tuple[str, _VT]]\n\n    def __init__(\n        self,\n        c: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n        **d: _VT,\n    ) -> None:\n        self._store = OrderedDict()\n        if c is None:\n            c = {}\n        self.update(c, **d)\n\n    def __setitem__(self, e: str, f: _VT) -> None:\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        self._store[e.lower()] = (e, f)\n\n    def __getitem__(self, g: str) -> _VT:\n        return self._store[g.lower()][1]\n\n    def __delitem__(self, h: str) -> None:\n        del self._store[h.lower()]\n\n    def __iter__(self) -> Iterator[str]:\n        return (i for i, j in self._store.values())\n\n    def __len__(self) -> int:\n        return len(self._store)\n\n    def a(self) -> Iterator[tuple[str, _VT]]:\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        return ((k, l[1]) for (k, l) in self._store.items())\n\n    def __eq__(self, m: object) -> bool:\n        if isinstance(m, Mapping):\n            n: CaseInsensitiveDict[Any] = CaseInsensitiveDict(m)  # type: ignore[reportUnknownArgumentType]\n        else:\n            return NotImplemented\n        # Compare insensitively\n        return dict(self.a()) == dict(n.lower_items())\n\n    # Copy is required\n    def b(self) -> CaseInsensitiveDict[_VT]:\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self) -> str:\n        return str(dict(self.items()))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-72f1aedcdd4e6f8a", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "ed6837276ca57976cffb1e138999e81f7b89a66c063eb6f323e338cf69c07007", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 80, "local_path": "identifiers/garble-identifiers/I04__requests__CaseInsensitiveDict__d36a6f0b.py", "order": 4, "original_content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "parent_variant_id": "pyint-eff5721d7a56-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L20-L93", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 30, "identifiers_declared": 14}, "unit_kind": "class", "unit_name": "CaseInsensitiveDict", "variant_id": "pyint-4ef5d36a6f0b-I04", "group_id": "py-72f1aedcdd4e6f8a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 915, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8ae2ff980588-I05", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n\n    _store: OrderedDict[str, tuple[str, _VT]]\n\n    def __init__(\n        self,\n        data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n        **kwargs: _VT,\n    ) -> None:\n        self._store = OrderedDict()\n        if data is None:\n            data = {}\n        self.update(data, **kwargs)\n\n    def __setitem__(self, key: str, value: _VT) -> None:\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        self._store[key.lower()] = (key, value)\n\n    def __getitem__(self, key: str) -> _VT:\n        return self._store[key.lower()][0x1]\n\n    def __delitem__(self, key: str) -> None:\n        del self._store[key.lower()]\n\n    def __iter__(self) -> Iterator[str]:\n        return (casedkey for casedkey, _ in self._store.values())\n\n    def __len__(self) -> int:\n        return len(self._store)\n\n    def lower_items(self) -> Iterator[tuple[str, _VT]]:\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        return ((lowerkey, keyval[0x1]) for (lowerkey, keyval) in self._store.items())\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, Mapping):\n            other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other)  # type: ignore[reportUnknownArgumentType]\n        else:\n            return NotImplemented\n        # Compare insensitively\n        return dict(self.lower_items()) == dict(other_dict.lower_items())\n\n    # Copy is required\n    def copy(self) -> CaseInsensitiveDict[_VT]:\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self) -> str:\n        return str(dict(self.items()))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-72f1aedcdd4e6f8a", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "91475352d067f033b611449834e02a051b45eba77d93db1241902b2297f393af", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 80, "local_path": "expressions/encode-integer-literals/I05__requests__CaseInsensitiveDict__ff980588.py", "order": 5, "original_content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "parent_variant_id": "pyint-eff5721d7a56-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L20-L93", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 2}, "unit_kind": "class", "unit_name": "CaseInsensitiveDict", "variant_id": "pyint-8ae2ff980588-I05", "group_id": "py-72f1aedcdd4e6f8a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 916, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fd5108bdbbaa-I06", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n\n    _store: OrderedDict[str, tuple[str, _VT]]\n\n    def __init__(\n        self,\n        data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n        **kwargs: _VT,\n    ) -> None:\n        self._store = OrderedDict()\n        if not (data is None):\n            pass\n        else:\n            data = {}\n        self.update(data, **kwargs)\n\n    def __setitem__(self, key: str, value: _VT) -> None:\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        self._store[key.lower()] = (key, value)\n\n    def __getitem__(self, key: str) -> _VT:\n        return self._store[key.lower()][1]\n\n    def __delitem__(self, key: str) -> None:\n        del self._store[key.lower()]\n\n    def __iter__(self) -> Iterator[str]:\n        return (casedkey for casedkey, _ in self._store.values())\n\n    def __len__(self) -> int:\n        return len(self._store)\n\n    def lower_items(self) -> Iterator[tuple[str, _VT]]:\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())\n\n    def __eq__(self, other: object) -> bool:\n        if not (isinstance(other, Mapping)):\n            return NotImplemented\n        else:\n            other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other)  # type: ignore[reportUnknownArgumentType]\n        # Compare insensitively\n        return dict(self.lower_items()) == dict(other_dict.lower_items())\n\n    # Copy is required\n    def copy(self) -> CaseInsensitiveDict[_VT]:\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self) -> str:\n        return str(dict(self.items()))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-72f1aedcdd4e6f8a", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "d0d6245b4a40b55a07ef8c0415c37690c1bd7e97c02602b0a07f4bb7630604a3", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 82, "local_path": "expressions/invert-conditions/I06__requests__CaseInsensitiveDict__08bdbbaa.py", "order": 6, "original_content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "parent_variant_id": "pyint-eff5721d7a56-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L20-L93", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 2}, "unit_kind": "class", "unit_name": "CaseInsensitiveDict", "variant_id": "pyint-fd5108bdbbaa-I06", "group_id": "py-72f1aedcdd4e6f8a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 917, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c5639f6f2a52-I07", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n\n    _store: OrderedDict[str, tuple[str, _VT]]\n\n    def __init__(\n        self,\n        data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n        **kwargs: _VT,\n    ) -> None:\n        if ((0x683a ^ 0x683a) != 0):\n            raise AssertionError()\n        self._store = OrderedDict()\n        if data is None:\n            data = {}\n        self.update(data, **kwargs)\n\n    def __setitem__(self, key: str, value: _VT) -> None:\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        if ((0x44dd ^ 0x44dd) != 0):\n            raise AssertionError()\n        self._store[key.lower()] = (key, value)\n\n    def __getitem__(self, key: str) -> _VT:\n        if ((0x4765 ^ 0x4765) != 0):\n            raise AssertionError()\n        return self._store[key.lower()][1]\n\n    def __delitem__(self, key: str) -> None:\n        if ((0x46e5 ^ 0x46e5) != 0):\n            raise AssertionError()\n        del self._store[key.lower()]\n\n    def __iter__(self) -> Iterator[str]:\n        if ((0xccbd ^ 0xccbd) != 0):\n            raise AssertionError()\n        return (casedkey for casedkey, _ in self._store.values())\n\n    def __len__(self) -> int:\n        if ((0xe0c5 ^ 0xe0c5) != 0):\n            raise AssertionError()\n        return len(self._store)\n\n    def lower_items(self) -> Iterator[tuple[str, _VT]]:\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        if ((0x4858 ^ 0x4858) != 0):\n            raise AssertionError()\n        return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())\n\n    def __eq__(self, other: object) -> bool:\n        if ((0xb41 ^ 0xb41) != 0):\n            raise AssertionError()\n        if isinstance(other, Mapping):\n            other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other)  # type: ignore[reportUnknownArgumentType]\n        else:\n            return NotImplemented\n        # Compare insensitively\n        return dict(self.lower_items()) == dict(other_dict.lower_items())\n\n    # Copy is required\n    def copy(self) -> CaseInsensitiveDict[_VT]:\n        if ((0x45d8 ^ 0x45d8) != 0):\n            raise AssertionError()\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self) -> str:\n        if ((0x279f ^ 0x279f) != 0):\n            raise AssertionError()\n        return str(dict(self.items()))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-72f1aedcdd4e6f8a", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "28bb39dfa1eb757c07ff30a7f6118d53997e56e97d3d11c48c5ec636437e9f3c", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 100, "local_path": "code-injection/insert-dead-branches/I07__requests__CaseInsensitiveDict__9f6f2a52.py", "order": 7, "original_content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "parent_variant_id": "pyint-eff5721d7a56-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L20-L93", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 10}, "unit_kind": "class", "unit_name": "CaseInsensitiveDict", "variant_id": "pyint-c5639f6f2a52-I07", "group_id": "py-72f1aedcdd4e6f8a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 918, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-aea035ef9ee2-I08", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n\n    _store: OrderedDict[str, tuple[str, _VT]]\n\n    def __init__(\n        self,\n        data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n        **kwargs: _VT,\n    ) -> None:\n        self._store = OrderedDict()\n        if data is None:\n            data = {}\n        self.update(data, **kwargs)\n\n    def __setitem__(self, key: str, value: _VT) -> None:\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        self._store[key.lower()] = (key, value)\n\n    def __getitem__(self, key: str) -> _VT:\n        return self._store[key.lower()][1]\n\n    def __delitem__(self, key: str) -> None:\n        del self._store[key.lower()]\n\n    def __iter__(self) -> Iterator[str]:\n        return (casedkey for casedkey, _ in self._store.values())\n\n    def __len__(self) -> int:\n        return len(self._store)\n\n    def lower_items(self) -> Iterator[tuple[str, _VT]]:\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, Mapping):\n            other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other)  # type: ignore[reportUnknownArgumentType]\n        else:\n            return NotImplemented\n        # Compare insensitively\n        return dict(self.lower_items()) == dict(other_dict.lower_items())\n\n    # Copy is required\n    def copy(self) -> CaseInsensitiveDict[_VT]:\n        remaining_steps = 3\n        while remaining_steps > 0:\n            remaining_steps -= 1\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self) -> str:\n        return str(dict(self.items()))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-72f1aedcdd4e6f8a", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "a6df32997dddb6e5d3759b3743ff86341372fa8a92de4fd50d7be726e59b28f0", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 83, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__CaseInsensitiveDict__35ef9ee2.py", "order": 8, "original_content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "parent_variant_id": "pyint-eff5721d7a56-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L20-L93", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 1}, "unit_kind": "class", "unit_name": "CaseInsensitiveDict", "variant_id": "pyint-aea035ef9ee2-I08", "group_id": "py-72f1aedcdd4e6f8a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 919, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c71433ce8d92-I09", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n\n    _store: OrderedDict[str, tuple[str, _VT]]\n\n    def __init__(\n        self,\n        data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n        **kwargs: _VT,\n    ) -> None:\n        self._store = OrderedDict()\n        if data is None:\n            data = {}\n        self.update(data, **kwargs)\n\n    def __setitem__(self, key: str, value: _VT) -> None:\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        self._store[key.lower()] = (key, value)\n\n    def __getitem__(self, key: str) -> _VT:\n        lI0O_ef028acd = 0x2cb9 ^ 0x2cb9\n        if lI0O_ef028acd == 0:\n            lI0O_ef028acd |= 0\n        else:\n            lI0O_ef028acd &= 0\n        return self._store[key.lower()][1]\n\n    def __delitem__(self, key: str) -> None:\n        del self._store[key.lower()]\n\n    def __iter__(self) -> Iterator[str]:\n        return (casedkey for casedkey, _ in self._store.values())\n\n    def __len__(self) -> int:\n        return len(self._store)\n\n    def lower_items(self) -> Iterator[tuple[str, _VT]]:\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, Mapping):\n            other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other)  # type: ignore[reportUnknownArgumentType]\n        else:\n            return NotImplemented\n        # Compare insensitively\n        return dict(self.lower_items()) == dict(other_dict.lower_items())\n\n    # Copy is required\n    def copy(self) -> CaseInsensitiveDict[_VT]:\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self) -> str:\n        return str(dict(self.items()))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-72f1aedcdd4e6f8a", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "191883b4dc273031860c7c46f8f7bba0a9bc806f3a88d4918e896e447fa6225c", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 85, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__CaseInsensitiveDict__33ce8d92.py", "order": 9, "original_content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "parent_variant_id": "pyint-eff5721d7a56-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L20-L93", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 6}, "unit_kind": "class", "unit_name": "CaseInsensitiveDict", "variant_id": "pyint-c71433ce8d92-I09", "group_id": "py-72f1aedcdd4e6f8a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 920, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-299d6f54d0f4-I10", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\nclass CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n    _store: OrderedDict[str, tuple[str, _VT]]\n\n    def __init__(\n        self,\n        data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n        **kwargs: _VT,     ) -> None:\n        self._store = OrderedDict()\n        if data is None:\n            data = {}\n        self.update(data, **kwargs)\n\n    def __setitem__(self, key: str, value: _VT) -> None:\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        self._store[key.lower()] = (key, value)\n\n    def __getitem__(self, key: str) -> _VT:\n        return self._store[key.lower()][1]\n\n    def __delitem__(self, key: str) -> None:\n        del self._store[key.lower()]\n\n    def __iter__(self) -> Iterator[str]:\n        return (casedkey for casedkey, _ in self._store.values())\n\n    def __len__(self) -> int:\n        return len(self._store)\n\n    def lower_items(self) -> Iterator[tuple[str, _VT]]:\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, Mapping):\n            other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other)  # type: ignore[reportUnknownArgumentType]\n        else:\n            return NotImplemented\n        # Compare insensitively\n        return dict(self.lower_items()) == dict(other_dict.lower_items())\n\n    # Copy is required\n    def copy(self) -> CaseInsensitiveDict[_VT]:\n        return CaseInsensitiveDict(self._store.values())\n    def __repr__(self) -> str:\n        return str(dict(self.items()))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-72f1aedcdd4e6f8a", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "58a0cdc2e5d0b7d5aa7695f291d0655c034d89499c0da80d366d74d6401d8b81", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 72, "local_path": "layout/partially-compact-layout/I10__requests__CaseInsensitiveDict__6f54d0f4.py", "order": 10, "original_content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "parent_variant_id": "pyint-eff5721d7a56-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L20-L93", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 21, "line_break_groups_removed": 8, "line_breaks_removed": 8, "whitespace_characters_removed": 7}, "unit_kind": "class", "unit_name": "CaseInsensitiveDict", "variant_id": "pyint-299d6f54d0f4-I10", "group_id": "py-72f1aedcdd4e6f8a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 921, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1dbf4c644394-I11", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n\n    _store: OrderedDict[str, tuple[str, _VT]]\n\n    def __init__(\n        self,\n        data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n        **kwargs: _VT,\n    ) -> None:\n        self._store = OrderedDict()\n        if data is None:\n            data = {}\n        self.update(data, **kwargs)\n\n    def __setitem__(self, key: str, value: _VT) -> None:\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        self._store[key.lower()] = (key, value)\n\n    def __getitem__(self, key: str) -> _VT:\n        a = 2\n        b = -1\n        return self._store[key.lower()][(a + b)]\n\n    def __delitem__(self, key: str) -> None:\n        del self._store[key.lower()]\n\n    def __iter__(self) -> Iterator[str]:\n        return (casedkey for casedkey, _ in self._store.values())\n\n    def __len__(self) -> int:\n        return len(self._store)\n\n    def lower_items(self) -> Iterator[tuple[str, _VT]]:\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        c = 2\n        d = -1\n        return ((lowerkey, keyval[(c + d)]) for (lowerkey, keyval) in self._store.items())\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, Mapping):\n            other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other)  # type: ignore[reportUnknownArgumentType]\n        else:\n            return NotImplemented\n        # Compare insensitively\n        return dict(self.lower_items()) == dict(other_dict.lower_items())\n\n    # Copy is required\n    def copy(self) -> CaseInsensitiveDict[_VT]:\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self) -> str:\n        return str(dict(self.items()))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-72f1aedcdd4e6f8a", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "315fe6865589f42eeea7308dc485eb64e67045f7903a778f4e932867d84ceac3", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 84, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__CaseInsensitiveDict__4c644394.py", "order": 11, "original_content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "parent_variant_id": "pyint-eff5721d7a56-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L20-L93", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 2, "intermediate_variables_introduced": 4, "statements_augmented": 2}, "unit_kind": "class", "unit_name": "CaseInsensitiveDict", "variant_id": "pyint-1dbf4c644394-I11", "group_id": "py-72f1aedcdd4e6f8a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 922, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-37e475c5a71a-I12", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n\n    _store: OrderedDict[str, tuple[str, _VT]]\n\n    def __init__(\n        self,\n        data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n        **kwargs: _VT,\n    ) -> None:\n        self._store = OrderedDict()\n        if data is None:\n            data = {}\n        self.update(data, **kwargs)\n\n    def __setitem__(self, key: str, value: _VT) -> None:\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        self._store[key.lower()] = (key, value)\n\n    def __getitem__(self, key: str) -> _VT:\n        return self._store[key.lower()][1]\n\n    def __delitem__(self, key: str) -> None:\n        del self._store[key.lower()]\n\n    def __iter__(self) -> Iterator[str]:\n        return (casedkey for casedkey, _ in self._store.values())\n\n    def __len__(self) -> int:\n        return len(self._store)\n\n    def lower_items(self) -> Iterator[tuple[str, _VT]]:\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, Mapping):\n            other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other)  # type: ignore[reportUnknownArgumentType]\n        else:\n            return NotImplemented\n        # Compare insensitively\n        return dict(self.lower_items()) == dict(other_dict.lower_items())\n\n    # Copy is required\n    def copy(self) -> CaseInsensitiveDict[_VT]:\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self) -> str:\n        return str(dict(self.items()))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-72f1aedcdd4e6f8a", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 80, "local_path": "data-flow/inline-intermediate-variables/I12__requests__CaseInsensitiveDict__75c5a71a.py", "order": 12, "original_content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "parent_variant_id": "pyint-eff5721d7a56-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L20-L93", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "CaseInsensitiveDict", "variant_id": "pyint-37e475c5a71a-I12", "group_id": "py-72f1aedcdd4e6f8a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 923, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d6adc2c7f9cc-I13", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n\n    _store: OrderedDict[str, tuple[str, _VT]]\n\n    def __init__(\n        self,\n        data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n        **kwargs: _VT,\n    ) -> None:\n        self._store = OrderedDict()\n        if data is None:\n            data = {}\n        self.update(data, **kwargs)\n\n    def __setitem__(self, key: str, value: _VT) -> None:\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        self._store[key.lower()] = (key, value)\n\n    def __getitem__(self, key: str) -> _VT:\n        return self._store[key.lower()][1]\n\n    def __delitem__(self, key: str) -> None:\n        del self._store[key.lower()]\n\n    def __iter__(self) -> Iterator[str]:\n        return (casedkey for casedkey, _ in self._store.values())\n\n    def __len__(self) -> int:\n        return len(self._store)\n\n    def lower_items(self) -> Iterator[tuple[str, _VT]]:\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, Mapping):\n            other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other)  # type: ignore[reportUnknownArgumentType]\n        else:\n            return NotImplemented\n        # Compare insensitively\n        return dict(self.lower_items()) == dict(other_dict.lower_items())\n\n    # Copy is required\n    def copy(self) -> CaseInsensitiveDict[_VT]:\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self) -> str:\n        return str(dict(self.items()))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-72f1aedcdd4e6f8a", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 80, "local_path": "control-flow/lower-for-to-while/I13__requests__CaseInsensitiveDict__c2c7f9cc.py", "order": 13, "original_content_sha256": "a6b1ae9e5d2c661356e72c2172d2135f042f0b52a22c5808c1a8f865e4300fcb", "parent_variant_id": "pyint-eff5721d7a56-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L20-L93", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "CaseInsensitiveDict", "variant_id": "pyint-d6adc2c7f9cc-I13", "group_id": "py-72f1aedcdd4e6f8a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 924, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-82d5e16c6695-SRC", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SessionMixin(MutableMapping[str, t.Any]):\n    \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n\n    @property\n    def permanent(self) -> bool:\n        \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n        return self.get(\"_permanent\", False)  # type: ignore[no-any-return]\n\n    @permanent.setter\n    def permanent(self, value: bool) -> None:\n        self[\"_permanent\"] = bool(value)\n\n    #: Some implementations can detect whether a session is newly\n    #: created, but that is not guaranteed. Use with caution. The mixin\n    # default is hard-coded ``False``.\n    new = False\n\n    #: Some implementations can detect changes to the session and set\n    #: this when that happens. The mixin default is hard coded to\n    #: ``True``.\n    modified = True\n\n    accessed = False\n    \"\"\"Indicates if the session was accessed, even if it was not modified. This\n    is set when the session object is accessed through the request context,\n    including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n    be added if this is ``True``.\n\n    .. versionchanged:: 3.1.3\n        This is tracked by the request context.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-763480aa9d605f89", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 43, "local_path": "source-original/SRC__flask__SessionMixin__e16c6695.py", "order": 0, "original_content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L24-L54", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "SessionMixin", "variant_id": "pyint-82d5e16c6695-SRC", "group_id": "py-763480aa9d605f89", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 575, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3dac93ff84d0-I01", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SessionMixin(MutableMapping[str, t.Any]):\n    \n\n    @property\n    def permanent(self) -> bool:\n        \n        return self.get(\"_permanent\", False)   \n\n    @permanent.setter\n    def permanent(self, value: bool) -> None:\n        self[\"_permanent\"] = bool(value)\n\n     \n     \n     \n    new = False\n\n     \n     \n     \n    modified = True\n\n    accessed = False\n    \"\"\"Indicates if the session was accessed, even if it was not modified. This\n    is set when the session object is accessed through the request context,\n    including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n    be added if this is ``True``.\n\n    .. versionchanged:: 3.1.3\n        This is tracked by the request context.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-763480aa9d605f89", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "1fc73133717b14a12ecfb6de90ce6f0943e77496f125f703cc929ebb0a06b769", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 43, "local_path": "comments/remove-comments/I01__flask__SessionMixin__93ff84d0.py", "order": 1, "original_content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "parent_variant_id": "pyint-82d5e16c6695-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L24-L54", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 436, "comments_removed": 9, "docstrings_removed": 2, "line_comments_removed": 7}, "unit_kind": "class", "unit_name": "SessionMixin", "variant_id": "pyint-3dac93ff84d0-I01", "group_id": "py-763480aa9d605f89", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 576, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-494c2b583d15-I02", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SessionMixin(MutableMapping[str, t.Any]):\n    \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n\n    @property\n    def per2(self) -> bool:\n        \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n        return self.get(\"_permanent\", False)  # type: ignore[no-any-return]\n\n    @permanent.setter\n    def per2(self, val: bool) -> None:\n        self[\"_permanent\"] = bool(val)\n\n    #: Some implementations can detect whether a session is newly\n    #: created, but that is not guaranteed. Use with caution. The mixin\n    # default is hard-coded ``False``.\n    new = False\n\n    #: Some implementations can detect changes to the session and set\n    #: this when that happens. The mixin default is hard coded to\n    #: ``True``.\n    modified = True\n\n    accessed = False\n    \"\"\"Indicates if the session was accessed, even if it was not modified. This\n    is set when the session object is accessed through the request context,\n    including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n    be added if this is ``True``.\n\n    .. versionchanged:: 3.1.3\n        This is tracked by the request context.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-763480aa9d605f89", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "472a5e34c76731f4692c271bf6ff15630e7f9a0118ba0790dbcbd32fa63557ba", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 43, "local_path": "identifiers/shorten-identifiers/I02__flask__SessionMixin__2b583d15.py", "order": 2, "original_content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "parent_variant_id": "pyint-82d5e16c6695-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L24-L54", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 4, "identifiers_declared": 3}, "unit_kind": "class", "unit_name": "SessionMixin", "variant_id": "pyint-494c2b583d15-I02", "group_id": "py-763480aa9d605f89", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 577, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9c0f56278a7f-I03", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SessionMixin(MutableMapping[str, t.Any]):\n    \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n\n    @property\n    def buildMode(self) -> bool:\n        \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n        return self.get(\"_permanent\", False)  # type: ignore[no-any-return]\n\n    @permanent.setter\n    def buildMode(self, event: bool) -> None:\n        self[\"_permanent\"] = bool(event)\n\n    #: Some implementations can detect whether a session is newly\n    #: created, but that is not guaranteed. Use with caution. The mixin\n    # default is hard-coded ``False``.\n    new = False\n\n    #: Some implementations can detect changes to the session and set\n    #: this when that happens. The mixin default is hard coded to\n    #: ``True``.\n    modified = True\n\n    accessed = False\n    \"\"\"Indicates if the session was accessed, even if it was not modified. This\n    is set when the session object is accessed through the request context,\n    including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n    be added if this is ``True``.\n\n    .. versionchanged:: 3.1.3\n        This is tracked by the request context.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-763480aa9d605f89", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "adf774fea9b18bbda1d75e1a6bcbbd9db4050ecb575d3c164fa472ddde096912", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 43, "local_path": "identifiers/mislead-identifiers/I03__flask__SessionMixin__56278a7f.py", "order": 3, "original_content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "parent_variant_id": "pyint-82d5e16c6695-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L24-L54", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 4, "identifiers_declared": 3, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 1, "local_random_pool_selections": 1, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 2, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "SessionMixin", "variant_id": "pyint-9c0f56278a7f-I03", "group_id": "py-763480aa9d605f89", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 578, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-31df94551093-I04", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SessionMixin(MutableMapping[str, t.Any]):\n    \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n\n    @property\n    def b(self) -> bool:\n        \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n        return self.get(\"_permanent\", False)  # type: ignore[no-any-return]\n\n    @permanent.setter\n    def b(self, c: bool) -> None:\n        self[\"_permanent\"] = bool(c)\n\n    #: Some implementations can detect whether a session is newly\n    #: created, but that is not guaranteed. Use with caution. The mixin\n    # default is hard-coded ``False``.\n    new = False\n\n    #: Some implementations can detect changes to the session and set\n    #: this when that happens. The mixin default is hard coded to\n    #: ``True``.\n    modified = True\n\n    accessed = False\n    \"\"\"Indicates if the session was accessed, even if it was not modified. This\n    is set when the session object is accessed through the request context,\n    including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n    be added if this is ``True``.\n\n    .. versionchanged:: 3.1.3\n        This is tracked by the request context.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-763480aa9d605f89", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "13f51913dd9e2d5114685e3970b8ee2b6244b91e4a9dcddc87ae6ee12f2745b8", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 43, "local_path": "identifiers/garble-identifiers/I04__flask__SessionMixin__94551093.py", "order": 4, "original_content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "parent_variant_id": "pyint-82d5e16c6695-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L24-L54", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 4, "identifiers_declared": 3}, "unit_kind": "class", "unit_name": "SessionMixin", "variant_id": "pyint-31df94551093-I04", "group_id": "py-763480aa9d605f89", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 579, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-af2ebddc7288-I05", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SessionMixin(MutableMapping[str, t.Any]):\n    \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n\n    @property\n    def permanent(self) -> bool:\n        \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n        return self.get(\"_permanent\", False)  # type: ignore[no-any-return]\n\n    @permanent.setter\n    def permanent(self, value: bool) -> None:\n        self[\"_permanent\"] = bool(value)\n\n    #: Some implementations can detect whether a session is newly\n    #: created, but that is not guaranteed. Use with caution. The mixin\n    # default is hard-coded ``False``.\n    new = False\n\n    #: Some implementations can detect changes to the session and set\n    #: this when that happens. The mixin default is hard coded to\n    #: ``True``.\n    modified = True\n\n    accessed = False\n    \"\"\"Indicates if the session was accessed, even if it was not modified. This\n    is set when the session object is accessed through the request context,\n    including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n    be added if this is ``True``.\n\n    .. versionchanged:: 3.1.3\n        This is tracked by the request context.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-763480aa9d605f89", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 43, "local_path": "expressions/encode-integer-literals/I05__flask__SessionMixin__bddc7288.py", "order": 5, "original_content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "parent_variant_id": "pyint-82d5e16c6695-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L24-L54", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "SessionMixin", "variant_id": "pyint-af2ebddc7288-I05", "group_id": "py-763480aa9d605f89", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 580, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5349a4423f92-I06", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SessionMixin(MutableMapping[str, t.Any]):\n    \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n\n    @property\n    def permanent(self) -> bool:\n        \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n        return self.get(\"_permanent\", False)  # type: ignore[no-any-return]\n\n    @permanent.setter\n    def permanent(self, value: bool) -> None:\n        self[\"_permanent\"] = bool(value)\n\n    #: Some implementations can detect whether a session is newly\n    #: created, but that is not guaranteed. Use with caution. The mixin\n    # default is hard-coded ``False``.\n    new = False\n\n    #: Some implementations can detect changes to the session and set\n    #: this when that happens. The mixin default is hard coded to\n    #: ``True``.\n    modified = True\n\n    accessed = False\n    \"\"\"Indicates if the session was accessed, even if it was not modified. This\n    is set when the session object is accessed through the request context,\n    including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n    be added if this is ``True``.\n\n    .. versionchanged:: 3.1.3\n        This is tracked by the request context.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-763480aa9d605f89", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 43, "local_path": "expressions/invert-conditions/I06__flask__SessionMixin__a4423f92.py", "order": 6, "original_content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "parent_variant_id": "pyint-82d5e16c6695-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L24-L54", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "SessionMixin", "variant_id": "pyint-5349a4423f92-I06", "group_id": "py-763480aa9d605f89", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 581, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ef7497d8ec78-I07", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SessionMixin(MutableMapping[str, t.Any]):\n    \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n\n    @property\n    def permanent(self) -> bool:\n        \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n        if ((0x3779 ^ 0x3779) != 0):\n            raise AssertionError()\n        return self.get(\"_permanent\", False)  # type: ignore[no-any-return]\n\n    @permanent.setter\n    def permanent(self, value: bool) -> None:\n        if ((0x9199 ^ 0x9199) != 0):\n            raise AssertionError()\n        self[\"_permanent\"] = bool(value)\n\n    #: Some implementations can detect whether a session is newly\n    #: created, but that is not guaranteed. Use with caution. The mixin\n    # default is hard-coded ``False``.\n    new = False\n\n    #: Some implementations can detect changes to the session and set\n    #: this when that happens. The mixin default is hard coded to\n    #: ``True``.\n    modified = True\n\n    accessed = False\n    \"\"\"Indicates if the session was accessed, even if it was not modified. This\n    is set when the session object is accessed through the request context,\n    including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n    be added if this is ``True``.\n\n    .. versionchanged:: 3.1.3\n        This is tracked by the request context.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-763480aa9d605f89", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "78556c0a560e684b618354e6124d352d8564d232468aaa02e343686559e8a9b3", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 47, "local_path": "code-injection/insert-dead-branches/I07__flask__SessionMixin__97d8ec78.py", "order": 7, "original_content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "parent_variant_id": "pyint-82d5e16c6695-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L24-L54", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "SessionMixin", "variant_id": "pyint-ef7497d8ec78-I07", "group_id": "py-763480aa9d605f89", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 582, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6ee864ac5609-I08", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SessionMixin(MutableMapping[str, t.Any]):\n    \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n\n    @property\n    def permanent(self) -> bool:\n        \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n        factorial = 1\n        for current_factor in range(2, 5):\n            factorial *= current_factor\n        return self.get(\"_permanent\", False)  # type: ignore[no-any-return]\n\n    @permanent.setter\n    def permanent(self, value: bool) -> None:\n        self[\"_permanent\"] = bool(value)\n\n    #: Some implementations can detect whether a session is newly\n    #: created, but that is not guaranteed. Use with caution. The mixin\n    # default is hard-coded ``False``.\n    new = False\n\n    #: Some implementations can detect changes to the session and set\n    #: this when that happens. The mixin default is hard coded to\n    #: ``True``.\n    modified = True\n\n    accessed = False\n    \"\"\"Indicates if the session was accessed, even if it was not modified. This\n    is set when the session object is accessed through the request context,\n    including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n    be added if this is ``True``.\n\n    .. versionchanged:: 3.1.3\n        This is tracked by the request context.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-763480aa9d605f89", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "890abe4561d936aba7ee1699e0878dc020ae079287b2a926e16617d16852fd61", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 46, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__SessionMixin__64ac5609.py", "order": 8, "original_content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "parent_variant_id": "pyint-82d5e16c6695-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L24-L54", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 6}, "unit_kind": "class", "unit_name": "SessionMixin", "variant_id": "pyint-6ee864ac5609-I08", "group_id": "py-763480aa9d605f89", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 583, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6cd9594888b5-I09", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SessionMixin(MutableMapping[str, t.Any]):\n    \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n\n    @property\n    def permanent(self) -> bool:\n        \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n        return self.get(\"_permanent\", False)  # type: ignore[no-any-return]\n\n    @permanent.setter\n    def permanent(self, value: bool) -> None:\n        lI0O_42d9febf = 0x87bd ^ 0x87bd\n        if lI0O_42d9febf == 0:\n            lI0O_42d9febf |= 0\n        else:\n            lI0O_42d9febf &= 0\n        self[\"_permanent\"] = bool(value)\n\n    #: Some implementations can detect whether a session is newly\n    #: created, but that is not guaranteed. Use with caution. The mixin\n    # default is hard-coded ``False``.\n    new = False\n\n    #: Some implementations can detect changes to the session and set\n    #: this when that happens. The mixin default is hard coded to\n    #: ``True``.\n    modified = True\n\n    accessed = False\n    \"\"\"Indicates if the session was accessed, even if it was not modified. This\n    is set when the session object is accessed through the request context,\n    including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n    be added if this is ``True``.\n\n    .. versionchanged:: 3.1.3\n        This is tracked by the request context.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-763480aa9d605f89", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "fff216c274a6bc6fda38d3c41c6ef7e591feb5351bc024ffc37844c144b0f1d8", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 48, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__SessionMixin__594888b5.py", "order": 9, "original_content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "parent_variant_id": "pyint-82d5e16c6695-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L24-L54", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 6}, "unit_kind": "class", "unit_name": "SessionMixin", "variant_id": "pyint-6cd9594888b5-I09", "group_id": "py-763480aa9d605f89", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 584, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e2087edf19dd-I10", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\nclass SessionMixin(MutableMapping[str, t.Any]):\n    \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n    @property\n    def permanent(self) -> bool:\n        \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n        return self.get(\"_permanent\", False)  # type: ignore[no-any-return]\n\n    @permanent.setter\n    def permanent(self, value: bool) -> None:\n        self[\"_permanent\"] = bool(value)\n\n    #: Some implementations can detect whether a session is newly\n    #: created, but that is not guaranteed. Use with caution. The mixin\n    # default is hard-coded ``False``.\n    new = False\n\n    #: Some implementations can detect changes to the session and set\n    #: this when that happens. The mixin default is hard coded to\n    #: ``True``.\n    modified = True\n\n    accessed = False\n    \"\"\"Indicates if the session was accessed, even if it was not modified. This\n    is set when the session object is accessed through the request context,\n    including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n    be added if this is ``True``.\n\n    .. versionchanged:: 3.1.3\n        This is tracked by the request context.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-763480aa9d605f89", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "fe1944152c0f1dc0c02f2823f645cf6eba83d84b290fff7a97c7ed79c5d36e14", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 41, "local_path": "layout/partially-compact-layout/I10__flask__SessionMixin__7edf19dd.py", "order": 10, "original_content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "parent_variant_id": "pyint-82d5e16c6695-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L24-L54", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 7, "line_break_groups_removed": 2, "line_breaks_removed": 2, "whitespace_characters_removed": 2}, "unit_kind": "class", "unit_name": "SessionMixin", "variant_id": "pyint-e2087edf19dd-I10", "group_id": "py-763480aa9d605f89", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 585, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-45d9db423421-I11", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SessionMixin(MutableMapping[str, t.Any]):\n    \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n\n    @property\n    def permanent(self) -> bool:\n        \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n        return self.get(\"_permanent\", False)  # type: ignore[no-any-return]\n\n    @permanent.setter\n    def permanent(self, value: bool) -> None:\n        self[\"_permanent\"] = bool(value)\n\n    #: Some implementations can detect whether a session is newly\n    #: created, but that is not guaranteed. Use with caution. The mixin\n    # default is hard-coded ``False``.\n    new = False\n\n    #: Some implementations can detect changes to the session and set\n    #: this when that happens. The mixin default is hard coded to\n    #: ``True``.\n    modified = True\n\n    accessed = False\n    \"\"\"Indicates if the session was accessed, even if it was not modified. This\n    is set when the session object is accessed through the request context,\n    including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n    be added if this is ``True``.\n\n    .. versionchanged:: 3.1.3\n        This is tracked by the request context.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-763480aa9d605f89", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 43, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__SessionMixin__db423421.py", "order": 11, "original_content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "parent_variant_id": "pyint-82d5e16c6695-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L24-L54", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "SessionMixin", "variant_id": "pyint-45d9db423421-I11", "group_id": "py-763480aa9d605f89", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 586, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-49a04dd7947c-I12", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SessionMixin(MutableMapping[str, t.Any]):\n    \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n\n    @property\n    def permanent(self) -> bool:\n        \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n        return self.get(\"_permanent\", False)  # type: ignore[no-any-return]\n\n    @permanent.setter\n    def permanent(self, value: bool) -> None:\n        self[\"_permanent\"] = bool(value)\n\n    #: Some implementations can detect whether a session is newly\n    #: created, but that is not guaranteed. Use with caution. The mixin\n    # default is hard-coded ``False``.\n    new = False\n\n    #: Some implementations can detect changes to the session and set\n    #: this when that happens. The mixin default is hard coded to\n    #: ``True``.\n    modified = True\n\n    accessed = False\n    \"\"\"Indicates if the session was accessed, even if it was not modified. This\n    is set when the session object is accessed through the request context,\n    including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n    be added if this is ``True``.\n\n    .. versionchanged:: 3.1.3\n        This is tracked by the request context.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-763480aa9d605f89", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 43, "local_path": "data-flow/inline-intermediate-variables/I12__flask__SessionMixin__4dd7947c.py", "order": 12, "original_content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "parent_variant_id": "pyint-82d5e16c6695-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L24-L54", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "SessionMixin", "variant_id": "pyint-49a04dd7947c-I12", "group_id": "py-763480aa9d605f89", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 587, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ccf455e964fe-I13", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SessionMixin(MutableMapping[str, t.Any]):\n    \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n\n    @property\n    def permanent(self) -> bool:\n        \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n        return self.get(\"_permanent\", False)  # type: ignore[no-any-return]\n\n    @permanent.setter\n    def permanent(self, value: bool) -> None:\n        self[\"_permanent\"] = bool(value)\n\n    #: Some implementations can detect whether a session is newly\n    #: created, but that is not guaranteed. Use with caution. The mixin\n    # default is hard-coded ``False``.\n    new = False\n\n    #: Some implementations can detect changes to the session and set\n    #: this when that happens. The mixin default is hard coded to\n    #: ``True``.\n    modified = True\n\n    accessed = False\n    \"\"\"Indicates if the session was accessed, even if it was not modified. This\n    is set when the session object is accessed through the request context,\n    including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n    be added if this is ``True``.\n\n    .. versionchanged:: 3.1.3\n        This is tracked by the request context.\n    \"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-763480aa9d605f89", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 43, "local_path": "control-flow/lower-for-to-while/I13__flask__SessionMixin__55e964fe.py", "order": 13, "original_content_sha256": "fe557250d1c6a2f96b6c3af5b7f4a6c4df298877e529f65809778ce32a7a5a3c", "parent_variant_id": "pyint-82d5e16c6695-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L24-L54", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "SessionMixin", "variant_id": "pyint-ccf455e964fe-I13", "group_id": "py-763480aa9d605f89", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 588, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5c2b55814568-SRC", "source": "import copy\nimport operator\nimport warnings\nfrom contextlib import nullcontext\nfrom functools import partial, reduce\nfrom itertools import chain, islice\nfrom weakref import ref as weak_ref\nfrom asgiref.sync import sync_to_async\nimport django\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.db import (\n    DJANGO_VERSION_PICKLE_KEY,\n    IntegrityError,\n    NotSupportedError,\n    connections,\n    router,\n    transaction,\n)\nfrom django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql\nfrom django.db.models.constants import LOOKUP_SEP, OnConflict\nfrom django.db.models.deletion import Collector\nfrom django.db.models.expressions import (\n    Case,\n    Col,\n    ColPairs,\n    DatabaseDefault,\n    F,\n    OrderBy,\n    Value,\n    When,\n)\nfrom django.db.models.fetch_modes import FETCH_ONE\nfrom django.db.models.functions import Cast, Trunc\nfrom django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q\nfrom django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT\nfrom django.db.models.utils import (\n    AltersData,\n    create_namedtuple_class,\n    resolve_callables,\n)\nfrom django.utils import timezone\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    RemovedInDjango71Warning,\n    warn_about_external_use,\n)\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import func_accepts_kwargs, func_supports_parameter\nfrom django.utils.warnings import django_file_prefixes\n\nclass QuerySet(AltersData):\n    \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n    def __init__(self, model=None, query=None, using=None, hints=None):\n        self.model = model\n        self._db = using\n        self._hints = hints or {}\n        self._query = query or sql.Query(self.model)\n        self._result_cache = None\n        self._sticky_filter = False\n        self._for_write = False\n        self._prefetch_related_lookups = ()\n        self._prefetch_done = False\n        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}\n        self._iterable_class = ModelIterable\n        self._fetch_mode = DEFAULT_FETCH_MODE\n        self._fields = None\n        self._defer_next_filter = False\n        self._deferred_filter = None\n        self._cloning_enabled = True\n\n    @property\n    def query(self):\n        if self._deferred_filter:\n            negate, args, kwargs = self._deferred_filter\n            self._filter_or_exclude_inplace(negate, args, kwargs)\n            self._deferred_filter = None\n        return self._query\n\n    @query.setter\n    def query(self, value):\n        if value.values_select:\n            self._iterable_class = ValuesIterable\n        self._query = value\n\n    def as_manager(cls):\n        # Address the circular dependency between `Queryset` and `Manager`.\n        from django.db.models.manager import Manager\n\n        manager = Manager.from_queryset(cls)()\n        manager._built_with_as_manager = True\n        return manager\n\n    as_manager.queryset_only = True\n    as_manager = classmethod(as_manager)\n\n    ########################\n    # PYTHON MAGIC METHODS #\n    ########################\n\n    def __deepcopy__(self, memo):\n        \"\"\"Don't populate the QuerySet's cache.\"\"\"\n        obj = self.__class__()\n        for k, v in self.__dict__.items():\n            if k == \"_result_cache\":\n                obj.__dict__[k] = None\n            else:\n                obj.__dict__[k] = copy.deepcopy(v, memo)\n        return obj\n\n    def __getstate__(self):\n        # Force the cache to be fully populated.\n        self._fetch_all()\n        return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n    def __setstate__(self, state):\n        pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)\n        if pickled_version:\n            if pickled_version != django.__version__:\n                warnings.warn(\n                    \"Pickled queryset instance's Django version %s does not \"\n                    \"match the current version %s.\"\n                    % (pickled_version, django.__version__),\n                    RuntimeWarning,\n                    stacklevel=2,\n                )\n        else:\n            warnings.warn(\n                \"Pickled queryset instance's Django version is not specified.\",\n                RuntimeWarning,\n                stacklevel=2,\n            )\n        self.__dict__.update(state)\n\n    def __repr__(self):\n        data = list(self[: REPR_OUTPUT_SIZE + 1])\n        if len(data) > REPR_OUTPUT_SIZE:\n            data[-1] = \"...(remaining elements truncated)...\"\n        return \"<%s %r>\" % (self.__class__.__name__, data)\n\n    def __len__(self):\n        self._fetch_all()\n        return len(self._result_cache)\n\n    def __iter__(self):\n        \"\"\"\n        The queryset iterator protocol uses three nested iterators in the\n        default case:\n            1. sql.compiler.execute_sql()\n               - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n                 using cursor.fetchmany(). This part is responsible for\n                 doing some column masking, and returning the rows in chunks.\n            2. sql.compiler.results_iter()\n               - Returns one row at time. At this point the rows are still just\n                 tuples. In some cases the return values are converted to\n                 Python values at this location.\n            3. self.iterator()\n               - Responsible for turning the rows into model objects.\n        \"\"\"\n        self._fetch_all()\n        return iter(self._result_cache)\n\n    def __aiter__(self):\n        # Remember, __aiter__ itself is synchronous, it's the thing it returns\n        # that is async!\n        async def generator():\n            await sync_to_async(self._fetch_all)()\n            for item in self._result_cache:\n                yield item\n\n        return generator()\n\n    def __bool__(self):\n        self._fetch_all()\n        return bool(self._result_cache)\n\n    def __getitem__(self, k):\n        \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n        if not isinstance(k, (int, slice)):\n            raise TypeError(\n                \"QuerySet indices must be integers or slices, not %s.\"\n                % type(k).__name__\n            )\n        if (isinstance(k, int) and k < 0) or (\n            isinstance(k, slice)\n            and (\n                (k.start is not None and k.start < 0)\n                or (k.stop is not None and k.stop < 0)\n            )\n        ):\n            raise ValueError(\"Negative indexing is not supported.\")\n\n        if self._result_cache is not None:\n            return self._result_cache[k]\n\n        if isinstance(k, slice):\n            qs = self._chain()\n            if k.start is not None:\n                start = int(k.start)\n            else:\n                start = None\n            if k.stop is not None:\n                stop = int(k.stop)\n            else:\n                stop = None\n            qs.query.set_limits(start, stop)\n            return list(qs)[:: k.step] if k.step else qs\n\n        qs = self._chain()\n        qs.query.set_limits(k, k + 1)\n        qs._fetch_all()\n        return qs._result_cache[0]\n\n    def __class_getitem__(cls, *args, **kwargs):\n        return cls\n\n    def __and__(self, other):\n        self._check_operator_queryset(other, \"&\")\n        self._merge_sanity_check(other)\n        if isinstance(other, EmptyQuerySet):\n            return other\n        if isinstance(self, EmptyQuerySet):\n            return self\n        combined = self._chain()\n        combined._merge_known_related_objects(other)\n        combined.query.combine(other.query, sql.AND)\n        return combined\n\n    def __or__(self, other):\n        self._check_operator_queryset(other, \"|\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.OR)\n        return combined\n\n    def __xor__(self, other):\n        self._check_operator_queryset(other, \"^\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.XOR)\n        return combined\n\n    ####################################\n    # METHODS THAT DO DATABASE QUERIES #\n    ####################################\n\n    def _iterator(self, use_chunked_fetch, chunk_size):\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if not self._prefetch_related_lookups or chunk_size is None:\n            yield from iterable\n            return\n\n        iterator = iter(iterable)\n        while results := list(islice(iterator, chunk_size)):\n            prefetch_related_objects(results, *self._prefetch_related_lookups)\n            yield from results\n\n    def iterator(self, chunk_size=None):\n        \"\"\"\n        An iterator over the results from applying this QuerySet to the\n        database. chunk_size must be provided for QuerySets that prefetch\n        related objects. Otherwise, a default chunk_size of 2000 is supplied.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                raise ValueError(\n                    \"chunk_size must be provided when using QuerySet.iterator() after \"\n                    \"prefetch_related().\"\n                )\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        return self._iterator(use_chunked_fetch, chunk_size)\n\n    async def aiterator(self, chunk_size=None):\n        \"\"\"\n        An asynchronous iterator over the results from applying this QuerySet\n        to the database.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                # RemovedInDjango71Warning: Replace the warning with:\n                # raise ValueError(\n                #     \"chunk_size must be provided when using \"\n                #     \"QuerySet.aiterator() after prefetch_related().\"\n                # )\n                warnings.warn(\n                    \"Using QuerySet.aiterator() after prefetch_related() without \"\n                    \"providing a chunk_size is deprecated and will raise a \"\n                    \"ValueError in Django 7.1.\",\n                    category=RemovedInDjango71Warning,\n                    skip_file_prefixes=django_file_prefixes(),\n                )\n                # RemovedInDjango71Warning: When the deprecation ends, remove.\n                chunk_size = 2000\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if self._prefetch_related_lookups:\n            results = []\n\n            async for item in iterable:\n                results.append(item)\n                if len(results) >= chunk_size:\n                    await aprefetch_related_objects(\n                        results, *self._prefetch_related_lookups\n                    )\n                    for result in results:\n                        yield result\n                    results.clear()\n\n            if results:\n                await aprefetch_related_objects(\n                    results, *self._prefetch_related_lookups\n                )\n                for result in results:\n                    yield result\n        else:\n            async for item in iterable:\n                yield item\n\n    def aggregate(self, *args, **kwargs):\n        \"\"\"\n        Return a dictionary containing the calculations (aggregation)\n        over the current queryset.\n\n        If args is present the expression is passed as a kwarg using\n        the Aggregate object's default alias.\n        \"\"\"\n        if self.query.distinct_fields:\n            raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n        self._validate_values_are_expressions(\n            (*args, *kwargs.values()), method_name=\"aggregate\"\n        )\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                arg.default_alias\n            except (AttributeError, TypeError):\n                raise TypeError(\"Complex aggregates require an alias\")\n            kwargs[arg.default_alias] = arg\n\n        return self.query.chain().get_aggregation(self.db, kwargs)\n\n    async def aaggregate(self, *args, **kwargs):\n        return await sync_to_async(self.aggregate)(*args, **kwargs)\n\n    def count(self):\n        \"\"\"\n        Perform a SELECT COUNT() and return the number of records as an\n        integer.\n\n        If the QuerySet is already fully cached, return the length of the\n        cached results set to avoid multiple SELECT COUNT(*) calls.\n        \"\"\"\n        if self._result_cache is not None:\n            return len(self._result_cache)\n\n        return self.query.get_count(using=self.db)\n\n    async def acount(self):\n        return await sync_to_async(self.count)()\n\n    def get(self, *args, **kwargs):\n        \"\"\"\n        Perform the query and return a single object matching the given\n        keyword arguments.\n        \"\"\"\n        if self.query.combinator and (args or kwargs):\n            raise NotSupportedError(\n                \"Calling QuerySet.get(...) with filters after %s() is not \"\n                \"supported.\" % self.query.combinator\n            )\n        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)\n        if self.query.can_filter() and not self.query.distinct_fields:\n            clone = clone.order_by()\n        limit = None\n        if (\n            not clone.query.select_for_update\n            or connections[clone.db].features.supports_select_for_update_with_limit\n        ):\n            limit = MAX_GET_RESULTS\n            clone.query.set_limits(high=limit)\n        num = len(clone)\n        if num == 1:\n            return clone._result_cache[0]\n        if not num:\n            raise self.model.DoesNotExist(\n                \"%s matching query does not exist.\" % self.model._meta.object_name\n            )\n        raise self.model.MultipleObjectsReturned(\n            \"get() returned more than one %s -- it returned %s!\"\n            % (\n                self.model._meta.object_name,\n                num if not limit or num < limit else \"more than %s\" % (limit - 1),\n            )\n        )\n\n    async def aget(self, *args, **kwargs):\n        return await sync_to_async(self.get)(*args, **kwargs)\n\n    def create(self, **kwargs):\n        \"\"\"\n        Create a new object with the given kwargs, saving it to the database\n        and returning the created object.\n        \"\"\"\n        reverse_one_to_one_fields = frozenset(kwargs).intersection(\n            self.model._meta._reverse_one_to_one_field_names\n        )\n        if reverse_one_to_one_fields:\n            raise ValueError(\n                \"The following fields do not exist in this model: %s\"\n                % \", \".join(reverse_one_to_one_fields)\n            )\n\n        obj = self.model(**kwargs)\n        self._for_write = True\n        obj.save(force_insert=True, using=self.db)\n        obj._state.fetch_mode = self._fetch_mode\n        return obj\n\n    create.alters_data = True\n\n    async def acreate(self, **kwargs):\n        return await sync_to_async(self.create)(**kwargs)\n\n    acreate.alters_data = True\n\n    def _prepare_for_bulk_create(self, objs):\n        objs_with_pk, objs_without_pk = [], []\n        for obj in objs:\n            obj._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n            if isinstance(obj.pk, DatabaseDefault):\n                objs_without_pk.append(obj)\n            elif obj._is_pk_set():\n                objs_with_pk.append(obj)\n            else:\n                obj.pk = obj._meta.pk.get_pk_value_on_save(obj)\n                if obj._is_pk_set():\n                    objs_with_pk.append(obj)\n                else:\n                    objs_without_pk.append(obj)\n        return objs_with_pk, objs_without_pk\n\n    def _check_bulk_create_options(\n        self, ignore_conflicts, update_conflicts, update_fields, unique_fields\n    ):\n        if ignore_conflicts and update_conflicts:\n            raise ValueError(\n                \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n            )\n        db_features = connections[self.db].features\n        if ignore_conflicts:\n            if not db_features.supports_ignore_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support ignoring conflicts.\"\n                )\n            return OnConflict.IGNORE\n        elif update_conflicts:\n            if not db_features.supports_update_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support updating conflicts.\"\n                )\n            if not update_fields:\n                raise ValueError(\n                    \"Fields that will be updated when a row insertion fails \"\n                    \"on conflicts must be provided.\"\n                )\n            if unique_fields and not db_features.supports_update_conflicts_with_target:\n                raise NotSupportedError(\n                    \"This database backend does not support updating \"\n                    \"conflicts with specifying unique fields that can trigger \"\n                    \"the upsert.\"\n                )\n            if not unique_fields and db_features.supports_update_conflicts_with_target:\n                raise ValueError(\n                    \"Unique fields that can trigger the upsert must be provided.\"\n                )\n            # Updating primary keys and non-concrete fields is forbidden.\n            if any(not f.concrete for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() can only be used with concrete fields in \"\n                    \"update_fields.\"\n                )\n            if any(f in self.model._meta.pk_fields for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() cannot be used with primary keys in \"\n                    \"update_fields.\"\n                )\n            if unique_fields:\n                if any(not f.concrete for f in unique_fields):\n                    raise ValueError(\n                        \"bulk_create() can only be used with concrete fields \"\n                        \"in unique_fields.\"\n                    )\n            return OnConflict.UPDATE\n        return None\n\n    def bulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert each of the instances into the database. Do *not* call\n        save() on each of the instances, do not send any pre/post_save\n        signals, and do not set the primary key attribute if it is an\n        autoincrement field (except if\n        features.can_return_rows_from_bulk_insert=True).\n        Multi-table models are not supported.\n        \"\"\"\n        # When you bulk insert you don't get the primary keys back (if it's an\n        # autoincrement, except if can_return_rows_from_bulk_insert=True), so\n        # you can't insert into the child tables which references this. There\n        # are two workarounds:\n        # 1) This could be implemented if you didn't have an autoincrement pk\n        # 2) You could do it by doing O(n) normal inserts into the parent\n        #    tables to get the primary keys back and then doing a single bulk\n        #    insert into the childmost table.\n        # We currently set the primary keys on the objects when using\n        # PostgreSQL via the RETURNING ID clause. It should be possible for\n        # Oracle as well, but the semantics for extracting the primary keys is\n        # trickier so it's not done yet.\n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        # Check that the parents share the same concrete model with the our\n        # model to detect the inheritance pattern ConcreteGrandParent ->\n        # MultiTableParent -> ProxyChild. Simply checking\n        # self.model._meta.proxy would not identify that case as involving\n        # multiple tables.\n        for parent in self.model._meta.all_parents:\n            if parent._meta.concrete_model is not self.model._meta.concrete_model:\n                raise ValueError(\"Can't bulk create a multi-table inherited model\")\n        if not objs:\n            return objs\n        opts = self.model._meta\n        if unique_fields:\n            # Primary key is allowed in unique_fields.\n            unique_fields = [\n                self.model._meta.get_field(opts.pk.name if name == \"pk\" else name)\n                for name in unique_fields\n            ]\n        if update_fields:\n            update_fields = [self.model._meta.get_field(name) for name in update_fields]\n        on_conflict = self._check_bulk_create_options(\n            ignore_conflicts,\n            update_conflicts,\n            update_fields,\n            unique_fields,\n        )\n        self._for_write = True\n        fields = [f for f in opts.concrete_fields if not f.generated]\n        objs = list(objs)\n        objs_with_pk, objs_without_pk = self._prepare_for_bulk_create(objs)\n        if objs_with_pk and objs_without_pk:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            self._handle_order_with_respect_to(objs)\n            if objs_with_pk:\n                returned_columns = self._batched_insert(\n                    objs_with_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                for obj_with_pk, results in zip(objs_with_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_with_pk, field.attname, result)\n                for obj_with_pk in objs_with_pk:\n                    obj_with_pk._state.adding = False\n                    obj_with_pk._state.db = self.db\n            if objs_without_pk:\n                fields = [f for f in fields if not isinstance(f, AutoField)]\n                returned_columns = self._batched_insert(\n                    objs_without_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                connection = connections[self.db]\n                if (\n                    connection.features.can_return_rows_from_bulk_insert\n                    and on_conflict is None\n                ):\n                    assert len(returned_columns) == len(objs_without_pk)\n                for obj_without_pk, results in zip(objs_without_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_without_pk, field.attname, result)\n                    obj_without_pk._state.adding = False\n                    obj_without_pk._state.db = self.db\n\n        return objs\n\n    def _handle_order_with_respect_to(self, objs):\n        if objs and (order_wrt := self.model._meta.order_with_respect_to):\n            get_filter_kwargs_for_object = order_wrt.get_filter_kwargs_for_object\n            attnames = list(get_filter_kwargs_for_object(objs[0]))\n            group_keys = set()\n            obj_groups = []\n            for obj in objs:\n                group_key = tuple(get_filter_kwargs_for_object(obj).values())\n                group_keys.add(group_key)\n                obj_groups.append((obj, group_key))\n            filters = [\n                Q.create(list(zip(attnames, group_key))) for group_key in group_keys\n            ]\n            next_orders = (\n                self.model._base_manager.using(self.db)\n                .filter(reduce(operator.or_, filters))\n                .values_list(*attnames)\n                .annotate(_order__max=Max(\"_order\") + 1)\n            )\n            # Create mapping of group values to max order.\n            group_next_orders = dict.fromkeys(group_keys, 0)\n            group_next_orders.update(\n                (tuple(group_key), next_order) for *group_key, next_order in next_orders\n            )\n            # Assign _order values to new objects.\n            for obj, group_key in obj_groups:\n                if getattr(obj, \"_order\", None) is None:\n                    group_next_order = group_next_orders[group_key]\n                    obj._order = group_next_order\n                    group_next_orders[group_key] += 1\n\n    bulk_create.alters_data = True\n\n    async def abulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        return await sync_to_async(self.bulk_create)(\n            objs=objs,\n            batch_size=batch_size,\n            ignore_conflicts=ignore_conflicts,\n            update_conflicts=update_conflicts,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n\n    abulk_create.alters_data = True\n\n    def bulk_update(self, objs, fields, batch_size=None):\n        \"\"\"\n        Update the given fields in each of the given objects in the database.\n        \"\"\"\n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        if not fields:\n            raise ValueError(\"Field names must be given to bulk_update().\")\n        objs = tuple(objs)\n        if not all(obj._is_pk_set() for obj in objs):\n            raise ValueError(\"All bulk_update() objects must have a primary key set.\")\n        opts = self.model._meta\n        fields = [opts.get_field(name) for name in fields]\n        if any(not f.concrete for f in fields):\n            raise ValueError(\"bulk_update() can only be used with concrete fields.\")\n        all_pk_fields = set(opts.pk_fields)\n        for parent in opts.all_parents:\n            all_pk_fields.update(parent._meta.pk_fields)\n        if any(f in all_pk_fields for f in fields):\n            raise ValueError(\"bulk_update() cannot be used with primary key fields.\")\n        if not objs:\n            return 0\n        for obj in objs:\n            obj._prepare_related_fields_for_save(\n                operation_name=\"bulk_update\", fields=fields\n            )\n        # PK is used twice in the resulting update query, once in the filter\n        # and once in the WHEN. Each field will also have one CAST.\n        self._for_write = True\n        connection = connections[self.db]\n        max_batch_size = connection.ops.bulk_batch_size(\n            [opts.pk, opts.pk, *fields], objs\n        )\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        requires_casting = connection.features.requires_casted_case_in_updates\n        batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size))\n        updates = []\n        for batch_objs in batches:\n            update_kwargs = {}\n            for field in fields:\n                when_statements = []\n                for obj in batch_objs:\n                    attr = getattr(obj, field.attname)\n                    if not hasattr(attr, \"resolve_expression\"):\n                        attr = Value(attr, output_field=field)\n                    when_statements.append(When(pk=obj.pk, then=attr))\n                case_statement = Case(*when_statements, output_field=field)\n                if requires_casting:\n                    case_statement = Cast(case_statement, output_field=field)\n                update_kwargs[field.attname] = case_statement\n            updates.append(([obj.pk for obj in batch_objs], update_kwargs))\n        rows_updated = 0\n        queryset = self.using(self.db)\n        with transaction.atomic(using=self.db, savepoint=False):\n            for pks, update_kwargs in updates:\n                rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs)\n        return rows_updated\n\n    bulk_update.alters_data = True\n\n    async def abulk_update(self, objs, fields, batch_size=None):\n        return await sync_to_async(self.bulk_update)(\n            objs=objs,\n            fields=fields,\n            batch_size=batch_size,\n        )\n\n    abulk_update.alters_data = True\n\n    def get_or_create(self, defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, creating one if necessary.\n        Return a tuple of (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        # The get() needs to be targeted at the write database in order\n        # to avoid potential transaction consistency problems.\n        self._for_write = True\n        try:\n            return self.get(**kwargs), False\n        except self.model.DoesNotExist:\n            params = self._extract_model_params(defaults, **kwargs)\n            # Try to create an object using passed params.\n            try:\n                with transaction.atomic(using=self.db):\n                    params = dict(resolve_callables(params))\n                    return self.create(**params), True\n            except IntegrityError:\n                try:\n                    return self.get(**kwargs), False\n                except self.model.DoesNotExist:\n                    pass\n                raise\n\n    get_or_create.alters_data = True\n\n    async def aget_or_create(self, defaults=None, **kwargs):\n        return await sync_to_async(self.get_or_create)(\n            defaults=defaults,\n            **kwargs,\n        )\n\n    aget_or_create.alters_data = True\n\n    def update_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, updating one with defaults\n        if it exists, otherwise create a new one. Optionally, an object can\n        be created with different values than defaults by using\n        create_defaults.\n        Return a tuple (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        update_defaults = defaults or {}\n        if create_defaults is None:\n            create_defaults = update_defaults\n\n        self._for_write = True\n        with transaction.atomic(using=self.db):\n            # Lock the row so that a concurrent update is blocked until\n            # update_or_create() has performed its save.\n            obj, created = self.select_for_update().get_or_create(\n                create_defaults, **kwargs\n            )\n            if created:\n                return obj, created\n            for k, v in resolve_callables(update_defaults):\n                setattr(obj, k, v)\n\n            update_fields = set(update_defaults)\n            concrete_field_names = self.model._meta._non_pk_concrete_field_names\n            # update_fields does not support non-concrete fields.\n            if concrete_field_names.issuperset(update_fields):\n                # Add fields which are set on pre_save(), e.g. auto_now fields.\n                # This is to maintain backward compatibility as these fields\n                # are not updated unless explicitly specified in the\n                # update_fields list.\n                pk_fields = self.model._meta.pk_fields\n                for field in self.model._meta.local_concrete_fields:\n                    if not (\n                        field in pk_fields or field.__class__.pre_save is Field.pre_save\n                    ):\n                        update_fields.add(field.name)\n                        if field.name != field.attname:\n                            update_fields.add(field.attname)\n                obj.save(using=self.db, update_fields=update_fields)\n            else:\n                obj.save(using=self.db)\n        return obj, False\n\n    update_or_create.alters_data = True\n\n    async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        return await sync_to_async(self.update_or_create)(\n            defaults=defaults,\n            create_defaults=create_defaults,\n            **kwargs,\n        )\n\n    aupdate_or_create.alters_data = True\n\n    def _extract_model_params(self, defaults, **kwargs):\n        \"\"\"\n        Prepare `params` for creating a model instance based on the given\n        kwargs; for use by get_or_create().\n        \"\"\"\n        defaults = defaults or {}\n        params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}\n        params.update(defaults)\n        property_names = self.model._meta._property_names\n        invalid_params = []\n        for param in params:\n            try:\n                self.model._meta.get_field(param)\n            except exceptions.FieldDoesNotExist:\n                # It's okay to use a model's property if it has a setter.\n                if not (param in property_names and getattr(self.model, param).fset):\n                    invalid_params.append(param)\n        if invalid_params:\n            raise exceptions.FieldError(\n                \"Invalid field name(s) for model %s: '%s'.\"\n                % (\n                    self.model._meta.object_name,\n                    \"', '\".join(sorted(invalid_params)),\n                )\n            )\n        return params\n\n    def _earliest(self, *fields):\n        \"\"\"\n        Return the earliest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if fields:\n            order_by = fields\n        else:\n            order_by = getattr(self.model._meta, \"get_latest_by\")\n            if order_by and not isinstance(order_by, (tuple, list)):\n                order_by = (order_by,)\n        if order_by is None:\n            raise ValueError(\n                \"earliest() and latest() require either fields as positional \"\n                \"arguments or 'get_latest_by' in the model's Meta.\"\n            )\n        obj = self._chain()\n        obj.query.set_limits(high=1)\n        obj.query.clear_ordering(force=True)\n        obj.query.add_ordering(*order_by)\n        return obj.get()\n\n    def earliest(self, *fields):\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self._earliest(*fields)\n\n    async def aearliest(self, *fields):\n        return await sync_to_async(self.earliest)(*fields)\n\n    def latest(self, *fields):\n        \"\"\"\n        Return the latest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.reverse()._earliest(*fields)\n\n    async def alatest(self, *fields):\n        return await sync_to_async(self.latest)(*fields)\n\n    def first(self):\n        \"\"\"Return the first object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"first\")\n            queryset = self.order_by(\"pk\")\n        for obj in queryset[:1]:\n            return obj\n\n    async def afirst(self):\n        return await sync_to_async(self.first)()\n\n    def last(self):\n        \"\"\"Return the last object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self.reverse()\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"last\")\n            queryset = self.order_by(\"-pk\")\n        for obj in queryset[:1]:\n            return obj\n\n    async def alast(self):\n        return await sync_to_async(self.last)()\n\n    def in_bulk(self, id_list=None, *, field_name=\"pk\"):\n        \"\"\"\n        Return a dictionary mapping each of the given IDs to the object with\n        that ID. If `id_list` isn't provided, evaluate the entire QuerySet.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with in_bulk().\")\n        if id_list is not None and not id_list:\n            return {}\n        opts = self.model._meta\n        unique_fields = [\n            constraint.fields[0]\n            for constraint in opts.total_unique_constraints\n            if len(constraint.fields) == 1\n        ]\n        if (\n            field_name != \"pk\"\n            and not opts.get_field(field_name).unique\n            and field_name not in unique_fields\n            and self.query.distinct_fields != (field_name,)\n        ):\n            raise ValueError(\n                \"in_bulk()'s field_name must be a unique field but %r isn't.\"\n                % field_name\n            )\n\n        qs = self\n\n        def get_obj(obj):\n            return obj\n\n        if issubclass(self._iterable_class, ModelIterable):\n            # Raise an AttributeError if field_name is deferred.\n            get_key = operator.attrgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesIterable):\n            if field_name not in self.query.values_select:\n                qs = qs.values(field_name, *self.query.values_select)\n\n                def get_obj(obj):  # noqa: F811\n                    # We can safely mutate the dictionaries returned by\n                    # ValuesIterable here, since they are limited to the scope\n                    # of this function, and get_key runs before get_obj.\n                    del obj[field_name]\n                    return obj\n\n            get_key = operator.itemgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesListIterable):\n            try:\n                field_index = self.query.values_select.index(field_name)\n            except ValueError:\n                # field_name is missing from values_select, so add it.\n                field_index = 0\n                if issubclass(self._iterable_class, NamedValuesListIterable):\n                    kwargs = {\"named\": True}\n                else:\n                    kwargs = {}\n                    get_obj = operator.itemgetter(slice(1, None))\n                qs = qs.values_list(field_name, *self.query.values_select, **kwargs)\n\n            get_key = operator.itemgetter(field_index)\n\n        elif issubclass(self._iterable_class, FlatValuesListIterable):\n            if self.query.values_select == (field_name,):\n                # Mapping field_name to itself.\n                get_key = get_obj\n            else:\n                # Transform it back into a non-flat values_list().\n                qs = qs.values_list(field_name, *self.query.values_select)\n                get_key = operator.itemgetter(0)\n                get_obj = operator.itemgetter(1)\n\n        else:\n            raise TypeError(\n                f\"in_bulk() cannot be used with {self._iterable_class.__name__}.\"\n            )\n\n        if id_list is not None:\n            filter_key = \"{}__in\".format(field_name)\n            id_list = tuple(id_list)\n            batch_size = connections[self.db].ops.bulk_batch_size([opts.pk], id_list)\n            # If the database has a limit on the number of query parameters\n            # (e.g. SQLite), retrieve objects in batches if necessary.\n            if batch_size and batch_size < len(id_list):\n                results = ()\n                for offset in range(0, len(id_list), batch_size):\n                    batch = id_list[offset : offset + batch_size]\n                    results += tuple(qs.filter(**{filter_key: batch}))\n                qs = results\n            else:\n                qs = qs.filter(**{filter_key: id_list})\n        else:\n            qs = qs._chain()\n        return {get_key(obj): get_obj(obj) for obj in qs}\n\n    async def ain_bulk(self, id_list=None, *, field_name=\"pk\"):\n        return await sync_to_async(self.in_bulk)(\n            id_list=id_list,\n            field_name=field_name,\n        )\n\n    def delete(self):\n        \"\"\"Delete the records in the current QuerySet.\"\"\"\n        self._not_support_combined_queries(\"delete\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with delete().\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call delete() after .distinct(*fields).\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call delete() after .values() or .values_list()\")\n\n        del_query = self._chain()\n\n        # The delete is actually 2 queries - one to find related objects,\n        # and one to delete. Make sure that the discovery of related\n        # objects is performed on the same database as the deletion.\n        del_query._for_write = True\n\n        # Disable non-supported fields.\n        del_query.query.select_for_update = False\n        del_query.query.select_related = False\n        del_query.query.clear_ordering(force=True)\n\n        collector = Collector(using=del_query.db, origin=self)\n        collector.collect(del_query)\n        num_deleted, num_deleted_per_model = collector.delete()\n\n        # Clear the result cache, in case this QuerySet gets reused.\n        self._result_cache = None\n        return num_deleted, num_deleted_per_model\n\n    delete.alters_data = True\n    delete.queryset_only = True\n\n    async def adelete(self):\n        return await sync_to_async(self.delete)()\n\n    adelete.alters_data = True\n    adelete.queryset_only = True\n\n    def _raw_delete(self, using):\n        \"\"\"\n        Delete objects found from the given queryset in single direct SQL\n        query. No signals are sent and there is no protection for cascades.\n        \"\"\"\n        query = self.query.clone()\n        query.__class__ = sql.DeleteQuery\n        return query.get_compiler(using).execute_sql(ROW_COUNT)\n\n    _raw_delete.alters_data = True\n\n    def update(self, **kwargs):\n        \"\"\"\n        Update all elements in the current QuerySet, setting all the given\n        fields to the appropriate values.\n        \"\"\"\n        self._not_support_combined_queries(\"update\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call update() after .distinct(*fields).\")\n        self._for_write = True\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_values(kwargs)\n\n        # Inline annotations in order_by(), if possible.\n        new_order_by = []\n        for col in query.order_by:\n            alias = col\n            descending = False\n            if isinstance(alias, str) and alias.startswith(\"-\"):\n                alias = alias.removeprefix(\"-\")\n                descending = True\n            if annotation := query.annotations.get(alias):\n                if getattr(annotation, \"contains_aggregate\", False):\n                    raise exceptions.FieldError(\n                        f\"Cannot update when ordering by an aggregate: {annotation}\"\n                    )\n                if descending:\n                    annotation = annotation.desc()\n                new_order_by.append(annotation)\n            else:\n                new_order_by.append(col)\n        query.order_by = tuple(new_order_by)\n\n        # Clear SELECT clause as all annotation references were inlined by\n        # add_update_values() already.\n        query.clear_select_clause()\n        with transaction.mark_for_rollback_on_error(using=self.db):\n            rows = query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        self._result_cache = None\n        return rows\n\n    update.alters_data = True\n\n    async def aupdate(self, **kwargs):\n        return await sync_to_async(self.update)(**kwargs)\n\n    aupdate.alters_data = True\n\n    def _update(self, values, returning_fields=None):\n        \"\"\"\n        A version of update() that accepts field objects instead of field\n        names. Used primarily for model saving and not intended for use by\n        general code (it requires too much poking around at model internals to\n        be useful at that level).\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_fields(values)\n        # Clear any annotations so that they won't be present in subqueries.\n        query.annotations = {}\n        self._result_cache = None\n        if returning_fields is None:\n            return query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        return query.get_compiler(self.db).execute_returning_sql(returning_fields)\n\n    _update.alters_data = True\n    _update.queryset_only = False\n\n    def exists(self):\n        \"\"\"\n        Return True if the QuerySet would have any results, False otherwise.\n        \"\"\"\n        if self._result_cache is None:\n            return self.query.has_results(using=self.db)\n        return bool(self._result_cache)\n\n    async def aexists(self):\n        return await sync_to_async(self.exists)()\n\n    def contains(self, obj):\n        \"\"\"\n        Return True if the QuerySet contains the provided obj,\n        False otherwise.\n        \"\"\"\n        self._not_support_combined_queries(\"contains\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call QuerySet.contains() after .values() or .values_list().\"\n            )\n        try:\n            if obj._meta.concrete_model != self.model._meta.concrete_model:\n                return False\n        except AttributeError:\n            raise TypeError(\"'obj' must be a model instance.\")\n        if not obj._is_pk_set():\n            raise ValueError(\"QuerySet.contains() cannot be used on unsaved objects.\")\n        if self._result_cache is not None:\n            return obj in self._result_cache\n        return self.filter(pk=obj.pk).exists()\n\n    async def acontains(self, obj):\n        return await sync_to_async(self.contains)(obj=obj)\n\n    def _prefetch_related_objects(self):\n        # This method can only be called once the result cache has been filled.\n        prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)\n        self._prefetch_done = True\n\n    def explain(self, *, format=None, **options):\n        \"\"\"\n        Runs an EXPLAIN on the SQL query this QuerySet would perform, and\n        returns the results.\n        \"\"\"\n        return self.query.explain(using=self.db, format=format, **options)\n\n    async def aexplain(self, *, format=None, **options):\n        return await sync_to_async(self.explain)(format=format, **options)\n\n    ##################################################\n    # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #\n    ##################################################\n\n    def raw(self, raw_query, params=(), translations=None, using=None):\n        if using is None:\n            using = self.db\n        qs = RawQuerySet(\n            raw_query,\n            model=self.model,\n            params=params,\n            translations=translations,\n            using=using,\n            fetch_mode=self._fetch_mode,\n        )\n        qs._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        return qs\n\n    def _values(self, *fields, **expressions):\n        clone = self._chain()\n        if expressions:\n            # RemovedInDjango70Warning: When the deprecation ends, deindent as:\n            # clone = clone.annotate(**expressions)\n            with warnings.catch_warnings(\n                action=\"ignore\", category=RemovedInDjango70Warning\n            ):\n                clone = clone.annotate(**expressions)\n        clone._fields = fields\n        clone.query.set_values(fields)\n        return clone\n\n    def values(self, *fields, **expressions):\n        fields += tuple(expressions)\n        clone = self._values(*fields, **expressions)\n        clone._iterable_class = ValuesIterable\n        return clone\n\n    def values_list(self, *fields, flat=False, named=False):\n        if flat and named:\n            raise TypeError(\"'flat' and 'named' can't be used together.\")\n        if flat:\n            if len(fields) > 1:\n                raise TypeError(\n                    \"'flat' is not valid when values_list is called with more than one \"\n                    \"field.\"\n                )\n            elif not fields:\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # raise TypeError(\n                #     \"'flat' is not valid when values_list is called with no \"\n                #     \"fields.\"\n                # )\n                warnings.warn(\n                    \"Calling values_list() with no field name and flat=True \"\n                    \"is deprecated. Pass an explicit field name instead, like \"\n                    \"'pk'.\",\n                    RemovedInDjango70Warning,\n                )\n                fields = [self.model._meta.concrete_fields[0].attname]\n\n        field_names = {f: False for f in fields if not hasattr(f, \"resolve_expression\")}\n        _fields = []\n        expressions = {}\n        counter = 1\n        for field in fields:\n            field_name = field\n            expression = None\n            if hasattr(field, \"resolve_expression\"):\n                field_name = getattr(\n                    field, \"default_alias\", field.__class__.__name__.lower()\n                )\n                expression = field\n                # For backward compatibility reasons expressions are always\n                # prefixed with the counter even if their default alias doesn't\n                # collide with field names. Changing this logic could break\n                # some usage of named=True.\n                seen = True\n            elif seen := field_names[field_name]:\n                expression = F(field_name)\n            if seen:\n                field_name_prefix = field_name\n                while (field_name := f\"{field_name_prefix}{counter}\") in field_names:\n                    counter += 1\n            if expression is not None:\n                expressions[field_name] = expression\n            field_names[field_name] = True\n            _fields.append(field_name)\n\n        clone = self._values(*_fields, **expressions)\n        clone._iterable_class = (\n            NamedValuesListIterable\n            if named\n            else FlatValuesListIterable if flat else ValuesListIterable\n        )\n        return clone\n\n    def dates(self, field_name, kind, order=\"ASC\"):\n        \"\"\"\n        Return a list of date objects representing all available dates for\n        the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\"):\n            raise ValueError(\"'kind' must be one of 'year', 'month', 'week', or 'day'.\")\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        return (\n            self.annotate(\n                datefield=Trunc(field_name, kind, output_field=DateField()),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datefield\")\n        )\n\n    def datetimes(self, field_name, kind, order=\"ASC\", tzinfo=None):\n        \"\"\"\n        Return a list of datetime objects representing all available\n        datetimes for the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"):\n            raise ValueError(\n                \"'kind' must be one of 'year', 'month', 'week', 'day', \"\n                \"'hour', 'minute', or 'second'.\"\n            )\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        if settings.USE_TZ:\n            if tzinfo is None:\n                tzinfo = timezone.get_current_timezone()\n        else:\n            tzinfo = None\n        return (\n            self.annotate(\n                datetimefield=Trunc(\n                    field_name,\n                    kind,\n                    output_field=DateTimeField(),\n                    tzinfo=tzinfo,\n                ),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datetimefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datetimefield\")\n        )\n\n    def none(self):\n        \"\"\"Return an empty QuerySet.\"\"\"\n        clone = self._chain()\n        clone.query.set_empty()\n        return clone\n\n    ##################################################################\n    # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #\n    ##################################################################\n\n    def all(self):\n        \"\"\"\n        Return a new QuerySet that is a copy of the current one. This allows a\n        QuerySet to proxy for a model manager in some cases.\n        \"\"\"\n        return self._chain()\n\n    def filter(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with the args ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"filter\")\n        return self._filter_or_exclude(False, args, kwargs)\n\n    def exclude(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with NOT (args) ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"exclude\")\n        return self._filter_or_exclude(True, args, kwargs)\n\n    def _filter_or_exclude(self, negate, args, kwargs):\n        if (args or kwargs) and self.query.is_sliced:\n            raise TypeError(\"Cannot filter a query once a slice has been taken.\")\n        clone = self._chain()\n        if self._defer_next_filter:\n            self._defer_next_filter = False\n            clone._deferred_filter = negate, args, kwargs\n        else:\n            clone._filter_or_exclude_inplace(negate, args, kwargs)\n        return clone\n\n    def _filter_or_exclude_inplace(self, negate, args, kwargs):\n        if invalid_kwargs := PROHIBITED_FILTER_KWARGS.intersection(kwargs):\n            invalid_kwargs_str = \", \".join(f\"'{k}'\" for k in sorted(invalid_kwargs))\n            raise TypeError(f\"The following kwargs are invalid: {invalid_kwargs_str}\")\n        if negate:\n            self._query.add_q(~Q(*args, **kwargs))\n        else:\n            self._query.add_q(Q(*args, **kwargs))\n\n    def complex_filter(self, filter_obj):\n        \"\"\"\n        Return a new QuerySet instance with filter_obj added to the filters.\n\n        filter_obj can be a Q object or a dictionary of keyword lookup\n        arguments.\n\n        This exists to support framework features such as 'limit_choices_to',\n        and usually it will be more natural to use other methods.\n        \"\"\"\n        if isinstance(filter_obj, Q):\n            clone = self._chain()\n            clone.query.add_q(filter_obj)\n            return clone\n        else:\n            return self._filter_or_exclude(False, args=(), kwargs=filter_obj)\n\n    def _combinator_query(self, combinator, *other_qs, all=False):\n        # Clone the query to inherit the select list and everything\n        clone = self._chain()\n        # Clear limits and ordering so they can be reapplied\n        clone.query.clear_ordering(force=True)\n        clone.query.default_ordering = True\n        self._clear_ordering_in_combined_queries(clone.query, other_qs)\n        clone.query.clear_limits()\n        clone.query.combinator = combinator\n        clone.query.combinator_all = all\n        return clone\n\n    def union(self, *other_qs, all=False):\n        # If the query is an EmptyQuerySet, combine all nonempty querysets.\n        if isinstance(self, EmptyQuerySet):\n            qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)]\n            if not qs:\n                return self\n            if len(qs) == 1:\n                return qs[0]\n            return qs[0]._combinator_query(\"union\", *qs[1:], all=all)\n        elif not other_qs:\n            return self\n        return self._combinator_query(\"union\", *other_qs, all=all)\n\n    def intersection(self, *other_qs):\n        # If any query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        for other in other_qs:\n            if isinstance(other, EmptyQuerySet):\n                return other\n        return self._combinator_query(\"intersection\", *other_qs)\n\n    def difference(self, *other_qs):\n        # If the query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        return self._combinator_query(\"difference\", *other_qs)\n\n    def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False):\n        \"\"\"\n        Return a new QuerySet instance that will select objects with a\n        FOR UPDATE lock.\n        \"\"\"\n        if nowait and skip_locked:\n            raise ValueError(\"The nowait option cannot be used with skip_locked.\")\n        obj = self._chain()\n        obj._for_write = True\n        obj.query.select_for_update = True\n        obj.query.select_for_update_nowait = nowait\n        obj.query.select_for_update_skip_locked = skip_locked\n        obj.query.select_for_update_of = of\n        obj.query.select_for_no_key_update = no_key\n        return obj\n\n    def select_related(self, *fields):\n        \"\"\"\n        Return a new QuerySet instance that will select related objects.\n\n        If fields are specified, they must be ForeignKey fields and only those\n        related objects are included in the selection.\n\n        If select_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"select_related\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call select_related() after .values() or .values_list()\"\n            )\n\n        obj = self._chain()\n        if fields == (None,):\n            obj.query.select_related = False\n        elif fields:\n            obj.query.add_select_related(fields)\n        else:\n            # RemovedInDjango70Warning: when the deprecation ends, raise a\n            # TypeError instead.\n            warn_about_external_use(\n                \"Calling select_related() with no arguments is deprecated. \"\n                \"Specify the fields to fetch instead.\",\n                category=RemovedInDjango70Warning,\n                skip_name_prefixes=(\"django.db.models\",),\n            )\n            obj.query.select_related = True\n        return obj\n\n    def prefetch_related(self, *lookups):\n        \"\"\"\n        Return a new QuerySet instance that will prefetch the specified\n        Many-To-One and Many-To-Many related objects when the QuerySet is\n        evaluated.\n\n        When prefetch_related() is called more than once, append to the list of\n        prefetch lookups. If prefetch_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"prefetch_related\")\n        clone = self._chain()\n        if lookups == (None,):\n            clone._prefetch_related_lookups = ()\n        else:\n            for lookup in lookups:\n                if isinstance(lookup, Prefetch):\n                    lookup = lookup.prefetch_to\n                lookup = lookup.split(LOOKUP_SEP, 1)[0]\n                if lookup in self.query._filtered_relations:\n                    raise ValueError(\n                        \"prefetch_related() is not supported with FilteredRelation.\"\n                    )\n            clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups\n        return clone\n\n    def annotate(self, *args, **kwargs):\n        \"\"\"\n        Return a query set in which the returned objects have been annotated\n        with extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"annotate\")\n        return self._annotate(args, kwargs, select=True)\n\n    def alias(self, *args, **kwargs):\n        \"\"\"\n        Return a query set with added aliases for extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"alias\")\n        return self._annotate(args, kwargs, select=False)\n\n    def _annotate(self, args, kwargs, select=True):\n        self._validate_values_are_expressions(\n            args + tuple(kwargs.values()), method_name=\"annotate\"\n        )\n        annotations = {}\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                if arg.default_alias in kwargs:\n                    raise ValueError(\n                        \"The named annotation '%s' conflicts with the \"\n                        \"default name for another annotation.\" % arg.default_alias\n                    )\n            except (TypeError, AttributeError):\n                raise TypeError(\"Complex annotations require an alias\")\n            annotations[arg.default_alias] = arg\n        annotations.update(kwargs)\n\n        clone = self._chain()\n        names = self._fields\n        if names is None:\n            names = set(\n                chain.from_iterable(\n                    (\n                        (field.name, field.attname)\n                        if hasattr(field, \"attname\")\n                        else (field.name,)\n                    )\n                    for field in self.model._meta.get_fields()\n                )\n            )\n\n        for alias, annotation in annotations.items():\n            if alias in names:\n                raise ValueError(\n                    \"The annotation '%s' conflicts with a field on \"\n                    \"the model.\" % alias\n                )\n            if isinstance(annotation, FilteredRelation):\n                clone.query.add_filtered_relation(annotation, alias)\n            else:\n                clone.query.add_annotation(\n                    annotation,\n                    alias,\n                    select=select,\n                )\n        for alias, annotation in clone.query.annotations.items():\n            if alias in annotations and annotation.contains_aggregate:\n                if clone._fields is None:\n                    clone.query.group_by = True\n                else:\n                    clone.query.set_group_by()\n                break\n\n        return clone\n\n    def order_by(self, *field_names):\n        \"\"\"Return a new QuerySet instance with the ordering changed.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reorder a query once a slice has been taken.\")\n        obj = self._chain()\n        obj.query.clear_ordering(force=True, clear_default=False)\n        obj.query.add_ordering(*field_names)\n        return obj\n\n    def distinct(self, *field_names):\n        \"\"\"\n        Return a new QuerySet instance that will select only distinct results.\n        \"\"\"\n        self._not_support_combined_queries(\"distinct\")\n        if self.query.is_sliced:\n            raise TypeError(\n                \"Cannot create distinct fields once a slice has been taken.\"\n            )\n        obj = self._chain()\n        obj.query.add_distinct_fields(*field_names)\n        return obj\n\n    def extra(\n        self,\n        select=None,\n        where=None,\n        params=None,\n        tables=None,\n        order_by=None,\n        select_params=None,\n    ):\n        \"\"\"Add extra SQL fragments to the query.\"\"\"\n        self._not_support_combined_queries(\"extra\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.add_extra(select, select_params, where, params, tables, order_by)\n        return clone\n\n    def reverse(self):\n        \"\"\"Reverse the ordering of the QuerySet.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reverse a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.standard_ordering = not clone.query.standard_ordering\n        return clone\n\n    def defer(self, *fields):\n        \"\"\"\n        Defer the loading of data for certain fields until they are accessed.\n        Add the set of deferred fields to any existing set of deferred fields.\n        The only exception to this is if None is passed in as the only\n        parameter, in which case remove all deferrals.\n        \"\"\"\n        self._not_support_combined_queries(\"defer\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call defer() after .values() or .values_list()\")\n        clone = self._chain()\n        if fields == (None,):\n            clone.query.clear_deferred_loading()\n        else:\n            clone.query.add_deferred_loading(fields)\n        return clone\n\n    def only(self, *fields):\n        \"\"\"\n        Essentially, the opposite of defer(). Only the fields passed into this\n        method and that are not already specified as deferred are loaded\n        immediately when the queryset is evaluated.\n        \"\"\"\n        self._not_support_combined_queries(\"only\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call only() after .values() or .values_list()\")\n        if fields == (None,):\n            # Can only pass None to defer(), not only(), as the rest option.\n            # That won't stop people trying to do this, so let's be explicit.\n            raise TypeError(\"Cannot pass None as an argument to only().\")\n        for field in fields:\n            field = field.split(LOOKUP_SEP, 1)[0]\n            if field in self.query._filtered_relations:\n                raise ValueError(\"only() is not supported with FilteredRelation.\")\n        clone = self._chain()\n        clone.query.add_immediate_loading(fields)\n        return clone\n\n    def using(self, alias):\n        \"\"\"Select which database this QuerySet should execute against.\"\"\"\n        clone = self._chain()\n        clone._db = alias\n        return clone\n\n    def fetch_mode(self, fetch_mode):\n        \"\"\"Set the fetch mode for the QuerySet.\"\"\"\n        clone = self._chain()\n        clone._fetch_mode = fetch_mode\n        return clone\n\n    ###################################\n    # PUBLIC INTROSPECTION ATTRIBUTES #\n    ###################################\n\n    @property\n    def ordered(self):\n        \"\"\"\n        Return True if the QuerySet is ordered -- i.e. has an order_by()\n        clause or a default ordering on the model (or is empty).\n        \"\"\"\n        if isinstance(self, EmptyQuerySet):\n            return True\n        if self.query.extra_order_by or self.query.order_by:\n            return True\n        elif (\n            self.query.default_ordering\n            and self.query.get_meta().ordering\n            and\n            # A default ordering doesn't affect GROUP BY queries.\n            not self.query.group_by\n        ):\n            return True\n        else:\n            return False\n\n    @property\n    def totally_ordered(self):\n        \"\"\"\n        Returns True if the QuerySet is ordered and the ordering is\n        deterministic. This requires that the ordering includes a field\n        (or set of fields) that is unique and non-nullable.\n\n        For queries involving a GROUP BY clause, the model's default\n        ordering is ignored. Ordering specified via .extra(order_by=...)\n        is also ignored.\n        \"\"\"\n        if not self.ordered:\n            return False\n        ordering = self.query.order_by\n        if not ordering and self.query.default_ordering:\n            ordering = self.query.get_meta().ordering\n        if not ordering:\n            return False\n        opts = self.model._meta\n        pk_fields = {f.attname for f in opts.pk_fields}\n        candidate_fields = set()\n        for part in ordering:\n            # Search for single field providing a total ordering.\n            field_name = None\n            if isinstance(part, str):\n                field_name = part.lstrip(\"-\")\n            elif isinstance(part, F):\n                field_name = part.name\n            elif isinstance(part, OrderBy) and isinstance(part.expression, F):\n                field_name = part.expression.name\n            if annotation_col := self.query.annotations.get(field_name):\n                if isinstance(annotation_col, Col):\n                    if annotation_col.alias == self.query.base_table:\n                        candidate_fields.add(annotation_col.target)\n                elif isinstance(annotation_col, ColPairs):\n                    candidate_fields |= {\n                        c.target\n                        for c in annotation_col.get_cols()\n                        if c.alias == self.query.base_table\n                    }\n            elif field_name:\n                if field_name == \"pk\":\n                    return True\n                # Normalize attname references by using get_field().\n                try:\n                    field = opts.get_field(field_name)\n                except exceptions.FieldDoesNotExist:\n                    # Could be \"?\" for random ordering or a related field\n                    # lookup. Skip this part of introspection for now.\n                    continue\n                else:\n                    # Ordering by a related field name orders by the referenced\n                    # model's ordering. Skip this introspection for now.\n                    if field.remote_field and field_name == field.name:\n                        continue\n                    candidate_fields.add(field)\n\n        candidate_attnames = set()\n        for field in candidate_fields:\n            if field.unique and not field.null:\n                return True\n            candidate_attnames.add(field.attname)\n\n        # Account for members of a CompositePrimaryKey.\n        if candidate_attnames.issuperset(pk_fields):\n            return True\n        # No single total ordering field, try unique_together and total\n        # unique constraints.\n        constraint_field_names = (\n            *opts.unique_together,\n            *(constraint.fields for constraint in opts.total_unique_constraints),\n        )\n        for field_names in constraint_field_names:\n            # Normalize attname references by using get_field().\n            try:\n                fields = [opts.get_field(field_name) for field_name in field_names]\n            except exceptions.FieldDoesNotExist:\n                continue\n            # Composite unique constraints containing a nullable column\n            # cannot ensure total ordering.\n            if any(field.null for field in fields):\n                continue\n            if candidate_attnames.issuperset(field.attname for field in fields):\n                return True\n\n        return False\n\n    @property\n    def db(self):\n        \"\"\"Return the database used if this query is executed now.\"\"\"\n        if self._for_write:\n            return self._db or router.db_for_write(self.model, **self._hints)\n        return self._db or router.db_for_read(self.model, **self._hints)\n\n    ###################\n    # PRIVATE METHODS #\n    ###################\n\n    def _insert(\n        self,\n        objs,\n        fields,\n        returning_fields=None,\n        raw=False,\n        using=None,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert a new record for the given model. This provides an interface to\n        the InsertQuery class and is how Model.save() is implemented.\n        \"\"\"\n        self._for_write = True\n        if using is None:\n            using = self.db\n        query = sql.InsertQuery(\n            self.model,\n            on_conflict=on_conflict,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n        query.insert_values(fields, objs, raw=raw)\n        return query.get_compiler(using=using).execute_sql(returning_fields)\n\n    _insert.alters_data = True\n    _insert.queryset_only = False\n\n    def _batched_insert(\n        self,\n        objs,\n        fields,\n        batch_size,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Helper method for bulk_create() to insert objs one batch at a time.\n        \"\"\"\n        connection = connections[self.db]\n        ops = connection.ops\n        max_batch_size = max(ops.bulk_batch_size(fields, objs), 1)\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        inserted_rows = []\n        returning_fields = (\n            self.model._meta.db_returning_fields\n            if (\n                connection.features.can_return_rows_from_bulk_insert\n                and (on_conflict is None or on_conflict == OnConflict.UPDATE)\n            )\n            else None\n        )\n        batches = [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]\n        if len(batches) > 1:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            for item in batches:\n                inserted_rows.extend(\n                    self._insert(\n                        item,\n                        fields=fields,\n                        using=self.db,\n                        on_conflict=on_conflict,\n                        update_fields=update_fields,\n                        unique_fields=unique_fields,\n                        returning_fields=returning_fields,\n                    )\n                )\n        return inserted_rows\n\n    def _disable_cloning(self):\n        \"\"\"\n        Prevent calls to _chain() from creating a new QuerySet via _clone().\n        All subsequent QuerySet mutations will occur on this instance until\n        _enable_cloning() is used.\n        \"\"\"\n        self._cloning_enabled = False\n        return self\n\n    def _enable_cloning(self):\n        \"\"\"\n        Allow calls to _chain() to create a new QuerySet via _clone(). Restores\n        the default behavior where any QuerySet mutation will return a new\n        QuerySet instance. Necessary only when there has been a\n        _disable_cloning() call previously.\n        \"\"\"\n        self._cloning_enabled = True\n        return self\n\n    def _avoid_cloning(self):\n        \"\"\"\n        Temporarily prevent QuerySet _clone() operations, restoring the default\n        behavior on exit. For the duration of the context managed statement,\n        all operations (e.g. filter(), exclude(), etc.) will mutate the same\n        QuerySet instance.\n\n        @contextlib.contextmanager is intentionally not used for performance\n        reasons.\n        \"\"\"\n        return PreventQuerySetCloning(self)\n\n    def _chain(self):\n        \"\"\"\n        Return a copy of the current QuerySet that's ready for another\n        operation.\n\n        If the QuerySet has opted in to in-place mutations via\n        _disable_cloning() temporarily, the copy doesn't occur and instead the\n        same QuerySet instance will be modified.\n        \"\"\"\n        if not self._cloning_enabled:\n            obj = self\n        else:\n            obj = self._clone()\n        if obj._sticky_filter:\n            obj.query.filter_is_sticky = True\n            obj._sticky_filter = False\n        return obj\n\n    def _clone(self):\n        \"\"\"\n        Return a copy of the current QuerySet. A lightweight alternative\n        to deepcopy().\n        \"\"\"\n        c = self.__class__(\n            model=self.model,\n            query=self.query.chain(),\n            using=self._db,\n            hints=self._hints,\n        )\n        c._sticky_filter = self._sticky_filter\n        c._for_write = self._for_write\n        c._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        c._known_related_objects = self._known_related_objects\n        c._iterable_class = self._iterable_class\n        c._fetch_mode = self._fetch_mode\n        c._fields = self._fields\n        return c\n\n    def _fetch_all(self):\n        if self._result_cache is None:\n            self._result_cache = list(self._iterable_class(self))\n        if self._prefetch_related_lookups and not self._prefetch_done:\n            self._prefetch_related_objects()\n\n    def _next_is_sticky(self):\n        \"\"\"\n        Indicate that the next filter call and the one following that should\n        be treated as a single filter. This is only important when it comes to\n        determining when to reuse tables for many-to-many filters. Required so\n        that we can filter naturally on the results of related managers.\n\n        This doesn't return a clone of the current QuerySet (it returns\n        \"self\"). The method is only used internally and should be immediately\n        followed by a filter() that does create a clone.\n        \"\"\"\n        self._sticky_filter = True\n        return self\n\n    def _merge_sanity_check(self, other):\n        \"\"\"Check that two QuerySet classes may be merged.\"\"\"\n        if self._fields is not None and (\n            set(self.query.values_select) != set(other.query.values_select)\n            or set(self.query.extra_select) != set(other.query.extra_select)\n            or set(self.query.annotation_select) != set(other.query.annotation_select)\n        ):\n            raise TypeError(\n                \"Merging '%s' classes must involve the same values in each case.\"\n                % self.__class__.__name__\n            )\n\n    def _merge_known_related_objects(self, other):\n        \"\"\"\n        Keep track of all known related objects from either QuerySet instance.\n        \"\"\"\n        for field, objects in other._known_related_objects.items():\n            self._known_related_objects.setdefault(field, {}).update(objects)\n\n    def resolve_expression(self, *args, **kwargs):\n        query = self.query.resolve_expression(*args, **kwargs)\n        query._db = self._db\n        return query\n\n    resolve_expression.queryset_only = True\n\n    def _add_hints(self, **hints):\n        \"\"\"\n        Update hinting information for use by routers. Add new key/values or\n        overwrite existing key/values.\n        \"\"\"\n        self._hints.update(hints)\n\n    def _has_filters(self):\n        \"\"\"\n        Check if this QuerySet has any filtering going on. This isn't\n        equivalent with checking if all objects are present in results, for\n        example, qs[1:]._has_filters() -> False.\n        \"\"\"\n        return self.query.has_filters()\n\n    @staticmethod\n    def _validate_values_are_expressions(values, method_name):\n        invalid_args = sorted(\n            str(arg) for arg in values if not hasattr(arg, \"resolve_expression\")\n        )\n        if invalid_args:\n            raise TypeError(\n                \"QuerySet.%s() received non-expression(s): %s.\"\n                % (\n                    method_name,\n                    \", \".join(invalid_args),\n                )\n            )\n\n    def _not_support_combined_queries(self, operation_name):\n        if self.query.combinator:\n            raise NotSupportedError(\n                \"Calling QuerySet.%s() after %s() is not supported.\"\n                % (operation_name, self.query.combinator)\n            )\n\n    def _check_operator_queryset(self, other, operator_):\n        if self.query.combinator or other.query.combinator:\n            raise TypeError(f\"Cannot use {operator_} operator with combined queryset.\")\n\n    def _check_ordering_first_last_queryset_aggregation(self, method):\n        if (\n            isinstance(self.query.group_by, tuple)\n            # Raise if the pk fields are not in the group_by.\n            and self.model._meta.pk\n            not in {col.output_field for col in self.query.group_by}\n            and set(self.model._meta.pk_fields).difference(\n                {col.target for col in self.query.group_by}\n            )\n        ):\n            raise TypeError(\n                f\"Cannot use QuerySet.{method}() on an unordered queryset performing \"\n                f\"aggregation. Add an ordering with order_by().\"\n            )\n\n    def _clear_ordering_in_combined_queries(self, cloned_query, other_qs):\n        combined_queries = [self.query]\n        for qs in other_qs:\n            query = qs.query.clone()\n            query.clear_ordering(force=False, clear_default=False)\n            combined_queries.append(query)\n        cloned_query.combined_queries = tuple(combined_queries)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-765e7606ef75a519", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 2102, "local_path": "source-original/SRC__django__QuerySet__55814568.py", "order": 0, "original_content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/query.py#L374-L2424", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "QuerySet", "variant_id": "pyint-5c2b55814568-SRC", "group_id": "py-765e7606ef75a519", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 225, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-91dcdffeee4d-I01", "source": "import copy\nimport operator\nimport warnings\nfrom contextlib import nullcontext\nfrom functools import partial, reduce\nfrom itertools import chain, islice\nfrom weakref import ref as weak_ref\nfrom asgiref.sync import sync_to_async\nimport django\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.db import (\n    DJANGO_VERSION_PICKLE_KEY,\n    IntegrityError,\n    NotSupportedError,\n    connections,\n    router,\n    transaction,\n)\nfrom django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql\nfrom django.db.models.constants import LOOKUP_SEP, OnConflict\nfrom django.db.models.deletion import Collector\nfrom django.db.models.expressions import (\n    Case,\n    Col,\n    ColPairs,\n    DatabaseDefault,\n    F,\n    OrderBy,\n    Value,\n    When,\n)\nfrom django.db.models.fetch_modes import FETCH_ONE\nfrom django.db.models.functions import Cast, Trunc\nfrom django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q\nfrom django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT\nfrom django.db.models.utils import (\n    AltersData,\n    create_namedtuple_class,\n    resolve_callables,\n)\nfrom django.utils import timezone\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    RemovedInDjango71Warning,\n    warn_about_external_use,\n)\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import func_accepts_kwargs, func_supports_parameter\nfrom django.utils.warnings import django_file_prefixes\n\nclass QuerySet(AltersData):\n    \n\n    def __init__(self, model=None, query=None, using=None, hints=None):\n        self.model = model\n        self._db = using\n        self._hints = hints or {}\n        self._query = query or sql.Query(self.model)\n        self._result_cache = None\n        self._sticky_filter = False\n        self._for_write = False\n        self._prefetch_related_lookups = ()\n        self._prefetch_done = False\n        self._known_related_objects = {}   \n        self._iterable_class = ModelIterable\n        self._fetch_mode = DEFAULT_FETCH_MODE\n        self._fields = None\n        self._defer_next_filter = False\n        self._deferred_filter = None\n        self._cloning_enabled = True\n\n    @property\n    def query(self):\n        if self._deferred_filter:\n            negate, args, kwargs = self._deferred_filter\n            self._filter_or_exclude_inplace(negate, args, kwargs)\n            self._deferred_filter = None\n        return self._query\n\n    @query.setter\n    def query(self, value):\n        if value.values_select:\n            self._iterable_class = ValuesIterable\n        self._query = value\n\n    def as_manager(cls):\n         \n        from django.db.models.manager import Manager\n\n        manager = Manager.from_queryset(cls)()\n        manager._built_with_as_manager = True\n        return manager\n\n    as_manager.queryset_only = True\n    as_manager = classmethod(as_manager)\n\n     \n     \n     \n\n    def __deepcopy__(self, memo):\n        \n        obj = self.__class__()\n        for k, v in self.__dict__.items():\n            if k == \"_result_cache\":\n                obj.__dict__[k] = None\n            else:\n                obj.__dict__[k] = copy.deepcopy(v, memo)\n        return obj\n\n    def __getstate__(self):\n         \n        self._fetch_all()\n        return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n    def __setstate__(self, state):\n        pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)\n        if pickled_version:\n            if pickled_version != django.__version__:\n                warnings.warn(\n                    \"Pickled queryset instance's Django version %s does not \"\n                    \"match the current version %s.\"\n                    % (pickled_version, django.__version__),\n                    RuntimeWarning,\n                    stacklevel=2,\n                )\n        else:\n            warnings.warn(\n                \"Pickled queryset instance's Django version is not specified.\",\n                RuntimeWarning,\n                stacklevel=2,\n            )\n        self.__dict__.update(state)\n\n    def __repr__(self):\n        data = list(self[: REPR_OUTPUT_SIZE + 1])\n        if len(data) > REPR_OUTPUT_SIZE:\n            data[-1] = \"...(remaining elements truncated)...\"\n        return \"<%s %r>\" % (self.__class__.__name__, data)\n\n    def __len__(self):\n        self._fetch_all()\n        return len(self._result_cache)\n\n    def __iter__(self):\n        \n        self._fetch_all()\n        return iter(self._result_cache)\n\n    def __aiter__(self):\n         \n         \n        async def generator():\n            await sync_to_async(self._fetch_all)()\n            for item in self._result_cache:\n                yield item\n\n        return generator()\n\n    def __bool__(self):\n        self._fetch_all()\n        return bool(self._result_cache)\n\n    def __getitem__(self, k):\n        \n        if not isinstance(k, (int, slice)):\n            raise TypeError(\n                \"QuerySet indices must be integers or slices, not %s.\"\n                % type(k).__name__\n            )\n        if (isinstance(k, int) and k < 0) or (\n            isinstance(k, slice)\n            and (\n                (k.start is not None and k.start < 0)\n                or (k.stop is not None and k.stop < 0)\n            )\n        ):\n            raise ValueError(\"Negative indexing is not supported.\")\n\n        if self._result_cache is not None:\n            return self._result_cache[k]\n\n        if isinstance(k, slice):\n            qs = self._chain()\n            if k.start is not None:\n                start = int(k.start)\n            else:\n                start = None\n            if k.stop is not None:\n                stop = int(k.stop)\n            else:\n                stop = None\n            qs.query.set_limits(start, stop)\n            return list(qs)[:: k.step] if k.step else qs\n\n        qs = self._chain()\n        qs.query.set_limits(k, k + 1)\n        qs._fetch_all()\n        return qs._result_cache[0]\n\n    def __class_getitem__(cls, *args, **kwargs):\n        return cls\n\n    def __and__(self, other):\n        self._check_operator_queryset(other, \"&\")\n        self._merge_sanity_check(other)\n        if isinstance(other, EmptyQuerySet):\n            return other\n        if isinstance(self, EmptyQuerySet):\n            return self\n        combined = self._chain()\n        combined._merge_known_related_objects(other)\n        combined.query.combine(other.query, sql.AND)\n        return combined\n\n    def __or__(self, other):\n        self._check_operator_queryset(other, \"|\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.OR)\n        return combined\n\n    def __xor__(self, other):\n        self._check_operator_queryset(other, \"^\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.XOR)\n        return combined\n\n     \n     \n     \n\n    def _iterator(self, use_chunked_fetch, chunk_size):\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if not self._prefetch_related_lookups or chunk_size is None:\n            yield from iterable\n            return\n\n        iterator = iter(iterable)\n        while results := list(islice(iterator, chunk_size)):\n            prefetch_related_objects(results, *self._prefetch_related_lookups)\n            yield from results\n\n    def iterator(self, chunk_size=None):\n        \n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                raise ValueError(\n                    \"chunk_size must be provided when using QuerySet.iterator() after \"\n                    \"prefetch_related().\"\n                )\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        return self._iterator(use_chunked_fetch, chunk_size)\n\n    async def aiterator(self, chunk_size=None):\n        \n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                 \n                 \n                 \n                 \n                 \n                warnings.warn(\n                    \"Using QuerySet.aiterator() after prefetch_related() without \"\n                    \"providing a chunk_size is deprecated and will raise a \"\n                    \"ValueError in Django 7.1.\",\n                    category=RemovedInDjango71Warning,\n                    skip_file_prefixes=django_file_prefixes(),\n                )\n                 \n                chunk_size = 2000\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if self._prefetch_related_lookups:\n            results = []\n\n            async for item in iterable:\n                results.append(item)\n                if len(results) >= chunk_size:\n                    await aprefetch_related_objects(\n                        results, *self._prefetch_related_lookups\n                    )\n                    for result in results:\n                        yield result\n                    results.clear()\n\n            if results:\n                await aprefetch_related_objects(\n                    results, *self._prefetch_related_lookups\n                )\n                for result in results:\n                    yield result\n        else:\n            async for item in iterable:\n                yield item\n\n    def aggregate(self, *args, **kwargs):\n        \n        if self.query.distinct_fields:\n            raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n        self._validate_values_are_expressions(\n            (*args, *kwargs.values()), method_name=\"aggregate\"\n        )\n        for arg in args:\n             \n             \n             \n            try:\n                arg.default_alias\n            except (AttributeError, TypeError):\n                raise TypeError(\"Complex aggregates require an alias\")\n            kwargs[arg.default_alias] = arg\n\n        return self.query.chain().get_aggregation(self.db, kwargs)\n\n    async def aaggregate(self, *args, **kwargs):\n        return await sync_to_async(self.aggregate)(*args, **kwargs)\n\n    def count(self):\n        \n        if self._result_cache is not None:\n            return len(self._result_cache)\n\n        return self.query.get_count(using=self.db)\n\n    async def acount(self):\n        return await sync_to_async(self.count)()\n\n    def get(self, *args, **kwargs):\n        \n        if self.query.combinator and (args or kwargs):\n            raise NotSupportedError(\n                \"Calling QuerySet.get(...) with filters after %s() is not \"\n                \"supported.\" % self.query.combinator\n            )\n        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)\n        if self.query.can_filter() and not self.query.distinct_fields:\n            clone = clone.order_by()\n        limit = None\n        if (\n            not clone.query.select_for_update\n            or connections[clone.db].features.supports_select_for_update_with_limit\n        ):\n            limit = MAX_GET_RESULTS\n            clone.query.set_limits(high=limit)\n        num = len(clone)\n        if num == 1:\n            return clone._result_cache[0]\n        if not num:\n            raise self.model.DoesNotExist(\n                \"%s matching query does not exist.\" % self.model._meta.object_name\n            )\n        raise self.model.MultipleObjectsReturned(\n            \"get() returned more than one %s -- it returned %s!\"\n            % (\n                self.model._meta.object_name,\n                num if not limit or num < limit else \"more than %s\" % (limit - 1),\n            )\n        )\n\n    async def aget(self, *args, **kwargs):\n        return await sync_to_async(self.get)(*args, **kwargs)\n\n    def create(self, **kwargs):\n        \n        reverse_one_to_one_fields = frozenset(kwargs).intersection(\n            self.model._meta._reverse_one_to_one_field_names\n        )\n        if reverse_one_to_one_fields:\n            raise ValueError(\n                \"The following fields do not exist in this model: %s\"\n                % \", \".join(reverse_one_to_one_fields)\n            )\n\n        obj = self.model(**kwargs)\n        self._for_write = True\n        obj.save(force_insert=True, using=self.db)\n        obj._state.fetch_mode = self._fetch_mode\n        return obj\n\n    create.alters_data = True\n\n    async def acreate(self, **kwargs):\n        return await sync_to_async(self.create)(**kwargs)\n\n    acreate.alters_data = True\n\n    def _prepare_for_bulk_create(self, objs):\n        objs_with_pk, objs_without_pk = [], []\n        for obj in objs:\n            obj._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n            if isinstance(obj.pk, DatabaseDefault):\n                objs_without_pk.append(obj)\n            elif obj._is_pk_set():\n                objs_with_pk.append(obj)\n            else:\n                obj.pk = obj._meta.pk.get_pk_value_on_save(obj)\n                if obj._is_pk_set():\n                    objs_with_pk.append(obj)\n                else:\n                    objs_without_pk.append(obj)\n        return objs_with_pk, objs_without_pk\n\n    def _check_bulk_create_options(\n        self, ignore_conflicts, update_conflicts, update_fields, unique_fields\n    ):\n        if ignore_conflicts and update_conflicts:\n            raise ValueError(\n                \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n            )\n        db_features = connections[self.db].features\n        if ignore_conflicts:\n            if not db_features.supports_ignore_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support ignoring conflicts.\"\n                )\n            return OnConflict.IGNORE\n        elif update_conflicts:\n            if not db_features.supports_update_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support updating conflicts.\"\n                )\n            if not update_fields:\n                raise ValueError(\n                    \"Fields that will be updated when a row insertion fails \"\n                    \"on conflicts must be provided.\"\n                )\n            if unique_fields and not db_features.supports_update_conflicts_with_target:\n                raise NotSupportedError(\n                    \"This database backend does not support updating \"\n                    \"conflicts with specifying unique fields that can trigger \"\n                    \"the upsert.\"\n                )\n            if not unique_fields and db_features.supports_update_conflicts_with_target:\n                raise ValueError(\n                    \"Unique fields that can trigger the upsert must be provided.\"\n                )\n             \n            if any(not f.concrete for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() can only be used with concrete fields in \"\n                    \"update_fields.\"\n                )\n            if any(f in self.model._meta.pk_fields for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() cannot be used with primary keys in \"\n                    \"update_fields.\"\n                )\n            if unique_fields:\n                if any(not f.concrete for f in unique_fields):\n                    raise ValueError(\n                        \"bulk_create() can only be used with concrete fields \"\n                        \"in unique_fields.\"\n                    )\n            return OnConflict.UPDATE\n        return None\n\n    def bulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n         \n         \n         \n         \n         \n        for parent in self.model._meta.all_parents:\n            if parent._meta.concrete_model is not self.model._meta.concrete_model:\n                raise ValueError(\"Can't bulk create a multi-table inherited model\")\n        if not objs:\n            return objs\n        opts = self.model._meta\n        if unique_fields:\n             \n            unique_fields = [\n                self.model._meta.get_field(opts.pk.name if name == \"pk\" else name)\n                for name in unique_fields\n            ]\n        if update_fields:\n            update_fields = [self.model._meta.get_field(name) for name in update_fields]\n        on_conflict = self._check_bulk_create_options(\n            ignore_conflicts,\n            update_conflicts,\n            update_fields,\n            unique_fields,\n        )\n        self._for_write = True\n        fields = [f for f in opts.concrete_fields if not f.generated]\n        objs = list(objs)\n        objs_with_pk, objs_without_pk = self._prepare_for_bulk_create(objs)\n        if objs_with_pk and objs_without_pk:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            self._handle_order_with_respect_to(objs)\n            if objs_with_pk:\n                returned_columns = self._batched_insert(\n                    objs_with_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                for obj_with_pk, results in zip(objs_with_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_with_pk, field.attname, result)\n                for obj_with_pk in objs_with_pk:\n                    obj_with_pk._state.adding = False\n                    obj_with_pk._state.db = self.db\n            if objs_without_pk:\n                fields = [f for f in fields if not isinstance(f, AutoField)]\n                returned_columns = self._batched_insert(\n                    objs_without_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                connection = connections[self.db]\n                if (\n                    connection.features.can_return_rows_from_bulk_insert\n                    and on_conflict is None\n                ):\n                    assert len(returned_columns) == len(objs_without_pk)\n                for obj_without_pk, results in zip(objs_without_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_without_pk, field.attname, result)\n                    obj_without_pk._state.adding = False\n                    obj_without_pk._state.db = self.db\n\n        return objs\n\n    def _handle_order_with_respect_to(self, objs):\n        if objs and (order_wrt := self.model._meta.order_with_respect_to):\n            get_filter_kwargs_for_object = order_wrt.get_filter_kwargs_for_object\n            attnames = list(get_filter_kwargs_for_object(objs[0]))\n            group_keys = set()\n            obj_groups = []\n            for obj in objs:\n                group_key = tuple(get_filter_kwargs_for_object(obj).values())\n                group_keys.add(group_key)\n                obj_groups.append((obj, group_key))\n            filters = [\n                Q.create(list(zip(attnames, group_key))) for group_key in group_keys\n            ]\n            next_orders = (\n                self.model._base_manager.using(self.db)\n                .filter(reduce(operator.or_, filters))\n                .values_list(*attnames)\n                .annotate(_order__max=Max(\"_order\") + 1)\n            )\n             \n            group_next_orders = dict.fromkeys(group_keys, 0)\n            group_next_orders.update(\n                (tuple(group_key), next_order) for *group_key, next_order in next_orders\n            )\n             \n            for obj, group_key in obj_groups:\n                if getattr(obj, \"_order\", None) is None:\n                    group_next_order = group_next_orders[group_key]\n                    obj._order = group_next_order\n                    group_next_orders[group_key] += 1\n\n    bulk_create.alters_data = True\n\n    async def abulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        return await sync_to_async(self.bulk_create)(\n            objs=objs,\n            batch_size=batch_size,\n            ignore_conflicts=ignore_conflicts,\n            update_conflicts=update_conflicts,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n\n    abulk_create.alters_data = True\n\n    def bulk_update(self, objs, fields, batch_size=None):\n        \n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        if not fields:\n            raise ValueError(\"Field names must be given to bulk_update().\")\n        objs = tuple(objs)\n        if not all(obj._is_pk_set() for obj in objs):\n            raise ValueError(\"All bulk_update() objects must have a primary key set.\")\n        opts = self.model._meta\n        fields = [opts.get_field(name) for name in fields]\n        if any(not f.concrete for f in fields):\n            raise ValueError(\"bulk_update() can only be used with concrete fields.\")\n        all_pk_fields = set(opts.pk_fields)\n        for parent in opts.all_parents:\n            all_pk_fields.update(parent._meta.pk_fields)\n        if any(f in all_pk_fields for f in fields):\n            raise ValueError(\"bulk_update() cannot be used with primary key fields.\")\n        if not objs:\n            return 0\n        for obj in objs:\n            obj._prepare_related_fields_for_save(\n                operation_name=\"bulk_update\", fields=fields\n            )\n         \n         \n        self._for_write = True\n        connection = connections[self.db]\n        max_batch_size = connection.ops.bulk_batch_size(\n            [opts.pk, opts.pk, *fields], objs\n        )\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        requires_casting = connection.features.requires_casted_case_in_updates\n        batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size))\n        updates = []\n        for batch_objs in batches:\n            update_kwargs = {}\n            for field in fields:\n                when_statements = []\n                for obj in batch_objs:\n                    attr = getattr(obj, field.attname)\n                    if not hasattr(attr, \"resolve_expression\"):\n                        attr = Value(attr, output_field=field)\n                    when_statements.append(When(pk=obj.pk, then=attr))\n                case_statement = Case(*when_statements, output_field=field)\n                if requires_casting:\n                    case_statement = Cast(case_statement, output_field=field)\n                update_kwargs[field.attname] = case_statement\n            updates.append(([obj.pk for obj in batch_objs], update_kwargs))\n        rows_updated = 0\n        queryset = self.using(self.db)\n        with transaction.atomic(using=self.db, savepoint=False):\n            for pks, update_kwargs in updates:\n                rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs)\n        return rows_updated\n\n    bulk_update.alters_data = True\n\n    async def abulk_update(self, objs, fields, batch_size=None):\n        return await sync_to_async(self.bulk_update)(\n            objs=objs,\n            fields=fields,\n            batch_size=batch_size,\n        )\n\n    abulk_update.alters_data = True\n\n    def get_or_create(self, defaults=None, **kwargs):\n        \n         \n         \n        self._for_write = True\n        try:\n            return self.get(**kwargs), False\n        except self.model.DoesNotExist:\n            params = self._extract_model_params(defaults, **kwargs)\n             \n            try:\n                with transaction.atomic(using=self.db):\n                    params = dict(resolve_callables(params))\n                    return self.create(**params), True\n            except IntegrityError:\n                try:\n                    return self.get(**kwargs), False\n                except self.model.DoesNotExist:\n                    pass\n                raise\n\n    get_or_create.alters_data = True\n\n    async def aget_or_create(self, defaults=None, **kwargs):\n        return await sync_to_async(self.get_or_create)(\n            defaults=defaults,\n            **kwargs,\n        )\n\n    aget_or_create.alters_data = True\n\n    def update_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        \n        update_defaults = defaults or {}\n        if create_defaults is None:\n            create_defaults = update_defaults\n\n        self._for_write = True\n        with transaction.atomic(using=self.db):\n             \n             \n            obj, created = self.select_for_update().get_or_create(\n                create_defaults, **kwargs\n            )\n            if created:\n                return obj, created\n            for k, v in resolve_callables(update_defaults):\n                setattr(obj, k, v)\n\n            update_fields = set(update_defaults)\n            concrete_field_names = self.model._meta._non_pk_concrete_field_names\n             \n            if concrete_field_names.issuperset(update_fields):\n                 \n                 \n                 \n                 \n                pk_fields = self.model._meta.pk_fields\n                for field in self.model._meta.local_concrete_fields:\n                    if not (\n                        field in pk_fields or field.__class__.pre_save is Field.pre_save\n                    ):\n                        update_fields.add(field.name)\n                        if field.name != field.attname:\n                            update_fields.add(field.attname)\n                obj.save(using=self.db, update_fields=update_fields)\n            else:\n                obj.save(using=self.db)\n        return obj, False\n\n    update_or_create.alters_data = True\n\n    async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        return await sync_to_async(self.update_or_create)(\n            defaults=defaults,\n            create_defaults=create_defaults,\n            **kwargs,\n        )\n\n    aupdate_or_create.alters_data = True\n\n    def _extract_model_params(self, defaults, **kwargs):\n        \n        defaults = defaults or {}\n        params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}\n        params.update(defaults)\n        property_names = self.model._meta._property_names\n        invalid_params = []\n        for param in params:\n            try:\n                self.model._meta.get_field(param)\n            except exceptions.FieldDoesNotExist:\n                 \n                if not (param in property_names and getattr(self.model, param).fset):\n                    invalid_params.append(param)\n        if invalid_params:\n            raise exceptions.FieldError(\n                \"Invalid field name(s) for model %s: '%s'.\"\n                % (\n                    self.model._meta.object_name,\n                    \"', '\".join(sorted(invalid_params)),\n                )\n            )\n        return params\n\n    def _earliest(self, *fields):\n        \n        if fields:\n            order_by = fields\n        else:\n            order_by = getattr(self.model._meta, \"get_latest_by\")\n            if order_by and not isinstance(order_by, (tuple, list)):\n                order_by = (order_by,)\n        if order_by is None:\n            raise ValueError(\n                \"earliest() and latest() require either fields as positional \"\n                \"arguments or 'get_latest_by' in the model's Meta.\"\n            )\n        obj = self._chain()\n        obj.query.set_limits(high=1)\n        obj.query.clear_ordering(force=True)\n        obj.query.add_ordering(*order_by)\n        return obj.get()\n\n    def earliest(self, *fields):\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self._earliest(*fields)\n\n    async def aearliest(self, *fields):\n        return await sync_to_async(self.earliest)(*fields)\n\n    def latest(self, *fields):\n        \n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.reverse()._earliest(*fields)\n\n    async def alatest(self, *fields):\n        return await sync_to_async(self.latest)(*fields)\n\n    def first(self):\n        \n        if self.ordered or not self.query.default_ordering:\n            queryset = self\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"first\")\n            queryset = self.order_by(\"pk\")\n        for obj in queryset[:1]:\n            return obj\n\n    async def afirst(self):\n        return await sync_to_async(self.first)()\n\n    def last(self):\n        \n        if self.ordered or not self.query.default_ordering:\n            queryset = self.reverse()\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"last\")\n            queryset = self.order_by(\"-pk\")\n        for obj in queryset[:1]:\n            return obj\n\n    async def alast(self):\n        return await sync_to_async(self.last)()\n\n    def in_bulk(self, id_list=None, *, field_name=\"pk\"):\n        \n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with in_bulk().\")\n        if id_list is not None and not id_list:\n            return {}\n        opts = self.model._meta\n        unique_fields = [\n            constraint.fields[0]\n            for constraint in opts.total_unique_constraints\n            if len(constraint.fields) == 1\n        ]\n        if (\n            field_name != \"pk\"\n            and not opts.get_field(field_name).unique\n            and field_name not in unique_fields\n            and self.query.distinct_fields != (field_name,)\n        ):\n            raise ValueError(\n                \"in_bulk()'s field_name must be a unique field but %r isn't.\"\n                % field_name\n            )\n\n        qs = self\n\n        def get_obj(obj):\n            return obj\n\n        if issubclass(self._iterable_class, ModelIterable):\n             \n            get_key = operator.attrgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesIterable):\n            if field_name not in self.query.values_select:\n                qs = qs.values(field_name, *self.query.values_select)\n\n                def get_obj(obj):   \n                     \n                     \n                     \n                    del obj[field_name]\n                    return obj\n\n            get_key = operator.itemgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesListIterable):\n            try:\n                field_index = self.query.values_select.index(field_name)\n            except ValueError:\n                 \n                field_index = 0\n                if issubclass(self._iterable_class, NamedValuesListIterable):\n                    kwargs = {\"named\": True}\n                else:\n                    kwargs = {}\n                    get_obj = operator.itemgetter(slice(1, None))\n                qs = qs.values_list(field_name, *self.query.values_select, **kwargs)\n\n            get_key = operator.itemgetter(field_index)\n\n        elif issubclass(self._iterable_class, FlatValuesListIterable):\n            if self.query.values_select == (field_name,):\n                 \n                get_key = get_obj\n            else:\n                 \n                qs = qs.values_list(field_name, *self.query.values_select)\n                get_key = operator.itemgetter(0)\n                get_obj = operator.itemgetter(1)\n\n        else:\n            raise TypeError(\n                f\"in_bulk() cannot be used with {self._iterable_class.__name__}.\"\n            )\n\n        if id_list is not None:\n            filter_key = \"{}__in\".format(field_name)\n            id_list = tuple(id_list)\n            batch_size = connections[self.db].ops.bulk_batch_size([opts.pk], id_list)\n             \n             \n            if batch_size and batch_size < len(id_list):\n                results = ()\n                for offset in range(0, len(id_list), batch_size):\n                    batch = id_list[offset : offset + batch_size]\n                    results += tuple(qs.filter(**{filter_key: batch}))\n                qs = results\n            else:\n                qs = qs.filter(**{filter_key: id_list})\n        else:\n            qs = qs._chain()\n        return {get_key(obj): get_obj(obj) for obj in qs}\n\n    async def ain_bulk(self, id_list=None, *, field_name=\"pk\"):\n        return await sync_to_async(self.in_bulk)(\n            id_list=id_list,\n            field_name=field_name,\n        )\n\n    def delete(self):\n        \n        self._not_support_combined_queries(\"delete\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with delete().\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call delete() after .distinct(*fields).\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call delete() after .values() or .values_list()\")\n\n        del_query = self._chain()\n\n         \n         \n         \n        del_query._for_write = True\n\n         \n        del_query.query.select_for_update = False\n        del_query.query.select_related = False\n        del_query.query.clear_ordering(force=True)\n\n        collector = Collector(using=del_query.db, origin=self)\n        collector.collect(del_query)\n        num_deleted, num_deleted_per_model = collector.delete()\n\n         \n        self._result_cache = None\n        return num_deleted, num_deleted_per_model\n\n    delete.alters_data = True\n    delete.queryset_only = True\n\n    async def adelete(self):\n        return await sync_to_async(self.delete)()\n\n    adelete.alters_data = True\n    adelete.queryset_only = True\n\n    def _raw_delete(self, using):\n        \n        query = self.query.clone()\n        query.__class__ = sql.DeleteQuery\n        return query.get_compiler(using).execute_sql(ROW_COUNT)\n\n    _raw_delete.alters_data = True\n\n    def update(self, **kwargs):\n        \n        self._not_support_combined_queries(\"update\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call update() after .distinct(*fields).\")\n        self._for_write = True\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_values(kwargs)\n\n         \n        new_order_by = []\n        for col in query.order_by:\n            alias = col\n            descending = False\n            if isinstance(alias, str) and alias.startswith(\"-\"):\n                alias = alias.removeprefix(\"-\")\n                descending = True\n            if annotation := query.annotations.get(alias):\n                if getattr(annotation, \"contains_aggregate\", False):\n                    raise exceptions.FieldError(\n                        f\"Cannot update when ordering by an aggregate: {annotation}\"\n                    )\n                if descending:\n                    annotation = annotation.desc()\n                new_order_by.append(annotation)\n            else:\n                new_order_by.append(col)\n        query.order_by = tuple(new_order_by)\n\n         \n         \n        query.clear_select_clause()\n        with transaction.mark_for_rollback_on_error(using=self.db):\n            rows = query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        self._result_cache = None\n        return rows\n\n    update.alters_data = True\n\n    async def aupdate(self, **kwargs):\n        return await sync_to_async(self.update)(**kwargs)\n\n    aupdate.alters_data = True\n\n    def _update(self, values, returning_fields=None):\n        \n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_fields(values)\n         \n        query.annotations = {}\n        self._result_cache = None\n        if returning_fields is None:\n            return query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        return query.get_compiler(self.db).execute_returning_sql(returning_fields)\n\n    _update.alters_data = True\n    _update.queryset_only = False\n\n    def exists(self):\n        \n        if self._result_cache is None:\n            return self.query.has_results(using=self.db)\n        return bool(self._result_cache)\n\n    async def aexists(self):\n        return await sync_to_async(self.exists)()\n\n    def contains(self, obj):\n        \n        self._not_support_combined_queries(\"contains\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call QuerySet.contains() after .values() or .values_list().\"\n            )\n        try:\n            if obj._meta.concrete_model != self.model._meta.concrete_model:\n                return False\n        except AttributeError:\n            raise TypeError(\"'obj' must be a model instance.\")\n        if not obj._is_pk_set():\n            raise ValueError(\"QuerySet.contains() cannot be used on unsaved objects.\")\n        if self._result_cache is not None:\n            return obj in self._result_cache\n        return self.filter(pk=obj.pk).exists()\n\n    async def acontains(self, obj):\n        return await sync_to_async(self.contains)(obj=obj)\n\n    def _prefetch_related_objects(self):\n         \n        prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)\n        self._prefetch_done = True\n\n    def explain(self, *, format=None, **options):\n        \n        return self.query.explain(using=self.db, format=format, **options)\n\n    async def aexplain(self, *, format=None, **options):\n        return await sync_to_async(self.explain)(format=format, **options)\n\n     \n     \n     \n\n    def raw(self, raw_query, params=(), translations=None, using=None):\n        if using is None:\n            using = self.db\n        qs = RawQuerySet(\n            raw_query,\n            model=self.model,\n            params=params,\n            translations=translations,\n            using=using,\n            fetch_mode=self._fetch_mode,\n        )\n        qs._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        return qs\n\n    def _values(self, *fields, **expressions):\n        clone = self._chain()\n        if expressions:\n             \n             \n            with warnings.catch_warnings(\n                action=\"ignore\", category=RemovedInDjango70Warning\n            ):\n                clone = clone.annotate(**expressions)\n        clone._fields = fields\n        clone.query.set_values(fields)\n        return clone\n\n    def values(self, *fields, **expressions):\n        fields += tuple(expressions)\n        clone = self._values(*fields, **expressions)\n        clone._iterable_class = ValuesIterable\n        return clone\n\n    def values_list(self, *fields, flat=False, named=False):\n        if flat and named:\n            raise TypeError(\"'flat' and 'named' can't be used together.\")\n        if flat:\n            if len(fields) > 1:\n                raise TypeError(\n                    \"'flat' is not valid when values_list is called with more than one \"\n                    \"field.\"\n                )\n            elif not fields:\n                 \n                 \n                 \n                 \n                 \n                 \n                warnings.warn(\n                    \"Calling values_list() with no field name and flat=True \"\n                    \"is deprecated. Pass an explicit field name instead, like \"\n                    \"'pk'.\",\n                    RemovedInDjango70Warning,\n                )\n                fields = [self.model._meta.concrete_fields[0].attname]\n\n        field_names = {f: False for f in fields if not hasattr(f, \"resolve_expression\")}\n        _fields = []\n        expressions = {}\n        counter = 1\n        for field in fields:\n            field_name = field\n            expression = None\n            if hasattr(field, \"resolve_expression\"):\n                field_name = getattr(\n                    field, \"default_alias\", field.__class__.__name__.lower()\n                )\n                expression = field\n                 \n                 \n                 \n                 \n                seen = True\n            elif seen := field_names[field_name]:\n                expression = F(field_name)\n            if seen:\n                field_name_prefix = field_name\n                while (field_name := f\"{field_name_prefix}{counter}\") in field_names:\n                    counter += 1\n            if expression is not None:\n                expressions[field_name] = expression\n            field_names[field_name] = True\n            _fields.append(field_name)\n\n        clone = self._values(*_fields, **expressions)\n        clone._iterable_class = (\n            NamedValuesListIterable\n            if named\n            else FlatValuesListIterable if flat else ValuesListIterable\n        )\n        return clone\n\n    def dates(self, field_name, kind, order=\"ASC\"):\n        \n        if kind not in (\"year\", \"month\", \"week\", \"day\"):\n            raise ValueError(\"'kind' must be one of 'year', 'month', 'week', or 'day'.\")\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        return (\n            self.annotate(\n                datefield=Trunc(field_name, kind, output_field=DateField()),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datefield\")\n        )\n\n    def datetimes(self, field_name, kind, order=\"ASC\", tzinfo=None):\n        \n        if kind not in (\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"):\n            raise ValueError(\n                \"'kind' must be one of 'year', 'month', 'week', 'day', \"\n                \"'hour', 'minute', or 'second'.\"\n            )\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        if settings.USE_TZ:\n            if tzinfo is None:\n                tzinfo = timezone.get_current_timezone()\n        else:\n            tzinfo = None\n        return (\n            self.annotate(\n                datetimefield=Trunc(\n                    field_name,\n                    kind,\n                    output_field=DateTimeField(),\n                    tzinfo=tzinfo,\n                ),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datetimefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datetimefield\")\n        )\n\n    def none(self):\n        \n        clone = self._chain()\n        clone.query.set_empty()\n        return clone\n\n     \n     \n     \n\n    def all(self):\n        \n        return self._chain()\n\n    def filter(self, *args, **kwargs):\n        \n        self._not_support_combined_queries(\"filter\")\n        return self._filter_or_exclude(False, args, kwargs)\n\n    def exclude(self, *args, **kwargs):\n        \n        self._not_support_combined_queries(\"exclude\")\n        return self._filter_or_exclude(True, args, kwargs)\n\n    def _filter_or_exclude(self, negate, args, kwargs):\n        if (args or kwargs) and self.query.is_sliced:\n            raise TypeError(\"Cannot filter a query once a slice has been taken.\")\n        clone = self._chain()\n        if self._defer_next_filter:\n            self._defer_next_filter = False\n            clone._deferred_filter = negate, args, kwargs\n        else:\n            clone._filter_or_exclude_inplace(negate, args, kwargs)\n        return clone\n\n    def _filter_or_exclude_inplace(self, negate, args, kwargs):\n        if invalid_kwargs := PROHIBITED_FILTER_KWARGS.intersection(kwargs):\n            invalid_kwargs_str = \", \".join(f\"'{k}'\" for k in sorted(invalid_kwargs))\n            raise TypeError(f\"The following kwargs are invalid: {invalid_kwargs_str}\")\n        if negate:\n            self._query.add_q(~Q(*args, **kwargs))\n        else:\n            self._query.add_q(Q(*args, **kwargs))\n\n    def complex_filter(self, filter_obj):\n        \n        if isinstance(filter_obj, Q):\n            clone = self._chain()\n            clone.query.add_q(filter_obj)\n            return clone\n        else:\n            return self._filter_or_exclude(False, args=(), kwargs=filter_obj)\n\n    def _combinator_query(self, combinator, *other_qs, all=False):\n         \n        clone = self._chain()\n         \n        clone.query.clear_ordering(force=True)\n        clone.query.default_ordering = True\n        self._clear_ordering_in_combined_queries(clone.query, other_qs)\n        clone.query.clear_limits()\n        clone.query.combinator = combinator\n        clone.query.combinator_all = all\n        return clone\n\n    def union(self, *other_qs, all=False):\n         \n        if isinstance(self, EmptyQuerySet):\n            qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)]\n            if not qs:\n                return self\n            if len(qs) == 1:\n                return qs[0]\n            return qs[0]._combinator_query(\"union\", *qs[1:], all=all)\n        elif not other_qs:\n            return self\n        return self._combinator_query(\"union\", *other_qs, all=all)\n\n    def intersection(self, *other_qs):\n         \n        if isinstance(self, EmptyQuerySet):\n            return self\n        for other in other_qs:\n            if isinstance(other, EmptyQuerySet):\n                return other\n        return self._combinator_query(\"intersection\", *other_qs)\n\n    def difference(self, *other_qs):\n         \n        if isinstance(self, EmptyQuerySet):\n            return self\n        return self._combinator_query(\"difference\", *other_qs)\n\n    def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False):\n        \n        if nowait and skip_locked:\n            raise ValueError(\"The nowait option cannot be used with skip_locked.\")\n        obj = self._chain()\n        obj._for_write = True\n        obj.query.select_for_update = True\n        obj.query.select_for_update_nowait = nowait\n        obj.query.select_for_update_skip_locked = skip_locked\n        obj.query.select_for_update_of = of\n        obj.query.select_for_no_key_update = no_key\n        return obj\n\n    def select_related(self, *fields):\n        \n        self._not_support_combined_queries(\"select_related\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call select_related() after .values() or .values_list()\"\n            )\n\n        obj = self._chain()\n        if fields == (None,):\n            obj.query.select_related = False\n        elif fields:\n            obj.query.add_select_related(fields)\n        else:\n             \n             \n            warn_about_external_use(\n                \"Calling select_related() with no arguments is deprecated. \"\n                \"Specify the fields to fetch instead.\",\n                category=RemovedInDjango70Warning,\n                skip_name_prefixes=(\"django.db.models\",),\n            )\n            obj.query.select_related = True\n        return obj\n\n    def prefetch_related(self, *lookups):\n        \n        self._not_support_combined_queries(\"prefetch_related\")\n        clone = self._chain()\n        if lookups == (None,):\n            clone._prefetch_related_lookups = ()\n        else:\n            for lookup in lookups:\n                if isinstance(lookup, Prefetch):\n                    lookup = lookup.prefetch_to\n                lookup = lookup.split(LOOKUP_SEP, 1)[0]\n                if lookup in self.query._filtered_relations:\n                    raise ValueError(\n                        \"prefetch_related() is not supported with FilteredRelation.\"\n                    )\n            clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups\n        return clone\n\n    def annotate(self, *args, **kwargs):\n        \n        self._not_support_combined_queries(\"annotate\")\n        return self._annotate(args, kwargs, select=True)\n\n    def alias(self, *args, **kwargs):\n        \n        self._not_support_combined_queries(\"alias\")\n        return self._annotate(args, kwargs, select=False)\n\n    def _annotate(self, args, kwargs, select=True):\n        self._validate_values_are_expressions(\n            args + tuple(kwargs.values()), method_name=\"annotate\"\n        )\n        annotations = {}\n        for arg in args:\n             \n             \n             \n            try:\n                if arg.default_alias in kwargs:\n                    raise ValueError(\n                        \"The named annotation '%s' conflicts with the \"\n                        \"default name for another annotation.\" % arg.default_alias\n                    )\n            except (TypeError, AttributeError):\n                raise TypeError(\"Complex annotations require an alias\")\n            annotations[arg.default_alias] = arg\n        annotations.update(kwargs)\n\n        clone = self._chain()\n        names = self._fields\n        if names is None:\n            names = set(\n                chain.from_iterable(\n                    (\n                        (field.name, field.attname)\n                        if hasattr(field, \"attname\")\n                        else (field.name,)\n                    )\n                    for field in self.model._meta.get_fields()\n                )\n            )\n\n        for alias, annotation in annotations.items():\n            if alias in names:\n                raise ValueError(\n                    \"The annotation '%s' conflicts with a field on \"\n                    \"the model.\" % alias\n                )\n            if isinstance(annotation, FilteredRelation):\n                clone.query.add_filtered_relation(annotation, alias)\n            else:\n                clone.query.add_annotation(\n                    annotation,\n                    alias,\n                    select=select,\n                )\n        for alias, annotation in clone.query.annotations.items():\n            if alias in annotations and annotation.contains_aggregate:\n                if clone._fields is None:\n                    clone.query.group_by = True\n                else:\n                    clone.query.set_group_by()\n                break\n\n        return clone\n\n    def order_by(self, *field_names):\n        \n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reorder a query once a slice has been taken.\")\n        obj = self._chain()\n        obj.query.clear_ordering(force=True, clear_default=False)\n        obj.query.add_ordering(*field_names)\n        return obj\n\n    def distinct(self, *field_names):\n        \n        self._not_support_combined_queries(\"distinct\")\n        if self.query.is_sliced:\n            raise TypeError(\n                \"Cannot create distinct fields once a slice has been taken.\"\n            )\n        obj = self._chain()\n        obj.query.add_distinct_fields(*field_names)\n        return obj\n\n    def extra(\n        self,\n        select=None,\n        where=None,\n        params=None,\n        tables=None,\n        order_by=None,\n        select_params=None,\n    ):\n        \n        self._not_support_combined_queries(\"extra\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.add_extra(select, select_params, where, params, tables, order_by)\n        return clone\n\n    def reverse(self):\n        \n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reverse a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.standard_ordering = not clone.query.standard_ordering\n        return clone\n\n    def defer(self, *fields):\n        \n        self._not_support_combined_queries(\"defer\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call defer() after .values() or .values_list()\")\n        clone = self._chain()\n        if fields == (None,):\n            clone.query.clear_deferred_loading()\n        else:\n            clone.query.add_deferred_loading(fields)\n        return clone\n\n    def only(self, *fields):\n        \n        self._not_support_combined_queries(\"only\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call only() after .values() or .values_list()\")\n        if fields == (None,):\n             \n             \n            raise TypeError(\"Cannot pass None as an argument to only().\")\n        for field in fields:\n            field = field.split(LOOKUP_SEP, 1)[0]\n            if field in self.query._filtered_relations:\n                raise ValueError(\"only() is not supported with FilteredRelation.\")\n        clone = self._chain()\n        clone.query.add_immediate_loading(fields)\n        return clone\n\n    def using(self, alias):\n        \n        clone = self._chain()\n        clone._db = alias\n        return clone\n\n    def fetch_mode(self, fetch_mode):\n        \n        clone = self._chain()\n        clone._fetch_mode = fetch_mode\n        return clone\n\n     \n     \n     \n\n    @property\n    def ordered(self):\n        \n        if isinstance(self, EmptyQuerySet):\n            return True\n        if self.query.extra_order_by or self.query.order_by:\n            return True\n        elif (\n            self.query.default_ordering\n            and self.query.get_meta().ordering\n            and\n             \n            not self.query.group_by\n        ):\n            return True\n        else:\n            return False\n\n    @property\n    def totally_ordered(self):\n        \n        if not self.ordered:\n            return False\n        ordering = self.query.order_by\n        if not ordering and self.query.default_ordering:\n            ordering = self.query.get_meta().ordering\n        if not ordering:\n            return False\n        opts = self.model._meta\n        pk_fields = {f.attname for f in opts.pk_fields}\n        candidate_fields = set()\n        for part in ordering:\n             \n            field_name = None\n            if isinstance(part, str):\n                field_name = part.lstrip(\"-\")\n            elif isinstance(part, F):\n                field_name = part.name\n            elif isinstance(part, OrderBy) and isinstance(part.expression, F):\n                field_name = part.expression.name\n            if annotation_col := self.query.annotations.get(field_name):\n                if isinstance(annotation_col, Col):\n                    if annotation_col.alias == self.query.base_table:\n                        candidate_fields.add(annotation_col.target)\n                elif isinstance(annotation_col, ColPairs):\n                    candidate_fields |= {\n                        c.target\n                        for c in annotation_col.get_cols()\n                        if c.alias == self.query.base_table\n                    }\n            elif field_name:\n                if field_name == \"pk\":\n                    return True\n                 \n                try:\n                    field = opts.get_field(field_name)\n                except exceptions.FieldDoesNotExist:\n                     \n                     \n                    continue\n                else:\n                     \n                     \n                    if field.remote_field and field_name == field.name:\n                        continue\n                    candidate_fields.add(field)\n\n        candidate_attnames = set()\n        for field in candidate_fields:\n            if field.unique and not field.null:\n                return True\n            candidate_attnames.add(field.attname)\n\n         \n        if candidate_attnames.issuperset(pk_fields):\n            return True\n         \n         \n        constraint_field_names = (\n            *opts.unique_together,\n            *(constraint.fields for constraint in opts.total_unique_constraints),\n        )\n        for field_names in constraint_field_names:\n             \n            try:\n                fields = [opts.get_field(field_name) for field_name in field_names]\n            except exceptions.FieldDoesNotExist:\n                continue\n             \n             \n            if any(field.null for field in fields):\n                continue\n            if candidate_attnames.issuperset(field.attname for field in fields):\n                return True\n\n        return False\n\n    @property\n    def db(self):\n        \n        if self._for_write:\n            return self._db or router.db_for_write(self.model, **self._hints)\n        return self._db or router.db_for_read(self.model, **self._hints)\n\n     \n     \n     \n\n    def _insert(\n        self,\n        objs,\n        fields,\n        returning_fields=None,\n        raw=False,\n        using=None,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \n        self._for_write = True\n        if using is None:\n            using = self.db\n        query = sql.InsertQuery(\n            self.model,\n            on_conflict=on_conflict,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n        query.insert_values(fields, objs, raw=raw)\n        return query.get_compiler(using=using).execute_sql(returning_fields)\n\n    _insert.alters_data = True\n    _insert.queryset_only = False\n\n    def _batched_insert(\n        self,\n        objs,\n        fields,\n        batch_size,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \n        connection = connections[self.db]\n        ops = connection.ops\n        max_batch_size = max(ops.bulk_batch_size(fields, objs), 1)\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        inserted_rows = []\n        returning_fields = (\n            self.model._meta.db_returning_fields\n            if (\n                connection.features.can_return_rows_from_bulk_insert\n                and (on_conflict is None or on_conflict == OnConflict.UPDATE)\n            )\n            else None\n        )\n        batches = [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]\n        if len(batches) > 1:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            for item in batches:\n                inserted_rows.extend(\n                    self._insert(\n                        item,\n                        fields=fields,\n                        using=self.db,\n                        on_conflict=on_conflict,\n                        update_fields=update_fields,\n                        unique_fields=unique_fields,\n                        returning_fields=returning_fields,\n                    )\n                )\n        return inserted_rows\n\n    def _disable_cloning(self):\n        \n        self._cloning_enabled = False\n        return self\n\n    def _enable_cloning(self):\n        \n        self._cloning_enabled = True\n        return self\n\n    def _avoid_cloning(self):\n        \n        return PreventQuerySetCloning(self)\n\n    def _chain(self):\n        \n        if not self._cloning_enabled:\n            obj = self\n        else:\n            obj = self._clone()\n        if obj._sticky_filter:\n            obj.query.filter_is_sticky = True\n            obj._sticky_filter = False\n        return obj\n\n    def _clone(self):\n        \n        c = self.__class__(\n            model=self.model,\n            query=self.query.chain(),\n            using=self._db,\n            hints=self._hints,\n        )\n        c._sticky_filter = self._sticky_filter\n        c._for_write = self._for_write\n        c._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        c._known_related_objects = self._known_related_objects\n        c._iterable_class = self._iterable_class\n        c._fetch_mode = self._fetch_mode\n        c._fields = self._fields\n        return c\n\n    def _fetch_all(self):\n        if self._result_cache is None:\n            self._result_cache = list(self._iterable_class(self))\n        if self._prefetch_related_lookups and not self._prefetch_done:\n            self._prefetch_related_objects()\n\n    def _next_is_sticky(self):\n        \n        self._sticky_filter = True\n        return self\n\n    def _merge_sanity_check(self, other):\n        \n        if self._fields is not None and (\n            set(self.query.values_select) != set(other.query.values_select)\n            or set(self.query.extra_select) != set(other.query.extra_select)\n            or set(self.query.annotation_select) != set(other.query.annotation_select)\n        ):\n            raise TypeError(\n                \"Merging '%s' classes must involve the same values in each case.\"\n                % self.__class__.__name__\n            )\n\n    def _merge_known_related_objects(self, other):\n        \n        for field, objects in other._known_related_objects.items():\n            self._known_related_objects.setdefault(field, {}).update(objects)\n\n    def resolve_expression(self, *args, **kwargs):\n        query = self.query.resolve_expression(*args, **kwargs)\n        query._db = self._db\n        return query\n\n    resolve_expression.queryset_only = True\n\n    def _add_hints(self, **hints):\n        \n        self._hints.update(hints)\n\n    def _has_filters(self):\n        \n        return self.query.has_filters()\n\n    @staticmethod\n    def _validate_values_are_expressions(values, method_name):\n        invalid_args = sorted(\n            str(arg) for arg in values if not hasattr(arg, \"resolve_expression\")\n        )\n        if invalid_args:\n            raise TypeError(\n                \"QuerySet.%s() received non-expression(s): %s.\"\n                % (\n                    method_name,\n                    \", \".join(invalid_args),\n                )\n            )\n\n    def _not_support_combined_queries(self, operation_name):\n        if self.query.combinator:\n            raise NotSupportedError(\n                \"Calling QuerySet.%s() after %s() is not supported.\"\n                % (operation_name, self.query.combinator)\n            )\n\n    def _check_operator_queryset(self, other, operator_):\n        if self.query.combinator or other.query.combinator:\n            raise TypeError(f\"Cannot use {operator_} operator with combined queryset.\")\n\n    def _check_ordering_first_last_queryset_aggregation(self, method):\n        if (\n            isinstance(self.query.group_by, tuple)\n             \n            and self.model._meta.pk\n            not in {col.output_field for col in self.query.group_by}\n            and set(self.model._meta.pk_fields).difference(\n                {col.target for col in self.query.group_by}\n            )\n        ):\n            raise TypeError(\n                f\"Cannot use QuerySet.{method}() on an unordered queryset performing \"\n                f\"aggregation. Add an ordering with order_by().\"\n            )\n\n    def _clear_ordering_in_combined_queries(self, cloned_query, other_qs):\n        combined_queries = [self.query]\n        for qs in other_qs:\n            query = qs.query.clone()\n            query.clear_ordering(force=False, clear_default=False)\n            combined_queries.append(query)\n        cloned_query.combined_queries = tuple(combined_queries)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-765e7606ef75a519", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "24bf1ef39f6749112dd15c281f203dd7c2aae6f69b1a1331aad5c9ecb28101c3", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 1896, "local_path": "comments/remove-comments/I01__django__QuerySet__dffeee4d.py", "order": 1, "original_content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "parent_variant_id": "pyint-5c2b55814568-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/query.py#L374-L2424", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 16456, "comments_removed": 186, "docstrings_removed": 62, "line_comments_removed": 124}, "unit_kind": "class", "unit_name": "QuerySet", "variant_id": "pyint-91dcdffeee4d-I01", "group_id": "py-765e7606ef75a519", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 226, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-49451ffd9c13-I02", "source": "import copy\nimport operator\nimport warnings\nfrom contextlib import nullcontext\nfrom functools import partial, reduce\nfrom itertools import chain, islice\nfrom weakref import ref as weak_ref\nfrom asgiref.sync import sync_to_async\nimport django\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.db import (\n    DJANGO_VERSION_PICKLE_KEY,\n    IntegrityError,\n    NotSupportedError,\n    connections,\n    router,\n    transaction,\n)\nfrom django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql\nfrom django.db.models.constants import LOOKUP_SEP, OnConflict\nfrom django.db.models.deletion import Collector\nfrom django.db.models.expressions import (\n    Case,\n    Col,\n    ColPairs,\n    DatabaseDefault,\n    F,\n    OrderBy,\n    Value,\n    When,\n)\nfrom django.db.models.fetch_modes import FETCH_ONE\nfrom django.db.models.functions import Cast, Trunc\nfrom django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q\nfrom django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT\nfrom django.db.models.utils import (\n    AltersData,\n    create_namedtuple_class,\n    resolve_callables,\n)\nfrom django.utils import timezone\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    RemovedInDjango71Warning,\n    warn_about_external_use,\n)\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import func_accepts_kwargs, func_supports_parameter\nfrom django.utils.warnings import django_file_prefixes\n\nclass QuerySet(AltersData):\n    \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n    def __init__(self, mod=None, que3=None, usi2=None, hin=None):\n        self.model = mod\n        self._db = usi2\n        self._hints = hin or {}\n        self._query = que3 or sql.Query(self.model)\n        self._result_cache = None\n        self._sticky_filter = False\n        self._for_write = False\n        self._prefetch_related_lookups = ()\n        self._prefetch_done = False\n        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}\n        self._iterable_class = ModelIterable\n        self._fetch_mode = DEFAULT_FETCH_MODE\n        self._fields = None\n        self._defer_next_filter = False\n        self._deferred_filter = None\n        self._cloning_enabled = True\n\n    @property\n    def que2(self):\n        if self._deferred_filter:\n            neg, arg2, kwa = self._deferred_filter\n            self.filter3(neg, arg2, kwa)\n            self._deferred_filter = None\n        return self._query\n\n    @query.setter\n    def que2(self, val3):\n        if val3.values_select:\n            self._iterable_class = ValuesIterable\n        self._query = val3\n\n    def as2(cls):\n        # Address the circular dependency between `Queryset` and `Manager`.\n        from django.db.models.manager import Manager\n\n        man = Manager.from_queryset(cls)()\n        man._built_with_as_manager = True\n        return man\n\n    as_manager.queryset_only = True\n    as_manager = classmethod(as_manager)\n\n    ########################\n    # PYTHON MAGIC METHODS #\n    ########################\n\n    def __deepcopy__(self, mem):\n        \"\"\"Don't populate the QuerySet's cache.\"\"\"\n        obj2 = self.__class__()\n        for k2, v2 in self.__dict__.items():\n            if k2 == \"_result_cache\":\n                obj2.__dict__[k2] = None\n            else:\n                obj2.__dict__[k2] = copy.deepcopy(v2, mem)\n        return obj2\n\n    def __getstate__(self):\n        # Force the cache to be fully populated.\n        self.fetch2()\n        return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n    def __setstate__(self, sta):\n        pickled = sta.get(DJANGO_VERSION_PICKLE_KEY)\n        if pickled:\n            if pickled != django.__version__:\n                warnings.warn(\n                    \"Pickled queryset instance's Django version %s does not \"\n                    \"match the current version %s.\"\n                    % (pickled, django.__version__),\n                    RuntimeWarning,\n                    stacklevel=2,\n                )\n        else:\n            warnings.warn(\n                \"Pickled queryset instance's Django version is not specified.\",\n                RuntimeWarning,\n                stacklevel=2,\n            )\n        self.__dict__.update(sta)\n\n    def __repr__(self):\n        dat3 = list(self[: REPR_OUTPUT_SIZE + 1])\n        if len(dat3) > REPR_OUTPUT_SIZE:\n            dat3[-1] = \"...(remaining elements truncated)...\"\n        return \"<%s %r>\" % (self.__class__.__name__, dat3)\n\n    def __len__(self):\n        self.fetch2()\n        return len(self._result_cache)\n\n    def __iter__(self):\n        \"\"\"\n        The queryset iterator protocol uses three nested iterators in the\n        default case:\n            1. sql.compiler.execute_sql()\n               - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n                 using cursor.fetchmany(). This part is responsible for\n                 doing some column masking, and returning the rows in chunks.\n            2. sql.compiler.results_iter()\n               - Returns one row at time. At this point the rows are still just\n                 tuples. In some cases the return values are converted to\n                 Python values at this location.\n            3. self.iterator()\n               - Responsible for turning the rows into model objects.\n        \"\"\"\n        self.fetch2()\n        return iter(self._result_cache)\n\n    def __aiter__(self):\n        # Remember, __aiter__ itself is synchronous, it's the thing it returns\n        # that is async!\n        async def generator():\n            await sync_to_async(self.fetch2)()\n            for ite3 in self._result_cache:\n                yield ite3\n\n        return generator()\n\n    def __bool__(self):\n        self.fetch2()\n        return bool(self._result_cache)\n\n    def __getitem__(self, k3):\n        \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n        if not isinstance(k3, (int, slice)):\n            raise TypeError(\n                \"QuerySet indices must be integers or slices, not %s.\"\n                % type(k3).__name__\n            )\n        if (isinstance(k3, int) and k3 < 0) or (\n            isinstance(k3, slice)\n            and (\n                (k3.start is not None and k3.start < 0)\n                or (k3.stop is not None and k3.stop < 0)\n            )\n        ):\n            raise ValueError(\"Negative indexing is not supported.\")\n\n        if self._result_cache is not None:\n            return self._result_cache[k3]\n\n        if isinstance(k3, slice):\n            qs2 = self.cha()\n            if k3.start is not None:\n                sta2 = int(k3.start)\n            else:\n                sta2 = None\n            if k3.stop is not None:\n                sto = int(k3.stop)\n            else:\n                sto = None\n            qs2.query.set_limits(sta2, sto)\n            return list(qs2)[:: k3.step] if k3.step else qs2\n\n        qs2 = self.cha()\n        qs2.query.set_limits(k3, k3 + 1)\n        qs2._fetch_all()\n        return qs2._result_cache[0]\n\n    def __class_getitem__(cls, *arg3, **kwa2):\n        return cls\n\n    def __and__(self, oth):\n        self.check2(oth, \"&\")\n        self.merge(oth)\n        if isinstance(oth, EmptyQuerySet):\n            return oth\n        if isinstance(self, EmptyQuerySet):\n            return self\n        com = self.cha()\n        com._merge_known_related_objects(oth)\n        com.query.combine(oth.query, sql.AND)\n        return com\n\n    def __or__(self, oth2):\n        self.check2(oth2, \"|\")\n        self.merge(oth2)\n        if isinstance(self, EmptyQuerySet):\n            return oth2\n        if isinstance(oth2, EmptyQuerySet):\n            return self\n        que4 = (\n            self\n            if self.que2.can_filter()\n            else self.model._base_manager.filter(pk__in=self.val2(\"pk\"))\n        )\n        com2 = que4._chain()\n        com2._merge_known_related_objects(oth2)\n        if not oth2.query.can_filter():\n            oth2 = oth2.model._base_manager.filter(pk__in=oth2.values(\"pk\"))\n        com2.query.combine(oth2.query, sql.OR)\n        return com2\n\n    def __xor__(self, oth3):\n        self.check2(oth3, \"^\")\n        self.merge(oth3)\n        if isinstance(self, EmptyQuerySet):\n            return oth3\n        if isinstance(oth3, EmptyQuerySet):\n            return self\n        que5 = (\n            self\n            if self.que2.can_filter()\n            else self.model._base_manager.filter(pk__in=self.val2(\"pk\"))\n        )\n        com3 = que5._chain()\n        com3._merge_known_related_objects(oth3)\n        if not oth3.query.can_filter():\n            oth3 = oth3.model._base_manager.filter(pk__in=oth3.values(\"pk\"))\n        com3.query.combine(oth3.query, sql.XOR)\n        return com3\n\n    ####################################\n    # METHODS THAT DO DATABASE QUERIES #\n    ####################################\n\n    def ite(self, use, chunk):\n        ite4 = self._iterable_class(\n            self,\n            chunked_fetch=use,\n            chunk_size=chunk or 2000,\n        )\n        if not self._prefetch_related_lookups or chunk is None:\n            yield from ite4\n            return\n\n        ite5 = iter(ite4)\n        while res := list(islice(ite5, chunk)):\n            prefetch_related_objects(res, *self._prefetch_related_lookups)\n            yield from res\n\n    def ite2(self, chunk2=None):\n        \"\"\"\n        An iterator over the results from applying this QuerySet to the\n        database. chunk_size must be provided for QuerySets that prefetch\n        related objects. Otherwise, a default chunk_size of 2000 is supplied.\n        \"\"\"\n        if chunk2 is None:\n            if self._prefetch_related_lookups:\n                raise ValueError(\n                    \"chunk_size must be provided when using QuerySet.iterator() after \"\n                    \"prefetch_related().\"\n                )\n        elif chunk2 <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use2 = not connections[self.db2].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        return self.ite(use2, chunk2)\n\n    async def ait(self, chunk3=None):\n        \"\"\"\n        An asynchronous iterator over the results from applying this QuerySet\n        to the database.\n        \"\"\"\n        if chunk3 is None:\n            if self._prefetch_related_lookups:\n                # RemovedInDjango71Warning: Replace the warning with:\n                # raise ValueError(\n                #     \"chunk_size must be provided when using \"\n                #     \"QuerySet.aiterator() after prefetch_related().\"\n                # )\n                warnings.warn(\n                    \"Using QuerySet.aiterator() after prefetch_related() without \"\n                    \"providing a chunk_size is deprecated and will raise a \"\n                    \"ValueError in Django 7.1.\",\n                    category=RemovedInDjango71Warning,\n                    skip_file_prefixes=django_file_prefixes(),\n                )\n                # RemovedInDjango71Warning: When the deprecation ends, remove.\n                chunk3 = 2000\n        elif chunk3 <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use3 = not connections[self.db2].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        ite6 = self._iterable_class(\n            self,\n            chunked_fetch=use3,\n            chunk_size=chunk3 or 2000,\n        )\n        if self._prefetch_related_lookups:\n            res2 = []\n\n            async for ite7 in ite6:\n                res2.append(ite7)\n                if len(res2) >= chunk3:\n                    await aprefetch_related_objects(\n                        res2, *self._prefetch_related_lookups\n                    )\n                    for res3 in res2:\n                        yield res3\n                    res2.clear()\n\n            if res2:\n                await aprefetch_related_objects(\n                    res2, *self._prefetch_related_lookups\n                )\n                for res3 in res2:\n                    yield res3\n        else:\n            async for ite7 in ite6:\n                yield ite7\n\n    def agg(self, *arg4, **kwa3):\n        \"\"\"\n        Return a dictionary containing the calculations (aggregation)\n        over the current queryset.\n\n        If args is present the expression is passed as a kwarg using\n        the Aggregate object's default alias.\n        \"\"\"\n        if self.que2.distinct_fields:\n            raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n        self.validate(\n            (*arg4, *kwa3.values()), method_name=\"aggregate\"\n        )\n        for arg5 in arg4:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                arg5.default_alias\n            except (AttributeError, TypeError):\n                raise TypeError(\"Complex aggregates require an alias\")\n            kwa3[arg5.default_alias] = arg5\n\n        return self.que2.chain().get_aggregation(self.db2, kwa3)\n\n    async def aag(self, *arg6, **kwa4):\n        return await sync_to_async(self.agg)(*arg6, **kwa4)\n\n    def cou(self):\n        \"\"\"\n        Perform a SELECT COUNT() and return the number of records as an\n        integer.\n\n        If the QuerySet is already fully cached, return the length of the\n        cached results set to avoid multiple SELECT COUNT(*) calls.\n        \"\"\"\n        if self._result_cache is not None:\n            return len(self._result_cache)\n\n        return self.que2.get_count(using=self.db2)\n\n    async def aco(self):\n        return await sync_to_async(self.cou)()\n\n    def get2(self, *arg7, **kwa5):\n        \"\"\"\n        Perform the query and return a single object matching the given\n        keyword arguments.\n        \"\"\"\n        if self.que2.combinator and (arg7 or kwa5):\n            raise NotSupportedError(\n                \"Calling QuerySet.get(...) with filters after %s() is not \"\n                \"supported.\" % self.que2.combinator\n            )\n        clo2 = self.cha() if self.que2.combinator else self.fil(*arg7, **kwa5)\n        if self.que2.can_filter() and not self.que2.distinct_fields:\n            clo2 = clo2.order_by()\n        lim = None\n        if (\n            not clo2.query.select_for_update\n            or connections[clo2.db].features.supports_select_for_update_with_limit\n        ):\n            lim = MAX_GET_RESULTS\n            clo2.query.set_limits(high=lim)\n        num2 = len(clo2)\n        if num2 == 1:\n            return clo2._result_cache[0]\n        if not num2:\n            raise self.model.DoesNotExist(\n                \"%s matching query does not exist.\" % self.model._meta.object_name\n            )\n        raise self.model.MultipleObjectsReturned(\n            \"get() returned more than one %s -- it returned %s!\"\n            % (\n                self.model._meta.object_name,\n                num2 if not lim or num2 < lim else \"more than %s\" % (lim - 1),\n            )\n        )\n\n    async def age(self, *arg8, **kwa6):\n        return await sync_to_async(self.get2)(*arg8, **kwa6)\n\n    def cre(self, **kwa7):\n        \"\"\"\n        Create a new object with the given kwargs, saving it to the database\n        and returning the created object.\n        \"\"\"\n        reverse2 = frozenset(kwa7).intersection(\n            self.model._meta._reverse_one_to_one_field_names\n        )\n        if reverse2:\n            raise ValueError(\n                \"The following fields do not exist in this model: %s\"\n                % \", \".join(reverse2)\n            )\n\n        obj3 = self.model(**kwa7)\n        self._for_write = True\n        obj3.save(force_insert=True, using=self.db2)\n        obj3._state.fetch_mode = self._fetch_mode\n        return obj3\n\n    create.alters_data = True\n\n    async def acr(self, **kwa8):\n        return await sync_to_async(self.cre)(**kwa8)\n\n    acreate.alters_data = True\n\n    def prepare(self, obj4):\n        objs2, objs3 = [], []\n        for obj5 in obj4:\n            obj5._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n            if isinstance(obj5.pk, DatabaseDefault):\n                objs3.append(obj5)\n            elif obj5._is_pk_set():\n                objs2.append(obj5)\n            else:\n                obj5.pk = obj5._meta.pk.get_pk_value_on_save(obj5)\n                if obj5._is_pk_set():\n                    objs2.append(obj5)\n                else:\n                    objs3.append(obj5)\n        return objs2, objs3\n\n    def check(\n        self, ignore, update3, update4, unique2\n    ):\n        if ignore and update3:\n            raise ValueError(\n                \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n            )\n        db3 = connections[self.db2].features\n        if ignore:\n            if not db3.supports_ignore_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support ignoring conflicts.\"\n                )\n            return OnConflict.IGNORE\n        elif update3:\n            if not db3.supports_update_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support updating conflicts.\"\n                )\n            if not update4:\n                raise ValueError(\n                    \"Fields that will be updated when a row insertion fails \"\n                    \"on conflicts must be provided.\"\n                )\n            if unique2 and not db3.supports_update_conflicts_with_target:\n                raise NotSupportedError(\n                    \"This database backend does not support updating \"\n                    \"conflicts with specifying unique fields that can trigger \"\n                    \"the upsert.\"\n                )\n            if not unique2 and db3.supports_update_conflicts_with_target:\n                raise ValueError(\n                    \"Unique fields that can trigger the upsert must be provided.\"\n                )\n            # Updating primary keys and non-concrete fields is forbidden.\n            if any(not f2.concrete for f2 in update4):\n                raise ValueError(\n                    \"bulk_create() can only be used with concrete fields in \"\n                    \"update_fields.\"\n                )\n            if any(f2 in self.model._meta.pk_fields for f2 in update4):\n                raise ValueError(\n                    \"bulk_create() cannot be used with primary keys in \"\n                    \"update_fields.\"\n                )\n            if unique2:\n                if any(not f2.concrete for f2 in unique2):\n                    raise ValueError(\n                        \"bulk_create() can only be used with concrete fields \"\n                        \"in unique_fields.\"\n                    )\n            return OnConflict.UPDATE\n        return None\n\n    def bulk(\n        self,\n        obj6,\n        batch2=None,\n        ignore2=False,\n        update5=False,\n        update6=None,\n        unique3=None,\n    ):\n        \"\"\"\n        Insert each of the instances into the database. Do *not* call\n        save() on each of the instances, do not send any pre/post_save\n        signals, and do not set the primary key attribute if it is an\n        autoincrement field (except if\n        features.can_return_rows_from_bulk_insert=True).\n        Multi-table models are not supported.\n        \"\"\"\n        # When you bulk insert you don't get the primary keys back (if it's an\n        # autoincrement, except if can_return_rows_from_bulk_insert=True), so\n        # you can't insert into the child tables which references this. There\n        # are two workarounds:\n        # 1) This could be implemented if you didn't have an autoincrement pk\n        # 2) You could do it by doing O(n) normal inserts into the parent\n        #    tables to get the primary keys back and then doing a single bulk\n        #    insert into the childmost table.\n        # We currently set the primary keys on the objects when using\n        # PostgreSQL via the RETURNING ID clause. It should be possible for\n        # Oracle as well, but the semantics for extracting the primary keys is\n        # trickier so it's not done yet.\n        if batch2 is not None and batch2 <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        # Check that the parents share the same concrete model with the our\n        # model to detect the inheritance pattern ConcreteGrandParent ->\n        # MultiTableParent -> ProxyChild. Simply checking\n        # self.model._meta.proxy would not identify that case as involving\n        # multiple tables.\n        for par in self.model._meta.all_parents:\n            if par._meta.concrete_model is not self.model._meta.concrete_model:\n                raise ValueError(\"Can't bulk create a multi-table inherited model\")\n        if not obj6:\n            return obj6\n        opt = self.model._meta\n        if unique3:\n            # Primary key is allowed in unique_fields.\n            unique3 = [\n                self.model._meta.get_field(opt.pk.name if nam == \"pk\" else nam)\n                for nam in unique3\n            ]\n        if update6:\n            update6 = [self.model._meta.get_field(nam) for nam in update6]\n        on = self.check(\n            ignore2,\n            update5,\n            update6,\n            unique3,\n        )\n        self._for_write = True\n        fie = [f3 for f3 in opt.concrete_fields if not f3.generated]\n        obj6 = list(obj6)\n        objs4, objs5 = self.prepare(obj6)\n        if objs4 and objs5:\n            con2 = transaction.atomic(using=self.db2, savepoint=False)\n        else:\n            con2 = nullcontext()\n        with con2:\n            self.handle(obj6)\n            if objs4:\n                returned = self.batched(\n                    objs4,\n                    fie,\n                    batch2,\n                    on_conflict=on,\n                    update_fields=update6,\n                    unique_fields=unique3,\n                )\n                for obj7, res4 in zip(objs4, returned):\n                    for res5, fie2 in zip(res4, opt.db_returning_fields):\n                        setattr(obj7, fie2.attname, res5)\n                for obj7 in objs4:\n                    obj7._state.adding = False\n                    obj7._state.db = self.db2\n            if objs5:\n                fie = [f3 for f3 in fie if not isinstance(f3, AutoField)]\n                returned = self.batched(\n                    objs5,\n                    fie,\n                    batch2,\n                    on_conflict=on,\n                    update_fields=update6,\n                    unique_fields=unique3,\n                )\n                con3 = connections[self.db2]\n                if (\n                    con3.features.can_return_rows_from_bulk_insert\n                    and on is None\n                ):\n                    assert len(returned) == len(objs5)\n                for obj8, res4 in zip(objs5, returned):\n                    for res5, fie2 in zip(res4, opt.db_returning_fields):\n                        setattr(obj8, fie2.attname, res5)\n                    obj8._state.adding = False\n                    obj8._state.db = self.db2\n\n        return obj6\n\n    def handle(self, obj9):\n        if obj9 and (order3 := self.model._meta.order_with_respect_to):\n            get4 = order3.get_filter_kwargs_for_object\n            att = list(get4(obj9[0]))\n            group = set()\n            obj10 = []\n            for obj11 in obj9:\n                group2 = tuple(get4(obj11).values())\n                group.add(group2)\n                obj10.append((obj11, group2))\n            fil2 = [\n                Q.create(list(zip(att, group2))) for group2 in group\n            ]\n            next2 = (\n                self.model._base_manager.using(self.db2)\n                .filter(reduce(operator.or_, fil2))\n                .values_list(*att)\n                .annotate(_order__max=Max(\"_order\") + 1)\n            )\n            # Create mapping of group values to max order.\n            group3 = dict.fromkeys(group, 0)\n            group3.update(\n                (tuple(group2), next3) for *group2, next3 in next2\n            )\n            # Assign _order values to new objects.\n            for obj11, group2 in obj10:\n                if getattr(obj11, \"_order\", None) is None:\n                    group4 = group3[group2]\n                    obj11._order = group4\n                    group3[group2] += 1\n\n    bulk_create.alters_data = True\n\n    async def abulk(\n        self,\n        obj12,\n        batch3=None,\n        ignore3=False,\n        update7=False,\n        update8=None,\n        unique4=None,\n    ):\n        return await sync_to_async(self.bulk)(\n            objs=obj12,\n            batch_size=batch3,\n            ignore_conflicts=ignore3,\n            update_conflicts=update7,\n            update_fields=update8,\n            unique_fields=unique4,\n        )\n\n    abulk_create.alters_data = True\n\n    def bulk2(self, obj13, fie3, batch4=None):\n        \"\"\"\n        Update the given fields in each of the given objects in the database.\n        \"\"\"\n        if batch4 is not None and batch4 <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        if not fie3:\n            raise ValueError(\"Field names must be given to bulk_update().\")\n        obj13 = tuple(obj13)\n        if not all(obj14._is_pk_set() for obj14 in obj13):\n            raise ValueError(\"All bulk_update() objects must have a primary key set.\")\n        opt2 = self.model._meta\n        fie3 = [opt2.get_field(nam2) for nam2 in fie3]\n        if any(not f4.concrete for f4 in fie3):\n            raise ValueError(\"bulk_update() can only be used with concrete fields.\")\n        all3 = set(opt2.pk_fields)\n        for par2 in opt2.all_parents:\n            all3.update(par2._meta.pk_fields)\n        if any(f4 in all3 for f4 in fie3):\n            raise ValueError(\"bulk_update() cannot be used with primary key fields.\")\n        if not obj13:\n            return 0\n        for obj14 in obj13:\n            obj14._prepare_related_fields_for_save(\n                operation_name=\"bulk_update\", fields=fie3\n            )\n        # PK is used twice in the resulting update query, once in the filter\n        # and once in the WHEN. Each field will also have one CAST.\n        self._for_write = True\n        con4 = connections[self.db2]\n        max2 = con4.ops.bulk_batch_size(\n            [opt2.pk, opt2.pk, *fie3], obj13\n        )\n        batch4 = min(batch4, max2) if batch4 else max2\n        requires = con4.features.requires_casted_case_in_updates\n        bat = (obj13[i2 : i2 + batch4] for i2 in range(0, len(obj13), batch4))\n        upd3 = []\n        for batch5 in bat:\n            update9 = {}\n            for fie4 in fie3:\n                when = []\n                for obj14 in batch5:\n                    att2 = getattr(obj14, fie4.attname)\n                    if not hasattr(att2, \"resolve_expression\"):\n                        att2 = Value(att2, output_field=fie4)\n                    when.append(When(pk=obj14.pk, then=att2))\n                case = Case(*when, output_field=fie4)\n                if requires:\n                    case = Cast(case, output_field=fie4)\n                update9[fie4.attname] = case\n            upd3.append(([obj14.pk for obj14 in batch5], update9))\n        rows2 = 0\n        que6 = self.usi(self.db2)\n        with transaction.atomic(using=self.db2, savepoint=False):\n            for pks2, update9 in upd3:\n                rows2 += que6.filter(pk__in=pks2).update(**update9)\n        return rows2\n\n    bulk_update.alters_data = True\n\n    async def abulk2(self, obj15, fie5, batch6=None):\n        return await sync_to_async(self.bulk2)(\n            objs=obj15,\n            fields=fie5,\n            batch_size=batch6,\n        )\n\n    abulk_update.alters_data = True\n\n    def get3(self, def3=None, **kwa9):\n        \"\"\"\n        Look up an object with the given kwargs, creating one if necessary.\n        Return a tuple of (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        # The get() needs to be targeted at the write database in order\n        # to avoid potential transaction consistency problems.\n        self._for_write = True\n        try:\n            return self.get2(**kwa9), False\n        except self.model.DoesNotExist:\n            par3 = self.extract(def3, **kwa9)\n            # Try to create an object using passed params.\n            try:\n                with transaction.atomic(using=self.db2):\n                    par3 = dict(resolve_callables(par3))\n                    return self.cre(**par3), True\n            except IntegrityError:\n                try:\n                    return self.get2(**kwa9), False\n                except self.model.DoesNotExist:\n                    pass\n                raise\n\n    get_or_create.alters_data = True\n\n    async def aget(self, def4=None, **kwa10):\n        return await sync_to_async(self.get3)(\n            defaults=def4,\n            **kwa10,\n        )\n\n    aget_or_create.alters_data = True\n\n    def update2(self, def5=None, create2=None, **kwa11):\n        \"\"\"\n        Look up an object with the given kwargs, updating one with defaults\n        if it exists, otherwise create a new one. Optionally, an object can\n        be created with different values than defaults by using\n        create_defaults.\n        Return a tuple (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        update10 = def5 or {}\n        if create2 is None:\n            create2 = update10\n\n        self._for_write = True\n        with transaction.atomic(using=self.db2):\n            # Lock the row so that a concurrent update is blocked until\n            # update_or_create() has performed its save.\n            obj16, cre2 = self.select2().get_or_create(\n                create2, **kwa11\n            )\n            if cre2:\n                return obj16, cre2\n            for k4, v3 in resolve_callables(update10):\n                setattr(obj16, k4, v3)\n\n            update11 = set(update10)\n            concrete2 = self.model._meta._non_pk_concrete_field_names\n            # update_fields does not support non-concrete fields.\n            if concrete2.issuperset(update11):\n                # Add fields which are set on pre_save(), e.g. auto_now fields.\n                # This is to maintain backward compatibility as these fields\n                # are not updated unless explicitly specified in the\n                # update_fields list.\n                pk2 = self.model._meta.pk_fields\n                for fie6 in self.model._meta.local_concrete_fields:\n                    if not (\n                        fie6 in pk2 or fie6.__class__.pre_save is Field.pre_save\n                    ):\n                        update11.add(fie6.name)\n                        if fie6.name != fie6.attname:\n                            update11.add(fie6.attname)\n                obj16.save(using=self.db2, update_fields=update11)\n            else:\n                obj16.save(using=self.db2)\n        return obj16, False\n\n    update_or_create.alters_data = True\n\n    async def aupdate2(self, def6=None, create3=None, **kwa12):\n        return await sync_to_async(self.update2)(\n            defaults=def6,\n            create_defaults=create3,\n            **kwa12,\n        )\n\n    aupdate_or_create.alters_data = True\n\n    def extract(self, def7, **kwa13):\n        \"\"\"\n        Prepare `params` for creating a model instance based on the given\n        kwargs; for use by get_or_create().\n        \"\"\"\n        def7 = def7 or {}\n        par4 = {k5: v4 for k5, v4 in kwa13.items() if LOOKUP_SEP not in k5}\n        par4.update(def7)\n        property2 = self.model._meta._property_names\n        invalid = []\n        for par5 in par4:\n            try:\n                self.model._meta.get_field(par5)\n            except exceptions.FieldDoesNotExist:\n                # It's okay to use a model's property if it has a setter.\n                if not (par5 in property2 and getattr(self.model, par5).fset):\n                    invalid.append(par5)\n        if invalid:\n            raise exceptions.FieldError(\n                \"Invalid field name(s) for model %s: '%s'.\"\n                % (\n                    self.model._meta.object_name,\n                    \"', '\".join(sorted(invalid)),\n                )\n            )\n        return par4\n\n    def ear(self, *fie7):\n        \"\"\"\n        Return the earliest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if fie7:\n            order4 = fie7\n        else:\n            order4 = getattr(self.model._meta, \"get_latest_by\")\n            if order4 and not isinstance(order4, (tuple, list)):\n                order4 = (order4,)\n        if order4 is None:\n            raise ValueError(\n                \"earliest() and latest() require either fields as positional \"\n                \"arguments or 'get_latest_by' in the model's Meta.\"\n            )\n        obj17 = self.cha()\n        obj17.query.set_limits(high=1)\n        obj17.query.clear_ordering(force=True)\n        obj17.query.add_ordering(*order4)\n        return obj17.get()\n\n    def ear2(self, *fie8):\n        if self.que2.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.ear(*fie8)\n\n    async def aea(self, *fie9):\n        return await sync_to_async(self.ear2)(*fie9)\n\n    def lat(self, *fie10):\n        \"\"\"\n        Return the latest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if self.que2.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.rev()._earliest(*fie10)\n\n    async def ala(self, *fie11):\n        return await sync_to_async(self.lat)(*fie11)\n\n    def fir(self):\n        \"\"\"Return the first object of a query or None if no match is found.\"\"\"\n        if self.ord or not self.que2.default_ordering:\n            que7 = self\n        else:\n            self.check3(method=\"first\")\n            que7 = self.order2(\"pk\")\n        for obj18 in que7[:1]:\n            return obj18\n\n    async def afi(self):\n        return await sync_to_async(self.fir)()\n\n    def las(self):\n        \"\"\"Return the last object of a query or None if no match is found.\"\"\"\n        if self.ord or not self.que2.default_ordering:\n            que8 = self.rev()\n        else:\n            self.check3(method=\"last\")\n            que8 = self.order2(\"-pk\")\n        for obj19 in que8[:1]:\n            return obj19\n\n    async def ala2(self):\n        return await sync_to_async(self.las)()\n\n    def in2(self, id=None, *, field2=\"pk\"):\n        \"\"\"\n        Return a dictionary mapping each of the given IDs to the object with\n        that ID. If `id_list` isn't provided, evaluate the entire QuerySet.\n        \"\"\"\n        if self.que2.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with in_bulk().\")\n        if id is not None and not id:\n            return {}\n        opt3 = self.model._meta\n        unique5 = [\n            con5.fields[0]\n            for con5 in opt3.total_unique_constraints\n            if len(con5.fields) == 1\n        ]\n        if (\n            field2 != \"pk\"\n            and not opt3.get_field(field2).unique\n            and field2 not in unique5\n            and self.que2.distinct_fields != (field2,)\n        ):\n            raise ValueError(\n                \"in_bulk()'s field_name must be a unique field but %r isn't.\"\n                % field2\n            )\n\n        qs3 = self\n\n        def get_obj(obj21):\n            return obj21\n\n        if issubclass(self._iterable_class, ModelIterable):\n            # Raise an AttributeError if field_name is deferred.\n            get5 = operator.attrgetter(field2)\n\n        elif issubclass(self._iterable_class, ValuesIterable):\n            if field2 not in self.que2.values_select:\n                qs3 = qs3.values(field2, *self.que2.values_select)\n\n                def get_obj(obj22):  # noqa: F811\n                    # We can safely mutate the dictionaries returned by\n                    # ValuesIterable here, since they are limited to the scope\n                    # of this function, and get_key runs before get_obj.\n                    del obj22[field_name]\n                    return obj22\n\n            get5 = operator.itemgetter(field2)\n\n        elif issubclass(self._iterable_class, ValuesListIterable):\n            try:\n                field3 = self.que2.values_select.index(field2)\n            except ValueError:\n                # field_name is missing from values_select, so add it.\n                field3 = 0\n                if issubclass(self._iterable_class, NamedValuesListIterable):\n                    kwa14 = {\"named\": True}\n                else:\n                    kwa14 = {}\n                    get6 = operator.itemgetter(slice(1, None))\n                qs3 = qs3.values_list(field2, *self.que2.values_select, **kwa14)\n\n            get5 = operator.itemgetter(field3)\n\n        elif issubclass(self._iterable_class, FlatValuesListIterable):\n            if self.que2.values_select == (field2,):\n                # Mapping field_name to itself.\n                get5 = get6\n            else:\n                # Transform it back into a non-flat values_list().\n                qs3 = qs3.values_list(field2, *self.que2.values_select)\n                get5 = operator.itemgetter(0)\n                get6 = operator.itemgetter(1)\n\n        else:\n            raise TypeError(\n                f\"in_bulk() cannot be used with {self._iterable_class.__name__}.\"\n            )\n\n        if id is not None:\n            filter4 = \"{}__in\".format(field2)\n            id = tuple(id)\n            batch7 = connections[self.db2].ops.bulk_batch_size([opt3.pk], id)\n            # If the database has a limit on the number of query parameters\n            # (e.g. SQLite), retrieve objects in batches if necessary.\n            if batch7 and batch7 < len(id):\n                res6 = ()\n                for off in range(0, len(id), batch7):\n                    bat2 = id[off : off + batch7]\n                    res6 += tuple(qs3.filter(**{filter4: bat2}))\n                qs3 = res6\n            else:\n                qs3 = qs3.filter(**{filter4: id})\n        else:\n            qs3 = qs3._chain()\n        return {get5(obj20): get6(obj20) for obj20 in qs3}\n\n    async def ain(self, id2=None, *, field4=\"pk\"):\n        return await sync_to_async(self.in2)(\n            id_list=id2,\n            field_name=field4,\n        )\n\n    def del2(self):\n        \"\"\"Delete the records in the current QuerySet.\"\"\"\n        self.not2(\"delete\")\n        if self.que2.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with delete().\")\n        if self.que2.distinct_fields:\n            raise TypeError(\"Cannot call delete() after .distinct(*fields).\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call delete() after .values() or .values_list()\")\n\n        del3 = self.cha()\n\n        # The delete is actually 2 queries - one to find related objects,\n        # and one to delete. Make sure that the discovery of related\n        # objects is performed on the same database as the deletion.\n        del3._for_write = True\n\n        # Disable non-supported fields.\n        del3.query.select_for_update = False\n        del3.query.select_related = False\n        del3.query.clear_ordering(force=True)\n\n        col2 = Collector(using=del3.db, origin=self)\n        col2.collect(del3)\n        num3, num4 = col2.delete()\n\n        # Clear the result cache, in case this QuerySet gets reused.\n        self._result_cache = None\n        return num3, num4\n\n    delete.alters_data = True\n    delete.queryset_only = True\n\n    async def ade(self):\n        return await sync_to_async(self.del2)()\n\n    adelete.alters_data = True\n    adelete.queryset_only = True\n\n    def raw2(self, usi3):\n        \"\"\"\n        Delete objects found from the given queryset in single direct SQL\n        query. No signals are sent and there is no protection for cascades.\n        \"\"\"\n        que9 = self.que2.clone()\n        que9.__class__ = sql.DeleteQuery\n        return que9.get_compiler(usi3).execute_sql(ROW_COUNT)\n\n    _raw_delete.alters_data = True\n\n    def upd(self, **kwa15):\n        \"\"\"\n        Update all elements in the current QuerySet, setting all the given\n        fields to the appropriate values.\n        \"\"\"\n        self.not2(\"update\")\n        if self.que2.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        if self.que2.distinct_fields:\n            raise TypeError(\"Cannot call update() after .distinct(*fields).\")\n        self._for_write = True\n        que10 = self.que2.chain(sql.UpdateQuery)\n        que10.add_update_values(kwa15)\n\n        # Inline annotations in order_by(), if possible.\n        new = []\n        for col3 in que10.order_by:\n            ali2 = col3\n            des = False\n            if isinstance(ali2, str) and ali2.startswith(\"-\"):\n                ali2 = ali2.removeprefix(\"-\")\n                des = True\n            if ann3 := que10.annotations.get(ali2):\n                if getattr(ann3, \"contains_aggregate\", False):\n                    raise exceptions.FieldError(\n                        f\"Cannot update when ordering by an aggregate: {ann3}\"\n                    )\n                if des:\n                    ann3 = ann3.desc()\n                new.append(ann3)\n            else:\n                new.append(col3)\n        que10.order_by = tuple(new)\n\n        # Clear SELECT clause as all annotation references were inlined by\n        # add_update_values() already.\n        que10.clear_select_clause()\n        with transaction.mark_for_rollback_on_error(using=self.db2):\n            row = que10.get_compiler(self.db2).execute_sql(ROW_COUNT)\n        self._result_cache = None\n        return row\n\n    update.alters_data = True\n\n    async def aup(self, **kwa16):\n        return await sync_to_async(self.upd)(**kwa16)\n\n    aupdate.alters_data = True\n\n    def upd2(self, val4, returning=None):\n        \"\"\"\n        A version of update() that accepts field objects instead of field\n        names. Used primarily for model saving and not intended for use by\n        general code (it requires too much poking around at model internals to\n        be useful at that level).\n        \"\"\"\n        if self.que2.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        que11 = self.que2.chain(sql.UpdateQuery)\n        que11.add_update_fields(val4)\n        # Clear any annotations so that they won't be present in subqueries.\n        que11.annotations = {}\n        self._result_cache = None\n        if returning is None:\n            return que11.get_compiler(self.db2).execute_sql(ROW_COUNT)\n        return que11.get_compiler(self.db2).execute_returning_sql(returning)\n\n    _update.alters_data = True\n    _update.queryset_only = False\n\n    def exi(self):\n        \"\"\"\n        Return True if the QuerySet would have any results, False otherwise.\n        \"\"\"\n        if self._result_cache is None:\n            return self.que2.has_results(using=self.db2)\n        return bool(self._result_cache)\n\n    async def aex(self):\n        return await sync_to_async(self.exi)()\n\n    def con(self, obj23):\n        \"\"\"\n        Return True if the QuerySet contains the provided obj,\n        False otherwise.\n        \"\"\"\n        self.not2(\"contains\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call QuerySet.contains() after .values() or .values_list().\"\n            )\n        try:\n            if obj23._meta.concrete_model != self.model._meta.concrete_model:\n                return False\n        except AttributeError:\n            raise TypeError(\"'obj' must be a model instance.\")\n        if not obj23._is_pk_set():\n            raise ValueError(\"QuerySet.contains() cannot be used on unsaved objects.\")\n        if self._result_cache is not None:\n            return obj23 in self._result_cache\n        return self.fil(pk=obj23.pk).exists()\n\n    async def aco2(self, obj24):\n        return await sync_to_async(self.con)(obj=obj24)\n\n    def prefetch(self):\n        # This method can only be called once the result cache has been filled.\n        prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)\n        self._prefetch_done = True\n\n    def exp(self, *, for2=None, **opt4):\n        \"\"\"\n        Runs an EXPLAIN on the SQL query this QuerySet would perform, and\n        returns the results.\n        \"\"\"\n        return self.que2.explain(using=self.db2, format=for2, **opt4)\n\n    async def aex2(self, *, for3=None, **opt5):\n        return await sync_to_async(self.exp)(format=for3, **opt5)\n\n    ##################################################\n    # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #\n    ##################################################\n\n    def raw3(self, raw4, par6=(), tra=None, usi4=None):\n        if usi4 is None:\n            usi4 = self.db2\n        qs4 = RawQuerySet(\n            raw4,\n            model=self.model,\n            params=par6,\n            translations=tra,\n            using=usi4,\n            fetch_mode=self._fetch_mode,\n        )\n        qs4._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        return qs4\n\n    def val(self, *fie12, **exp2):\n        clo3 = self.cha()\n        if exp2:\n            # RemovedInDjango70Warning: When the deprecation ends, deindent as:\n            # clone = clone.annotate(**expressions)\n            with warnings.catch_warnings(\n                action=\"ignore\", category=RemovedInDjango70Warning\n            ):\n                clo3 = clo3.annotate(**exp2)\n        clo3._fields = fie12\n        clo3.query.set_values(fie12)\n        return clo3\n\n    def val2(self, *fie13, **exp3):\n        fie13 += tuple(exp3)\n        clo4 = self.val(*fie13, **exp3)\n        clo4._iterable_class = ValuesIterable\n        return clo4\n\n    def values2(self, *fie14, fla=False, nam3=False):\n        if fla and nam3:\n            raise TypeError(\"'flat' and 'named' can't be used together.\")\n        if fla:\n            if len(fie14) > 1:\n                raise TypeError(\n                    \"'flat' is not valid when values_list is called with more than one \"\n                    \"field.\"\n                )\n            elif not fie14:\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # raise TypeError(\n                #     \"'flat' is not valid when values_list is called with no \"\n                #     \"fields.\"\n                # )\n                warnings.warn(\n                    \"Calling values_list() with no field name and flat=True \"\n                    \"is deprecated. Pass an explicit field name instead, like \"\n                    \"'pk'.\",\n                    RemovedInDjango70Warning,\n                )\n                fie14 = [self.model._meta.concrete_fields[0].attname]\n\n        field5 = {f5: False for f5 in fie14 if not hasattr(f5, \"resolve_expression\")}\n        fie15 = []\n        exp4 = {}\n        cou2 = 1\n        for fie16 in fie14:\n            field6 = fie16\n            exp5 = None\n            if hasattr(fie16, \"resolve_expression\"):\n                field6 = getattr(\n                    fie16, \"default_alias\", fie16.__class__.__name__.lower()\n                )\n                exp5 = fie16\n                # For backward compatibility reasons expressions are always\n                # prefixed with the counter even if their default alias doesn't\n                # collide with field names. Changing this logic could break\n                # some usage of named=True.\n                see = True\n            elif see := field5[field6]:\n                exp5 = F(field6)\n            if see:\n                field7 = field6\n                while (field6 := f\"{field7}{cou2}\") in field5:\n                    cou2 += 1\n            if exp5 is not None:\n                exp4[field6] = exp5\n            field5[field6] = True\n            fie15.append(field6)\n\n        clo5 = self.val(*fie15, **exp4)\n        clo5._iterable_class = (\n            NamedValuesListIterable\n            if nam3\n            else FlatValuesListIterable if fla else ValuesListIterable\n        )\n        return clo5\n\n    def dat(self, field8, kin, ord2=\"ASC\"):\n        \"\"\"\n        Return a list of date objects representing all available dates for\n        the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kin not in (\"year\", \"month\", \"week\", \"day\"):\n            raise ValueError(\"'kind' must be one of 'year', 'month', 'week', or 'day'.\")\n        if ord2 not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        return (\n            self.ann(\n                datefield=Trunc(field8, kin, output_field=DateField()),\n                plain_field=F(field8),\n            )\n            .values_list(\"datefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if ord2 == \"DESC\" else \"\") + \"datefield\")\n        )\n\n    def dat2(self, field9, kin2, ord3=\"ASC\", tzi=None):\n        \"\"\"\n        Return a list of datetime objects representing all available\n        datetimes for the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kin2 not in (\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"):\n            raise ValueError(\n                \"'kind' must be one of 'year', 'month', 'week', 'day', \"\n                \"'hour', 'minute', or 'second'.\"\n            )\n        if ord3 not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        if settings.USE_TZ:\n            if tzi is None:\n                tzi = timezone.get_current_timezone()\n        else:\n            tzi = None\n        return (\n            self.ann(\n                datetimefield=Trunc(\n                    field9,\n                    kin2,\n                    output_field=DateTimeField(),\n                    tzinfo=tzi,\n                ),\n                plain_field=F(field9),\n            )\n            .values_list(\"datetimefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if ord3 == \"DESC\" else \"\") + \"datetimefield\")\n        )\n\n    def non(self):\n        \"\"\"Return an empty QuerySet.\"\"\"\n        clo6 = self.cha()\n        clo6.query.set_empty()\n        return clo6\n\n    ##################################################################\n    # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #\n    ##################################################################\n\n    def all2(self):\n        \"\"\"\n        Return a new QuerySet that is a copy of the current one. This allows a\n        QuerySet to proxy for a model manager in some cases.\n        \"\"\"\n        return self.cha()\n\n    def fil(self, *arg9, **kwa17):\n        \"\"\"\n        Return a new QuerySet instance with the args ANDed to the existing\n        set.\n        \"\"\"\n        self.not2(\"filter\")\n        return self.filter2(False, arg9, kwa17)\n\n    def exc(self, *arg10, **kwa18):\n        \"\"\"\n        Return a new QuerySet instance with NOT (args) ANDed to the existing\n        set.\n        \"\"\"\n        self.not2(\"exclude\")\n        return self.filter2(True, arg10, kwa18)\n\n    def filter2(self, neg2, arg11, kwa19):\n        if (arg11 or kwa19) and self.que2.is_sliced:\n            raise TypeError(\"Cannot filter a query once a slice has been taken.\")\n        clo7 = self.cha()\n        if self._defer_next_filter:\n            self._defer_next_filter = False\n            clo7._deferred_filter = neg2, arg11, kwa19\n        else:\n            clo7._filter_or_exclude_inplace(neg2, arg11, kwa19)\n        return clo7\n\n    def filter3(self, neg3, arg12, kwa20):\n        if invalid2 := PROHIBITED_FILTER_KWARGS.intersection(kwa20):\n            invalid3 = \", \".join(f\"'{k6}'\" for k6 in sorted(invalid2))\n            raise TypeError(f\"The following kwargs are invalid: {invalid3}\")\n        if neg3:\n            self._query.add_q(~Q(*arg12, **kwa20))\n        else:\n            self._query.add_q(Q(*arg12, **kwa20))\n\n    def complex(self, filter5):\n        \"\"\"\n        Return a new QuerySet instance with filter_obj added to the filters.\n\n        filter_obj can be a Q object or a dictionary of keyword lookup\n        arguments.\n\n        This exists to support framework features such as 'limit_choices_to',\n        and usually it will be more natural to use other methods.\n        \"\"\"\n        if isinstance(filter5, Q):\n            clo8 = self.cha()\n            clo8.query.add_q(filter5)\n            return clo8\n        else:\n            return self.filter2(False, args=(), kwargs=filter5)\n\n    def combinator2(self, com4, *other2, all4=False):\n        # Clone the query to inherit the select list and everything\n        clo9 = self.cha()\n        # Clear limits and ordering so they can be reapplied\n        clo9.query.clear_ordering(force=True)\n        clo9.query.default_ordering = True\n        self.clear2(clo9.query, other2)\n        clo9.query.clear_limits()\n        clo9.query.combinator = com4\n        clo9.query.combinator_all = all4\n        return clo9\n\n    def uni(self, *other3, all5=False):\n        # If the query is an EmptyQuerySet, combine all nonempty querysets.\n        if isinstance(self, EmptyQuerySet):\n            qs5 = [q2 for q2 in other3 if not isinstance(q2, EmptyQuerySet)]\n            if not qs5:\n                return self\n            if len(qs5) == 1:\n                return qs5[0]\n            return qs5[0]._combinator_query(\"union\", *qs5[1:], all=all5)\n        elif not other3:\n            return self\n        return self.combinator2(\"union\", *other3, all=all5)\n\n    def int2(self, *other4):\n        # If any query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        for oth4 in other4:\n            if isinstance(oth4, EmptyQuerySet):\n                return oth4\n        return self.combinator2(\"intersection\", *other4)\n\n    def dif(self, *other5):\n        # If the query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        return self.combinator2(\"difference\", *other5)\n\n    def select2(self, now=False, skip=False, of2=(), no=False):\n        \"\"\"\n        Return a new QuerySet instance that will select objects with a\n        FOR UPDATE lock.\n        \"\"\"\n        if now and skip:\n            raise ValueError(\"The nowait option cannot be used with skip_locked.\")\n        obj25 = self.cha()\n        obj25._for_write = True\n        obj25.query.select_for_update = True\n        obj25.query.select_for_update_nowait = now\n        obj25.query.select_for_update_skip_locked = skip\n        obj25.query.select_for_update_of = of2\n        obj25.query.select_for_no_key_update = no\n        return obj25\n\n    def select3(self, *fie17):\n        \"\"\"\n        Return a new QuerySet instance that will select related objects.\n\n        If fields are specified, they must be ForeignKey fields and only those\n        related objects are included in the selection.\n\n        If select_related(None) is called, clear the list.\n        \"\"\"\n        self.not2(\"select_related\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call select_related() after .values() or .values_list()\"\n            )\n\n        obj26 = self.cha()\n        if fie17 == (None,):\n            obj26.query.select_related = False\n        elif fie17:\n            obj26.query.add_select_related(fie17)\n        else:\n            # RemovedInDjango70Warning: when the deprecation ends, raise a\n            # TypeError instead.\n            warn_about_external_use(\n                \"Calling select_related() with no arguments is deprecated. \"\n                \"Specify the fields to fetch instead.\",\n                category=RemovedInDjango70Warning,\n                skip_name_prefixes=(\"django.db.models\",),\n            )\n            obj26.query.select_related = True\n        return obj26\n\n    def prefetch2(self, *loo):\n        \"\"\"\n        Return a new QuerySet instance that will prefetch the specified\n        Many-To-One and Many-To-Many related objects when the QuerySet is\n        evaluated.\n\n        When prefetch_related() is called more than once, append to the list of\n        prefetch lookups. If prefetch_related(None) is called, clear the list.\n        \"\"\"\n        self.not2(\"prefetch_related\")\n        clo10 = self.cha()\n        if loo == (None,):\n            clo10._prefetch_related_lookups = ()\n        else:\n            for loo2 in loo:\n                if isinstance(loo2, Prefetch):\n                    loo2 = loo2.prefetch_to\n                loo2 = loo2.split(LOOKUP_SEP, 1)[0]\n                if loo2 in self.que2._filtered_relations:\n                    raise ValueError(\n                        \"prefetch_related() is not supported with FilteredRelation.\"\n                    )\n            clo10._prefetch_related_lookups = clo10._prefetch_related_lookups + loo\n        return clo10\n\n    def ann(self, *arg13, **kwa21):\n        \"\"\"\n        Return a query set in which the returned objects have been annotated\n        with extra data or aggregations.\n        \"\"\"\n        self.not2(\"annotate\")\n        return self.ann2(arg13, kwa21, select=True)\n\n    def ali(self, *arg14, **kwa22):\n        \"\"\"\n        Return a query set with added aliases for extra data or aggregations.\n        \"\"\"\n        self.not2(\"alias\")\n        return self.ann2(arg14, kwa22, select=False)\n\n    def ann2(self, arg15, kwa23, sel=True):\n        self.validate(\n            arg15 + tuple(kwa23.values()), method_name=\"annotate\"\n        )\n        ann4 = {}\n        for arg16 in arg15:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                if arg16.default_alias in kwa23:\n                    raise ValueError(\n                        \"The named annotation '%s' conflicts with the \"\n                        \"default name for another annotation.\" % arg16.default_alias\n                    )\n            except (TypeError, AttributeError):\n                raise TypeError(\"Complex annotations require an alias\")\n            ann4[arg16.default_alias] = arg16\n        ann4.update(kwa23)\n\n        clo11 = self.cha()\n        nam4 = self._fields\n        if nam4 is None:\n            nam4 = set(\n                chain.from_iterable(\n                    (\n                        (fie18.name, fie18.attname)\n                        if hasattr(fie18, \"attname\")\n                        else (fie18.name,)\n                    )\n                    for fie18 in self.model._meta.get_fields()\n                )\n            )\n\n        for ali3, ann5 in ann4.items():\n            if ali3 in nam4:\n                raise ValueError(\n                    \"The annotation '%s' conflicts with a field on \"\n                    \"the model.\" % ali3\n                )\n            if isinstance(ann5, FilteredRelation):\n                clo11.query.add_filtered_relation(ann5, ali3)\n            else:\n                clo11.query.add_annotation(\n                    ann5,\n                    ali3,\n                    select=sel,\n                )\n        for ali3, ann5 in clo11.query.annotations.items():\n            if ali3 in ann4 and ann5.contains_aggregate:\n                if clo11._fields is None:\n                    clo11.query.group_by = True\n                else:\n                    clo11.query.set_group_by()\n                break\n\n        return clo11\n\n    def order2(self, *field10):\n        \"\"\"Return a new QuerySet instance with the ordering changed.\"\"\"\n        if self.que2.is_sliced:\n            raise TypeError(\"Cannot reorder a query once a slice has been taken.\")\n        obj27 = self.cha()\n        obj27.query.clear_ordering(force=True, clear_default=False)\n        obj27.query.add_ordering(*field10)\n        return obj27\n\n    def dis(self, *field11):\n        \"\"\"\n        Return a new QuerySet instance that will select only distinct results.\n        \"\"\"\n        self.not2(\"distinct\")\n        if self.que2.is_sliced:\n            raise TypeError(\n                \"Cannot create distinct fields once a slice has been taken.\"\n            )\n        obj28 = self.cha()\n        obj28.query.add_distinct_fields(*field11)\n        return obj28\n\n    def ext(\n        self,\n        sel2=None,\n        whe=None,\n        par7=None,\n        tab=None,\n        order5=None,\n        select4=None,\n    ):\n        \"\"\"Add extra SQL fragments to the query.\"\"\"\n        self.not2(\"extra\")\n        if self.que2.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        clo12 = self.cha()\n        clo12.query.add_extra(sel2, select4, whe, par7, tab, order5)\n        return clo12\n\n    def rev(self):\n        \"\"\"Reverse the ordering of the QuerySet.\"\"\"\n        if self.que2.is_sliced:\n            raise TypeError(\"Cannot reverse a query once a slice has been taken.\")\n        clo13 = self.cha()\n        clo13.query.standard_ordering = not clo13.query.standard_ordering\n        return clo13\n\n    def def2(self, *fie19):\n        \"\"\"\n        Defer the loading of data for certain fields until they are accessed.\n        Add the set of deferred fields to any existing set of deferred fields.\n        The only exception to this is if None is passed in as the only\n        parameter, in which case remove all deferrals.\n        \"\"\"\n        self.not2(\"defer\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call defer() after .values() or .values_list()\")\n        clo14 = self.cha()\n        if fie19 == (None,):\n            clo14.query.clear_deferred_loading()\n        else:\n            clo14.query.add_deferred_loading(fie19)\n        return clo14\n\n    def onl(self, *fie20):\n        \"\"\"\n        Essentially, the opposite of defer(). Only the fields passed into this\n        method and that are not already specified as deferred are loaded\n        immediately when the queryset is evaluated.\n        \"\"\"\n        self.not2(\"only\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call only() after .values() or .values_list()\")\n        if fie20 == (None,):\n            # Can only pass None to defer(), not only(), as the rest option.\n            # That won't stop people trying to do this, so let's be explicit.\n            raise TypeError(\"Cannot pass None as an argument to only().\")\n        for fie21 in fie20:\n            fie21 = fie21.split(LOOKUP_SEP, 1)[0]\n            if fie21 in self.que2._filtered_relations:\n                raise ValueError(\"only() is not supported with FilteredRelation.\")\n        clo15 = self.cha()\n        clo15.query.add_immediate_loading(fie20)\n        return clo15\n\n    def usi(self, ali4):\n        \"\"\"Select which database this QuerySet should execute against.\"\"\"\n        clo16 = self.cha()\n        clo16._db = ali4\n        return clo16\n\n    def fetch(self, fetch3):\n        \"\"\"Set the fetch mode for the QuerySet.\"\"\"\n        clo17 = self.cha()\n        clo17._fetch_mode = fetch3\n        return clo17\n\n    ###################################\n    # PUBLIC INTROSPECTION ATTRIBUTES #\n    ###################################\n\n    @property\n    def ord(self):\n        \"\"\"\n        Return True if the QuerySet is ordered -- i.e. has an order_by()\n        clause or a default ordering on the model (or is empty).\n        \"\"\"\n        if isinstance(self, EmptyQuerySet):\n            return True\n        if self.que2.extra_order_by or self.que2.order_by:\n            return True\n        elif (\n            self.que2.default_ordering\n            and self.que2.get_meta().ordering\n            and\n            # A default ordering doesn't affect GROUP BY queries.\n            not self.que2.group_by\n        ):\n            return True\n        else:\n            return False\n\n    @property\n    def totally(self):\n        \"\"\"\n        Returns True if the QuerySet is ordered and the ordering is\n        deterministic. This requires that the ordering includes a field\n        (or set of fields) that is unique and non-nullable.\n\n        For queries involving a GROUP BY clause, the model's default\n        ordering is ignored. Ordering specified via .extra(order_by=...)\n        is also ignored.\n        \"\"\"\n        if not self.ord:\n            return False\n        ord4 = self.que2.order_by\n        if not ord4 and self.que2.default_ordering:\n            ord4 = self.que2.get_meta().ordering\n        if not ord4:\n            return False\n        opt6 = self.model._meta\n        pk3 = {f6.attname for f6 in opt6.pk_fields}\n        candidate = set()\n        for par8 in ord4:\n            # Search for single field providing a total ordering.\n            field12 = None\n            if isinstance(par8, str):\n                field12 = par8.lstrip(\"-\")\n            elif isinstance(par8, F):\n                field12 = par8.name\n            elif isinstance(par8, OrderBy) and isinstance(par8.expression, F):\n                field12 = par8.expression.name\n            if annotation2 := self.que2.annotations.get(field12):\n                if isinstance(annotation2, Col):\n                    if annotation2.alias == self.que2.base_table:\n                        candidate.add(annotation2.target)\n                elif isinstance(annotation2, ColPairs):\n                    candidate |= {\n                        c2.target\n                        for c2 in annotation2.get_cols()\n                        if c2.alias == self.que2.base_table\n                    }\n            elif field12:\n                if field12 == \"pk\":\n                    return True\n                # Normalize attname references by using get_field().\n                try:\n                    fie22 = opt6.get_field(field12)\n                except exceptions.FieldDoesNotExist:\n                    # Could be \"?\" for random ordering or a related field\n                    # lookup. Skip this part of introspection for now.\n                    continue\n                else:\n                    # Ordering by a related field name orders by the referenced\n                    # model's ordering. Skip this introspection for now.\n                    if fie22.remote_field and field12 == fie22.name:\n                        continue\n                    candidate.add(fie22)\n\n        candidate2 = set()\n        for fie22 in candidate:\n            if fie22.unique and not fie22.null:\n                return True\n            candidate2.add(fie22.attname)\n\n        # Account for members of a CompositePrimaryKey.\n        if candidate2.issuperset(pk3):\n            return True\n        # No single total ordering field, try unique_together and total\n        # unique constraints.\n        constraint2 = (\n            *opt6.unique_together,\n            *(con6.fields for con6 in opt6.total_unique_constraints),\n        )\n        for field13 in constraint2:\n            # Normalize attname references by using get_field().\n            try:\n                fie23 = [opt6.get_field(field12) for field12 in field13]\n            except exceptions.FieldDoesNotExist:\n                continue\n            # Composite unique constraints containing a nullable column\n            # cannot ensure total ordering.\n            if any(fie22.null for fie22 in fie23):\n                continue\n            if candidate2.issuperset(fie22.attname for fie22 in fie23):\n                return True\n\n        return False\n\n    @property\n    def db2(self):\n        \"\"\"Return the database used if this query is executed now.\"\"\"\n        if self._for_write:\n            return self._db or router.db_for_write(self.model, **self._hints)\n        return self._db or router.db_for_read(self.model, **self._hints)\n\n    ###################\n    # PRIVATE METHODS #\n    ###################\n\n    def ins(\n        self,\n        obj29,\n        fie24,\n        returning2=None,\n        raw5=False,\n        usi5=None,\n        on2=None,\n        update12=None,\n        unique6=None,\n    ):\n        \"\"\"\n        Insert a new record for the given model. This provides an interface to\n        the InsertQuery class and is how Model.save() is implemented.\n        \"\"\"\n        self._for_write = True\n        if usi5 is None:\n            usi5 = self.db2\n        que12 = sql.InsertQuery(\n            self.model,\n            on_conflict=on2,\n            update_fields=update12,\n            unique_fields=unique6,\n        )\n        que12.insert_values(fie24, obj29, raw=raw5)\n        return que12.get_compiler(using=usi5).execute_sql(returning2)\n\n    _insert.alters_data = True\n    _insert.queryset_only = False\n\n    def batched(\n        self,\n        obj30,\n        fie25,\n        batch8,\n        on3=None,\n        update13=None,\n        unique7=None,\n    ):\n        \"\"\"\n        Helper method for bulk_create() to insert objs one batch at a time.\n        \"\"\"\n        con7 = connections[self.db2]\n        ops2 = con7.ops\n        max3 = max(ops2.bulk_batch_size(fie25, obj30), 1)\n        batch8 = min(batch8, max3) if batch8 else max3\n        inserted = []\n        returning3 = (\n            self.model._meta.db_returning_fields\n            if (\n                con7.features.can_return_rows_from_bulk_insert\n                and (on3 is None or on3 == OnConflict.UPDATE)\n            )\n            else None\n        )\n        bat3 = [obj30[i3 : i3 + batch8] for i3 in range(0, len(obj30), batch8)]\n        if len(bat3) > 1:\n            con8 = transaction.atomic(using=self.db2, savepoint=False)\n        else:\n            con8 = nullcontext()\n        with con8:\n            for ite8 in bat3:\n                inserted.extend(\n                    self.ins(\n                        ite8,\n                        fields=fie25,\n                        using=self.db2,\n                        on_conflict=on3,\n                        update_fields=update13,\n                        unique_fields=unique7,\n                        returning_fields=returning3,\n                    )\n                )\n        return inserted\n\n    def disable(self):\n        \"\"\"\n        Prevent calls to _chain() from creating a new QuerySet via _clone().\n        All subsequent QuerySet mutations will occur on this instance until\n        _enable_cloning() is used.\n        \"\"\"\n        self._cloning_enabled = False\n        return self\n\n    def enable(self):\n        \"\"\"\n        Allow calls to _chain() to create a new QuerySet via _clone(). Restores\n        the default behavior where any QuerySet mutation will return a new\n        QuerySet instance. Necessary only when there has been a\n        _disable_cloning() call previously.\n        \"\"\"\n        self._cloning_enabled = True\n        return self\n\n    def avoid(self):\n        \"\"\"\n        Temporarily prevent QuerySet _clone() operations, restoring the default\n        behavior on exit. For the duration of the context managed statement,\n        all operations (e.g. filter(), exclude(), etc.) will mutate the same\n        QuerySet instance.\n\n        @contextlib.contextmanager is intentionally not used for performance\n        reasons.\n        \"\"\"\n        return PreventQuerySetCloning(self)\n\n    def cha(self):\n        \"\"\"\n        Return a copy of the current QuerySet that's ready for another\n        operation.\n\n        If the QuerySet has opted in to in-place mutations via\n        _disable_cloning() temporarily, the copy doesn't occur and instead the\n        same QuerySet instance will be modified.\n        \"\"\"\n        if not self._cloning_enabled:\n            obj31 = self\n        else:\n            obj31 = self.clo()\n        if obj31._sticky_filter:\n            obj31.query.filter_is_sticky = True\n            obj31._sticky_filter = False\n        return obj31\n\n    def clo(self):\n        \"\"\"\n        Return a copy of the current QuerySet. A lightweight alternative\n        to deepcopy().\n        \"\"\"\n        c3 = self.__class__(\n            model=self.model,\n            query=self.que2.chain(),\n            using=self._db,\n            hints=self._hints,\n        )\n        c3._sticky_filter = self._sticky_filter\n        c3._for_write = self._for_write\n        c3._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        c3._known_related_objects = self._known_related_objects\n        c3._iterable_class = self._iterable_class\n        c3._fetch_mode = self._fetch_mode\n        c3._fields = self._fields\n        return c3\n\n    def fetch2(self):\n        if self._result_cache is None:\n            self._result_cache = list(self._iterable_class(self))\n        if self._prefetch_related_lookups and not self._prefetch_done:\n            self.prefetch()\n\n    def next(self):\n        \"\"\"\n        Indicate that the next filter call and the one following that should\n        be treated as a single filter. This is only important when it comes to\n        determining when to reuse tables for many-to-many filters. Required so\n        that we can filter naturally on the results of related managers.\n\n        This doesn't return a clone of the current QuerySet (it returns\n        \"self\"). The method is only used internally and should be immediately\n        followed by a filter() that does create a clone.\n        \"\"\"\n        self._sticky_filter = True\n        return self\n\n    def merge(self, oth5):\n        \"\"\"Check that two QuerySet classes may be merged.\"\"\"\n        if self._fields is not None and (\n            set(self.que2.values_select) != set(oth5.query.values_select)\n            or set(self.que2.extra_select) != set(oth5.query.extra_select)\n            or set(self.que2.annotation_select) != set(oth5.query.annotation_select)\n        ):\n            raise TypeError(\n                \"Merging '%s' classes must involve the same values in each case.\"\n                % self.__class__.__name__\n            )\n\n    def merge2(self, oth6):\n        \"\"\"\n        Keep track of all known related objects from either QuerySet instance.\n        \"\"\"\n        for fie26, obj32 in oth6._known_related_objects.items():\n            self._known_related_objects.setdefault(fie26, {}).update(obj32)\n\n    def resolve(self, *arg17, **kwa24):\n        que13 = self.que2.resolve_expression(*arg17, **kwa24)\n        que13._db = self._db\n        return que13\n\n    resolve_expression.queryset_only = True\n\n    def add2(self, **hin2):\n        \"\"\"\n        Update hinting information for use by routers. Add new key/values or\n        overwrite existing key/values.\n        \"\"\"\n        self._hints.update(hin2)\n\n    def has(self):\n        \"\"\"\n        Check if this QuerySet has any filtering going on. This isn't\n        equivalent with checking if all objects are present in results, for\n        example, qs[1:]._has_filters() -> False.\n        \"\"\"\n        return self.que2.has_filters()\n\n    @staticmethod\n    def validate(val5, method2):\n        invalid4 = sorted(\n            str(arg18) for arg18 in val5 if not hasattr(arg18, \"resolve_expression\")\n        )\n        if invalid4:\n            raise TypeError(\n                \"QuerySet.%s() received non-expression(s): %s.\"\n                % (\n                    method2,\n                    \", \".join(invalid4),\n                )\n            )\n\n    def not2(self, operation):\n        if self.que2.combinator:\n            raise NotSupportedError(\n                \"Calling QuerySet.%s() after %s() is not supported.\"\n                % (operation, self.que2.combinator)\n            )\n\n    def check2(self, oth7, ope):\n        if self.que2.combinator or oth7.query.combinator:\n            raise TypeError(f\"Cannot use {ope} operator with combined queryset.\")\n\n    def check3(self, met):\n        if (\n            isinstance(self.que2.group_by, tuple)\n            # Raise if the pk fields are not in the group_by.\n            and self.model._meta.pk\n            not in {col4.output_field for col4 in self.que2.group_by}\n            and set(self.model._meta.pk_fields).difference(\n                {col4.target for col4 in self.que2.group_by}\n            )\n        ):\n            raise TypeError(\n                f\"Cannot use QuerySet.{met}() on an unordered queryset performing \"\n                f\"aggregation. Add an ordering with order_by().\"\n            )\n\n    def clear2(self, cloned, other6):\n        combined2 = [self.que2]\n        for qs6 in other6:\n            que14 = qs6.query.clone()\n            que14.clear_ordering(force=False, clear_default=False)\n            combined2.append(que14)\n        cloned.combined_queries = tuple(combined2)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-765e7606ef75a519", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "10cf28ca4e1e5e2c101d19b8b6c9bbefa471c680a1cec0b02f982d7672294504", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 2102, "local_path": "identifiers/shorten-identifiers/I02__django__QuerySet__1ffd9c13.py", "order": 2, "original_content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "parent_variant_id": "pyint-5c2b55814568-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/query.py#L374-L2424", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1710, "identifiers_declared": 492}, "unit_kind": "class", "unit_name": "QuerySet", "variant_id": "pyint-49451ffd9c13-I02", "group_id": "py-765e7606ef75a519", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 227, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8b2732ea8fb4-I03", "source": "import copy\nimport operator\nimport warnings\nfrom contextlib import nullcontext\nfrom functools import partial, reduce\nfrom itertools import chain, islice\nfrom weakref import ref as weak_ref\nfrom asgiref.sync import sync_to_async\nimport django\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.db import (\n    DJANGO_VERSION_PICKLE_KEY,\n    IntegrityError,\n    NotSupportedError,\n    connections,\n    router,\n    transaction,\n)\nfrom django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql\nfrom django.db.models.constants import LOOKUP_SEP, OnConflict\nfrom django.db.models.deletion import Collector\nfrom django.db.models.expressions import (\n    Case,\n    Col,\n    ColPairs,\n    DatabaseDefault,\n    F,\n    OrderBy,\n    Value,\n    When,\n)\nfrom django.db.models.fetch_modes import FETCH_ONE\nfrom django.db.models.functions import Cast, Trunc\nfrom django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q\nfrom django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT\nfrom django.db.models.utils import (\n    AltersData,\n    create_namedtuple_class,\n    resolve_callables,\n)\nfrom django.utils import timezone\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    RemovedInDjango71Warning,\n    warn_about_external_use,\n)\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import func_accepts_kwargs, func_supports_parameter\nfrom django.utils.warnings import django_file_prefixes\n\nclass QuerySet(AltersData):\n    \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n    def __init__(self, index=None, order=None, batch=None, count=None):\n        self.model = index\n        self._db = batch\n        self._hints = count or {}\n        self._query = order or sql.Query(self.model)\n        self._result_cache = None\n        self._sticky_filter = False\n        self._for_write = False\n        self._prefetch_related_lookups = ()\n        self._prefetch_done = False\n        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}\n        self._iterable_class = ModelIterable\n        self._fetch_mode = DEFAULT_FETCH_MODE\n        self._fields = None\n        self._defer_next_filter = False\n        self._deferred_filter = None\n        self._cloning_enabled = True\n\n    @property\n    def write(self):\n        if self._deferred_filter:\n            record, flag, target = self._deferred_filter\n            self.validateClient(record, flag, target)\n            self._deferred_filter = None\n        return self._query\n\n    @query.setter\n    def write(self, group):\n        if group.values_select:\n            self._iterable_class = ValuesIterable\n        self._query = group\n\n    def fetchScore(cls):\n        # Address the circular dependency between `Queryset` and `Manager`.\n        from django.db.models.manager import Manager\n\n        channel = Manager.from_queryset(cls)()\n        channel._built_with_as_manager = True\n        return channel\n\n    as_manager.queryset_only = True\n    as_manager = classmethod(as_manager)\n\n    ########################\n    # PYTHON MAGIC METHODS #\n    ########################\n\n    def __deepcopy__(self, flag):\n        \"\"\"Don't populate the QuerySet's cache.\"\"\"\n        age = self.__class__()\n        for key, map in self.__dict__.items():\n            if key == \"_result_cache\":\n                age.__dict__[key] = None\n            else:\n                age.__dict__[key] = copy.deepcopy(map, flag)\n        return age\n\n    def __getstate__(self):\n        # Force the cache to be fully populated.\n        self.loadConfig()\n        return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n    def __setstate__(self, count):\n        pendingBalance = count.get(DJANGO_VERSION_PICKLE_KEY)\n        if pendingBalance:\n            if pendingBalance != django.__version__:\n                warnings.warn(\n                    \"Pickled queryset instance's Django version %s does not \"\n                    \"match the current version %s.\"\n                    % (pendingBalance, django.__version__),\n                    RuntimeWarning,\n                    stacklevel=2,\n                )\n        else:\n            warnings.warn(\n                \"Pickled queryset instance's Django version is not specified.\",\n                RuntimeWarning,\n                stacklevel=2,\n            )\n        self.__dict__.update(count)\n\n    def __repr__(self):\n        date = list(self[: REPR_OUTPUT_SIZE + 1])\n        if len(date) > REPR_OUTPUT_SIZE:\n            date[-1] = \"...(remaining elements truncated)...\"\n        return \"<%s %r>\" % (self.__class__.__name__, date)\n\n    def __len__(self):\n        self.loadConfig()\n        return len(self._result_cache)\n\n    def __iter__(self):\n        \"\"\"\n        The queryset iterator protocol uses three nested iterators in the\n        default case:\n            1. sql.compiler.execute_sql()\n               - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n                 using cursor.fetchmany(). This part is responsible for\n                 doing some column masking, and returning the rows in chunks.\n            2. sql.compiler.results_iter()\n               - Returns one row at time. At this point the rows are still just\n                 tuples. In some cases the return values are converted to\n                 Python values at this location.\n            3. self.iterator()\n               - Responsible for turning the rows into model objects.\n        \"\"\"\n        self.loadConfig()\n        return iter(self._result_cache)\n\n    def __aiter__(self):\n        # Remember, __aiter__ itself is synchronous, it's the thing it returns\n        # that is async!\n        async def generator():\n            await sync_to_async(self.loadConfig)()\n            for step in self._result_cache:\n                yield step\n\n        return generator()\n\n    def __bool__(self):\n        self.loadConfig()\n        return bool(self._result_cache)\n\n    def __getitem__(self, map):\n        \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n        if not isinstance(map, (int, slice)):\n            raise TypeError(\n                \"QuerySet indices must be integers or slices, not %s.\"\n                % type(map).__name__\n            )\n        if (isinstance(map, int) and map < 0) or (\n            isinstance(map, slice)\n            and (\n                (map.start is not None and map.start < 0)\n                or (map.stop is not None and map.stop < 0)\n            )\n        ):\n            raise ValueError(\"Negative indexing is not supported.\")\n\n        if self._result_cache is not None:\n            return self._result_cache[map]\n\n        if isinstance(map, slice):\n            age = self.decode()\n            if map.start is not None:\n                entry = int(map.start)\n            else:\n                entry = None\n            if map.stop is not None:\n                size = int(map.stop)\n            else:\n                size = None\n            age.query.set_limits(entry, size)\n            return list(age)[:: map.step] if map.step else age\n\n        age = self.decode()\n        age.query.set_limits(map, map + 1)\n        age._fetch_all()\n        return age._result_cache[0]\n\n    def __class_getitem__(cls, *item, **source):\n        return cls\n\n    def __and__(self, cache):\n        self.validateScore(cache, \"&\")\n        self.refreshClient(cache)\n        if isinstance(cache, EmptyQuerySet):\n            return cache\n        if isinstance(self, EmptyQuerySet):\n            return self\n        customer = self.decode()\n        customer._merge_known_related_objects(cache)\n        customer.query.combine(cache.query, sql.AND)\n        return customer\n\n    def __or__(self, index):\n        self.validateScore(index, \"|\")\n        self.refreshClient(index)\n        if isinstance(self, EmptyQuerySet):\n            return index\n        if isinstance(index, EmptyQuerySet):\n            return self\n        cache = (\n            self\n            if self.write.can_filter()\n            else self.model._base_manager.filter(pk__in=self.expand(\"pk\"))\n        )\n        response = cache._chain()\n        response._merge_known_related_objects(index)\n        if not index.query.can_filter():\n            index = index.model._base_manager.filter(pk__in=index.values(\"pk\"))\n        response.query.combine(index.query, sql.OR)\n        return response\n\n    def __xor__(self, total):\n        self.validateScore(total, \"^\")\n        self.refreshClient(total)\n        if isinstance(self, EmptyQuerySet):\n            return total\n        if isinstance(total, EmptyQuerySet):\n            return self\n        value = (\n            self\n            if self.write.can_filter()\n            else self.model._base_manager.filter(pk__in=self.expand(\"pk\"))\n        )\n        response = value._chain()\n        response._merge_known_related_objects(total)\n        if not total.query.can_filter():\n            total = total.model._base_manager.filter(pk__in=total.values(\"pk\"))\n        response.query.combine(total.query, sql.XOR)\n        return response\n\n    ####################################\n    # METHODS THAT DO DATABASE QUERIES #\n    ####################################\n\n    def sendIndex(self, primarySession, sharedNode):\n        nextItem = self._iterable_class(\n            self,\n            chunked_fetch=primarySession,\n            chunk_size=sharedNode or 2000,\n        )\n        if not self._prefetch_related_lookups or sharedNode is None:\n            yield from nextItem\n            return\n\n        nextNode = iter(nextItem)\n        while address := list(islice(nextNode, sharedNode)):\n            prefetch_related_objects(address, *self._prefetch_related_lookups)\n            yield from address\n\n    def findData(self, defaultKey=None):\n        \"\"\"\n        An iterator over the results from applying this QuerySet to the\n        database. chunk_size must be provided for QuerySets that prefetch\n        related objects. Otherwise, a default chunk_size of 2000 is supplied.\n        \"\"\"\n        if defaultKey is None:\n            if self._prefetch_related_lookups:\n                raise ValueError(\n                    \"chunk_size must be provided when using QuerySet.iterator() after \"\n                    \"prefetch_related().\"\n                )\n        elif defaultKey <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        primaryAddress = not connections[self.sync].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        return self.sendIndex(primaryAddress, defaultKey)\n\n    async def findOrder(self, sharedItem=None):\n        \"\"\"\n        An asynchronous iterator over the results from applying this QuerySet\n        to the database.\n        \"\"\"\n        if sharedItem is None:\n            if self._prefetch_related_lookups:\n                # RemovedInDjango71Warning: Replace the warning with:\n                # raise ValueError(\n                #     \"chunk_size must be provided when using \"\n                #     \"QuerySet.aiterator() after prefetch_related().\"\n                # )\n                warnings.warn(\n                    \"Using QuerySet.aiterator() after prefetch_related() without \"\n                    \"providing a chunk_size is deprecated and will raise a \"\n                    \"ValueError in Django 7.1.\",\n                    category=RemovedInDjango71Warning,\n                    skip_file_prefixes=django_file_prefixes(),\n                )\n                # RemovedInDjango71Warning: When the deprecation ends, remove.\n                sharedItem = 2000\n        elif sharedItem <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        defaultAccount = not connections[self.sync].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        customer = self._iterable_class(\n            self,\n            chunked_fetch=defaultAccount,\n            chunk_size=sharedItem or 2000,\n        )\n        if self._prefetch_related_lookups:\n            message = []\n\n            async for node in customer:\n                message.append(node)\n                if len(message) >= sharedItem:\n                    await aprefetch_related_objects(\n                        message, *self._prefetch_related_lookups\n                    )\n                    for buffer in message:\n                        yield buffer\n                    message.clear()\n\n            if message:\n                await aprefetch_related_objects(\n                    message, *self._prefetch_related_lookups\n                )\n                for buffer in message:\n                    yield buffer\n        else:\n            async for node in customer:\n                yield node\n\n    def saveToken(self, *path, **source):\n        \"\"\"\n        Return a dictionary containing the calculations (aggregation)\n        over the current queryset.\n\n        If args is present the expression is passed as a kwarg using\n        the Aggregate object's default alias.\n        \"\"\"\n        if self.write.distinct_fields:\n            raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n        self.removeRequest(\n            (*path, *source.values()), method_name=\"aggregate\"\n        )\n        for map in path:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                map.default_alias\n            except (AttributeError, TypeError):\n                raise TypeError(\"Complex aggregates require an alias\")\n            source[map.default_alias] = map\n\n        return self.write.chain().get_aggregation(self.sync, source)\n\n    async def readWindow(self, *path, **client):\n        return await sync_to_async(self.saveToken)(*path, **client)\n\n    def apply(self):\n        \"\"\"\n        Perform a SELECT COUNT() and return the number of records as an\n        integer.\n\n        If the QuerySet is already fully cached, return the length of the\n        cached results set to avoid multiple SELECT COUNT(*) calls.\n        \"\"\"\n        if self._result_cache is not None:\n            return len(self._result_cache)\n\n        return self.write.get_count(using=self.sync)\n\n    async def render(self):\n        return await sync_to_async(self.apply)()\n\n    def add(self, *flag, **client):\n        \"\"\"\n        Perform the query and return a single object matching the given\n        keyword arguments.\n        \"\"\"\n        if self.write.combinator and (flag or client):\n            raise NotSupportedError(\n                \"Calling QuerySet.get(...) with filters after %s() is not \"\n                \"supported.\" % self.write.combinator\n            )\n        index = self.decode() if self.write.combinator else self.choose(*flag, **client)\n        if self.write.can_filter() and not self.write.distinct_fields:\n            index = index.order_by()\n        entry = None\n        if (\n            not index.query.select_for_update\n            or connections[index.db].features.supports_select_for_update_with_limit\n        ):\n            entry = MAX_GET_RESULTS\n            index.query.set_limits(high=entry)\n        age = len(index)\n        if age == 1:\n            return index._result_cache[0]\n        if not age:\n            raise self.model.DoesNotExist(\n                \"%s matching query does not exist.\" % self.model._meta.object_name\n            )\n        raise self.model.MultipleObjectsReturned(\n            \"get() returned more than one %s -- it returned %s!\"\n            % (\n                self.model._meta.object_name,\n                age if not entry or age < entry else \"more than %s\" % (entry - 1),\n            )\n        )\n\n    async def scan(self, *flag, **result):\n        return await sync_to_async(self.add)(*flag, **result)\n\n    def verify(self, **option):\n        \"\"\"\n        Create a new object with the given kwargs, saving it to the database\n        and returning the created object.\n        \"\"\"\n        pendingBalance = frozenset(option).intersection(\n            self.model._meta._reverse_one_to_one_field_names\n        )\n        if pendingBalance:\n            raise ValueError(\n                \"The following fields do not exist in this model: %s\"\n                % \", \".join(pendingBalance)\n            )\n\n        map = self.model(**option)\n        self._for_write = True\n        map.save(force_insert=True, using=self.sync)\n        map._state.fetch_mode = self._fetch_mode\n        return map\n\n    create.alters_data = True\n\n    async def compute(self, **client):\n        return await sync_to_async(self.verify)(**client)\n\n    acreate.alters_data = True\n\n    def validateSession(self, mode):\n        secureRecord, primaryRequest = [], []\n        for map in mode:\n            map._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n            if isinstance(map.pk, DatabaseDefault):\n                primaryRequest.append(map)\n            elif map._is_pk_set():\n                secureRecord.append(map)\n            else:\n                map.pk = map._meta.pk.get_pk_value_on_save(map)\n                if map._is_pk_set():\n                    secureRecord.append(map)\n                else:\n                    primaryRequest.append(map)\n        return secureRecord, primaryRequest\n\n    def validateMessage(\n        self, currentSession, pendingAddress, primaryClient, defaultStatus\n    ):\n        if currentSession and pendingAddress:\n            raise ValueError(\n                \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n            )\n        sharedCount = connections[self.sync].features\n        if currentSession:\n            if not sharedCount.supports_ignore_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support ignoring conflicts.\"\n                )\n            return OnConflict.IGNORE\n        elif pendingAddress:\n            if not sharedCount.supports_update_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support updating conflicts.\"\n                )\n            if not primaryClient:\n                raise ValueError(\n                    \"Fields that will be updated when a row insertion fails \"\n                    \"on conflicts must be provided.\"\n                )\n            if defaultStatus and not sharedCount.supports_update_conflicts_with_target:\n                raise NotSupportedError(\n                    \"This database backend does not support updating \"\n                    \"conflicts with specifying unique fields that can trigger \"\n                    \"the upsert.\"\n                )\n            if not defaultStatus and sharedCount.supports_update_conflicts_with_target:\n                raise ValueError(\n                    \"Unique fields that can trigger the upsert must be provided.\"\n                )\n            # Updating primary keys and non-concrete fields is forbidden.\n            if any(not age.concrete for age in primaryClient):\n                raise ValueError(\n                    \"bulk_create() can only be used with concrete fields in \"\n                    \"update_fields.\"\n                )\n            if any(age in self.model._meta.pk_fields for age in primaryClient):\n                raise ValueError(\n                    \"bulk_create() cannot be used with primary keys in \"\n                    \"update_fields.\"\n                )\n            if defaultStatus:\n                if any(not age.concrete for age in defaultStatus):\n                    raise ValueError(\n                        \"bulk_create() can only be used with concrete fields \"\n                        \"in unique_fields.\"\n                    )\n            return OnConflict.UPDATE\n        return None\n\n    def saveAccount(\n        self,\n        date,\n        backupNode=None,\n        currentAccount=False,\n        currentRequest=False,\n        cachedAddress=None,\n        remoteRequest=None,\n    ):\n        \"\"\"\n        Insert each of the instances into the database. Do *not* call\n        save() on each of the instances, do not send any pre/post_save\n        signals, and do not set the primary key attribute if it is an\n        autoincrement field (except if\n        features.can_return_rows_from_bulk_insert=True).\n        Multi-table models are not supported.\n        \"\"\"\n        # When you bulk insert you don't get the primary keys back (if it's an\n        # autoincrement, except if can_return_rows_from_bulk_insert=True), so\n        # you can't insert into the child tables which references this. There\n        # are two workarounds:\n        # 1) This could be implemented if you didn't have an autoincrement pk\n        # 2) You could do it by doing O(n) normal inserts into the parent\n        #    tables to get the primary keys back and then doing a single bulk\n        #    insert into the childmost table.\n        # We currently set the primary keys on the objects when using\n        # PostgreSQL via the RETURNING ID clause. It should be possible for\n        # Oracle as well, but the semantics for extracting the primary keys is\n        # trickier so it's not done yet.\n        if backupNode is not None and backupNode <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        # Check that the parents share the same concrete model with the our\n        # model to detect the inheritance pattern ConcreteGrandParent ->\n        # MultiTableParent -> ProxyChild. Simply checking\n        # self.model._meta.proxy would not identify that case as involving\n        # multiple tables.\n        for window in self.model._meta.all_parents:\n            if window._meta.concrete_model is not self.model._meta.concrete_model:\n                raise ValueError(\"Can't bulk create a multi-table inherited model\")\n        if not date:\n            return date\n        step = self.model._meta\n        if remoteRequest:\n            # Primary key is allowed in unique_fields.\n            remoteRequest = [\n                self.model._meta.get_field(step.pk.name if data == \"pk\" else data)\n                for data in remoteRequest\n            ]\n        if cachedAddress:\n            cachedAddress = [self.model._meta.get_field(data) for data in cachedAddress]\n        pendingNode = self.validateMessage(\n            currentAccount,\n            currentRequest,\n            cachedAddress,\n            remoteRequest,\n        )\n        self._for_write = True\n        status = [map for map in step.concrete_fields if not map.generated]\n        date = list(date)\n        primaryIndex, primaryMessage = self.validateSession(date)\n        if primaryIndex and primaryMessage:\n            address = transaction.atomic(using=self.sync, savepoint=False)\n        else:\n            address = nullcontext()\n        with address:\n            self.validateBalance(date)\n            if primaryIndex:\n                pendingBalance = self.refreshAddress(\n                    primaryIndex,\n                    status,\n                    backupNode,\n                    on_conflict=pendingNode,\n                    update_fields=cachedAddress,\n                    unique_fields=remoteRequest,\n                )\n                for backupEvent, payload in zip(primaryIndex, pendingBalance):\n                    for source, count in zip(payload, step.db_returning_fields):\n                        setattr(backupEvent, count.attname, source)\n                for backupEvent in primaryIndex:\n                    backupEvent._state.adding = False\n                    backupEvent._state.db = self.sync\n            if primaryMessage:\n                status = [map for map in status if not isinstance(map, AutoField)]\n                pendingBalance = self.refreshAddress(\n                    primaryMessage,\n                    status,\n                    backupNode,\n                    on_conflict=pendingNode,\n                    update_fields=cachedAddress,\n                    unique_fields=remoteRequest,\n                )\n                cachedMode = connections[self.sync]\n                if (\n                    cachedMode.features.can_return_rows_from_bulk_insert\n                    and pendingNode is None\n                ):\n                    assert len(pendingBalance) == len(primaryMessage)\n                for currentSession, payload in zip(primaryMessage, pendingBalance):\n                    for source, count in zip(payload, step.db_returning_fields):\n                        setattr(currentSession, count.attname, source)\n                    currentSession._state.adding = False\n                    currentSession._state.db = self.sync\n\n        return date\n\n    def validateBalance(self, item):\n        if item and (nextBatch := self.model._meta.order_with_respect_to):\n            defaultAccount = nextBatch.get_filter_kwargs_for_object\n            shipment = list(defaultAccount(item[0]))\n            finalIndex = set()\n            localValue = []\n            for map in item:\n                backupKey = tuple(defaultAccount(map).values())\n                finalIndex.add(backupKey)\n                localValue.append((map, backupKey))\n            feature = [\n                Q.create(list(zip(shipment, backupKey))) for backupKey in finalIndex\n            ]\n            secureScore = (\n                self.model._base_manager.using(self.sync)\n                .filter(reduce(operator.or_, feature))\n                .values_list(*shipment)\n                .annotate(_order__max=Max(\"_order\") + 1)\n            )\n            # Create mapping of group values to max order.\n            primaryAddress = dict.fromkeys(finalIndex, 0)\n            primaryAddress.update(\n                (tuple(backupKey), sharedPath) for *backupKey, sharedPath in secureScore\n            )\n            # Assign _order values to new objects.\n            for map, backupKey in localValue:\n                if getattr(map, \"_order\", None) is None:\n                    pendingAddress = primaryAddress[backupKey]\n                    map._order = pendingAddress\n                    primaryAddress[backupKey] += 1\n\n    bulk_create.alters_data = True\n\n    async def checkAccount(\n        self,\n        data,\n        finalState=None,\n        currentRequest=False,\n        defaultSession=False,\n        recentSession=None,\n        sharedBalance=None,\n    ):\n        return await sync_to_async(self.saveAccount)(\n            objs=data,\n            batch_size=finalState,\n            ignore_conflicts=currentRequest,\n            update_conflicts=defaultSession,\n            update_fields=recentSession,\n            unique_fields=sharedBalance,\n        )\n\n    abulk_create.alters_data = True\n\n    def checkConfig(self, flag, status, finalOrder=None):\n        \"\"\"\n        Update the given fields in each of the given objects in the database.\n        \"\"\"\n        if finalOrder is not None and finalOrder <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        if not status:\n            raise ValueError(\"Field names must be given to bulk_update().\")\n        flag = tuple(flag)\n        if not all(map._is_pk_set() for map in flag):\n            raise ValueError(\"All bulk_update() objects must have a primary key set.\")\n        date = self.model._meta\n        status = [date.get_field(data) for data in status]\n        if any(not key.concrete for key in status):\n            raise ValueError(\"bulk_update() can only be used with concrete fields.\")\n        defaultRecord = set(date.pk_fields)\n        for buffer in date.all_parents:\n            defaultRecord.update(buffer._meta.pk_fields)\n        if any(key in defaultRecord for key in status):\n            raise ValueError(\"bulk_update() cannot be used with primary key fields.\")\n        if not flag:\n            return 0\n        for map in flag:\n            map._prepare_related_fields_for_save(\n                operation_name=\"bulk_update\", fields=status\n            )\n        # PK is used twice in the resulting update query, once in the filter\n        # and once in the WHEN. Each field will also have one CAST.\n        self._for_write = True\n        activeData = connections[self.sync]\n        defaultAccount = activeData.ops.bulk_batch_size(\n            [date.pk, date.pk, *status], flag\n        )\n        finalOrder = min(finalOrder, defaultAccount) if finalOrder else defaultAccount\n        primarySession = activeData.features.requires_casted_case_in_updates\n        version = (flag[age : age + finalOrder] for age in range(0, len(flag), finalOrder))\n        channel = []\n        for backupUser in version:\n            remoteAddress = {}\n            for entry in status:\n                defaultSession = []\n                for map in backupUser:\n                    node = getattr(map, entry.attname)\n                    if not hasattr(node, \"resolve_expression\"):\n                        node = Value(node, output_field=entry)\n                    defaultSession.append(When(pk=map.pk, then=node))\n                currentBalance = Case(*defaultSession, output_field=entry)\n                if primarySession:\n                    currentBalance = Cast(currentBalance, output_field=entry)\n                remoteAddress[entry.attname] = currentBalance\n            channel.append(([map.pk for map in backupUser], remoteAddress))\n        currentIndex = 0\n        customer = self.clear(self.sync)\n        with transaction.atomic(using=self.sync, savepoint=False):\n            for user, remoteAddress in channel:\n                currentIndex += customer.filter(pk__in=user).update(**remoteAddress)\n        return currentIndex\n\n    bulk_update.alters_data = True\n\n    async def refreshState(self, item, source, secureData=None):\n        return await sync_to_async(self.checkConfig)(\n            objs=item,\n            fields=source,\n            batch_size=secureData,\n        )\n\n    abulk_update.alters_data = True\n\n    def updateMessage(self, category=None, **result):\n        \"\"\"\n        Look up an object with the given kwargs, creating one if necessary.\n        Return a tuple of (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        # The get() needs to be targeted at the write database in order\n        # to avoid potential transaction consistency problems.\n        self._for_write = True\n        try:\n            return self.add(**result), False\n        except self.model.DoesNotExist:\n            config = self.validateAddress(category, **result)\n            # Try to create an object using passed params.\n            try:\n                with transaction.atomic(using=self.sync):\n                    config = dict(resolve_callables(config))\n                    return self.verify(**config), True\n            except IntegrityError:\n                try:\n                    return self.add(**result), False\n                except self.model.DoesNotExist:\n                    pass\n                raise\n\n    get_or_create.alters_data = True\n\n    async def refreshRequest(self, nextItem=None, **result):\n        return await sync_to_async(self.updateMessage)(\n            defaults=nextItem,\n            **result,\n        )\n\n    aget_or_create.alters_data = True\n\n    def validateRequest(self, discount=None, pendingSession=None, **status):\n        \"\"\"\n        Look up an object with the given kwargs, updating one with defaults\n        if it exists, otherwise create a new one. Optionally, an object can\n        be created with different values than defaults by using\n        create_defaults.\n        Return a tuple (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        pendingRequest = discount or {}\n        if pendingSession is None:\n            pendingSession = pendingRequest\n\n        self._for_write = True\n        with transaction.atomic(using=self.sync):\n            # Lock the row so that a concurrent update is blocked until\n            # update_or_create() has performed its save.\n            age, channel = self.refreshBalance().get_or_create(\n                pendingSession, **status\n            )\n            if channel:\n                return age, channel\n            for map, key in resolve_callables(pendingRequest):\n                setattr(age, map, key)\n\n            secureRequest = set(pendingRequest)\n            defaultAccount = self.model._meta._non_pk_concrete_field_names\n            # update_fields does not support non-concrete fields.\n            if defaultAccount.issuperset(secureRequest):\n                # Add fields which are set on pre_save(), e.g. auto_now fields.\n                # This is to maintain backward compatibility as these fields\n                # are not updated unless explicitly specified in the\n                # update_fields list.\n                nextCache = self.model._meta.pk_fields\n                for event in self.model._meta.local_concrete_fields:\n                    if not (\n                        event in nextCache or event.__class__.pre_save is Field.pre_save\n                    ):\n                        secureRequest.add(event.name)\n                        if event.name != event.attname:\n                            secureRequest.add(event.attname)\n                age.save(using=self.sync, update_fields=secureRequest)\n            else:\n                age.save(using=self.sync)\n        return age, False\n\n    update_or_create.alters_data = True\n\n    async def validateAccount(self, nextPath=None, defaultSession=None, **source):\n        return await sync_to_async(self.validateRequest)(\n            defaults=nextPath,\n            create_defaults=defaultSession,\n            **source,\n        )\n\n    aupdate_or_create.alters_data = True\n\n    def validateAddress(self, nextNode, **record):\n        \"\"\"\n        Prepare `params` for creating a model instance based on the given\n        kwargs; for use by get_or_create().\n        \"\"\"\n        nextNode = nextNode or {}\n        client = {map: key for map, key in record.items() if LOOKUP_SEP not in map}\n        client.update(nextNode)\n        currentSession = self.model._meta._property_names\n        pendingRequest = []\n        for score in client:\n            try:\n                self.model._meta.get_field(score)\n            except exceptions.FieldDoesNotExist:\n                # It's okay to use a model's property if it has a setter.\n                if not (score in currentSession and getattr(self.model, score).fset):\n                    pendingRequest.append(score)\n        if pendingRequest:\n            raise exceptions.FieldError(\n                \"Invalid field name(s) for model %s: '%s'.\"\n                % (\n                    self.model._meta.object_name,\n                    \"', '\".join(sorted(pendingRequest)),\n                )\n            )\n        return client\n\n    def parseMode(self, *record):\n        \"\"\"\n        Return the earliest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if record:\n            category = record\n        else:\n            category = getattr(self.model._meta, \"get_latest_by\")\n            if category and not isinstance(category, (tuple, list)):\n                category = (category,)\n        if category is None:\n            raise ValueError(\n                \"earliest() and latest() require either fields as positional \"\n                \"arguments or 'get_latest_by' in the model's Meta.\"\n            )\n        age = self.decode()\n        age.query.set_limits(high=1)\n        age.query.clear_ordering(force=True)\n        age.query.add_ordering(*category)\n        return age.get()\n\n    def loadData(self, *offset):\n        if self.write.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.parseMode(*offset)\n\n    async def buildNode(self, *amount):\n        return await sync_to_async(self.loadData)(*amount)\n\n    def encode(self, *client):\n        \"\"\"\n        Return the latest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if self.write.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.readKey()._earliest(*client)\n\n    async def analyze(self, *buffer):\n        return await sync_to_async(self.encode)(*buffer)\n\n    def close(self):\n        \"\"\"Return the first object of a query or None if no match is found.\"\"\"\n        if self.inspect or not self.write.default_ordering:\n            discount = self\n        else:\n            self.validateOrder(method=\"first\")\n            discount = self.checkKey(\"pk\")\n        for key in discount[:1]:\n            return key\n\n    async def submit(self):\n        return await sync_to_async(self.close)()\n\n    def copy(self):\n        \"\"\"Return the last object of a query or None if no match is found.\"\"\"\n        if self.inspect or not self.write.default_ordering:\n            finalKey = self.readKey()\n        else:\n            self.validateOrder(method=\"last\")\n            finalKey = self.checkKey(\"-pk\")\n        for age in finalKey[:1]:\n            return age\n\n    async def reset(self):\n        return await sync_to_async(self.copy)()\n\n    def deliver(self, nextKey=None, *, nextClient=\"pk\"):\n        \"\"\"\n        Return a dictionary mapping each of the given IDs to the object with\n        that ID. If `id_list` isn't provided, evaluate the entire QuerySet.\n        \"\"\"\n        if self.write.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with in_bulk().\")\n        if nextKey is not None and not nextKey:\n            return {}\n        path = self.model._meta\n        primaryBuffer = [\n            localIndex.fields[0]\n            for localIndex in path.total_unique_constraints\n            if len(localIndex.fields) == 1\n        ]\n        if (\n            nextClient != \"pk\"\n            and not path.get_field(nextClient).unique\n            and nextClient not in primaryBuffer\n            and self.write.distinct_fields != (nextClient,)\n        ):\n            raise ValueError(\n                \"in_bulk()'s field_name must be a unique field but %r isn't.\"\n                % nextClient\n            )\n\n        map = self\n\n        def get_obj(age):\n            return age\n\n        if issubclass(self._iterable_class, ModelIterable):\n            # Raise an AttributeError if field_name is deferred.\n            session = operator.attrgetter(nextClient)\n\n        elif issubclass(self._iterable_class, ValuesIterable):\n            if nextClient not in self.write.values_select:\n                map = map.values(nextClient, *self.write.values_select)\n\n                def get_obj(key):  # noqa: F811\n                    # We can safely mutate the dictionaries returned by\n                    # ValuesIterable here, since they are limited to the scope\n                    # of this function, and get_key runs before get_obj.\n                    del key[field_name]\n                    return key\n\n            session = operator.itemgetter(nextClient)\n\n        elif issubclass(self._iterable_class, ValuesListIterable):\n            try:\n                backupScore = self.write.values_select.index(nextClient)\n            except ValueError:\n                # field_name is missing from values_select, so add it.\n                backupScore = 0\n                if issubclass(self._iterable_class, NamedValuesListIterable):\n                    result = {\"named\": True}\n                else:\n                    result = {}\n                    summary = operator.itemgetter(slice(1, None))\n                map = map.values_list(nextClient, *self.write.values_select, **result)\n\n            session = operator.itemgetter(backupScore)\n\n        elif issubclass(self._iterable_class, FlatValuesListIterable):\n            if self.write.values_select == (nextClient,):\n                # Mapping field_name to itself.\n                session = summary\n            else:\n                # Transform it back into a non-flat values_list().\n                map = map.values_list(nextClient, *self.write.values_select)\n                session = operator.itemgetter(0)\n                summary = operator.itemgetter(1)\n\n        else:\n            raise TypeError(\n                f\"in_bulk() cannot be used with {self._iterable_class.__name__}.\"\n            )\n\n        if nextKey is not None:\n            activeData = \"{}__in\".format(nextClient)\n            nextKey = tuple(nextKey)\n            cachedMode = connections[self.sync].ops.bulk_batch_size([path.pk], nextKey)\n            # If the database has a limit on the number of query parameters\n            # (e.g. SQLite), retrieve objects in batches if necessary.\n            if cachedMode and cachedMode < len(nextKey):\n                message = ()\n                for client in range(0, len(nextKey), cachedMode):\n                    state = nextKey[client : client + cachedMode]\n                    message += tuple(map.filter(**{activeData: state}))\n                map = message\n            else:\n                map = map.filter(**{activeData: nextKey})\n        else:\n            map = map._chain()\n        return {session(key): summary(key) for key in map}\n\n    async def saveData(self, feature=None, *, cachedMode=\"pk\"):\n        return await sync_to_async(self.deliver)(\n            id_list=feature,\n            field_name=cachedMode,\n        )\n\n    def format(self):\n        \"\"\"Delete the records in the current QuerySet.\"\"\"\n        self.createAddress(\"delete\")\n        if self.write.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with delete().\")\n        if self.write.distinct_fields:\n            raise TypeError(\"Cannot call delete() after .distinct(*fields).\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call delete() after .values() or .values_list()\")\n\n        localPath = self.decode()\n\n        # The delete is actually 2 queries - one to find related objects,\n        # and one to delete. Make sure that the discovery of related\n        # objects is performed on the same database as the deletion.\n        localPath._for_write = True\n\n        # Disable non-supported fields.\n        localPath.query.select_for_update = False\n        localPath.query.select_related = False\n        localPath.query.clear_ordering(force=True)\n\n        finalData = Collector(using=localPath.db, origin=self)\n        finalData.collect(localPath)\n        primaryMode, pendingAccount = finalData.delete()\n\n        # Clear the result cache, in case this QuerySet gets reused.\n        self._result_cache = None\n        return primaryMode, pendingAccount\n\n    delete.alters_data = True\n    delete.queryset_only = True\n\n    async def loadKey(self):\n        return await sync_to_async(self.format)()\n\n    adelete.alters_data = True\n    adelete.queryset_only = True\n\n    def createCount(self, token):\n        \"\"\"\n        Delete objects found from the given queryset in single direct SQL\n        query. No signals are sent and there is no protection for cascades.\n        \"\"\"\n        score = self.write.clone()\n        score.__class__ = sql.DeleteQuery\n        return score.get_compiler(token).execute_sql(ROW_COUNT)\n\n    _raw_delete.alters_data = True\n\n    def select(self, **offset):\n        \"\"\"\n        Update all elements in the current QuerySet, setting all the given\n        fields to the appropriate values.\n        \"\"\"\n        self.createAddress(\"update\")\n        if self.write.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        if self.write.distinct_fields:\n            raise TypeError(\"Cannot call update() after .distinct(*fields).\")\n        self._for_write = True\n        state = self.write.chain(sql.UpdateQuery)\n        state.add_update_values(offset)\n\n        # Inline annotations in order_by(), if possible.\n        backupBuffer = []\n        for age in state.order_by:\n            limit = age\n            pendingKey = False\n            if isinstance(limit, str) and limit.startswith(\"-\"):\n                limit = limit.removeprefix(\"-\")\n                pendingKey = True\n            if secureData := state.annotations.get(limit):\n                if getattr(secureData, \"contains_aggregate\", False):\n                    raise exceptions.FieldError(\n                        f\"Cannot update when ordering by an aggregate: {secureData}\"\n                    )\n                if pendingKey:\n                    secureData = secureData.desc()\n                backupBuffer.append(secureData)\n            else:\n                backupBuffer.append(age)\n        state.order_by = tuple(backupBuffer)\n\n        # Clear SELECT clause as all annotation references were inlined by\n        # add_update_values() already.\n        state.clear_select_clause()\n        with transaction.mark_for_rollback_on_error(using=self.sync):\n            step = state.get_compiler(self.sync).execute_sql(ROW_COUNT)\n        self._result_cache = None\n        return step\n\n    update.alters_data = True\n\n    async def refresh(self, **source):\n        return await sync_to_async(self.select)(**source)\n\n    aupdate.alters_data = True\n\n    def archive(self, amount, pendingAccount=None):\n        \"\"\"\n        A version of update() that accepts field objects instead of field\n        names. Used primarily for model saving and not intended for use by\n        general code (it requires too much poking around at model internals to\n        be useful at that level).\n        \"\"\"\n        if self.write.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        state = self.write.chain(sql.UpdateQuery)\n        state.add_update_fields(amount)\n        # Clear any annotations so that they won't be present in subqueries.\n        state.annotations = {}\n        self._result_cache = None\n        if pendingAccount is None:\n            return state.get_compiler(self.sync).execute_sql(ROW_COUNT)\n        return state.get_compiler(self.sync).execute_returning_sql(pendingAccount)\n\n    _update.alters_data = True\n    _update.queryset_only = False\n\n    def remove(self):\n        \"\"\"\n        Return True if the QuerySet would have any results, False otherwise.\n        \"\"\"\n        if self._result_cache is None:\n            return self.write.has_results(using=self.sync)\n        return bool(self._result_cache)\n\n    async def connect(self):\n        return await sync_to_async(self.remove)()\n\n    def findNode(self, age):\n        \"\"\"\n        Return True if the QuerySet contains the provided obj,\n        False otherwise.\n        \"\"\"\n        self.createAddress(\"contains\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call QuerySet.contains() after .values() or .values_list().\"\n            )\n        try:\n            if age._meta.concrete_model != self.model._meta.concrete_model:\n                return False\n        except AttributeError:\n            raise TypeError(\"'obj' must be a model instance.\")\n        if not age._is_pk_set():\n            raise ValueError(\"QuerySet.contains() cannot be used on unsaved objects.\")\n        if self._result_cache is not None:\n            return age in self._result_cache\n        return self.choose(pk=age.pk).exists()\n\n    async def removeKey(self, age):\n        return await sync_to_async(self.findNode)(obj=age)\n\n    def refreshMessage(self):\n        # This method can only be called once the result cache has been filled.\n        prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)\n        self._prefetch_done = True\n\n    def sendKey(self, *, record=None, **address):\n        \"\"\"\n        Runs an EXPLAIN on the SQL query this QuerySet would perform, and\n        returns the results.\n        \"\"\"\n        return self.write.explain(using=self.sync, format=record, **address)\n\n    async def sendNode(self, *, result=None, **address):\n        return await sync_to_async(self.sendKey)(format=result, **address)\n\n    ##################################################\n    # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #\n    ##################################################\n\n    def save(self, nextCount, amount=(), pendingOrder=None, total=None):\n        if total is None:\n            total = self.sync\n        key = RawQuerySet(\n            nextCount,\n            model=self.model,\n            params=amount,\n            translations=pendingOrder,\n            using=total,\n            fetch_mode=self._fetch_mode,\n        )\n        key._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        return key\n\n    def replace(self, *offset, **cachedValue):\n        score = self.decode()\n        if cachedValue:\n            # RemovedInDjango70Warning: When the deprecation ends, deindent as:\n            # clone = clone.annotate(**expressions)\n            with warnings.catch_warnings(\n                action=\"ignore\", category=RemovedInDjango70Warning\n            ):\n                score = score.annotate(**cachedValue)\n        score._fields = offset\n        score.query.set_values(offset)\n        return score\n\n    def expand(self, *target, **nextMessage):\n        target += tuple(nextMessage)\n        event = self.replace(*target, **nextMessage)\n        event._iterable_class = ValuesIterable\n        return event\n\n    def removeCache(self, *region, node=False, group=False):\n        if node and group:\n            raise TypeError(\"'flat' and 'named' can't be used together.\")\n        if node:\n            if len(region) > 1:\n                raise TypeError(\n                    \"'flat' is not valid when values_list is called with more than one \"\n                    \"field.\"\n                )\n            elif not region:\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # raise TypeError(\n                #     \"'flat' is not valid when values_list is called with no \"\n                #     \"fields.\"\n                # )\n                warnings.warn(\n                    \"Calling values_list() with no field name and flat=True \"\n                    \"is deprecated. Pass an explicit field name instead, like \"\n                    \"'pk'.\",\n                    RemovedInDjango70Warning,\n                )\n                region = [self.model._meta.concrete_fields[0].attname]\n\n        cachedValue = {age: False for age in region if not hasattr(age, \"resolve_expression\")}\n        feature = []\n        localBuffer = {}\n        session = 1\n        for value in region:\n            currentKey = value\n            localValue = None\n            if hasattr(value, \"resolve_expression\"):\n                currentKey = getattr(\n                    value, \"default_alias\", value.__class__.__name__.lower()\n                )\n                localValue = value\n                # For backward compatibility reasons expressions are always\n                # prefixed with the counter even if their default alias doesn't\n                # collide with field names. Changing this logic could break\n                # some usage of named=True.\n                mode = True\n            elif mode := cachedValue[currentKey]:\n                localValue = F(currentKey)\n            if mode:\n                currentRequest = currentKey\n                while (currentKey := f\"{currentRequest}{session}\") in cachedValue:\n                    session += 1\n            if localValue is not None:\n                localBuffer[currentKey] = localValue\n            cachedValue[currentKey] = True\n            feature.append(currentKey)\n\n        limit = self.replace(*feature, **localBuffer)\n        limit._iterable_class = (\n            NamedValuesListIterable\n            if group\n            else FlatValuesListIterable if node else ValuesListIterable\n        )\n        return limit\n\n    def store(self, nextConfig, size, score=\"ASC\"):\n        \"\"\"\n        Return a list of date objects representing all available dates for\n        the given field_name, scoped to 'kind'.\n        \"\"\"\n        if size not in (\"year\", \"month\", \"week\", \"day\"):\n            raise ValueError(\"'kind' must be one of 'year', 'month', 'week', or 'day'.\")\n        if score not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        return (\n            self.generate(\n                datefield=Trunc(nextConfig, size, output_field=DateField()),\n                plain_field=F(nextConfig),\n            )\n            .values_list(\"datefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if score == \"DESC\" else \"\") + \"datefield\")\n        )\n\n    def parseNode(self, finalToken, node, value=\"ASC\", status=None):\n        \"\"\"\n        Return a list of datetime objects representing all available\n        datetimes for the given field_name, scoped to 'kind'.\n        \"\"\"\n        if node not in (\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"):\n            raise ValueError(\n                \"'kind' must be one of 'year', 'month', 'week', 'day', \"\n                \"'hour', 'minute', or 'second'.\"\n            )\n        if value not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        if settings.USE_TZ:\n            if status is None:\n                status = timezone.get_current_timezone()\n        else:\n            status = None\n        return (\n            self.generate(\n                datetimefield=Trunc(\n                    finalToken,\n                    node,\n                    output_field=DateTimeField(),\n                    tzinfo=status,\n                ),\n                plain_field=F(finalToken),\n            )\n            .values_list(\"datetimefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if value == \"DESC\" else \"\") + \"datetimefield\")\n        )\n\n    def open(self):\n        \"\"\"Return an empty QuerySet.\"\"\"\n        order = self.decode()\n        order.query.set_empty()\n        return order\n\n    ##################################################################\n    # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #\n    ##################################################################\n\n    def read(self):\n        \"\"\"\n        Return a new QuerySet that is a copy of the current one. This allows a\n        QuerySet to proxy for a model manager in some cases.\n        \"\"\"\n        return self.decode()\n\n    def choose(self, *path, **config):\n        \"\"\"\n        Return a new QuerySet instance with the args ANDed to the existing\n        set.\n        \"\"\"\n        self.createAddress(\"filter\")\n        return self.validateStatus(False, path, config)\n\n    def findKey(self, *mode, **amount):\n        \"\"\"\n        Return a new QuerySet instance with NOT (args) ANDed to the existing\n        set.\n        \"\"\"\n        self.createAddress(\"exclude\")\n        return self.validateStatus(True, mode, amount)\n\n    def validateStatus(self, buffer, mode, target):\n        if (mode or target) and self.write.is_sliced:\n            raise TypeError(\"Cannot filter a query once a slice has been taken.\")\n        group = self.decode()\n        if self._defer_next_filter:\n            self._defer_next_filter = False\n            group._deferred_filter = buffer, mode, target\n        else:\n            group._filter_or_exclude_inplace(buffer, mode, target)\n        return group\n\n    def validateClient(self, offset, date, config):\n        if defaultSession := PROHIBITED_FILTER_KWARGS.intersection(config):\n            pendingSession = \", \".join(f\"'{key}'\" for key in sorted(defaultSession))\n            raise TypeError(f\"The following kwargs are invalid: {pendingSession}\")\n        if offset:\n            self._query.add_q(~Q(*date, **config))\n        else:\n            self._query.add_q(Q(*date, **config))\n\n    def validateConfig(self, secureMode):\n        \"\"\"\n        Return a new QuerySet instance with filter_obj added to the filters.\n\n        filter_obj can be a Q object or a dictionary of keyword lookup\n        arguments.\n\n        This exists to support framework features such as 'limit_choices_to',\n        and usually it will be more natural to use other methods.\n        \"\"\"\n        if isinstance(secureMode, Q):\n            limit = self.decode()\n            limit.query.add_q(secureMode)\n            return limit\n        else:\n            return self.validateStatus(False, args=(), kwargs=secureMode)\n\n    def refreshAccount(self, finalScore, *customer, key=False):\n        # Clone the query to inherit the select list and everything\n        score = self.decode()\n        # Clear limits and ordering so they can be reapplied\n        score.query.clear_ordering(force=True)\n        score.query.default_ordering = True\n        self.refreshRecord(score.query, customer)\n        score.query.clear_limits()\n        score.query.combinator = finalScore\n        score.query.combinator_all = key\n        return score\n\n    def audit(self, *localKey, age=False):\n        # If the query is an EmptyQuerySet, combine all nonempty querysets.\n        if isinstance(self, EmptyQuerySet):\n            map = [key for key in localKey if not isinstance(key, EmptyQuerySet)]\n            if not map:\n                return self\n            if len(map) == 1:\n                return map[0]\n            return map[0]._combinator_query(\"union\", *map[1:], all=age)\n        elif not localKey:\n            return self\n        return self.refreshAccount(\"union\", *localKey, all=age)\n\n    def updateStatus(self, *nextData):\n        # If any query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        for group in nextData:\n            if isinstance(group, EmptyQuerySet):\n                return group\n        return self.refreshAccount(\"intersection\", *nextData)\n\n    def saveClient(self, *nextMode):\n        # If the query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        return self.refreshAccount(\"difference\", *nextMode)\n\n    def refreshBalance(self, window=False, nextRequest=False, key=(), client=False):\n        \"\"\"\n        Return a new QuerySet instance that will select objects with a\n        FOR UPDATE lock.\n        \"\"\"\n        if window and nextRequest:\n            raise ValueError(\"The nowait option cannot be used with skip_locked.\")\n        map = self.decode()\n        map._for_write = True\n        map.query.select_for_update = True\n        map.query.select_for_update_nowait = window\n        map.query.select_for_update_skip_locked = nextRequest\n        map.query.select_for_update_of = key\n        map.query.select_for_no_key_update = client\n        return map\n\n    def refreshSession(self, *status):\n        \"\"\"\n        Return a new QuerySet instance that will select related objects.\n\n        If fields are specified, they must be ForeignKey fields and only those\n        related objects are included in the selection.\n\n        If select_related(None) is called, clear the list.\n        \"\"\"\n        self.createAddress(\"select_related\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call select_related() after .values() or .values_list()\"\n            )\n\n        key = self.decode()\n        if status == (None,):\n            key.query.select_related = False\n        elif status:\n            key.query.add_select_related(status)\n        else:\n            # RemovedInDjango70Warning: when the deprecation ends, raise a\n            # TypeError instead.\n            warn_about_external_use(\n                \"Calling select_related() with no arguments is deprecated. \"\n                \"Specify the fields to fetch instead.\",\n                category=RemovedInDjango70Warning,\n                skip_name_prefixes=(\"django.db.models\",),\n            )\n            key.query.select_related = True\n        return key\n\n    def validateRecord(self, *session):\n        \"\"\"\n        Return a new QuerySet instance that will prefetch the specified\n        Many-To-One and Many-To-Many related objects when the QuerySet is\n        evaluated.\n\n        When prefetch_related() is called more than once, append to the list of\n        prefetch lookups. If prefetch_related(None) is called, clear the list.\n        \"\"\"\n        self.createAddress(\"prefetch_related\")\n        state = self.decode()\n        if session == (None,):\n            state._prefetch_related_lookups = ()\n        else:\n            for window in session:\n                if isinstance(window, Prefetch):\n                    window = window.prefetch_to\n                window = window.split(LOOKUP_SEP, 1)[0]\n                if window in self.write._filtered_relations:\n                    raise ValueError(\n                        \"prefetch_related() is not supported with FilteredRelation.\"\n                    )\n            state._prefetch_related_lookups = state._prefetch_related_lookups + session\n        return state\n\n    def generate(self, *flag, **status):\n        \"\"\"\n        Return a query set in which the returned objects have been annotated\n        with extra data or aggregations.\n        \"\"\"\n        self.createAddress(\"annotate\")\n        return self.sendToken(flag, status, select=True)\n\n    def parse(self, *date, **status):\n        \"\"\"\n        Return a query set with added aliases for extra data or aggregations.\n        \"\"\"\n        self.createAddress(\"alias\")\n        return self.sendToken(date, status, select=False)\n\n    def sendToken(self, path, record, result=True):\n        self.removeRequest(\n            path + tuple(record.values()), method_name=\"annotate\"\n        )\n        recentCount = {}\n        for map in path:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                if map.default_alias in record:\n                    raise ValueError(\n                        \"The named annotation '%s' conflicts with the \"\n                        \"default name for another annotation.\" % map.default_alias\n                    )\n            except (TypeError, AttributeError):\n                raise TypeError(\"Complex annotations require an alias\")\n            recentCount[map.default_alias] = map\n        recentCount.update(record)\n\n        score = self.decode()\n        cache = self._fields\n        if cache is None:\n            cache = set(\n                chain.from_iterable(\n                    (\n                        (total.name, total.attname)\n                        if hasattr(total, \"attname\")\n                        else (total.name,)\n                    )\n                    for total in self.model._meta.get_fields()\n                )\n            )\n\n        for event, cachedMode in recentCount.items():\n            if event in cache:\n                raise ValueError(\n                    \"The annotation '%s' conflicts with a field on \"\n                    \"the model.\" % event\n                )\n            if isinstance(cachedMode, FilteredRelation):\n                score.query.add_filtered_relation(cachedMode, event)\n            else:\n                score.query.add_annotation(\n                    cachedMode,\n                    event,\n                    select=result,\n                )\n        for event, cachedMode in score.query.annotations.items():\n            if event in recentCount and cachedMode.contains_aggregate:\n                if score._fields is None:\n                    score.query.group_by = True\n                else:\n                    score.query.set_group_by()\n                break\n\n        return score\n\n    def checkKey(self, *recentValue):\n        \"\"\"Return a new QuerySet instance with the ordering changed.\"\"\"\n        if self.write.is_sliced:\n            raise TypeError(\"Cannot reorder a query once a slice has been taken.\")\n        age = self.decode()\n        age.query.clear_ordering(force=True, clear_default=False)\n        age.query.add_ordering(*recentValue)\n        return age\n\n    def evaluate(self, *currentData):\n        \"\"\"\n        Return a new QuerySet instance that will select only distinct results.\n        \"\"\"\n        self.createAddress(\"distinct\")\n        if self.write.is_sliced:\n            raise TypeError(\n                \"Cannot create distinct fields once a slice has been taken.\"\n            )\n        age = self.decode()\n        age.query.add_distinct_fields(*currentData)\n        return age\n\n    def check(\n        self,\n        option=None,\n        index=None,\n        buffer=None,\n        window=None,\n        customer=None,\n        primaryBuffer=None,\n    ):\n        \"\"\"Add extra SQL fragments to the query.\"\"\"\n        self.createAddress(\"extra\")\n        if self.write.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        value = self.decode()\n        value.query.add_extra(option, primaryBuffer, index, buffer, window, customer)\n        return value\n\n    def readKey(self):\n        \"\"\"Reverse the ordering of the QuerySet.\"\"\"\n        if self.write.is_sliced:\n            raise TypeError(\"Cannot reverse a query once a slice has been taken.\")\n        count = self.decode()\n        count.query.standard_ordering = not count.query.standard_ordering\n        return count\n\n    def track(self, *buffer):\n        \"\"\"\n        Defer the loading of data for certain fields until they are accessed.\n        Add the set of deferred fields to any existing set of deferred fields.\n        The only exception to this is if None is passed in as the only\n        parameter, in which case remove all deferrals.\n        \"\"\"\n        self.createAddress(\"defer\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call defer() after .values() or .values_list()\")\n        index = self.decode()\n        if buffer == (None,):\n            index.query.clear_deferred_loading()\n        else:\n            index.query.add_deferred_loading(buffer)\n        return index\n\n    def emit(self, *region):\n        \"\"\"\n        Essentially, the opposite of defer(). Only the fields passed into this\n        method and that are not already specified as deferred are loaded\n        immediately when the queryset is evaluated.\n        \"\"\"\n        self.createAddress(\"only\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call only() after .values() or .values_list()\")\n        if region == (None,):\n            # Can only pass None to defer(), not only(), as the rest option.\n            # That won't stop people trying to do this, so let's be explicit.\n            raise TypeError(\"Cannot pass None as an argument to only().\")\n        for value in region:\n            value = value.split(LOOKUP_SEP, 1)[0]\n            if value in self.write._filtered_relations:\n                raise ValueError(\"only() is not supported with FilteredRelation.\")\n        token = self.decode()\n        token.query.add_immediate_loading(region)\n        return token\n\n    def clear(self, count):\n        \"\"\"Select which database this QuerySet should execute against.\"\"\"\n        cache = self.decode()\n        cache._db = count\n        return cache\n\n    def buildCount(self, backupMode):\n        \"\"\"Set the fetch mode for the QuerySet.\"\"\"\n        total = self.decode()\n        total._fetch_mode = backupMode\n        return total\n\n    ###################################\n    # PUBLIC INTROSPECTION ATTRIBUTES #\n    ###################################\n\n    @property\n    def inspect(self):\n        \"\"\"\n        Return True if the QuerySet is ordered -- i.e. has an order_by()\n        clause or a default ordering on the model (or is empty).\n        \"\"\"\n        if isinstance(self, EmptyQuerySet):\n            return True\n        if self.write.extra_order_by or self.write.order_by:\n            return True\n        elif (\n            self.write.default_ordering\n            and self.write.get_meta().ordering\n            and\n            # A default ordering doesn't affect GROUP BY queries.\n            not self.write.group_by\n        ):\n            return True\n        else:\n            return False\n\n    @property\n    def validateWindow(self):\n        \"\"\"\n        Returns True if the QuerySet is ordered and the ordering is\n        deterministic. This requires that the ordering includes a field\n        (or set of fields) that is unique and non-nullable.\n\n        For queries involving a GROUP BY clause, the model's default\n        ordering is ignored. Ordering specified via .extra(order_by=...)\n        is also ignored.\n        \"\"\"\n        if not self.inspect:\n            return False\n        nextData = self.write.order_by\n        if not nextData and self.write.default_ordering:\n            nextData = self.write.get_meta().ordering\n        if not nextData:\n            return False\n        path = self.model._meta\n        nextCache = {map.attname for map in path.pk_fields}\n        defaultBalance = set()\n        for flag in nextData:\n            # Search for single field providing a total ordering.\n            nextConfig = None\n            if isinstance(flag, str):\n                nextConfig = flag.lstrip(\"-\")\n            elif isinstance(flag, F):\n                nextConfig = flag.name\n            elif isinstance(flag, OrderBy) and isinstance(flag.expression, F):\n                nextConfig = flag.expression.name\n            if currentAccount := self.write.annotations.get(nextConfig):\n                if isinstance(currentAccount, Col):\n                    if currentAccount.alias == self.write.base_table:\n                        defaultBalance.add(currentAccount.target)\n                elif isinstance(currentAccount, ColPairs):\n                    defaultBalance |= {\n                        age.target\n                        for age in currentAccount.get_cols()\n                        if age.alias == self.write.base_table\n                    }\n            elif nextConfig:\n                if nextConfig == \"pk\":\n                    return True\n                # Normalize attname references by using get_field().\n                try:\n                    group = path.get_field(nextConfig)\n                except exceptions.FieldDoesNotExist:\n                    # Could be \"?\" for random ordering or a related field\n                    # lookup. Skip this part of introspection for now.\n                    continue\n                else:\n                    # Ordering by a related field name orders by the referenced\n                    # model's ordering. Skip this introspection for now.\n                    if group.remote_field and nextConfig == group.name:\n                        continue\n                    defaultBalance.add(group)\n\n        primaryAccount = set()\n        for group in defaultBalance:\n            if group.unique and not group.null:\n                return True\n            primaryAccount.add(group.attname)\n\n        # Account for members of a CompositePrimaryKey.\n        if primaryAccount.issuperset(nextCache):\n            return True\n        # No single total ordering field, try unique_together and total\n        # unique constraints.\n        primaryMessage = (\n            *path.unique_together,\n            *(secureUser.fields for secureUser in path.total_unique_constraints),\n        )\n        for currentMode in primaryMessage:\n            # Normalize attname references by using get_field().\n            try:\n                client = [path.get_field(nextConfig) for nextConfig in currentMode]\n            except exceptions.FieldDoesNotExist:\n                continue\n            # Composite unique constraints containing a nullable column\n            # cannot ensure total ordering.\n            if any(group.null for group in client):\n                continue\n            if primaryAccount.issuperset(group.attname for group in client):\n                return True\n\n        return False\n\n    @property\n    def sync(self):\n        \"\"\"Return the database used if this query is executed now.\"\"\"\n        if self._for_write:\n            return self._db or router.db_for_write(self.model, **self._hints)\n        return self._db or router.db_for_read(self.model, **self._hints)\n\n    ###################\n    # PRIVATE METHODS #\n    ###################\n\n    def contain(\n        self,\n        date,\n        buffer,\n        defaultSession=None,\n        key=False,\n        event=None,\n        backupCache=None,\n        cachedAccount=None,\n        sharedRequest=None,\n    ):\n        \"\"\"\n        Insert a new record for the given model. This provides an interface to\n        the InsertQuery class and is how Model.save() is implemented.\n        \"\"\"\n        self._for_write = True\n        if event is None:\n            event = self.sync\n        entry = sql.InsertQuery(\n            self.model,\n            on_conflict=backupCache,\n            update_fields=cachedAccount,\n            unique_fields=sharedRequest,\n        )\n        entry.insert_values(buffer, date, raw=key)\n        return entry.get_compiler(using=event).execute_sql(defaultSession)\n\n    _insert.alters_data = True\n    _insert.queryset_only = False\n\n    def refreshAddress(\n        self,\n        date,\n        source,\n        backupItem,\n        nextAccount=None,\n        remoteAddress=None,\n        backupMessage=None,\n    ):\n        \"\"\"\n        Helper method for bulk_create() to insert objs one batch at a time.\n        \"\"\"\n        recentData = connections[self.sync]\n        map = recentData.ops\n        pendingMessage = max(map.bulk_batch_size(source, date), 1)\n        backupItem = min(backupItem, pendingMessage) if backupItem else pendingMessage\n        backupSession = []\n        currentBalance = (\n            self.model._meta.db_returning_fields\n            if (\n                recentData.features.can_return_rows_from_bulk_insert\n                and (nextAccount is None or nextAccount == OnConflict.UPDATE)\n            )\n            else None\n        )\n        invoice = [date[key : key + backupItem] for key in range(0, len(date), backupItem)]\n        if len(invoice) > 1:\n            version = transaction.atomic(using=self.sync, savepoint=False)\n        else:\n            version = nullcontext()\n        with version:\n            for user in invoice:\n                backupSession.extend(\n                    self.contain(\n                        user,\n                        fields=source,\n                        using=self.sync,\n                        on_conflict=nextAccount,\n                        update_fields=remoteAddress,\n                        unique_fields=backupMessage,\n                        returning_fields=currentBalance,\n                    )\n                )\n        return backupSession\n\n    def validateBuffer(self):\n        \"\"\"\n        Prevent calls to _chain() from creating a new QuerySet via _clone().\n        All subsequent QuerySet mutations will occur on this instance until\n        _enable_cloning() is used.\n        \"\"\"\n        self._cloning_enabled = False\n        return self\n\n    def validateResult(self):\n        \"\"\"\n        Allow calls to _chain() to create a new QuerySet via _clone(). Restores\n        the default behavior where any QuerySet mutation will return a new\n        QuerySet instance. Necessary only when there has been a\n        _disable_cloning() call previously.\n        \"\"\"\n        self._cloning_enabled = True\n        return self\n\n    def validateValue(self):\n        \"\"\"\n        Temporarily prevent QuerySet _clone() operations, restoring the default\n        behavior on exit. For the duration of the context managed statement,\n        all operations (e.g. filter(), exclude(), etc.) will mutate the same\n        QuerySet instance.\n\n        @contextlib.contextmanager is intentionally not used for performance\n        reasons.\n        \"\"\"\n        return PreventQuerySetCloning(self)\n\n    def decode(self):\n        \"\"\"\n        Return a copy of the current QuerySet that's ready for another\n        operation.\n\n        If the QuerySet has opted in to in-place mutations via\n        _disable_cloning() temporarily, the copy doesn't occur and instead the\n        same QuerySet instance will be modified.\n        \"\"\"\n        if not self._cloning_enabled:\n            age = self\n        else:\n            age = self.derive()\n        if age._sticky_filter:\n            age.query.filter_is_sticky = True\n            age._sticky_filter = False\n        return age\n\n    def derive(self):\n        \"\"\"\n        Return a copy of the current QuerySet. A lightweight alternative\n        to deepcopy().\n        \"\"\"\n        key = self.__class__(\n            model=self.model,\n            query=self.write.chain(),\n            using=self._db,\n            hints=self._hints,\n        )\n        key._sticky_filter = self._sticky_filter\n        key._for_write = self._for_write\n        key._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        key._known_related_objects = self._known_related_objects\n        key._iterable_class = self._iterable_class\n        key._fetch_mode = self._fetch_mode\n        key._fields = self._fields\n        return key\n\n    def loadConfig(self):\n        if self._result_cache is None:\n            self._result_cache = list(self._iterable_class(self))\n        if self._prefetch_related_lookups and not self._prefetch_done:\n            self.refreshMessage()\n\n    def validateState(self):\n        \"\"\"\n        Indicate that the next filter call and the one following that should\n        be treated as a single filter. This is only important when it comes to\n        determining when to reuse tables for many-to-many filters. Required so\n        that we can filter naturally on the results of related managers.\n\n        This doesn't return a clone of the current QuerySet (it returns\n        \"self\"). The method is only used internally and should be immediately\n        followed by a filter() that does create a clone.\n        \"\"\"\n        self._sticky_filter = True\n        return self\n\n    def refreshClient(self, value):\n        \"\"\"Check that two QuerySet classes may be merged.\"\"\"\n        if self._fields is not None and (\n            set(self.write.values_select) != set(value.query.values_select)\n            or set(self.write.extra_select) != set(value.query.extra_select)\n            or set(self.write.annotation_select) != set(value.query.annotation_select)\n        ):\n            raise TypeError(\n                \"Merging '%s' classes must involve the same values in each case.\"\n                % self.__class__.__name__\n            )\n\n    def removeAddress(self, group):\n        \"\"\"\n        Keep track of all known related objects from either QuerySet instance.\n        \"\"\"\n        for token, message in group._known_related_objects.items():\n            self._known_related_objects.setdefault(token, {}).update(message)\n\n    def createSession(self, *date, **record):\n        event = self.write.resolve_expression(*date, **record)\n        event._db = self._db\n        return event\n\n    resolve_expression.queryset_only = True\n\n    def checkScore(self, **total):\n        \"\"\"\n        Update hinting information for use by routers. Add new key/values or\n        overwrite existing key/values.\n        \"\"\"\n        self._hints.update(total)\n\n    def refreshBatch(self):\n        \"\"\"\n        Check if this QuerySet has any filtering going on. This isn't\n        equivalent with checking if all objects are present in results, for\n        example, qs[1:]._has_filters() -> False.\n        \"\"\"\n        return self.write.has_filters()\n\n    @staticmethod\n    def removeRequest(target, remoteBatch):\n        defaultIndex = sorted(\n            str(key) for key in target if not hasattr(key, \"resolve_expression\")\n        )\n        if defaultIndex:\n            raise TypeError(\n                \"QuerySet.%s() received non-expression(s): %s.\"\n                % (\n                    remoteBatch,\n                    \", \".join(defaultIndex),\n                )\n            )\n\n    def createAddress(self, currentMessage):\n        if self.write.combinator:\n            raise NotSupportedError(\n                \"Calling QuerySet.%s() after %s() is not supported.\"\n                % (currentMessage, self.write.combinator)\n            )\n\n    def validateScore(self, entry, localUser):\n        if self.write.combinator or entry.query.combinator:\n            raise TypeError(f\"Cannot use {localUser} operator with combined queryset.\")\n\n    def validateOrder(self, buffer):\n        if (\n            isinstance(self.write.group_by, tuple)\n            # Raise if the pk fields are not in the group_by.\n            and self.model._meta.pk\n            not in {key.output_field for key in self.write.group_by}\n            and set(self.model._meta.pk_fields).difference(\n                {key.target for key in self.write.group_by}\n            )\n        ):\n            raise TypeError(\n                f\"Cannot use QuerySet.{buffer}() on an unordered queryset performing \"\n                f\"aggregation. Add an ordering with order_by().\"\n            )\n\n    def refreshRecord(self, defaultCache, document):\n        pendingMessage = [self.write]\n        for key in document:\n            group = key.query.clone()\n            group.clear_ordering(force=False, clear_default=False)\n            pendingMessage.append(group)\n        defaultCache.combined_queries = tuple(pendingMessage)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-765e7606ef75a519", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "a85600372ff1d01ab30d1d5de3676eb34896aab0217a760b8c7c1f377f472adf", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 2102, "local_path": "identifiers/mislead-identifiers/I03__django__QuerySet__32ea8fb4.py", "order": 3, "original_content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "parent_variant_id": "pyint-5c2b55814568-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/query.py#L374-L2424", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1710, "identifiers_declared": 492, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 15, "local_exact_length_matches": 331, "local_random_pool_selections": 389, "local_total_length_difference": 147, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 317, "method_exact_length_matches": 73, "method_random_pool_selections": 103, "method_total_length_difference": 218}, "unit_kind": "class", "unit_name": "QuerySet", "variant_id": "pyint-8b2732ea8fb4-I03", "group_id": "py-765e7606ef75a519", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 228, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-911b07a52450-I04", "source": "import copy\nimport operator\nimport warnings\nfrom contextlib import nullcontext\nfrom functools import partial, reduce\nfrom itertools import chain, islice\nfrom weakref import ref as weak_ref\nfrom asgiref.sync import sync_to_async\nimport django\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.db import (\n    DJANGO_VERSION_PICKLE_KEY,\n    IntegrityError,\n    NotSupportedError,\n    connections,\n    router,\n    transaction,\n)\nfrom django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql\nfrom django.db.models.constants import LOOKUP_SEP, OnConflict\nfrom django.db.models.deletion import Collector\nfrom django.db.models.expressions import (\n    Case,\n    Col,\n    ColPairs,\n    DatabaseDefault,\n    F,\n    OrderBy,\n    Value,\n    When,\n)\nfrom django.db.models.fetch_modes import FETCH_ONE\nfrom django.db.models.functions import Cast, Trunc\nfrom django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q\nfrom django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT\nfrom django.db.models.utils import (\n    AltersData,\n    create_namedtuple_class,\n    resolve_callables,\n)\nfrom django.utils import timezone\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    RemovedInDjango71Warning,\n    warn_about_external_use,\n)\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import func_accepts_kwargs, func_supports_parameter\nfrom django.utils.warnings import django_file_prefixes\n\nclass QuerySet(AltersData):\n    \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n    def __init__(self, bi=None, bj=None, bk=None, bl=None):\n        self.model = bi\n        self._db = bk\n        self._hints = bl or {}\n        self._query = bj or sql.Query(self.model)\n        self._result_cache = None\n        self._sticky_filter = False\n        self._for_write = False\n        self._prefetch_related_lookups = ()\n        self._prefetch_done = False\n        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}\n        self._iterable_class = ModelIterable\n        self._fetch_mode = DEFAULT_FETCH_MODE\n        self._fields = None\n        self._defer_next_filter = False\n        self._deferred_filter = None\n        self._cloning_enabled = True\n\n    @property\n    def b(self):\n        if self._deferred_filter:\n            bm, bn, bo = self._deferred_filter\n            self.ar(bm, bn, bo)\n            self._deferred_filter = None\n        return self._query\n\n    @query.setter\n    def b(self, bp):\n        if bp.values_select:\n            self._iterable_class = ValuesIterable\n        self._query = bp\n\n    def d(cls):\n        # Address the circular dependency between `Queryset` and `Manager`.\n        from django.db.models.manager import Manager\n\n        bq = Manager.from_queryset(cls)()\n        bq._built_with_as_manager = True\n        return bq\n\n    as_manager.queryset_only = True\n    as_manager = classmethod(as_manager)\n\n    ########################\n    # PYTHON MAGIC METHODS #\n    ########################\n\n    def __deepcopy__(self, br):\n        \"\"\"Don't populate the QuerySet's cache.\"\"\"\n        bs = self.__class__()\n        for bt, bu in self.__dict__.items():\n            if bt == \"_result_cache\":\n                bs.__dict__[bt] = None\n            else:\n                bs.__dict__[bt] = copy.deepcopy(bu, br)\n        return bs\n\n    def __getstate__(self):\n        # Force the cache to be fully populated.\n        self.aW()\n        return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n    def __setstate__(self, bv):\n        bw = bv.get(DJANGO_VERSION_PICKLE_KEY)\n        if bw:\n            if bw != django.__version__:\n                warnings.warn(\n                    \"Pickled queryset instance's Django version %s does not \"\n                    \"match the current version %s.\"\n                    % (bw, django.__version__),\n                    RuntimeWarning,\n                    stacklevel=2,\n                )\n        else:\n            warnings.warn(\n                \"Pickled queryset instance's Django version is not specified.\",\n                RuntimeWarning,\n                stacklevel=2,\n            )\n        self.__dict__.update(bv)\n\n    def __repr__(self):\n        bx = list(self[: REPR_OUTPUT_SIZE + 1])\n        if len(bx) > REPR_OUTPUT_SIZE:\n            bx[-1] = \"...(remaining elements truncated)...\"\n        return \"<%s %r>\" % (self.__class__.__name__, bx)\n\n    def __len__(self):\n        self.aW()\n        return len(self._result_cache)\n\n    def __iter__(self):\n        \"\"\"\n        The queryset iterator protocol uses three nested iterators in the\n        default case:\n            1. sql.compiler.execute_sql()\n               - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n                 using cursor.fetchmany(). This part is responsible for\n                 doing some column masking, and returning the rows in chunks.\n            2. sql.compiler.results_iter()\n               - Returns one row at time. At this point the rows are still just\n                 tuples. In some cases the return values are converted to\n                 Python values at this location.\n            3. self.iterator()\n               - Responsible for turning the rows into model objects.\n        \"\"\"\n        self.aW()\n        return iter(self._result_cache)\n\n    def __aiter__(self):\n        # Remember, __aiter__ itself is synchronous, it's the thing it returns\n        # that is async!\n        async def generator():\n            await sync_to_async(self.aW)()\n            for by in self._result_cache:\n                yield by\n\n        return generator()\n\n    def __bool__(self):\n        self.aW()\n        return bool(self._result_cache)\n\n    def __getitem__(self, bz):\n        \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n        if not isinstance(bz, (int, slice)):\n            raise TypeError(\n                \"QuerySet indices must be integers or slices, not %s.\"\n                % type(bz).__name__\n            )\n        if (isinstance(bz, int) and bz < 0) or (\n            isinstance(bz, slice)\n            and (\n                (bz.start is not None and bz.start < 0)\n                or (bz.stop is not None and bz.stop < 0)\n            )\n        ):\n            raise ValueError(\"Negative indexing is not supported.\")\n\n        if self._result_cache is not None:\n            return self._result_cache[bz]\n\n        if isinstance(bz, slice):\n            bC = self.aU()\n            if bz.start is not None:\n                bA = int(bz.start)\n            else:\n                bA = None\n            if bz.stop is not None:\n                bB = int(bz.stop)\n            else:\n                bB = None\n            bC.query.set_limits(bA, bB)\n            return list(bC)[:: bz.step] if bz.step else bC\n\n        bC = self.aU()\n        bC.query.set_limits(bz, bz + 1)\n        bC._fetch_all()\n        return bC._result_cache[0]\n\n    def __class_getitem__(cls, *bD, **bE):\n        return cls\n\n    def __and__(self, bF):\n        self.bf(bF, \"&\")\n        self.aY(bF)\n        if isinstance(bF, EmptyQuerySet):\n            return bF\n        if isinstance(self, EmptyQuerySet):\n            return self\n        bG = self.aU()\n        bG._merge_known_related_objects(bF)\n        bG.query.combine(bF.query, sql.AND)\n        return bG\n\n    def __or__(self, bH):\n        self.bf(bH, \"|\")\n        self.aY(bH)\n        if isinstance(self, EmptyQuerySet):\n            return bH\n        if isinstance(bH, EmptyQuerySet):\n            return self\n        bI = (\n            self\n            if self.b.can_filter()\n            else self.model._base_manager.filter(pk__in=self.ai(\"pk\"))\n        )\n        bJ = bI._chain()\n        bJ._merge_known_related_objects(bH)\n        if not bH.query.can_filter():\n            bH = bH.model._base_manager.filter(pk__in=bH.values(\"pk\"))\n        bJ.query.combine(bH.query, sql.OR)\n        return bJ\n\n    def __xor__(self, bK):\n        self.bf(bK, \"^\")\n        self.aY(bK)\n        if isinstance(self, EmptyQuerySet):\n            return bK\n        if isinstance(bK, EmptyQuerySet):\n            return self\n        bL = (\n            self\n            if self.b.can_filter()\n            else self.model._base_manager.filter(pk__in=self.ai(\"pk\"))\n        )\n        bM = bL._chain()\n        bM._merge_known_related_objects(bK)\n        if not bK.query.can_filter():\n            bK = bK.model._base_manager.filter(pk__in=bK.values(\"pk\"))\n        bM.query.combine(bK.query, sql.XOR)\n        return bM\n\n    ####################################\n    # METHODS THAT DO DATABASE QUERIES #\n    ####################################\n\n    def e(self, bN, bO):\n        bP = self._iterable_class(\n            self,\n            chunked_fetch=bN,\n            chunk_size=bO or 2000,\n        )\n        if not self._prefetch_related_lookups or bO is None:\n            yield from bP\n            return\n\n        bQ = iter(bP)\n        while bR := list(islice(bQ, bO)):\n            prefetch_related_objects(bR, *self._prefetch_related_lookups)\n            yield from bR\n\n    def g(self, bS=None):\n        \"\"\"\n        An iterator over the results from applying this QuerySet to the\n        database. chunk_size must be provided for QuerySets that prefetch\n        related objects. Otherwise, a default chunk_size of 2000 is supplied.\n        \"\"\"\n        if bS is None:\n            if self._prefetch_related_lookups:\n                raise ValueError(\n                    \"chunk_size must be provided when using QuerySet.iterator() after \"\n                    \"prefetch_related().\"\n                )\n        elif bS <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        bT = not connections[self.aO].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        return self.e(bT, bS)\n\n    async def h(self, bU=None):\n        \"\"\"\n        An asynchronous iterator over the results from applying this QuerySet\n        to the database.\n        \"\"\"\n        if bU is None:\n            if self._prefetch_related_lookups:\n                # RemovedInDjango71Warning: Replace the warning with:\n                # raise ValueError(\n                #     \"chunk_size must be provided when using \"\n                #     \"QuerySet.aiterator() after prefetch_related().\"\n                # )\n                warnings.warn(\n                    \"Using QuerySet.aiterator() after prefetch_related() without \"\n                    \"providing a chunk_size is deprecated and will raise a \"\n                    \"ValueError in Django 7.1.\",\n                    category=RemovedInDjango71Warning,\n                    skip_file_prefixes=django_file_prefixes(),\n                )\n                # RemovedInDjango71Warning: When the deprecation ends, remove.\n                bU = 2000\n        elif bU <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        bV = not connections[self.aO].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        bW = self._iterable_class(\n            self,\n            chunked_fetch=bV,\n            chunk_size=bU or 2000,\n        )\n        if self._prefetch_related_lookups:\n            bX = []\n\n            async for bY in bW:\n                bX.append(bY)\n                if len(bX) >= bU:\n                    await aprefetch_related_objects(\n                        bX, *self._prefetch_related_lookups\n                    )\n                    for bZ in bX:\n                        yield bZ\n                    bX.clear()\n\n            if bX:\n                await aprefetch_related_objects(\n                    bX, *self._prefetch_related_lookups\n                )\n                for bZ in bX:\n                    yield bZ\n        else:\n            async for bY in bW:\n                yield bY\n\n    def j(self, *ca, **cb):\n        \"\"\"\n        Return a dictionary containing the calculations (aggregation)\n        over the current queryset.\n\n        If args is present the expression is passed as a kwarg using\n        the Aggregate object's default alias.\n        \"\"\"\n        if self.b.distinct_fields:\n            raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n        self.bd(\n            (*ca, *cb.values()), method_name=\"aggregate\"\n        )\n        for cc in ca:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                cc.default_alias\n            except (AttributeError, TypeError):\n                raise TypeError(\"Complex aggregates require an alias\")\n            cb[cc.default_alias] = cc\n\n        return self.b.chain().get_aggregation(self.aO, cb)\n\n    async def l(self, *cd, **ce):\n        return await sync_to_async(self.j)(*cd, **ce)\n\n    def m(self):\n        \"\"\"\n        Perform a SELECT COUNT() and return the number of records as an\n        integer.\n\n        If the QuerySet is already fully cached, return the length of the\n        cached results set to avoid multiple SELECT COUNT(*) calls.\n        \"\"\"\n        if self._result_cache is not None:\n            return len(self._result_cache)\n\n        return self.b.get_count(using=self.aO)\n\n    async def n(self):\n        return await sync_to_async(self.m)()\n\n    def o(self, *cf, **cg):\n        \"\"\"\n        Perform the query and return a single object matching the given\n        keyword arguments.\n        \"\"\"\n        if self.b.combinator and (cf or cg):\n            raise NotSupportedError(\n                \"Calling QuerySet.get(...) with filters after %s() is not \"\n                \"supported.\" % self.b.combinator\n            )\n        ch = self.aU() if self.b.combinator else self.ao(*cf, **cg)\n        if self.b.can_filter() and not self.b.distinct_fields:\n            ch = ch.order_by()\n        ci = None\n        if (\n            not ch.query.select_for_update\n            or connections[ch.db].features.supports_select_for_update_with_limit\n        ):\n            ci = MAX_GET_RESULTS\n            ch.query.set_limits(high=ci)\n        cj = len(ch)\n        if cj == 1:\n            return ch._result_cache[0]\n        if not cj:\n            raise self.model.DoesNotExist(\n                \"%s matching query does not exist.\" % self.model._meta.object_name\n            )\n        raise self.model.MultipleObjectsReturned(\n            \"get() returned more than one %s -- it returned %s!\"\n            % (\n                self.model._meta.object_name,\n                cj if not ci or cj < ci else \"more than %s\" % (ci - 1),\n            )\n        )\n\n    async def p(self, *ck, **cl):\n        return await sync_to_async(self.o)(*ck, **cl)\n\n    def r(self, **cm):\n        \"\"\"\n        Create a new object with the given kwargs, saving it to the database\n        and returning the created object.\n        \"\"\"\n        cn = frozenset(cm).intersection(\n            self.model._meta._reverse_one_to_one_field_names\n        )\n        if cn:\n            raise ValueError(\n                \"The following fields do not exist in this model: %s\"\n                % \", \".join(cn)\n            )\n\n        co = self.model(**cm)\n        self._for_write = True\n        co.save(force_insert=True, using=self.aO)\n        co._state.fetch_mode = self._fetch_mode\n        return co\n\n    create.alters_data = True\n\n    async def s(self, **cp):\n        return await sync_to_async(self.r)(**cp)\n\n    acreate.alters_data = True\n\n    def t(self, cq):\n        cr, cs = [], []\n        for ct in cq:\n            ct._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n            if isinstance(ct.pk, DatabaseDefault):\n                cs.append(ct)\n            elif ct._is_pk_set():\n                cr.append(ct)\n            else:\n                ct.pk = ct._meta.pk.get_pk_value_on_save(ct)\n                if ct._is_pk_set():\n                    cr.append(ct)\n                else:\n                    cs.append(ct)\n        return cr, cs\n\n    def u(\n        self, cu, cv, cw, cx\n    ):\n        if cu and cv:\n            raise ValueError(\n                \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n            )\n        cy = connections[self.aO].features\n        if cu:\n            if not cy.supports_ignore_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support ignoring conflicts.\"\n                )\n            return OnConflict.IGNORE\n        elif cv:\n            if not cy.supports_update_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support updating conflicts.\"\n                )\n            if not cw:\n                raise ValueError(\n                    \"Fields that will be updated when a row insertion fails \"\n                    \"on conflicts must be provided.\"\n                )\n            if cx and not cy.supports_update_conflicts_with_target:\n                raise NotSupportedError(\n                    \"This database backend does not support updating \"\n                    \"conflicts with specifying unique fields that can trigger \"\n                    \"the upsert.\"\n                )\n            if not cx and cy.supports_update_conflicts_with_target:\n                raise ValueError(\n                    \"Unique fields that can trigger the upsert must be provided.\"\n                )\n            # Updating primary keys and non-concrete fields is forbidden.\n            if any(not cz.concrete for cz in cw):\n                raise ValueError(\n                    \"bulk_create() can only be used with concrete fields in \"\n                    \"update_fields.\"\n                )\n            if any(cz in self.model._meta.pk_fields for cz in cw):\n                raise ValueError(\n                    \"bulk_create() cannot be used with primary keys in \"\n                    \"update_fields.\"\n                )\n            if cx:\n                if any(not cz.concrete for cz in cx):\n                    raise ValueError(\n                        \"bulk_create() can only be used with concrete fields \"\n                        \"in unique_fields.\"\n                    )\n            return OnConflict.UPDATE\n        return None\n\n    def w(\n        self,\n        cA,\n        cB=None,\n        cC=False,\n        cD=False,\n        cE=None,\n        cF=None,\n    ):\n        \"\"\"\n        Insert each of the instances into the database. Do *not* call\n        save() on each of the instances, do not send any pre/post_save\n        signals, and do not set the primary key attribute if it is an\n        autoincrement field (except if\n        features.can_return_rows_from_bulk_insert=True).\n        Multi-table models are not supported.\n        \"\"\"\n        # When you bulk insert you don't get the primary keys back (if it's an\n        # autoincrement, except if can_return_rows_from_bulk_insert=True), so\n        # you can't insert into the child tables which references this. There\n        # are two workarounds:\n        # 1) This could be implemented if you didn't have an autoincrement pk\n        # 2) You could do it by doing O(n) normal inserts into the parent\n        #    tables to get the primary keys back and then doing a single bulk\n        #    insert into the childmost table.\n        # We currently set the primary keys on the objects when using\n        # PostgreSQL via the RETURNING ID clause. It should be possible for\n        # Oracle as well, but the semantics for extracting the primary keys is\n        # trickier so it's not done yet.\n        if cB is not None and cB <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        # Check that the parents share the same concrete model with the our\n        # model to detect the inheritance pattern ConcreteGrandParent ->\n        # MultiTableParent -> ProxyChild. Simply checking\n        # self.model._meta.proxy would not identify that case as involving\n        # multiple tables.\n        for cG in self.model._meta.all_parents:\n            if cG._meta.concrete_model is not self.model._meta.concrete_model:\n                raise ValueError(\"Can't bulk create a multi-table inherited model\")\n        if not cA:\n            return cA\n        cH = self.model._meta\n        if cF:\n            # Primary key is allowed in unique_fields.\n            cF = [\n                self.model._meta.get_field(cH.pk.name if cI == \"pk\" else cI)\n                for cI in cF\n            ]\n        if cE:\n            cE = [self.model._meta.get_field(cI) for cI in cE]\n        cJ = self.u(\n            cC,\n            cD,\n            cE,\n            cF,\n        )\n        self._for_write = True\n        cK = [cL for cL in cH.concrete_fields if not cL.generated]\n        cA = list(cA)\n        cM, cN = self.t(cA)\n        if cM and cN:\n            cO = transaction.atomic(using=self.aO, savepoint=False)\n        else:\n            cO = nullcontext()\n        with cO:\n            self.x(cA)\n            if cM:\n                cP = self.aQ(\n                    cM,\n                    cK,\n                    cB,\n                    on_conflict=cJ,\n                    update_fields=cE,\n                    unique_fields=cF,\n                )\n                for cT, cQ in zip(cM, cP):\n                    for cR, cS in zip(cQ, cH.db_returning_fields):\n                        setattr(cT, cS.attname, cR)\n                for cT in cM:\n                    cT._state.adding = False\n                    cT._state.db = self.aO\n            if cN:\n                cK = [cL for cL in cK if not isinstance(cL, AutoField)]\n                cP = self.aQ(\n                    cN,\n                    cK,\n                    cB,\n                    on_conflict=cJ,\n                    update_fields=cE,\n                    unique_fields=cF,\n                )\n                cU = connections[self.aO]\n                if (\n                    cU.features.can_return_rows_from_bulk_insert\n                    and cJ is None\n                ):\n                    assert len(cP) == len(cN)\n                for cV, cQ in zip(cN, cP):\n                    for cR, cS in zip(cQ, cH.db_returning_fields):\n                        setattr(cV, cS.attname, cR)\n                    cV._state.adding = False\n                    cV._state.db = self.aO\n\n        return cA\n\n    def x(self, cW):\n        if cW and (cX := self.model._meta.order_with_respect_to):\n            cY = cX.get_filter_kwargs_for_object\n            cZ = list(cY(cW[0]))\n            da = set()\n            dc = []\n            for dd in cW:\n                de = tuple(cY(dd).values())\n                da.add(de)\n                dc.append((dd, de))\n            df = [\n                Q.create(list(zip(cZ, de))) for de in da\n            ]\n            dg = (\n                self.model._base_manager.using(self.aO)\n                .filter(reduce(operator.or_, df))\n                .values_list(*cZ)\n                .annotate(_order__max=Max(\"_order\") + 1)\n            )\n            # Create mapping of group values to max order.\n            dh = dict.fromkeys(da, 0)\n            dh.update(\n                (tuple(de), di) for *de, di in dg\n            )\n            # Assign _order values to new objects.\n            for dd, de in dc:\n                if getattr(dd, \"_order\", None) is None:\n                    dj = dh[de]\n                    dd._order = dj\n                    dh[de] += 1\n\n    bulk_create.alters_data = True\n\n    async def y(\n        self,\n        dk,\n        dl=None,\n        dm=False,\n        dn=False,\n        do=None,\n        dp=None,\n    ):\n        return await sync_to_async(self.w)(\n            objs=dk,\n            batch_size=dl,\n            ignore_conflicts=dm,\n            update_conflicts=dn,\n            update_fields=do,\n            unique_fields=dp,\n        )\n\n    abulk_create.alters_data = True\n\n    def z(self, dq, dr, ds=None):\n        \"\"\"\n        Update the given fields in each of the given objects in the database.\n        \"\"\"\n        if ds is not None and ds <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        if not dr:\n            raise ValueError(\"Field names must be given to bulk_update().\")\n        dq = tuple(dq)\n        if not all(dy._is_pk_set() for dy in dq):\n            raise ValueError(\"All bulk_update() objects must have a primary key set.\")\n        dt = self.model._meta\n        dr = [dt.get_field(du) for du in dr]\n        if any(not dv.concrete for dv in dr):\n            raise ValueError(\"bulk_update() can only be used with concrete fields.\")\n        dw = set(dt.pk_fields)\n        for dx in dt.all_parents:\n            dw.update(dx._meta.pk_fields)\n        if any(dv in dw for dv in dr):\n            raise ValueError(\"bulk_update() cannot be used with primary key fields.\")\n        if not dq:\n            return 0\n        for dy in dq:\n            dy._prepare_related_fields_for_save(\n                operation_name=\"bulk_update\", fields=dr\n            )\n        # PK is used twice in the resulting update query, once in the filter\n        # and once in the WHEN. Each field will also have one CAST.\n        self._for_write = True\n        dz = connections[self.aO]\n        dA = dz.ops.bulk_batch_size(\n            [dt.pk, dt.pk, *dr], dq\n        )\n        ds = min(ds, dA) if ds else dA\n        dB = dz.features.requires_casted_case_in_updates\n        dC = (dq[dD : dD + ds] for dD in range(0, len(dq), ds))\n        dE = []\n        for dF in dC:\n            dG = {}\n            for dH in dr:\n                dI = []\n                for dy in dF:\n                    dJ = getattr(dy, dH.attname)\n                    if not hasattr(dJ, \"resolve_expression\"):\n                        dJ = Value(dJ, output_field=dH)\n                    dI.append(When(pk=dy.pk, then=dJ))\n                dK = Case(*dI, output_field=dH)\n                if dB:\n                    dK = Cast(dK, output_field=dH)\n                dG[dH.attname] = dK\n            dE.append(([dy.pk for dy in dF], dG))\n        dL = 0\n        dM = self.aK(self.aO)\n        with transaction.atomic(using=self.aO, savepoint=False):\n            for dN, dG in dE:\n                dL += dM.filter(pk__in=dN).update(**dG)\n        return dL\n\n    bulk_update.alters_data = True\n\n    async def A(self, dO, dP, dQ=None):\n        return await sync_to_async(self.z)(\n            objs=dO,\n            fields=dP,\n            batch_size=dQ,\n        )\n\n    abulk_update.alters_data = True\n\n    def B(self, dR=None, **dS):\n        \"\"\"\n        Look up an object with the given kwargs, creating one if necessary.\n        Return a tuple of (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        # The get() needs to be targeted at the write database in order\n        # to avoid potential transaction consistency problems.\n        self._for_write = True\n        try:\n            return self.o(**dS), False\n        except self.model.DoesNotExist:\n            dT = self.G(dR, **dS)\n            # Try to create an object using passed params.\n            try:\n                with transaction.atomic(using=self.aO):\n                    dT = dict(resolve_callables(dT))\n                    return self.r(**dT), True\n            except IntegrityError:\n                try:\n                    return self.o(**dS), False\n                except self.model.DoesNotExist:\n                    pass\n                raise\n\n    get_or_create.alters_data = True\n\n    async def C(self, dU=None, **dV):\n        return await sync_to_async(self.B)(\n            defaults=dU,\n            **dV,\n        )\n\n    aget_or_create.alters_data = True\n\n    def D(self, dW=None, dX=None, **dY):\n        \"\"\"\n        Look up an object with the given kwargs, updating one with defaults\n        if it exists, otherwise create a new one. Optionally, an object can\n        be created with different values than defaults by using\n        create_defaults.\n        Return a tuple (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        dZ = dW or {}\n        if dX is None:\n            dX = dZ\n\n        self._for_write = True\n        with transaction.atomic(using=self.aO):\n            # Lock the row so that a concurrent update is blocked until\n            # update_or_create() has performed its save.\n            ea, eb = self.ay().get_or_create(\n                dX, **dY\n            )\n            if eb:\n                return ea, eb\n            for ec, ed in resolve_callables(dZ):\n                setattr(ea, ec, ed)\n\n            ee = set(dZ)\n            ef = self.model._meta._non_pk_concrete_field_names\n            # update_fields does not support non-concrete fields.\n            if ef.issuperset(ee):\n                # Add fields which are set on pre_save(), e.g. auto_now fields.\n                # This is to maintain backward compatibility as these fields\n                # are not updated unless explicitly specified in the\n                # update_fields list.\n                eg = self.model._meta.pk_fields\n                for eh in self.model._meta.local_concrete_fields:\n                    if not (\n                        eh in eg or eh.__class__.pre_save is Field.pre_save\n                    ):\n                        ee.add(eh.name)\n                        if eh.name != eh.attname:\n                            ee.add(eh.attname)\n                ea.save(using=self.aO, update_fields=ee)\n            else:\n                ea.save(using=self.aO)\n        return ea, False\n\n    update_or_create.alters_data = True\n\n    async def E(self, ei=None, ej=None, **ek):\n        return await sync_to_async(self.D)(\n            defaults=ei,\n            create_defaults=ej,\n            **ek,\n        )\n\n    aupdate_or_create.alters_data = True\n\n    def G(self, el, **em):\n        \"\"\"\n        Prepare `params` for creating a model instance based on the given\n        kwargs; for use by get_or_create().\n        \"\"\"\n        el = el or {}\n        en = {eo: ep for eo, ep in em.items() if LOOKUP_SEP not in eo}\n        en.update(el)\n        eq = self.model._meta._property_names\n        er = []\n        for es in en:\n            try:\n                self.model._meta.get_field(es)\n            except exceptions.FieldDoesNotExist:\n                # It's okay to use a model's property if it has a setter.\n                if not (es in eq and getattr(self.model, es).fset):\n                    er.append(es)\n        if er:\n            raise exceptions.FieldError(\n                \"Invalid field name(s) for model %s: '%s'.\"\n                % (\n                    self.model._meta.object_name,\n                    \"', '\".join(sorted(er)),\n                )\n            )\n        return en\n\n    def H(self, *et):\n        \"\"\"\n        Return the earliest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if et:\n            eu = et\n        else:\n            eu = getattr(self.model._meta, \"get_latest_by\")\n            if eu and not isinstance(eu, (tuple, list)):\n                eu = (eu,)\n        if eu is None:\n            raise ValueError(\n                \"earliest() and latest() require either fields as positional \"\n                \"arguments or 'get_latest_by' in the model's Meta.\"\n            )\n        ev = self.aU()\n        ev.query.set_limits(high=1)\n        ev.query.clear_ordering(force=True)\n        ev.query.add_ordering(*eu)\n        return ev.get()\n\n    def I(self, *ew):\n        if self.b.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.H(*ew)\n\n    async def J(self, *ex):\n        return await sync_to_async(self.I)(*ex)\n\n    def K(self, *ey):\n        \"\"\"\n        Return the latest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if self.b.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.aH()._earliest(*ey)\n\n    async def L(self, *ez):\n        return await sync_to_async(self.K)(*ez)\n\n    def M(self):\n        \"\"\"Return the first object of a query or None if no match is found.\"\"\"\n        if self.aM or not self.b.default_ordering:\n            eA = self\n        else:\n            self.bg(method=\"first\")\n            eA = self.aE(\"pk\")\n        for eB in eA[:1]:\n            return eB\n\n    async def N(self):\n        return await sync_to_async(self.M)()\n\n    def O(self):\n        \"\"\"Return the last object of a query or None if no match is found.\"\"\"\n        if self.aM or not self.b.default_ordering:\n            eC = self.aH()\n        else:\n            self.bg(method=\"last\")\n            eC = self.aE(\"-pk\")\n        for eD in eC[:1]:\n            return eD\n\n    async def P(self):\n        return await sync_to_async(self.O)()\n\n    def R(self, eE=None, *, eF=\"pk\"):\n        \"\"\"\n        Return a dictionary mapping each of the given IDs to the object with\n        that ID. If `id_list` isn't provided, evaluate the entire QuerySet.\n        \"\"\"\n        if self.b.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with in_bulk().\")\n        if eE is not None and not eE:\n            return {}\n        eG = self.model._meta\n        eH = [\n            eI.fields[0]\n            for eI in eG.total_unique_constraints\n            if len(eI.fields) == 1\n        ]\n        if (\n            eF != \"pk\"\n            and not eG.get_field(eF).unique\n            and eF not in eH\n            and self.b.distinct_fields != (eF,)\n        ):\n            raise ValueError(\n                \"in_bulk()'s field_name must be a unique field but %r isn't.\"\n                % eF\n            )\n\n        eJ = self\n\n        def get_obj(eU):\n            return eU\n\n        if issubclass(self._iterable_class, ModelIterable):\n            # Raise an AttributeError if field_name is deferred.\n            eK = operator.attrgetter(eF)\n\n        elif issubclass(self._iterable_class, ValuesIterable):\n            if eF not in self.b.values_select:\n                eJ = eJ.values(eF, *self.b.values_select)\n\n                def get_obj(eV):  # noqa: F811\n                    # We can safely mutate the dictionaries returned by\n                    # ValuesIterable here, since they are limited to the scope\n                    # of this function, and get_key runs before get_obj.\n                    del eV[field_name]\n                    return eV\n\n            eK = operator.itemgetter(eF)\n\n        elif issubclass(self._iterable_class, ValuesListIterable):\n            try:\n                eL = self.b.values_select.index(eF)\n            except ValueError:\n                # field_name is missing from values_select, so add it.\n                eL = 0\n                if issubclass(self._iterable_class, NamedValuesListIterable):\n                    eM = {\"named\": True}\n                else:\n                    eM = {}\n                    eN = operator.itemgetter(slice(1, None))\n                eJ = eJ.values_list(eF, *self.b.values_select, **eM)\n\n            eK = operator.itemgetter(eL)\n\n        elif issubclass(self._iterable_class, FlatValuesListIterable):\n            if self.b.values_select == (eF,):\n                # Mapping field_name to itself.\n                eK = eN\n            else:\n                # Transform it back into a non-flat values_list().\n                eJ = eJ.values_list(eF, *self.b.values_select)\n                eK = operator.itemgetter(0)\n                eN = operator.itemgetter(1)\n\n        else:\n            raise TypeError(\n                f\"in_bulk() cannot be used with {self._iterable_class.__name__}.\"\n            )\n\n        if eE is not None:\n            eO = \"{}__in\".format(eF)\n            eE = tuple(eE)\n            eP = connections[self.aO].ops.bulk_batch_size([eG.pk], eE)\n            # If the database has a limit on the number of query parameters\n            # (e.g. SQLite), retrieve objects in batches if necessary.\n            if eP and eP < len(eE):\n                eQ = ()\n                for eR in range(0, len(eE), eP):\n                    eS = eE[eR : eR + eP]\n                    eQ += tuple(eJ.filter(**{eO: eS}))\n                eJ = eQ\n            else:\n                eJ = eJ.filter(**{eO: eE})\n        else:\n            eJ = eJ._chain()\n        return {eK(eT): eN(eT) for eT in eJ}\n\n    async def S(self, eW=None, *, eX=\"pk\"):\n        return await sync_to_async(self.R)(\n            id_list=eW,\n            field_name=eX,\n        )\n\n    def T(self):\n        \"\"\"Delete the records in the current QuerySet.\"\"\"\n        self.be(\"delete\")\n        if self.b.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with delete().\")\n        if self.b.distinct_fields:\n            raise TypeError(\"Cannot call delete() after .distinct(*fields).\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call delete() after .values() or .values_list()\")\n\n        eY = self.aU()\n\n        # The delete is actually 2 queries - one to find related objects,\n        # and one to delete. Make sure that the discovery of related\n        # objects is performed on the same database as the deletion.\n        eY._for_write = True\n\n        # Disable non-supported fields.\n        eY.query.select_for_update = False\n        eY.query.select_related = False\n        eY.query.clear_ordering(force=True)\n\n        eZ = Collector(using=eY.db, origin=self)\n        eZ.collect(eY)\n        fa, fb = eZ.delete()\n\n        # Clear the result cache, in case this QuerySet gets reused.\n        self._result_cache = None\n        return fa, fb\n\n    delete.alters_data = True\n    delete.queryset_only = True\n\n    async def U(self):\n        return await sync_to_async(self.T)()\n\n    adelete.alters_data = True\n    adelete.queryset_only = True\n\n    def V(self, fc):\n        \"\"\"\n        Delete objects found from the given queryset in single direct SQL\n        query. No signals are sent and there is no protection for cascades.\n        \"\"\"\n        fd = self.b.clone()\n        fd.__class__ = sql.DeleteQuery\n        return fd.get_compiler(fc).execute_sql(ROW_COUNT)\n\n    _raw_delete.alters_data = True\n\n    def W(self, **fe):\n        \"\"\"\n        Update all elements in the current QuerySet, setting all the given\n        fields to the appropriate values.\n        \"\"\"\n        self.be(\"update\")\n        if self.b.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        if self.b.distinct_fields:\n            raise TypeError(\"Cannot call update() after .distinct(*fields).\")\n        self._for_write = True\n        ff = self.b.chain(sql.UpdateQuery)\n        ff.add_update_values(fe)\n\n        # Inline annotations in order_by(), if possible.\n        fg = []\n        for fh in ff.order_by:\n            fi = fh\n            fj = False\n            if isinstance(fi, str) and fi.startswith(\"-\"):\n                fi = fi.removeprefix(\"-\")\n                fj = True\n            if fk := ff.annotations.get(fi):\n                if getattr(fk, \"contains_aggregate\", False):\n                    raise exceptions.FieldError(\n                        f\"Cannot update when ordering by an aggregate: {fk}\"\n                    )\n                if fj:\n                    fk = fk.desc()\n                fg.append(fk)\n            else:\n                fg.append(fh)\n        ff.order_by = tuple(fg)\n\n        # Clear SELECT clause as all annotation references were inlined by\n        # add_update_values() already.\n        ff.clear_select_clause()\n        with transaction.mark_for_rollback_on_error(using=self.aO):\n            fl = ff.get_compiler(self.aO).execute_sql(ROW_COUNT)\n        self._result_cache = None\n        return fl\n\n    update.alters_data = True\n\n    async def X(self, **fm):\n        return await sync_to_async(self.W)(**fm)\n\n    aupdate.alters_data = True\n\n    def Y(self, fn, fo=None):\n        \"\"\"\n        A version of update() that accepts field objects instead of field\n        names. Used primarily for model saving and not intended for use by\n        general code (it requires too much poking around at model internals to\n        be useful at that level).\n        \"\"\"\n        if self.b.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        fp = self.b.chain(sql.UpdateQuery)\n        fp.add_update_fields(fn)\n        # Clear any annotations so that they won't be present in subqueries.\n        fp.annotations = {}\n        self._result_cache = None\n        if fo is None:\n            return fp.get_compiler(self.aO).execute_sql(ROW_COUNT)\n        return fp.get_compiler(self.aO).execute_returning_sql(fo)\n\n    _update.alters_data = True\n    _update.queryset_only = False\n\n    def Z(self):\n        \"\"\"\n        Return True if the QuerySet would have any results, False otherwise.\n        \"\"\"\n        if self._result_cache is None:\n            return self.b.has_results(using=self.aO)\n        return bool(self._result_cache)\n\n    async def aa(self):\n        return await sync_to_async(self.Z)()\n\n    def ab(self, fq):\n        \"\"\"\n        Return True if the QuerySet contains the provided obj,\n        False otherwise.\n        \"\"\"\n        self.be(\"contains\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call QuerySet.contains() after .values() or .values_list().\"\n            )\n        try:\n            if fq._meta.concrete_model != self.model._meta.concrete_model:\n                return False\n        except AttributeError:\n            raise TypeError(\"'obj' must be a model instance.\")\n        if not fq._is_pk_set():\n            raise ValueError(\"QuerySet.contains() cannot be used on unsaved objects.\")\n        if self._result_cache is not None:\n            return fq in self._result_cache\n        return self.ao(pk=fq.pk).exists()\n\n    async def ac(self, fr):\n        return await sync_to_async(self.ab)(obj=fr)\n\n    def ad(self):\n        # This method can only be called once the result cache has been filled.\n        prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)\n        self._prefetch_done = True\n\n    def ae(self, *, fs=None, **ft):\n        \"\"\"\n        Runs an EXPLAIN on the SQL query this QuerySet would perform, and\n        returns the results.\n        \"\"\"\n        return self.b.explain(using=self.aO, format=fs, **ft)\n\n    async def af(self, *, fu=None, **fv):\n        return await sync_to_async(self.ae)(format=fu, **fv)\n\n    ##################################################\n    # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #\n    ##################################################\n\n    def ag(self, fw, fx=(), fy=None, fz=None):\n        if fz is None:\n            fz = self.aO\n        fA = RawQuerySet(\n            fw,\n            model=self.model,\n            params=fx,\n            translations=fy,\n            using=fz,\n            fetch_mode=self._fetch_mode,\n        )\n        fA._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        return fA\n\n    def ah(self, *fB, **fC):\n        fD = self.aU()\n        if fC:\n            # RemovedInDjango70Warning: When the deprecation ends, deindent as:\n            # clone = clone.annotate(**expressions)\n            with warnings.catch_warnings(\n                action=\"ignore\", category=RemovedInDjango70Warning\n            ):\n                fD = fD.annotate(**fC)\n        fD._fields = fB\n        fD.query.set_values(fB)\n        return fD\n\n    def ai(self, *fE, **fF):\n        fE += tuple(fF)\n        fG = self.ah(*fE, **fF)\n        fG._iterable_class = ValuesIterable\n        return fG\n\n    def aj(self, *fH, fI=False, fJ=False):\n        if fI and fJ:\n            raise TypeError(\"'flat' and 'named' can't be used together.\")\n        if fI:\n            if len(fH) > 1:\n                raise TypeError(\n                    \"'flat' is not valid when values_list is called with more than one \"\n                    \"field.\"\n                )\n            elif not fH:\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # raise TypeError(\n                #     \"'flat' is not valid when values_list is called with no \"\n                #     \"fields.\"\n                # )\n                warnings.warn(\n                    \"Calling values_list() with no field name and flat=True \"\n                    \"is deprecated. Pass an explicit field name instead, like \"\n                    \"'pk'.\",\n                    RemovedInDjango70Warning,\n                )\n                fH = [self.model._meta.concrete_fields[0].attname]\n\n        fK = {fL: False for fL in fH if not hasattr(fL, \"resolve_expression\")}\n        fM = []\n        fN = {}\n        fO = 1\n        for fP in fH:\n            fQ = fP\n            fR = None\n            if hasattr(fP, \"resolve_expression\"):\n                fQ = getattr(\n                    fP, \"default_alias\", fP.__class__.__name__.lower()\n                )\n                fR = fP\n                # For backward compatibility reasons expressions are always\n                # prefixed with the counter even if their default alias doesn't\n                # collide with field names. Changing this logic could break\n                # some usage of named=True.\n                fS = True\n            elif fS := fK[fQ]:\n                fR = F(fQ)\n            if fS:\n                fT = fQ\n                while (fQ := f\"{fT}{fO}\") in fK:\n                    fO += 1\n            if fR is not None:\n                fN[fQ] = fR\n            fK[fQ] = True\n            fM.append(fQ)\n\n        fU = self.ah(*fM, **fN)\n        fU._iterable_class = (\n            NamedValuesListIterable\n            if fJ\n            else FlatValuesListIterable if fI else ValuesListIterable\n        )\n        return fU\n\n    def ak(self, fV, fW, fX=\"ASC\"):\n        \"\"\"\n        Return a list of date objects representing all available dates for\n        the given field_name, scoped to 'kind'.\n        \"\"\"\n        if fW not in (\"year\", \"month\", \"week\", \"day\"):\n            raise ValueError(\"'kind' must be one of 'year', 'month', 'week', or 'day'.\")\n        if fX not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        return (\n            self.aB(\n                datefield=Trunc(fV, fW, output_field=DateField()),\n                plain_field=F(fV),\n            )\n            .values_list(\"datefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if fX == \"DESC\" else \"\") + \"datefield\")\n        )\n\n    def al(self, fY, fZ, ga=\"ASC\", gb=None):\n        \"\"\"\n        Return a list of datetime objects representing all available\n        datetimes for the given field_name, scoped to 'kind'.\n        \"\"\"\n        if fZ not in (\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"):\n            raise ValueError(\n                \"'kind' must be one of 'year', 'month', 'week', 'day', \"\n                \"'hour', 'minute', or 'second'.\"\n            )\n        if ga not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        if settings.USE_TZ:\n            if gb is None:\n                gb = timezone.get_current_timezone()\n        else:\n            gb = None\n        return (\n            self.aB(\n                datetimefield=Trunc(\n                    fY,\n                    fZ,\n                    output_field=DateTimeField(),\n                    tzinfo=gb,\n                ),\n                plain_field=F(fY),\n            )\n            .values_list(\"datetimefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if ga == \"DESC\" else \"\") + \"datetimefield\")\n        )\n\n    def am(self):\n        \"\"\"Return an empty QuerySet.\"\"\"\n        gc = self.aU()\n        gc.query.set_empty()\n        return gc\n\n    ##################################################################\n    # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #\n    ##################################################################\n\n    def an(self):\n        \"\"\"\n        Return a new QuerySet that is a copy of the current one. This allows a\n        QuerySet to proxy for a model manager in some cases.\n        \"\"\"\n        return self.aU()\n\n    def ao(self, *gd, **ge):\n        \"\"\"\n        Return a new QuerySet instance with the args ANDed to the existing\n        set.\n        \"\"\"\n        self.be(\"filter\")\n        return self.aq(False, gd, ge)\n\n    def ap(self, *gf, **gg):\n        \"\"\"\n        Return a new QuerySet instance with NOT (args) ANDed to the existing\n        set.\n        \"\"\"\n        self.be(\"exclude\")\n        return self.aq(True, gf, gg)\n\n    def aq(self, gh, gi, gj):\n        if (gi or gj) and self.b.is_sliced:\n            raise TypeError(\"Cannot filter a query once a slice has been taken.\")\n        gk = self.aU()\n        if self._defer_next_filter:\n            self._defer_next_filter = False\n            gk._deferred_filter = gh, gi, gj\n        else:\n            gk._filter_or_exclude_inplace(gh, gi, gj)\n        return gk\n\n    def ar(self, gl, gm, gn):\n        if go := PROHIBITED_FILTER_KWARGS.intersection(gn):\n            gp = \", \".join(f\"'{gq}'\" for gq in sorted(go))\n            raise TypeError(f\"The following kwargs are invalid: {gp}\")\n        if gl:\n            self._query.add_q(~Q(*gm, **gn))\n        else:\n            self._query.add_q(Q(*gm, **gn))\n\n    def at(self, gr):\n        \"\"\"\n        Return a new QuerySet instance with filter_obj added to the filters.\n\n        filter_obj can be a Q object or a dictionary of keyword lookup\n        arguments.\n\n        This exists to support framework features such as 'limit_choices_to',\n        and usually it will be more natural to use other methods.\n        \"\"\"\n        if isinstance(gr, Q):\n            gs = self.aU()\n            gs.query.add_q(gr)\n            return gs\n        else:\n            return self.aq(False, args=(), kwargs=gr)\n\n    def au(self, gt, *gu, gv=False):\n        # Clone the query to inherit the select list and everything\n        gw = self.aU()\n        # Clear limits and ordering so they can be reapplied\n        gw.query.clear_ordering(force=True)\n        gw.query.default_ordering = True\n        self.bh(gw.query, gu)\n        gw.query.clear_limits()\n        gw.query.combinator = gt\n        gw.query.combinator_all = gv\n        return gw\n\n    def av(self, *gx, gy=False):\n        # If the query is an EmptyQuerySet, combine all nonempty querysets.\n        if isinstance(self, EmptyQuerySet):\n            gz = [gA for gA in gx if not isinstance(gA, EmptyQuerySet)]\n            if not gz:\n                return self\n            if len(gz) == 1:\n                return gz[0]\n            return gz[0]._combinator_query(\"union\", *gz[1:], all=gy)\n        elif not gx:\n            return self\n        return self.au(\"union\", *gx, all=gy)\n\n    def aw(self, *gB):\n        # If any query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        for gC in gB:\n            if isinstance(gC, EmptyQuerySet):\n                return gC\n        return self.au(\"intersection\", *gB)\n\n    def ax(self, *gD):\n        # If the query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        return self.au(\"difference\", *gD)\n\n    def ay(self, gE=False, gF=False, gG=(), gH=False):\n        \"\"\"\n        Return a new QuerySet instance that will select objects with a\n        FOR UPDATE lock.\n        \"\"\"\n        if gE and gF:\n            raise ValueError(\"The nowait option cannot be used with skip_locked.\")\n        gI = self.aU()\n        gI._for_write = True\n        gI.query.select_for_update = True\n        gI.query.select_for_update_nowait = gE\n        gI.query.select_for_update_skip_locked = gF\n        gI.query.select_for_update_of = gG\n        gI.query.select_for_no_key_update = gH\n        return gI\n\n    def az(self, *gJ):\n        \"\"\"\n        Return a new QuerySet instance that will select related objects.\n\n        If fields are specified, they must be ForeignKey fields and only those\n        related objects are included in the selection.\n\n        If select_related(None) is called, clear the list.\n        \"\"\"\n        self.be(\"select_related\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call select_related() after .values() or .values_list()\"\n            )\n\n        gK = self.aU()\n        if gJ == (None,):\n            gK.query.select_related = False\n        elif gJ:\n            gK.query.add_select_related(gJ)\n        else:\n            # RemovedInDjango70Warning: when the deprecation ends, raise a\n            # TypeError instead.\n            warn_about_external_use(\n                \"Calling select_related() with no arguments is deprecated. \"\n                \"Specify the fields to fetch instead.\",\n                category=RemovedInDjango70Warning,\n                skip_name_prefixes=(\"django.db.models\",),\n            )\n            gK.query.select_related = True\n        return gK\n\n    def aA(self, *gL):\n        \"\"\"\n        Return a new QuerySet instance that will prefetch the specified\n        Many-To-One and Many-To-Many related objects when the QuerySet is\n        evaluated.\n\n        When prefetch_related() is called more than once, append to the list of\n        prefetch lookups. If prefetch_related(None) is called, clear the list.\n        \"\"\"\n        self.be(\"prefetch_related\")\n        gM = self.aU()\n        if gL == (None,):\n            gM._prefetch_related_lookups = ()\n        else:\n            for gN in gL:\n                if isinstance(gN, Prefetch):\n                    gN = gN.prefetch_to\n                gN = gN.split(LOOKUP_SEP, 1)[0]\n                if gN in self.b._filtered_relations:\n                    raise ValueError(\n                        \"prefetch_related() is not supported with FilteredRelation.\"\n                    )\n            gM._prefetch_related_lookups = gM._prefetch_related_lookups + gL\n        return gM\n\n    def aB(self, *gO, **gP):\n        \"\"\"\n        Return a query set in which the returned objects have been annotated\n        with extra data or aggregations.\n        \"\"\"\n        self.be(\"annotate\")\n        return self.aD(gO, gP, select=True)\n\n    def aC(self, *gQ, **gR):\n        \"\"\"\n        Return a query set with added aliases for extra data or aggregations.\n        \"\"\"\n        self.be(\"alias\")\n        return self.aD(gQ, gR, select=False)\n\n    def aD(self, gS, gT, gU=True):\n        self.bd(\n            gS + tuple(gT.values()), method_name=\"annotate\"\n        )\n        gV = {}\n        for gW in gS:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                if gW.default_alias in gT:\n                    raise ValueError(\n                        \"The named annotation '%s' conflicts with the \"\n                        \"default name for another annotation.\" % gW.default_alias\n                    )\n            except (TypeError, AttributeError):\n                raise TypeError(\"Complex annotations require an alias\")\n            gV[gW.default_alias] = gW\n        gV.update(gT)\n\n        gX = self.aU()\n        gY = self._fields\n        if gY is None:\n            gY = set(\n                chain.from_iterable(\n                    (\n                        (gZ.name, gZ.attname)\n                        if hasattr(gZ, \"attname\")\n                        else (gZ.name,)\n                    )\n                    for gZ in self.model._meta.get_fields()\n                )\n            )\n\n        for ha, hb in gV.items():\n            if ha in gY:\n                raise ValueError(\n                    \"The annotation '%s' conflicts with a field on \"\n                    \"the model.\" % ha\n                )\n            if isinstance(hb, FilteredRelation):\n                gX.query.add_filtered_relation(hb, ha)\n            else:\n                gX.query.add_annotation(\n                    hb,\n                    ha,\n                    select=gU,\n                )\n        for ha, hb in gX.query.annotations.items():\n            if ha in gV and hb.contains_aggregate:\n                if gX._fields is None:\n                    gX.query.group_by = True\n                else:\n                    gX.query.set_group_by()\n                break\n\n        return gX\n\n    def aE(self, *hc):\n        \"\"\"Return a new QuerySet instance with the ordering changed.\"\"\"\n        if self.b.is_sliced:\n            raise TypeError(\"Cannot reorder a query once a slice has been taken.\")\n        hd = self.aU()\n        hd.query.clear_ordering(force=True, clear_default=False)\n        hd.query.add_ordering(*hc)\n        return hd\n\n    def aF(self, *he):\n        \"\"\"\n        Return a new QuerySet instance that will select only distinct results.\n        \"\"\"\n        self.be(\"distinct\")\n        if self.b.is_sliced:\n            raise TypeError(\n                \"Cannot create distinct fields once a slice has been taken.\"\n            )\n        hf = self.aU()\n        hf.query.add_distinct_fields(*he)\n        return hf\n\n    def aG(\n        self,\n        hg=None,\n        hh=None,\n        hi=None,\n        hj=None,\n        hk=None,\n        hl=None,\n    ):\n        \"\"\"Add extra SQL fragments to the query.\"\"\"\n        self.be(\"extra\")\n        if self.b.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        hm = self.aU()\n        hm.query.add_extra(hg, hl, hh, hi, hj, hk)\n        return hm\n\n    def aH(self):\n        \"\"\"Reverse the ordering of the QuerySet.\"\"\"\n        if self.b.is_sliced:\n            raise TypeError(\"Cannot reverse a query once a slice has been taken.\")\n        hn = self.aU()\n        hn.query.standard_ordering = not hn.query.standard_ordering\n        return hn\n\n    def aI(self, *ho):\n        \"\"\"\n        Defer the loading of data for certain fields until they are accessed.\n        Add the set of deferred fields to any existing set of deferred fields.\n        The only exception to this is if None is passed in as the only\n        parameter, in which case remove all deferrals.\n        \"\"\"\n        self.be(\"defer\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call defer() after .values() or .values_list()\")\n        hp = self.aU()\n        if ho == (None,):\n            hp.query.clear_deferred_loading()\n        else:\n            hp.query.add_deferred_loading(ho)\n        return hp\n\n    def aJ(self, *hq):\n        \"\"\"\n        Essentially, the opposite of defer(). Only the fields passed into this\n        method and that are not already specified as deferred are loaded\n        immediately when the queryset is evaluated.\n        \"\"\"\n        self.be(\"only\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call only() after .values() or .values_list()\")\n        if hq == (None,):\n            # Can only pass None to defer(), not only(), as the rest option.\n            # That won't stop people trying to do this, so let's be explicit.\n            raise TypeError(\"Cannot pass None as an argument to only().\")\n        for hr in hq:\n            hr = hr.split(LOOKUP_SEP, 1)[0]\n            if hr in self.b._filtered_relations:\n                raise ValueError(\"only() is not supported with FilteredRelation.\")\n        hs = self.aU()\n        hs.query.add_immediate_loading(hq)\n        return hs\n\n    def aK(self, ht):\n        \"\"\"Select which database this QuerySet should execute against.\"\"\"\n        hu = self.aU()\n        hu._db = ht\n        return hu\n\n    def aL(self, hv):\n        \"\"\"Set the fetch mode for the QuerySet.\"\"\"\n        hw = self.aU()\n        hw._fetch_mode = hv\n        return hw\n\n    ###################################\n    # PUBLIC INTROSPECTION ATTRIBUTES #\n    ###################################\n\n    @property\n    def aM(self):\n        \"\"\"\n        Return True if the QuerySet is ordered -- i.e. has an order_by()\n        clause or a default ordering on the model (or is empty).\n        \"\"\"\n        if isinstance(self, EmptyQuerySet):\n            return True\n        if self.b.extra_order_by or self.b.order_by:\n            return True\n        elif (\n            self.b.default_ordering\n            and self.b.get_meta().ordering\n            and\n            # A default ordering doesn't affect GROUP BY queries.\n            not self.b.group_by\n        ):\n            return True\n        else:\n            return False\n\n    @property\n    def aN(self):\n        \"\"\"\n        Returns True if the QuerySet is ordered and the ordering is\n        deterministic. This requires that the ordering includes a field\n        (or set of fields) that is unique and non-nullable.\n\n        For queries involving a GROUP BY clause, the model's default\n        ordering is ignored. Ordering specified via .extra(order_by=...)\n        is also ignored.\n        \"\"\"\n        if not self.aM:\n            return False\n        hx = self.b.order_by\n        if not hx and self.b.default_ordering:\n            hx = self.b.get_meta().ordering\n        if not hx:\n            return False\n        hy = self.model._meta\n        hz = {hA.attname for hA in hy.pk_fields}\n        hB = set()\n        for hC in hx:\n            # Search for single field providing a total ordering.\n            hD = None\n            if isinstance(hC, str):\n                hD = hC.lstrip(\"-\")\n            elif isinstance(hC, F):\n                hD = hC.name\n            elif isinstance(hC, OrderBy) and isinstance(hC.expression, F):\n                hD = hC.expression.name\n            if hE := self.b.annotations.get(hD):\n                if isinstance(hE, Col):\n                    if hE.alias == self.b.base_table:\n                        hB.add(hE.target)\n                elif isinstance(hE, ColPairs):\n                    hB |= {\n                        hF.target\n                        for hF in hE.get_cols()\n                        if hF.alias == self.b.base_table\n                    }\n            elif hD:\n                if hD == \"pk\":\n                    return True\n                # Normalize attname references by using get_field().\n                try:\n                    hH = hy.get_field(hD)\n                except exceptions.FieldDoesNotExist:\n                    # Could be \"?\" for random ordering or a related field\n                    # lookup. Skip this part of introspection for now.\n                    continue\n                else:\n                    # Ordering by a related field name orders by the referenced\n                    # model's ordering. Skip this introspection for now.\n                    if hH.remote_field and hD == hH.name:\n                        continue\n                    hB.add(hH)\n\n        hG = set()\n        for hH in hB:\n            if hH.unique and not hH.null:\n                return True\n            hG.add(hH.attname)\n\n        # Account for members of a CompositePrimaryKey.\n        if hG.issuperset(hz):\n            return True\n        # No single total ordering field, try unique_together and total\n        # unique constraints.\n        hI = (\n            *hy.unique_together,\n            *(hJ.fields for hJ in hy.total_unique_constraints),\n        )\n        for hK in hI:\n            # Normalize attname references by using get_field().\n            try:\n                hL = [hy.get_field(hD) for hD in hK]\n            except exceptions.FieldDoesNotExist:\n                continue\n            # Composite unique constraints containing a nullable column\n            # cannot ensure total ordering.\n            if any(hH.null for hH in hL):\n                continue\n            if hG.issuperset(hH.attname for hH in hL):\n                return True\n\n        return False\n\n    @property\n    def aO(self):\n        \"\"\"Return the database used if this query is executed now.\"\"\"\n        if self._for_write:\n            return self._db or router.db_for_write(self.model, **self._hints)\n        return self._db or router.db_for_read(self.model, **self._hints)\n\n    ###################\n    # PRIVATE METHODS #\n    ###################\n\n    def aP(\n        self,\n        hM,\n        hN,\n        hO=None,\n        hP=False,\n        hQ=None,\n        hR=None,\n        hS=None,\n        hT=None,\n    ):\n        \"\"\"\n        Insert a new record for the given model. This provides an interface to\n        the InsertQuery class and is how Model.save() is implemented.\n        \"\"\"\n        self._for_write = True\n        if hQ is None:\n            hQ = self.aO\n        hU = sql.InsertQuery(\n            self.model,\n            on_conflict=hR,\n            update_fields=hS,\n            unique_fields=hT,\n        )\n        hU.insert_values(hN, hM, raw=hP)\n        return hU.get_compiler(using=hQ).execute_sql(hO)\n\n    _insert.alters_data = True\n    _insert.queryset_only = False\n\n    def aQ(\n        self,\n        hV,\n        hW,\n        hX,\n        hY=None,\n        hZ=None,\n        ia=None,\n    ):\n        \"\"\"\n        Helper method for bulk_create() to insert objs one batch at a time.\n        \"\"\"\n        ib = connections[self.aO]\n        ic = ib.ops\n        id = max(ic.bulk_batch_size(hW, hV), 1)\n        hX = min(hX, id) if hX else id\n        ie = []\n        ig = (\n            self.model._meta.db_returning_fields\n            if (\n                ib.features.can_return_rows_from_bulk_insert\n                and (hY is None or hY == OnConflict.UPDATE)\n            )\n            else None\n        )\n        ih = [hV[ii : ii + hX] for ii in range(0, len(hV), hX)]\n        if len(ih) > 1:\n            ij = transaction.atomic(using=self.aO, savepoint=False)\n        else:\n            ij = nullcontext()\n        with ij:\n            for ik in ih:\n                ie.extend(\n                    self.aP(\n                        ik,\n                        fields=hW,\n                        using=self.aO,\n                        on_conflict=hY,\n                        update_fields=hZ,\n                        unique_fields=ia,\n                        returning_fields=ig,\n                    )\n                )\n        return ie\n\n    def aR(self):\n        \"\"\"\n        Prevent calls to _chain() from creating a new QuerySet via _clone().\n        All subsequent QuerySet mutations will occur on this instance until\n        _enable_cloning() is used.\n        \"\"\"\n        self._cloning_enabled = False\n        return self\n\n    def aS(self):\n        \"\"\"\n        Allow calls to _chain() to create a new QuerySet via _clone(). Restores\n        the default behavior where any QuerySet mutation will return a new\n        QuerySet instance. Necessary only when there has been a\n        _disable_cloning() call previously.\n        \"\"\"\n        self._cloning_enabled = True\n        return self\n\n    def aT(self):\n        \"\"\"\n        Temporarily prevent QuerySet _clone() operations, restoring the default\n        behavior on exit. For the duration of the context managed statement,\n        all operations (e.g. filter(), exclude(), etc.) will mutate the same\n        QuerySet instance.\n\n        @contextlib.contextmanager is intentionally not used for performance\n        reasons.\n        \"\"\"\n        return PreventQuerySetCloning(self)\n\n    def aU(self):\n        \"\"\"\n        Return a copy of the current QuerySet that's ready for another\n        operation.\n\n        If the QuerySet has opted in to in-place mutations via\n        _disable_cloning() temporarily, the copy doesn't occur and instead the\n        same QuerySet instance will be modified.\n        \"\"\"\n        if not self._cloning_enabled:\n            il = self\n        else:\n            il = self.aV()\n        if il._sticky_filter:\n            il.query.filter_is_sticky = True\n            il._sticky_filter = False\n        return il\n\n    def aV(self):\n        \"\"\"\n        Return a copy of the current QuerySet. A lightweight alternative\n        to deepcopy().\n        \"\"\"\n        im = self.__class__(\n            model=self.model,\n            query=self.b.chain(),\n            using=self._db,\n            hints=self._hints,\n        )\n        im._sticky_filter = self._sticky_filter\n        im._for_write = self._for_write\n        im._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        im._known_related_objects = self._known_related_objects\n        im._iterable_class = self._iterable_class\n        im._fetch_mode = self._fetch_mode\n        im._fields = self._fields\n        return im\n\n    def aW(self):\n        if self._result_cache is None:\n            self._result_cache = list(self._iterable_class(self))\n        if self._prefetch_related_lookups and not self._prefetch_done:\n            self.ad()\n\n    def aX(self):\n        \"\"\"\n        Indicate that the next filter call and the one following that should\n        be treated as a single filter. This is only important when it comes to\n        determining when to reuse tables for many-to-many filters. Required so\n        that we can filter naturally on the results of related managers.\n\n        This doesn't return a clone of the current QuerySet (it returns\n        \"self\"). The method is only used internally and should be immediately\n        followed by a filter() that does create a clone.\n        \"\"\"\n        self._sticky_filter = True\n        return self\n\n    def aY(self, io):\n        \"\"\"Check that two QuerySet classes may be merged.\"\"\"\n        if self._fields is not None and (\n            set(self.b.values_select) != set(io.query.values_select)\n            or set(self.b.extra_select) != set(io.query.extra_select)\n            or set(self.b.annotation_select) != set(io.query.annotation_select)\n        ):\n            raise TypeError(\n                \"Merging '%s' classes must involve the same values in each case.\"\n                % self.__class__.__name__\n            )\n\n    def aZ(self, ip):\n        \"\"\"\n        Keep track of all known related objects from either QuerySet instance.\n        \"\"\"\n        for iq, ir in ip._known_related_objects.items():\n            self._known_related_objects.setdefault(iq, {}).update(ir)\n\n    def ba(self, *it, **iu):\n        iv = self.b.resolve_expression(*it, **iu)\n        iv._db = self._db\n        return iv\n\n    resolve_expression.queryset_only = True\n\n    def bb(self, **iw):\n        \"\"\"\n        Update hinting information for use by routers. Add new key/values or\n        overwrite existing key/values.\n        \"\"\"\n        self._hints.update(iw)\n\n    def bc(self):\n        \"\"\"\n        Check if this QuerySet has any filtering going on. This isn't\n        equivalent with checking if all objects are present in results, for\n        example, qs[1:]._has_filters() -> False.\n        \"\"\"\n        return self.b.has_filters()\n\n    @staticmethod\n    def bd(ix, iy):\n        iz = sorted(\n            str(iA) for iA in ix if not hasattr(iA, \"resolve_expression\")\n        )\n        if iz:\n            raise TypeError(\n                \"QuerySet.%s() received non-expression(s): %s.\"\n                % (\n                    iy,\n                    \", \".join(iz),\n                )\n            )\n\n    def be(self, iB):\n        if self.b.combinator:\n            raise NotSupportedError(\n                \"Calling QuerySet.%s() after %s() is not supported.\"\n                % (iB, self.b.combinator)\n            )\n\n    def bf(self, iC, iD):\n        if self.b.combinator or iC.query.combinator:\n            raise TypeError(f\"Cannot use {iD} operator with combined queryset.\")\n\n    def bg(self, iE):\n        if (\n            isinstance(self.b.group_by, tuple)\n            # Raise if the pk fields are not in the group_by.\n            and self.model._meta.pk\n            not in {iF.output_field for iF in self.b.group_by}\n            and set(self.model._meta.pk_fields).difference(\n                {iF.target for iF in self.b.group_by}\n            )\n        ):\n            raise TypeError(\n                f\"Cannot use QuerySet.{iE}() on an unordered queryset performing \"\n                f\"aggregation. Add an ordering with order_by().\"\n            )\n\n    def bh(self, iG, iH):\n        iI = [self.b]\n        for iJ in iH:\n            iK = iJ.query.clone()\n            iK.clear_ordering(force=False, clear_default=False)\n            iI.append(iK)\n        iG.combined_queries = tuple(iI)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-765e7606ef75a519", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "552876f408740a7b015784bff20d774511ee2d9a07ed9821e35c56a773bd16b5", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 2102, "local_path": "identifiers/garble-identifiers/I04__django__QuerySet__07a52450.py", "order": 4, "original_content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "parent_variant_id": "pyint-5c2b55814568-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/query.py#L374-L2424", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1710, "identifiers_declared": 492}, "unit_kind": "class", "unit_name": "QuerySet", "variant_id": "pyint-911b07a52450-I04", "group_id": "py-765e7606ef75a519", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 229, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3b1cb43fb72e-I05", "source": "import copy\nimport operator\nimport warnings\nfrom contextlib import nullcontext\nfrom functools import partial, reduce\nfrom itertools import chain, islice\nfrom weakref import ref as weak_ref\nfrom asgiref.sync import sync_to_async\nimport django\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.db import (\n    DJANGO_VERSION_PICKLE_KEY,\n    IntegrityError,\n    NotSupportedError,\n    connections,\n    router,\n    transaction,\n)\nfrom django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql\nfrom django.db.models.constants import LOOKUP_SEP, OnConflict\nfrom django.db.models.deletion import Collector\nfrom django.db.models.expressions import (\n    Case,\n    Col,\n    ColPairs,\n    DatabaseDefault,\n    F,\n    OrderBy,\n    Value,\n    When,\n)\nfrom django.db.models.fetch_modes import FETCH_ONE\nfrom django.db.models.functions import Cast, Trunc\nfrom django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q\nfrom django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT\nfrom django.db.models.utils import (\n    AltersData,\n    create_namedtuple_class,\n    resolve_callables,\n)\nfrom django.utils import timezone\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    RemovedInDjango71Warning,\n    warn_about_external_use,\n)\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import func_accepts_kwargs, func_supports_parameter\nfrom django.utils.warnings import django_file_prefixes\n\nclass QuerySet(AltersData):\n    \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n    def __init__(self, model=None, query=None, using=None, hints=None):\n        self.model = model\n        self._db = using\n        self._hints = hints or {}\n        self._query = query or sql.Query(self.model)\n        self._result_cache = None\n        self._sticky_filter = False\n        self._for_write = False\n        self._prefetch_related_lookups = ()\n        self._prefetch_done = False\n        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}\n        self._iterable_class = ModelIterable\n        self._fetch_mode = DEFAULT_FETCH_MODE\n        self._fields = None\n        self._defer_next_filter = False\n        self._deferred_filter = None\n        self._cloning_enabled = True\n\n    @property\n    def query(self):\n        if self._deferred_filter:\n            negate, args, kwargs = self._deferred_filter\n            self._filter_or_exclude_inplace(negate, args, kwargs)\n            self._deferred_filter = None\n        return self._query\n\n    @query.setter\n    def query(self, value):\n        if value.values_select:\n            self._iterable_class = ValuesIterable\n        self._query = value\n\n    def as_manager(cls):\n        # Address the circular dependency between `Queryset` and `Manager`.\n        from django.db.models.manager import Manager\n\n        manager = Manager.from_queryset(cls)()\n        manager._built_with_as_manager = True\n        return manager\n\n    as_manager.queryset_only = True\n    as_manager = classmethod(as_manager)\n\n    ########################\n    # PYTHON MAGIC METHODS #\n    ########################\n\n    def __deepcopy__(self, memo):\n        \"\"\"Don't populate the QuerySet's cache.\"\"\"\n        obj = self.__class__()\n        for k, v in self.__dict__.items():\n            if k == \"_result_cache\":\n                obj.__dict__[k] = None\n            else:\n                obj.__dict__[k] = copy.deepcopy(v, memo)\n        return obj\n\n    def __getstate__(self):\n        # Force the cache to be fully populated.\n        self._fetch_all()\n        return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n    def __setstate__(self, state):\n        pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)\n        if pickled_version:\n            if pickled_version != django.__version__:\n                warnings.warn(\n                    \"Pickled queryset instance's Django version %s does not \"\n                    \"match the current version %s.\"\n                    % (pickled_version, django.__version__),\n                    RuntimeWarning,\n                    stacklevel=0x2,\n                )\n        else:\n            warnings.warn(\n                \"Pickled queryset instance's Django version is not specified.\",\n                RuntimeWarning,\n                stacklevel=0x2,\n            )\n        self.__dict__.update(state)\n\n    def __repr__(self):\n        data = list(self[: REPR_OUTPUT_SIZE + 0x1])\n        if len(data) > REPR_OUTPUT_SIZE:\n            data[-0x1] = \"...(remaining elements truncated)...\"\n        return \"<%s %r>\" % (self.__class__.__name__, data)\n\n    def __len__(self):\n        self._fetch_all()\n        return len(self._result_cache)\n\n    def __iter__(self):\n        \"\"\"\n        The queryset iterator protocol uses three nested iterators in the\n        default case:\n            1. sql.compiler.execute_sql()\n               - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n                 using cursor.fetchmany(). This part is responsible for\n                 doing some column masking, and returning the rows in chunks.\n            2. sql.compiler.results_iter()\n               - Returns one row at time. At this point the rows are still just\n                 tuples. In some cases the return values are converted to\n                 Python values at this location.\n            3. self.iterator()\n               - Responsible for turning the rows into model objects.\n        \"\"\"\n        self._fetch_all()\n        return iter(self._result_cache)\n\n    def __aiter__(self):\n        # Remember, __aiter__ itself is synchronous, it's the thing it returns\n        # that is async!\n        async def generator():\n            await sync_to_async(self._fetch_all)()\n            for item in self._result_cache:\n                yield item\n\n        return generator()\n\n    def __bool__(self):\n        self._fetch_all()\n        return bool(self._result_cache)\n\n    def __getitem__(self, k):\n        \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n        if not isinstance(k, (int, slice)):\n            raise TypeError(\n                \"QuerySet indices must be integers or slices, not %s.\"\n                % type(k).__name__\n            )\n        if (isinstance(k, int) and k < 0x0) or (\n            isinstance(k, slice)\n            and (\n                (k.start is not None and k.start < 0x0)\n                or (k.stop is not None and k.stop < 0x0)\n            )\n        ):\n            raise ValueError(\"Negative indexing is not supported.\")\n\n        if self._result_cache is not None:\n            return self._result_cache[k]\n\n        if isinstance(k, slice):\n            qs = self._chain()\n            if k.start is not None:\n                start = int(k.start)\n            else:\n                start = None\n            if k.stop is not None:\n                stop = int(k.stop)\n            else:\n                stop = None\n            qs.query.set_limits(start, stop)\n            return list(qs)[:: k.step] if k.step else qs\n\n        qs = self._chain()\n        qs.query.set_limits(k, k + 0x1)\n        qs._fetch_all()\n        return qs._result_cache[0x0]\n\n    def __class_getitem__(cls, *args, **kwargs):\n        return cls\n\n    def __and__(self, other):\n        self._check_operator_queryset(other, \"&\")\n        self._merge_sanity_check(other)\n        if isinstance(other, EmptyQuerySet):\n            return other\n        if isinstance(self, EmptyQuerySet):\n            return self\n        combined = self._chain()\n        combined._merge_known_related_objects(other)\n        combined.query.combine(other.query, sql.AND)\n        return combined\n\n    def __or__(self, other):\n        self._check_operator_queryset(other, \"|\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.OR)\n        return combined\n\n    def __xor__(self, other):\n        self._check_operator_queryset(other, \"^\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.XOR)\n        return combined\n\n    ####################################\n    # METHODS THAT DO DATABASE QUERIES #\n    ####################################\n\n    def _iterator(self, use_chunked_fetch, chunk_size):\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 0x7d0,\n        )\n        if not self._prefetch_related_lookups or chunk_size is None:\n            yield from iterable\n            return\n\n        iterator = iter(iterable)\n        while results := list(islice(iterator, chunk_size)):\n            prefetch_related_objects(results, *self._prefetch_related_lookups)\n            yield from results\n\n    def iterator(self, chunk_size=None):\n        \"\"\"\n        An iterator over the results from applying this QuerySet to the\n        database. chunk_size must be provided for QuerySets that prefetch\n        related objects. Otherwise, a default chunk_size of 2000 is supplied.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                raise ValueError(\n                    \"chunk_size must be provided when using QuerySet.iterator() after \"\n                    \"prefetch_related().\"\n                )\n        elif chunk_size <= 0x0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        return self._iterator(use_chunked_fetch, chunk_size)\n\n    async def aiterator(self, chunk_size=None):\n        \"\"\"\n        An asynchronous iterator over the results from applying this QuerySet\n        to the database.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                # RemovedInDjango71Warning: Replace the warning with:\n                # raise ValueError(\n                #     \"chunk_size must be provided when using \"\n                #     \"QuerySet.aiterator() after prefetch_related().\"\n                # )\n                warnings.warn(\n                    \"Using QuerySet.aiterator() after prefetch_related() without \"\n                    \"providing a chunk_size is deprecated and will raise a \"\n                    \"ValueError in Django 7.1.\",\n                    category=RemovedInDjango71Warning,\n                    skip_file_prefixes=django_file_prefixes(),\n                )\n                # RemovedInDjango71Warning: When the deprecation ends, remove.\n                chunk_size = 0x7d0\n        elif chunk_size <= 0x0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 0x7d0,\n        )\n        if self._prefetch_related_lookups:\n            results = []\n\n            async for item in iterable:\n                results.append(item)\n                if len(results) >= chunk_size:\n                    await aprefetch_related_objects(\n                        results, *self._prefetch_related_lookups\n                    )\n                    for result in results:\n                        yield result\n                    results.clear()\n\n            if results:\n                await aprefetch_related_objects(\n                    results, *self._prefetch_related_lookups\n                )\n                for result in results:\n                    yield result\n        else:\n            async for item in iterable:\n                yield item\n\n    def aggregate(self, *args, **kwargs):\n        \"\"\"\n        Return a dictionary containing the calculations (aggregation)\n        over the current queryset.\n\n        If args is present the expression is passed as a kwarg using\n        the Aggregate object's default alias.\n        \"\"\"\n        if self.query.distinct_fields:\n            raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n        self._validate_values_are_expressions(\n            (*args, *kwargs.values()), method_name=\"aggregate\"\n        )\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                arg.default_alias\n            except (AttributeError, TypeError):\n                raise TypeError(\"Complex aggregates require an alias\")\n            kwargs[arg.default_alias] = arg\n\n        return self.query.chain().get_aggregation(self.db, kwargs)\n\n    async def aaggregate(self, *args, **kwargs):\n        return await sync_to_async(self.aggregate)(*args, **kwargs)\n\n    def count(self):\n        \"\"\"\n        Perform a SELECT COUNT() and return the number of records as an\n        integer.\n\n        If the QuerySet is already fully cached, return the length of the\n        cached results set to avoid multiple SELECT COUNT(*) calls.\n        \"\"\"\n        if self._result_cache is not None:\n            return len(self._result_cache)\n\n        return self.query.get_count(using=self.db)\n\n    async def acount(self):\n        return await sync_to_async(self.count)()\n\n    def get(self, *args, **kwargs):\n        \"\"\"\n        Perform the query and return a single object matching the given\n        keyword arguments.\n        \"\"\"\n        if self.query.combinator and (args or kwargs):\n            raise NotSupportedError(\n                \"Calling QuerySet.get(...) with filters after %s() is not \"\n                \"supported.\" % self.query.combinator\n            )\n        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)\n        if self.query.can_filter() and not self.query.distinct_fields:\n            clone = clone.order_by()\n        limit = None\n        if (\n            not clone.query.select_for_update\n            or connections[clone.db].features.supports_select_for_update_with_limit\n        ):\n            limit = MAX_GET_RESULTS\n            clone.query.set_limits(high=limit)\n        num = len(clone)\n        if num == 0x1:\n            return clone._result_cache[0x0]\n        if not num:\n            raise self.model.DoesNotExist(\n                \"%s matching query does not exist.\" % self.model._meta.object_name\n            )\n        raise self.model.MultipleObjectsReturned(\n            \"get() returned more than one %s -- it returned %s!\"\n            % (\n                self.model._meta.object_name,\n                num if not limit or num < limit else \"more than %s\" % (limit - 0x1),\n            )\n        )\n\n    async def aget(self, *args, **kwargs):\n        return await sync_to_async(self.get)(*args, **kwargs)\n\n    def create(self, **kwargs):\n        \"\"\"\n        Create a new object with the given kwargs, saving it to the database\n        and returning the created object.\n        \"\"\"\n        reverse_one_to_one_fields = frozenset(kwargs).intersection(\n            self.model._meta._reverse_one_to_one_field_names\n        )\n        if reverse_one_to_one_fields:\n            raise ValueError(\n                \"The following fields do not exist in this model: %s\"\n                % \", \".join(reverse_one_to_one_fields)\n            )\n\n        obj = self.model(**kwargs)\n        self._for_write = True\n        obj.save(force_insert=True, using=self.db)\n        obj._state.fetch_mode = self._fetch_mode\n        return obj\n\n    create.alters_data = True\n\n    async def acreate(self, **kwargs):\n        return await sync_to_async(self.create)(**kwargs)\n\n    acreate.alters_data = True\n\n    def _prepare_for_bulk_create(self, objs):\n        objs_with_pk, objs_without_pk = [], []\n        for obj in objs:\n            obj._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n            if isinstance(obj.pk, DatabaseDefault):\n                objs_without_pk.append(obj)\n            elif obj._is_pk_set():\n                objs_with_pk.append(obj)\n            else:\n                obj.pk = obj._meta.pk.get_pk_value_on_save(obj)\n                if obj._is_pk_set():\n                    objs_with_pk.append(obj)\n                else:\n                    objs_without_pk.append(obj)\n        return objs_with_pk, objs_without_pk\n\n    def _check_bulk_create_options(\n        self, ignore_conflicts, update_conflicts, update_fields, unique_fields\n    ):\n        if ignore_conflicts and update_conflicts:\n            raise ValueError(\n                \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n            )\n        db_features = connections[self.db].features\n        if ignore_conflicts:\n            if not db_features.supports_ignore_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support ignoring conflicts.\"\n                )\n            return OnConflict.IGNORE\n        elif update_conflicts:\n            if not db_features.supports_update_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support updating conflicts.\"\n                )\n            if not update_fields:\n                raise ValueError(\n                    \"Fields that will be updated when a row insertion fails \"\n                    \"on conflicts must be provided.\"\n                )\n            if unique_fields and not db_features.supports_update_conflicts_with_target:\n                raise NotSupportedError(\n                    \"This database backend does not support updating \"\n                    \"conflicts with specifying unique fields that can trigger \"\n                    \"the upsert.\"\n                )\n            if not unique_fields and db_features.supports_update_conflicts_with_target:\n                raise ValueError(\n                    \"Unique fields that can trigger the upsert must be provided.\"\n                )\n            # Updating primary keys and non-concrete fields is forbidden.\n            if any(not f.concrete for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() can only be used with concrete fields in \"\n                    \"update_fields.\"\n                )\n            if any(f in self.model._meta.pk_fields for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() cannot be used with primary keys in \"\n                    \"update_fields.\"\n                )\n            if unique_fields:\n                if any(not f.concrete for f in unique_fields):\n                    raise ValueError(\n                        \"bulk_create() can only be used with concrete fields \"\n                        \"in unique_fields.\"\n                    )\n            return OnConflict.UPDATE\n        return None\n\n    def bulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert each of the instances into the database. Do *not* call\n        save() on each of the instances, do not send any pre/post_save\n        signals, and do not set the primary key attribute if it is an\n        autoincrement field (except if\n        features.can_return_rows_from_bulk_insert=True).\n        Multi-table models are not supported.\n        \"\"\"\n        # When you bulk insert you don't get the primary keys back (if it's an\n        # autoincrement, except if can_return_rows_from_bulk_insert=True), so\n        # you can't insert into the child tables which references this. There\n        # are two workarounds:\n        # 1) This could be implemented if you didn't have an autoincrement pk\n        # 2) You could do it by doing O(n) normal inserts into the parent\n        #    tables to get the primary keys back and then doing a single bulk\n        #    insert into the childmost table.\n        # We currently set the primary keys on the objects when using\n        # PostgreSQL via the RETURNING ID clause. It should be possible for\n        # Oracle as well, but the semantics for extracting the primary keys is\n        # trickier so it's not done yet.\n        if batch_size is not None and batch_size <= 0x0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        # Check that the parents share the same concrete model with the our\n        # model to detect the inheritance pattern ConcreteGrandParent ->\n        # MultiTableParent -> ProxyChild. Simply checking\n        # self.model._meta.proxy would not identify that case as involving\n        # multiple tables.\n        for parent in self.model._meta.all_parents:\n            if parent._meta.concrete_model is not self.model._meta.concrete_model:\n                raise ValueError(\"Can't bulk create a multi-table inherited model\")\n        if not objs:\n            return objs\n        opts = self.model._meta\n        if unique_fields:\n            # Primary key is allowed in unique_fields.\n            unique_fields = [\n                self.model._meta.get_field(opts.pk.name if name == \"pk\" else name)\n                for name in unique_fields\n            ]\n        if update_fields:\n            update_fields = [self.model._meta.get_field(name) for name in update_fields]\n        on_conflict = self._check_bulk_create_options(\n            ignore_conflicts,\n            update_conflicts,\n            update_fields,\n            unique_fields,\n        )\n        self._for_write = True\n        fields = [f for f in opts.concrete_fields if not f.generated]\n        objs = list(objs)\n        objs_with_pk, objs_without_pk = self._prepare_for_bulk_create(objs)\n        if objs_with_pk and objs_without_pk:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            self._handle_order_with_respect_to(objs)\n            if objs_with_pk:\n                returned_columns = self._batched_insert(\n                    objs_with_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                for obj_with_pk, results in zip(objs_with_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_with_pk, field.attname, result)\n                for obj_with_pk in objs_with_pk:\n                    obj_with_pk._state.adding = False\n                    obj_with_pk._state.db = self.db\n            if objs_without_pk:\n                fields = [f for f in fields if not isinstance(f, AutoField)]\n                returned_columns = self._batched_insert(\n                    objs_without_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                connection = connections[self.db]\n                if (\n                    connection.features.can_return_rows_from_bulk_insert\n                    and on_conflict is None\n                ):\n                    assert len(returned_columns) == len(objs_without_pk)\n                for obj_without_pk, results in zip(objs_without_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_without_pk, field.attname, result)\n                    obj_without_pk._state.adding = False\n                    obj_without_pk._state.db = self.db\n\n        return objs\n\n    def _handle_order_with_respect_to(self, objs):\n        if objs and (order_wrt := self.model._meta.order_with_respect_to):\n            get_filter_kwargs_for_object = order_wrt.get_filter_kwargs_for_object\n            attnames = list(get_filter_kwargs_for_object(objs[0x0]))\n            group_keys = set()\n            obj_groups = []\n            for obj in objs:\n                group_key = tuple(get_filter_kwargs_for_object(obj).values())\n                group_keys.add(group_key)\n                obj_groups.append((obj, group_key))\n            filters = [\n                Q.create(list(zip(attnames, group_key))) for group_key in group_keys\n            ]\n            next_orders = (\n                self.model._base_manager.using(self.db)\n                .filter(reduce(operator.or_, filters))\n                .values_list(*attnames)\n                .annotate(_order__max=Max(\"_order\") + 0x1)\n            )\n            # Create mapping of group values to max order.\n            group_next_orders = dict.fromkeys(group_keys, 0x0)\n            group_next_orders.update(\n                (tuple(group_key), next_order) for *group_key, next_order in next_orders\n            )\n            # Assign _order values to new objects.\n            for obj, group_key in obj_groups:\n                if getattr(obj, \"_order\", None) is None:\n                    group_next_order = group_next_orders[group_key]\n                    obj._order = group_next_order\n                    group_next_orders[group_key] += 0x1\n\n    bulk_create.alters_data = True\n\n    async def abulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        return await sync_to_async(self.bulk_create)(\n            objs=objs,\n            batch_size=batch_size,\n            ignore_conflicts=ignore_conflicts,\n            update_conflicts=update_conflicts,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n\n    abulk_create.alters_data = True\n\n    def bulk_update(self, objs, fields, batch_size=None):\n        \"\"\"\n        Update the given fields in each of the given objects in the database.\n        \"\"\"\n        if batch_size is not None and batch_size <= 0x0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        if not fields:\n            raise ValueError(\"Field names must be given to bulk_update().\")\n        objs = tuple(objs)\n        if not all(obj._is_pk_set() for obj in objs):\n            raise ValueError(\"All bulk_update() objects must have a primary key set.\")\n        opts = self.model._meta\n        fields = [opts.get_field(name) for name in fields]\n        if any(not f.concrete for f in fields):\n            raise ValueError(\"bulk_update() can only be used with concrete fields.\")\n        all_pk_fields = set(opts.pk_fields)\n        for parent in opts.all_parents:\n            all_pk_fields.update(parent._meta.pk_fields)\n        if any(f in all_pk_fields for f in fields):\n            raise ValueError(\"bulk_update() cannot be used with primary key fields.\")\n        if not objs:\n            return 0x0\n        for obj in objs:\n            obj._prepare_related_fields_for_save(\n                operation_name=\"bulk_update\", fields=fields\n            )\n        # PK is used twice in the resulting update query, once in the filter\n        # and once in the WHEN. Each field will also have one CAST.\n        self._for_write = True\n        connection = connections[self.db]\n        max_batch_size = connection.ops.bulk_batch_size(\n            [opts.pk, opts.pk, *fields], objs\n        )\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        requires_casting = connection.features.requires_casted_case_in_updates\n        batches = (objs[i : i + batch_size] for i in range(0x0, len(objs), batch_size))\n        updates = []\n        for batch_objs in batches:\n            update_kwargs = {}\n            for field in fields:\n                when_statements = []\n                for obj in batch_objs:\n                    attr = getattr(obj, field.attname)\n                    if not hasattr(attr, \"resolve_expression\"):\n                        attr = Value(attr, output_field=field)\n                    when_statements.append(When(pk=obj.pk, then=attr))\n                case_statement = Case(*when_statements, output_field=field)\n                if requires_casting:\n                    case_statement = Cast(case_statement, output_field=field)\n                update_kwargs[field.attname] = case_statement\n            updates.append(([obj.pk for obj in batch_objs], update_kwargs))\n        rows_updated = 0x0\n        queryset = self.using(self.db)\n        with transaction.atomic(using=self.db, savepoint=False):\n            for pks, update_kwargs in updates:\n                rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs)\n        return rows_updated\n\n    bulk_update.alters_data = True\n\n    async def abulk_update(self, objs, fields, batch_size=None):\n        return await sync_to_async(self.bulk_update)(\n            objs=objs,\n            fields=fields,\n            batch_size=batch_size,\n        )\n\n    abulk_update.alters_data = True\n\n    def get_or_create(self, defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, creating one if necessary.\n        Return a tuple of (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        # The get() needs to be targeted at the write database in order\n        # to avoid potential transaction consistency problems.\n        self._for_write = True\n        try:\n            return self.get(**kwargs), False\n        except self.model.DoesNotExist:\n            params = self._extract_model_params(defaults, **kwargs)\n            # Try to create an object using passed params.\n            try:\n                with transaction.atomic(using=self.db):\n                    params = dict(resolve_callables(params))\n                    return self.create(**params), True\n            except IntegrityError:\n                try:\n                    return self.get(**kwargs), False\n                except self.model.DoesNotExist:\n                    pass\n                raise\n\n    get_or_create.alters_data = True\n\n    async def aget_or_create(self, defaults=None, **kwargs):\n        return await sync_to_async(self.get_or_create)(\n            defaults=defaults,\n            **kwargs,\n        )\n\n    aget_or_create.alters_data = True\n\n    def update_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, updating one with defaults\n        if it exists, otherwise create a new one. Optionally, an object can\n        be created with different values than defaults by using\n        create_defaults.\n        Return a tuple (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        update_defaults = defaults or {}\n        if create_defaults is None:\n            create_defaults = update_defaults\n\n        self._for_write = True\n        with transaction.atomic(using=self.db):\n            # Lock the row so that a concurrent update is blocked until\n            # update_or_create() has performed its save.\n            obj, created = self.select_for_update().get_or_create(\n                create_defaults, **kwargs\n            )\n            if created:\n                return obj, created\n            for k, v in resolve_callables(update_defaults):\n                setattr(obj, k, v)\n\n            update_fields = set(update_defaults)\n            concrete_field_names = self.model._meta._non_pk_concrete_field_names\n            # update_fields does not support non-concrete fields.\n            if concrete_field_names.issuperset(update_fields):\n                # Add fields which are set on pre_save(), e.g. auto_now fields.\n                # This is to maintain backward compatibility as these fields\n                # are not updated unless explicitly specified in the\n                # update_fields list.\n                pk_fields = self.model._meta.pk_fields\n                for field in self.model._meta.local_concrete_fields:\n                    if not (\n                        field in pk_fields or field.__class__.pre_save is Field.pre_save\n                    ):\n                        update_fields.add(field.name)\n                        if field.name != field.attname:\n                            update_fields.add(field.attname)\n                obj.save(using=self.db, update_fields=update_fields)\n            else:\n                obj.save(using=self.db)\n        return obj, False\n\n    update_or_create.alters_data = True\n\n    async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        return await sync_to_async(self.update_or_create)(\n            defaults=defaults,\n            create_defaults=create_defaults,\n            **kwargs,\n        )\n\n    aupdate_or_create.alters_data = True\n\n    def _extract_model_params(self, defaults, **kwargs):\n        \"\"\"\n        Prepare `params` for creating a model instance based on the given\n        kwargs; for use by get_or_create().\n        \"\"\"\n        defaults = defaults or {}\n        params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}\n        params.update(defaults)\n        property_names = self.model._meta._property_names\n        invalid_params = []\n        for param in params:\n            try:\n                self.model._meta.get_field(param)\n            except exceptions.FieldDoesNotExist:\n                # It's okay to use a model's property if it has a setter.\n                if not (param in property_names and getattr(self.model, param).fset):\n                    invalid_params.append(param)\n        if invalid_params:\n            raise exceptions.FieldError(\n                \"Invalid field name(s) for model %s: '%s'.\"\n                % (\n                    self.model._meta.object_name,\n                    \"', '\".join(sorted(invalid_params)),\n                )\n            )\n        return params\n\n    def _earliest(self, *fields):\n        \"\"\"\n        Return the earliest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if fields:\n            order_by = fields\n        else:\n            order_by = getattr(self.model._meta, \"get_latest_by\")\n            if order_by and not isinstance(order_by, (tuple, list)):\n                order_by = (order_by,)\n        if order_by is None:\n            raise ValueError(\n                \"earliest() and latest() require either fields as positional \"\n                \"arguments or 'get_latest_by' in the model's Meta.\"\n            )\n        obj = self._chain()\n        obj.query.set_limits(high=0x1)\n        obj.query.clear_ordering(force=True)\n        obj.query.add_ordering(*order_by)\n        return obj.get()\n\n    def earliest(self, *fields):\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self._earliest(*fields)\n\n    async def aearliest(self, *fields):\n        return await sync_to_async(self.earliest)(*fields)\n\n    def latest(self, *fields):\n        \"\"\"\n        Return the latest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.reverse()._earliest(*fields)\n\n    async def alatest(self, *fields):\n        return await sync_to_async(self.latest)(*fields)\n\n    def first(self):\n        \"\"\"Return the first object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"first\")\n            queryset = self.order_by(\"pk\")\n        for obj in queryset[:0x1]:\n            return obj\n\n    async def afirst(self):\n        return await sync_to_async(self.first)()\n\n    def last(self):\n        \"\"\"Return the last object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self.reverse()\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"last\")\n            queryset = self.order_by(\"-pk\")\n        for obj in queryset[:0x1]:\n            return obj\n\n    async def alast(self):\n        return await sync_to_async(self.last)()\n\n    def in_bulk(self, id_list=None, *, field_name=\"pk\"):\n        \"\"\"\n        Return a dictionary mapping each of the given IDs to the object with\n        that ID. If `id_list` isn't provided, evaluate the entire QuerySet.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with in_bulk().\")\n        if id_list is not None and not id_list:\n            return {}\n        opts = self.model._meta\n        unique_fields = [\n            constraint.fields[0x0]\n            for constraint in opts.total_unique_constraints\n            if len(constraint.fields) == 0x1\n        ]\n        if (\n            field_name != \"pk\"\n            and not opts.get_field(field_name).unique\n            and field_name not in unique_fields\n            and self.query.distinct_fields != (field_name,)\n        ):\n            raise ValueError(\n                \"in_bulk()'s field_name must be a unique field but %r isn't.\"\n                % field_name\n            )\n\n        qs = self\n\n        def get_obj(obj):\n            return obj\n\n        if issubclass(self._iterable_class, ModelIterable):\n            # Raise an AttributeError if field_name is deferred.\n            get_key = operator.attrgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesIterable):\n            if field_name not in self.query.values_select:\n                qs = qs.values(field_name, *self.query.values_select)\n\n                def get_obj(obj):  # noqa: F811\n                    # We can safely mutate the dictionaries returned by\n                    # ValuesIterable here, since they are limited to the scope\n                    # of this function, and get_key runs before get_obj.\n                    del obj[field_name]\n                    return obj\n\n            get_key = operator.itemgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesListIterable):\n            try:\n                field_index = self.query.values_select.index(field_name)\n            except ValueError:\n                # field_name is missing from values_select, so add it.\n                field_index = 0x0\n                if issubclass(self._iterable_class, NamedValuesListIterable):\n                    kwargs = {\"named\": True}\n                else:\n                    kwargs = {}\n                    get_obj = operator.itemgetter(slice(0x1, None))\n                qs = qs.values_list(field_name, *self.query.values_select, **kwargs)\n\n            get_key = operator.itemgetter(field_index)\n\n        elif issubclass(self._iterable_class, FlatValuesListIterable):\n            if self.query.values_select == (field_name,):\n                # Mapping field_name to itself.\n                get_key = get_obj\n            else:\n                # Transform it back into a non-flat values_list().\n                qs = qs.values_list(field_name, *self.query.values_select)\n                get_key = operator.itemgetter(0x0)\n                get_obj = operator.itemgetter(0x1)\n\n        else:\n            raise TypeError(\n                f\"in_bulk() cannot be used with {self._iterable_class.__name__}.\"\n            )\n\n        if id_list is not None:\n            filter_key = \"{}__in\".format(field_name)\n            id_list = tuple(id_list)\n            batch_size = connections[self.db].ops.bulk_batch_size([opts.pk], id_list)\n            # If the database has a limit on the number of query parameters\n            # (e.g. SQLite), retrieve objects in batches if necessary.\n            if batch_size and batch_size < len(id_list):\n                results = ()\n                for offset in range(0x0, len(id_list), batch_size):\n                    batch = id_list[offset : offset + batch_size]\n                    results += tuple(qs.filter(**{filter_key: batch}))\n                qs = results\n            else:\n                qs = qs.filter(**{filter_key: id_list})\n        else:\n            qs = qs._chain()\n        return {get_key(obj): get_obj(obj) for obj in qs}\n\n    async def ain_bulk(self, id_list=None, *, field_name=\"pk\"):\n        return await sync_to_async(self.in_bulk)(\n            id_list=id_list,\n            field_name=field_name,\n        )\n\n    def delete(self):\n        \"\"\"Delete the records in the current QuerySet.\"\"\"\n        self._not_support_combined_queries(\"delete\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with delete().\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call delete() after .distinct(*fields).\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call delete() after .values() or .values_list()\")\n\n        del_query = self._chain()\n\n        # The delete is actually 2 queries - one to find related objects,\n        # and one to delete. Make sure that the discovery of related\n        # objects is performed on the same database as the deletion.\n        del_query._for_write = True\n\n        # Disable non-supported fields.\n        del_query.query.select_for_update = False\n        del_query.query.select_related = False\n        del_query.query.clear_ordering(force=True)\n\n        collector = Collector(using=del_query.db, origin=self)\n        collector.collect(del_query)\n        num_deleted, num_deleted_per_model = collector.delete()\n\n        # Clear the result cache, in case this QuerySet gets reused.\n        self._result_cache = None\n        return num_deleted, num_deleted_per_model\n\n    delete.alters_data = True\n    delete.queryset_only = True\n\n    async def adelete(self):\n        return await sync_to_async(self.delete)()\n\n    adelete.alters_data = True\n    adelete.queryset_only = True\n\n    def _raw_delete(self, using):\n        \"\"\"\n        Delete objects found from the given queryset in single direct SQL\n        query. No signals are sent and there is no protection for cascades.\n        \"\"\"\n        query = self.query.clone()\n        query.__class__ = sql.DeleteQuery\n        return query.get_compiler(using).execute_sql(ROW_COUNT)\n\n    _raw_delete.alters_data = True\n\n    def update(self, **kwargs):\n        \"\"\"\n        Update all elements in the current QuerySet, setting all the given\n        fields to the appropriate values.\n        \"\"\"\n        self._not_support_combined_queries(\"update\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call update() after .distinct(*fields).\")\n        self._for_write = True\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_values(kwargs)\n\n        # Inline annotations in order_by(), if possible.\n        new_order_by = []\n        for col in query.order_by:\n            alias = col\n            descending = False\n            if isinstance(alias, str) and alias.startswith(\"-\"):\n                alias = alias.removeprefix(\"-\")\n                descending = True\n            if annotation := query.annotations.get(alias):\n                if getattr(annotation, \"contains_aggregate\", False):\n                    raise exceptions.FieldError(\n                        f\"Cannot update when ordering by an aggregate: {annotation}\"\n                    )\n                if descending:\n                    annotation = annotation.desc()\n                new_order_by.append(annotation)\n            else:\n                new_order_by.append(col)\n        query.order_by = tuple(new_order_by)\n\n        # Clear SELECT clause as all annotation references were inlined by\n        # add_update_values() already.\n        query.clear_select_clause()\n        with transaction.mark_for_rollback_on_error(using=self.db):\n            rows = query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        self._result_cache = None\n        return rows\n\n    update.alters_data = True\n\n    async def aupdate(self, **kwargs):\n        return await sync_to_async(self.update)(**kwargs)\n\n    aupdate.alters_data = True\n\n    def _update(self, values, returning_fields=None):\n        \"\"\"\n        A version of update() that accepts field objects instead of field\n        names. Used primarily for model saving and not intended for use by\n        general code (it requires too much poking around at model internals to\n        be useful at that level).\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_fields(values)\n        # Clear any annotations so that they won't be present in subqueries.\n        query.annotations = {}\n        self._result_cache = None\n        if returning_fields is None:\n            return query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        return query.get_compiler(self.db).execute_returning_sql(returning_fields)\n\n    _update.alters_data = True\n    _update.queryset_only = False\n\n    def exists(self):\n        \"\"\"\n        Return True if the QuerySet would have any results, False otherwise.\n        \"\"\"\n        if self._result_cache is None:\n            return self.query.has_results(using=self.db)\n        return bool(self._result_cache)\n\n    async def aexists(self):\n        return await sync_to_async(self.exists)()\n\n    def contains(self, obj):\n        \"\"\"\n        Return True if the QuerySet contains the provided obj,\n        False otherwise.\n        \"\"\"\n        self._not_support_combined_queries(\"contains\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call QuerySet.contains() after .values() or .values_list().\"\n            )\n        try:\n            if obj._meta.concrete_model != self.model._meta.concrete_model:\n                return False\n        except AttributeError:\n            raise TypeError(\"'obj' must be a model instance.\")\n        if not obj._is_pk_set():\n            raise ValueError(\"QuerySet.contains() cannot be used on unsaved objects.\")\n        if self._result_cache is not None:\n            return obj in self._result_cache\n        return self.filter(pk=obj.pk).exists()\n\n    async def acontains(self, obj):\n        return await sync_to_async(self.contains)(obj=obj)\n\n    def _prefetch_related_objects(self):\n        # This method can only be called once the result cache has been filled.\n        prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)\n        self._prefetch_done = True\n\n    def explain(self, *, format=None, **options):\n        \"\"\"\n        Runs an EXPLAIN on the SQL query this QuerySet would perform, and\n        returns the results.\n        \"\"\"\n        return self.query.explain(using=self.db, format=format, **options)\n\n    async def aexplain(self, *, format=None, **options):\n        return await sync_to_async(self.explain)(format=format, **options)\n\n    ##################################################\n    # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #\n    ##################################################\n\n    def raw(self, raw_query, params=(), translations=None, using=None):\n        if using is None:\n            using = self.db\n        qs = RawQuerySet(\n            raw_query,\n            model=self.model,\n            params=params,\n            translations=translations,\n            using=using,\n            fetch_mode=self._fetch_mode,\n        )\n        qs._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        return qs\n\n    def _values(self, *fields, **expressions):\n        clone = self._chain()\n        if expressions:\n            # RemovedInDjango70Warning: When the deprecation ends, deindent as:\n            # clone = clone.annotate(**expressions)\n            with warnings.catch_warnings(\n                action=\"ignore\", category=RemovedInDjango70Warning\n            ):\n                clone = clone.annotate(**expressions)\n        clone._fields = fields\n        clone.query.set_values(fields)\n        return clone\n\n    def values(self, *fields, **expressions):\n        fields += tuple(expressions)\n        clone = self._values(*fields, **expressions)\n        clone._iterable_class = ValuesIterable\n        return clone\n\n    def values_list(self, *fields, flat=False, named=False):\n        if flat and named:\n            raise TypeError(\"'flat' and 'named' can't be used together.\")\n        if flat:\n            if len(fields) > 0x1:\n                raise TypeError(\n                    \"'flat' is not valid when values_list is called with more than one \"\n                    \"field.\"\n                )\n            elif not fields:\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # raise TypeError(\n                #     \"'flat' is not valid when values_list is called with no \"\n                #     \"fields.\"\n                # )\n                warnings.warn(\n                    \"Calling values_list() with no field name and flat=True \"\n                    \"is deprecated. Pass an explicit field name instead, like \"\n                    \"'pk'.\",\n                    RemovedInDjango70Warning,\n                )\n                fields = [self.model._meta.concrete_fields[0x0].attname]\n\n        field_names = {f: False for f in fields if not hasattr(f, \"resolve_expression\")}\n        _fields = []\n        expressions = {}\n        counter = 0x1\n        for field in fields:\n            field_name = field\n            expression = None\n            if hasattr(field, \"resolve_expression\"):\n                field_name = getattr(\n                    field, \"default_alias\", field.__class__.__name__.lower()\n                )\n                expression = field\n                # For backward compatibility reasons expressions are always\n                # prefixed with the counter even if their default alias doesn't\n                # collide with field names. Changing this logic could break\n                # some usage of named=True.\n                seen = True\n            elif seen := field_names[field_name]:\n                expression = F(field_name)\n            if seen:\n                field_name_prefix = field_name\n                while (field_name := f\"{field_name_prefix}{counter}\") in field_names:\n                    counter += 0x1\n            if expression is not None:\n                expressions[field_name] = expression\n            field_names[field_name] = True\n            _fields.append(field_name)\n\n        clone = self._values(*_fields, **expressions)\n        clone._iterable_class = (\n            NamedValuesListIterable\n            if named\n            else FlatValuesListIterable if flat else ValuesListIterable\n        )\n        return clone\n\n    def dates(self, field_name, kind, order=\"ASC\"):\n        \"\"\"\n        Return a list of date objects representing all available dates for\n        the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\"):\n            raise ValueError(\"'kind' must be one of 'year', 'month', 'week', or 'day'.\")\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        return (\n            self.annotate(\n                datefield=Trunc(field_name, kind, output_field=DateField()),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datefield\")\n        )\n\n    def datetimes(self, field_name, kind, order=\"ASC\", tzinfo=None):\n        \"\"\"\n        Return a list of datetime objects representing all available\n        datetimes for the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"):\n            raise ValueError(\n                \"'kind' must be one of 'year', 'month', 'week', 'day', \"\n                \"'hour', 'minute', or 'second'.\"\n            )\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        if settings.USE_TZ:\n            if tzinfo is None:\n                tzinfo = timezone.get_current_timezone()\n        else:\n            tzinfo = None\n        return (\n            self.annotate(\n                datetimefield=Trunc(\n                    field_name,\n                    kind,\n                    output_field=DateTimeField(),\n                    tzinfo=tzinfo,\n                ),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datetimefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datetimefield\")\n        )\n\n    def none(self):\n        \"\"\"Return an empty QuerySet.\"\"\"\n        clone = self._chain()\n        clone.query.set_empty()\n        return clone\n\n    ##################################################################\n    # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #\n    ##################################################################\n\n    def all(self):\n        \"\"\"\n        Return a new QuerySet that is a copy of the current one. This allows a\n        QuerySet to proxy for a model manager in some cases.\n        \"\"\"\n        return self._chain()\n\n    def filter(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with the args ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"filter\")\n        return self._filter_or_exclude(False, args, kwargs)\n\n    def exclude(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with NOT (args) ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"exclude\")\n        return self._filter_or_exclude(True, args, kwargs)\n\n    def _filter_or_exclude(self, negate, args, kwargs):\n        if (args or kwargs) and self.query.is_sliced:\n            raise TypeError(\"Cannot filter a query once a slice has been taken.\")\n        clone = self._chain()\n        if self._defer_next_filter:\n            self._defer_next_filter = False\n            clone._deferred_filter = negate, args, kwargs\n        else:\n            clone._filter_or_exclude_inplace(negate, args, kwargs)\n        return clone\n\n    def _filter_or_exclude_inplace(self, negate, args, kwargs):\n        if invalid_kwargs := PROHIBITED_FILTER_KWARGS.intersection(kwargs):\n            invalid_kwargs_str = \", \".join(f\"'{k}'\" for k in sorted(invalid_kwargs))\n            raise TypeError(f\"The following kwargs are invalid: {invalid_kwargs_str}\")\n        if negate:\n            self._query.add_q(~Q(*args, **kwargs))\n        else:\n            self._query.add_q(Q(*args, **kwargs))\n\n    def complex_filter(self, filter_obj):\n        \"\"\"\n        Return a new QuerySet instance with filter_obj added to the filters.\n\n        filter_obj can be a Q object or a dictionary of keyword lookup\n        arguments.\n\n        This exists to support framework features such as 'limit_choices_to',\n        and usually it will be more natural to use other methods.\n        \"\"\"\n        if isinstance(filter_obj, Q):\n            clone = self._chain()\n            clone.query.add_q(filter_obj)\n            return clone\n        else:\n            return self._filter_or_exclude(False, args=(), kwargs=filter_obj)\n\n    def _combinator_query(self, combinator, *other_qs, all=False):\n        # Clone the query to inherit the select list and everything\n        clone = self._chain()\n        # Clear limits and ordering so they can be reapplied\n        clone.query.clear_ordering(force=True)\n        clone.query.default_ordering = True\n        self._clear_ordering_in_combined_queries(clone.query, other_qs)\n        clone.query.clear_limits()\n        clone.query.combinator = combinator\n        clone.query.combinator_all = all\n        return clone\n\n    def union(self, *other_qs, all=False):\n        # If the query is an EmptyQuerySet, combine all nonempty querysets.\n        if isinstance(self, EmptyQuerySet):\n            qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)]\n            if not qs:\n                return self\n            if len(qs) == 0x1:\n                return qs[0x0]\n            return qs[0x0]._combinator_query(\"union\", *qs[0x1:], all=all)\n        elif not other_qs:\n            return self\n        return self._combinator_query(\"union\", *other_qs, all=all)\n\n    def intersection(self, *other_qs):\n        # If any query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        for other in other_qs:\n            if isinstance(other, EmptyQuerySet):\n                return other\n        return self._combinator_query(\"intersection\", *other_qs)\n\n    def difference(self, *other_qs):\n        # If the query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        return self._combinator_query(\"difference\", *other_qs)\n\n    def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False):\n        \"\"\"\n        Return a new QuerySet instance that will select objects with a\n        FOR UPDATE lock.\n        \"\"\"\n        if nowait and skip_locked:\n            raise ValueError(\"The nowait option cannot be used with skip_locked.\")\n        obj = self._chain()\n        obj._for_write = True\n        obj.query.select_for_update = True\n        obj.query.select_for_update_nowait = nowait\n        obj.query.select_for_update_skip_locked = skip_locked\n        obj.query.select_for_update_of = of\n        obj.query.select_for_no_key_update = no_key\n        return obj\n\n    def select_related(self, *fields):\n        \"\"\"\n        Return a new QuerySet instance that will select related objects.\n\n        If fields are specified, they must be ForeignKey fields and only those\n        related objects are included in the selection.\n\n        If select_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"select_related\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call select_related() after .values() or .values_list()\"\n            )\n\n        obj = self._chain()\n        if fields == (None,):\n            obj.query.select_related = False\n        elif fields:\n            obj.query.add_select_related(fields)\n        else:\n            # RemovedInDjango70Warning: when the deprecation ends, raise a\n            # TypeError instead.\n            warn_about_external_use(\n                \"Calling select_related() with no arguments is deprecated. \"\n                \"Specify the fields to fetch instead.\",\n                category=RemovedInDjango70Warning,\n                skip_name_prefixes=(\"django.db.models\",),\n            )\n            obj.query.select_related = True\n        return obj\n\n    def prefetch_related(self, *lookups):\n        \"\"\"\n        Return a new QuerySet instance that will prefetch the specified\n        Many-To-One and Many-To-Many related objects when the QuerySet is\n        evaluated.\n\n        When prefetch_related() is called more than once, append to the list of\n        prefetch lookups. If prefetch_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"prefetch_related\")\n        clone = self._chain()\n        if lookups == (None,):\n            clone._prefetch_related_lookups = ()\n        else:\n            for lookup in lookups:\n                if isinstance(lookup, Prefetch):\n                    lookup = lookup.prefetch_to\n                lookup = lookup.split(LOOKUP_SEP, 0x1)[0x0]\n                if lookup in self.query._filtered_relations:\n                    raise ValueError(\n                        \"prefetch_related() is not supported with FilteredRelation.\"\n                    )\n            clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups\n        return clone\n\n    def annotate(self, *args, **kwargs):\n        \"\"\"\n        Return a query set in which the returned objects have been annotated\n        with extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"annotate\")\n        return self._annotate(args, kwargs, select=True)\n\n    def alias(self, *args, **kwargs):\n        \"\"\"\n        Return a query set with added aliases for extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"alias\")\n        return self._annotate(args, kwargs, select=False)\n\n    def _annotate(self, args, kwargs, select=True):\n        self._validate_values_are_expressions(\n            args + tuple(kwargs.values()), method_name=\"annotate\"\n        )\n        annotations = {}\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                if arg.default_alias in kwargs:\n                    raise ValueError(\n                        \"The named annotation '%s' conflicts with the \"\n                        \"default name for another annotation.\" % arg.default_alias\n                    )\n            except (TypeError, AttributeError):\n                raise TypeError(\"Complex annotations require an alias\")\n            annotations[arg.default_alias] = arg\n        annotations.update(kwargs)\n\n        clone = self._chain()\n        names = self._fields\n        if names is None:\n            names = set(\n                chain.from_iterable(\n                    (\n                        (field.name, field.attname)\n                        if hasattr(field, \"attname\")\n                        else (field.name,)\n                    )\n                    for field in self.model._meta.get_fields()\n                )\n            )\n\n        for alias, annotation in annotations.items():\n            if alias in names:\n                raise ValueError(\n                    \"The annotation '%s' conflicts with a field on \"\n                    \"the model.\" % alias\n                )\n            if isinstance(annotation, FilteredRelation):\n                clone.query.add_filtered_relation(annotation, alias)\n            else:\n                clone.query.add_annotation(\n                    annotation,\n                    alias,\n                    select=select,\n                )\n        for alias, annotation in clone.query.annotations.items():\n            if alias in annotations and annotation.contains_aggregate:\n                if clone._fields is None:\n                    clone.query.group_by = True\n                else:\n                    clone.query.set_group_by()\n                break\n\n        return clone\n\n    def order_by(self, *field_names):\n        \"\"\"Return a new QuerySet instance with the ordering changed.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reorder a query once a slice has been taken.\")\n        obj = self._chain()\n        obj.query.clear_ordering(force=True, clear_default=False)\n        obj.query.add_ordering(*field_names)\n        return obj\n\n    def distinct(self, *field_names):\n        \"\"\"\n        Return a new QuerySet instance that will select only distinct results.\n        \"\"\"\n        self._not_support_combined_queries(\"distinct\")\n        if self.query.is_sliced:\n            raise TypeError(\n                \"Cannot create distinct fields once a slice has been taken.\"\n            )\n        obj = self._chain()\n        obj.query.add_distinct_fields(*field_names)\n        return obj\n\n    def extra(\n        self,\n        select=None,\n        where=None,\n        params=None,\n        tables=None,\n        order_by=None,\n        select_params=None,\n    ):\n        \"\"\"Add extra SQL fragments to the query.\"\"\"\n        self._not_support_combined_queries(\"extra\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.add_extra(select, select_params, where, params, tables, order_by)\n        return clone\n\n    def reverse(self):\n        \"\"\"Reverse the ordering of the QuerySet.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reverse a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.standard_ordering = not clone.query.standard_ordering\n        return clone\n\n    def defer(self, *fields):\n        \"\"\"\n        Defer the loading of data for certain fields until they are accessed.\n        Add the set of deferred fields to any existing set of deferred fields.\n        The only exception to this is if None is passed in as the only\n        parameter, in which case remove all deferrals.\n        \"\"\"\n        self._not_support_combined_queries(\"defer\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call defer() after .values() or .values_list()\")\n        clone = self._chain()\n        if fields == (None,):\n            clone.query.clear_deferred_loading()\n        else:\n            clone.query.add_deferred_loading(fields)\n        return clone\n\n    def only(self, *fields):\n        \"\"\"\n        Essentially, the opposite of defer(). Only the fields passed into this\n        method and that are not already specified as deferred are loaded\n        immediately when the queryset is evaluated.\n        \"\"\"\n        self._not_support_combined_queries(\"only\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call only() after .values() or .values_list()\")\n        if fields == (None,):\n            # Can only pass None to defer(), not only(), as the rest option.\n            # That won't stop people trying to do this, so let's be explicit.\n            raise TypeError(\"Cannot pass None as an argument to only().\")\n        for field in fields:\n            field = field.split(LOOKUP_SEP, 0x1)[0x0]\n            if field in self.query._filtered_relations:\n                raise ValueError(\"only() is not supported with FilteredRelation.\")\n        clone = self._chain()\n        clone.query.add_immediate_loading(fields)\n        return clone\n\n    def using(self, alias):\n        \"\"\"Select which database this QuerySet should execute against.\"\"\"\n        clone = self._chain()\n        clone._db = alias\n        return clone\n\n    def fetch_mode(self, fetch_mode):\n        \"\"\"Set the fetch mode for the QuerySet.\"\"\"\n        clone = self._chain()\n        clone._fetch_mode = fetch_mode\n        return clone\n\n    ###################################\n    # PUBLIC INTROSPECTION ATTRIBUTES #\n    ###################################\n\n    @property\n    def ordered(self):\n        \"\"\"\n        Return True if the QuerySet is ordered -- i.e. has an order_by()\n        clause or a default ordering on the model (or is empty).\n        \"\"\"\n        if isinstance(self, EmptyQuerySet):\n            return True\n        if self.query.extra_order_by or self.query.order_by:\n            return True\n        elif (\n            self.query.default_ordering\n            and self.query.get_meta().ordering\n            and\n            # A default ordering doesn't affect GROUP BY queries.\n            not self.query.group_by\n        ):\n            return True\n        else:\n            return False\n\n    @property\n    def totally_ordered(self):\n        \"\"\"\n        Returns True if the QuerySet is ordered and the ordering is\n        deterministic. This requires that the ordering includes a field\n        (or set of fields) that is unique and non-nullable.\n\n        For queries involving a GROUP BY clause, the model's default\n        ordering is ignored. Ordering specified via .extra(order_by=...)\n        is also ignored.\n        \"\"\"\n        if not self.ordered:\n            return False\n        ordering = self.query.order_by\n        if not ordering and self.query.default_ordering:\n            ordering = self.query.get_meta().ordering\n        if not ordering:\n            return False\n        opts = self.model._meta\n        pk_fields = {f.attname for f in opts.pk_fields}\n        candidate_fields = set()\n        for part in ordering:\n            # Search for single field providing a total ordering.\n            field_name = None\n            if isinstance(part, str):\n                field_name = part.lstrip(\"-\")\n            elif isinstance(part, F):\n                field_name = part.name\n            elif isinstance(part, OrderBy) and isinstance(part.expression, F):\n                field_name = part.expression.name\n            if annotation_col := self.query.annotations.get(field_name):\n                if isinstance(annotation_col, Col):\n                    if annotation_col.alias == self.query.base_table:\n                        candidate_fields.add(annotation_col.target)\n                elif isinstance(annotation_col, ColPairs):\n                    candidate_fields |= {\n                        c.target\n                        for c in annotation_col.get_cols()\n                        if c.alias == self.query.base_table\n                    }\n            elif field_name:\n                if field_name == \"pk\":\n                    return True\n                # Normalize attname references by using get_field().\n                try:\n                    field = opts.get_field(field_name)\n                except exceptions.FieldDoesNotExist:\n                    # Could be \"?\" for random ordering or a related field\n                    # lookup. Skip this part of introspection for now.\n                    continue\n                else:\n                    # Ordering by a related field name orders by the referenced\n                    # model's ordering. Skip this introspection for now.\n                    if field.remote_field and field_name == field.name:\n                        continue\n                    candidate_fields.add(field)\n\n        candidate_attnames = set()\n        for field in candidate_fields:\n            if field.unique and not field.null:\n                return True\n            candidate_attnames.add(field.attname)\n\n        # Account for members of a CompositePrimaryKey.\n        if candidate_attnames.issuperset(pk_fields):\n            return True\n        # No single total ordering field, try unique_together and total\n        # unique constraints.\n        constraint_field_names = (\n            *opts.unique_together,\n            *(constraint.fields for constraint in opts.total_unique_constraints),\n        )\n        for field_names in constraint_field_names:\n            # Normalize attname references by using get_field().\n            try:\n                fields = [opts.get_field(field_name) for field_name in field_names]\n            except exceptions.FieldDoesNotExist:\n                continue\n            # Composite unique constraints containing a nullable column\n            # cannot ensure total ordering.\n            if any(field.null for field in fields):\n                continue\n            if candidate_attnames.issuperset(field.attname for field in fields):\n                return True\n\n        return False\n\n    @property\n    def db(self):\n        \"\"\"Return the database used if this query is executed now.\"\"\"\n        if self._for_write:\n            return self._db or router.db_for_write(self.model, **self._hints)\n        return self._db or router.db_for_read(self.model, **self._hints)\n\n    ###################\n    # PRIVATE METHODS #\n    ###################\n\n    def _insert(\n        self,\n        objs,\n        fields,\n        returning_fields=None,\n        raw=False,\n        using=None,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert a new record for the given model. This provides an interface to\n        the InsertQuery class and is how Model.save() is implemented.\n        \"\"\"\n        self._for_write = True\n        if using is None:\n            using = self.db\n        query = sql.InsertQuery(\n            self.model,\n            on_conflict=on_conflict,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n        query.insert_values(fields, objs, raw=raw)\n        return query.get_compiler(using=using).execute_sql(returning_fields)\n\n    _insert.alters_data = True\n    _insert.queryset_only = False\n\n    def _batched_insert(\n        self,\n        objs,\n        fields,\n        batch_size,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Helper method for bulk_create() to insert objs one batch at a time.\n        \"\"\"\n        connection = connections[self.db]\n        ops = connection.ops\n        max_batch_size = max(ops.bulk_batch_size(fields, objs), 0x1)\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        inserted_rows = []\n        returning_fields = (\n            self.model._meta.db_returning_fields\n            if (\n                connection.features.can_return_rows_from_bulk_insert\n                and (on_conflict is None or on_conflict == OnConflict.UPDATE)\n            )\n            else None\n        )\n        batches = [objs[i : i + batch_size] for i in range(0x0, len(objs), batch_size)]\n        if len(batches) > 0x1:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            for item in batches:\n                inserted_rows.extend(\n                    self._insert(\n                        item,\n                        fields=fields,\n                        using=self.db,\n                        on_conflict=on_conflict,\n                        update_fields=update_fields,\n                        unique_fields=unique_fields,\n                        returning_fields=returning_fields,\n                    )\n                )\n        return inserted_rows\n\n    def _disable_cloning(self):\n        \"\"\"\n        Prevent calls to _chain() from creating a new QuerySet via _clone().\n        All subsequent QuerySet mutations will occur on this instance until\n        _enable_cloning() is used.\n        \"\"\"\n        self._cloning_enabled = False\n        return self\n\n    def _enable_cloning(self):\n        \"\"\"\n        Allow calls to _chain() to create a new QuerySet via _clone(). Restores\n        the default behavior where any QuerySet mutation will return a new\n        QuerySet instance. Necessary only when there has been a\n        _disable_cloning() call previously.\n        \"\"\"\n        self._cloning_enabled = True\n        return self\n\n    def _avoid_cloning(self):\n        \"\"\"\n        Temporarily prevent QuerySet _clone() operations, restoring the default\n        behavior on exit. For the duration of the context managed statement,\n        all operations (e.g. filter(), exclude(), etc.) will mutate the same\n        QuerySet instance.\n\n        @contextlib.contextmanager is intentionally not used for performance\n        reasons.\n        \"\"\"\n        return PreventQuerySetCloning(self)\n\n    def _chain(self):\n        \"\"\"\n        Return a copy of the current QuerySet that's ready for another\n        operation.\n\n        If the QuerySet has opted in to in-place mutations via\n        _disable_cloning() temporarily, the copy doesn't occur and instead the\n        same QuerySet instance will be modified.\n        \"\"\"\n        if not self._cloning_enabled:\n            obj = self\n        else:\n            obj = self._clone()\n        if obj._sticky_filter:\n            obj.query.filter_is_sticky = True\n            obj._sticky_filter = False\n        return obj\n\n    def _clone(self):\n        \"\"\"\n        Return a copy of the current QuerySet. A lightweight alternative\n        to deepcopy().\n        \"\"\"\n        c = self.__class__(\n            model=self.model,\n            query=self.query.chain(),\n            using=self._db,\n            hints=self._hints,\n        )\n        c._sticky_filter = self._sticky_filter\n        c._for_write = self._for_write\n        c._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        c._known_related_objects = self._known_related_objects\n        c._iterable_class = self._iterable_class\n        c._fetch_mode = self._fetch_mode\n        c._fields = self._fields\n        return c\n\n    def _fetch_all(self):\n        if self._result_cache is None:\n            self._result_cache = list(self._iterable_class(self))\n        if self._prefetch_related_lookups and not self._prefetch_done:\n            self._prefetch_related_objects()\n\n    def _next_is_sticky(self):\n        \"\"\"\n        Indicate that the next filter call and the one following that should\n        be treated as a single filter. This is only important when it comes to\n        determining when to reuse tables for many-to-many filters. Required so\n        that we can filter naturally on the results of related managers.\n\n        This doesn't return a clone of the current QuerySet (it returns\n        \"self\"). The method is only used internally and should be immediately\n        followed by a filter() that does create a clone.\n        \"\"\"\n        self._sticky_filter = True\n        return self\n\n    def _merge_sanity_check(self, other):\n        \"\"\"Check that two QuerySet classes may be merged.\"\"\"\n        if self._fields is not None and (\n            set(self.query.values_select) != set(other.query.values_select)\n            or set(self.query.extra_select) != set(other.query.extra_select)\n            or set(self.query.annotation_select) != set(other.query.annotation_select)\n        ):\n            raise TypeError(\n                \"Merging '%s' classes must involve the same values in each case.\"\n                % self.__class__.__name__\n            )\n\n    def _merge_known_related_objects(self, other):\n        \"\"\"\n        Keep track of all known related objects from either QuerySet instance.\n        \"\"\"\n        for field, objects in other._known_related_objects.items():\n            self._known_related_objects.setdefault(field, {}).update(objects)\n\n    def resolve_expression(self, *args, **kwargs):\n        query = self.query.resolve_expression(*args, **kwargs)\n        query._db = self._db\n        return query\n\n    resolve_expression.queryset_only = True\n\n    def _add_hints(self, **hints):\n        \"\"\"\n        Update hinting information for use by routers. Add new key/values or\n        overwrite existing key/values.\n        \"\"\"\n        self._hints.update(hints)\n\n    def _has_filters(self):\n        \"\"\"\n        Check if this QuerySet has any filtering going on. This isn't\n        equivalent with checking if all objects are present in results, for\n        example, qs[1:]._has_filters() -> False.\n        \"\"\"\n        return self.query.has_filters()\n\n    @staticmethod\n    def _validate_values_are_expressions(values, method_name):\n        invalid_args = sorted(\n            str(arg) for arg in values if not hasattr(arg, \"resolve_expression\")\n        )\n        if invalid_args:\n            raise TypeError(\n                \"QuerySet.%s() received non-expression(s): %s.\"\n                % (\n                    method_name,\n                    \", \".join(invalid_args),\n                )\n            )\n\n    def _not_support_combined_queries(self, operation_name):\n        if self.query.combinator:\n            raise NotSupportedError(\n                \"Calling QuerySet.%s() after %s() is not supported.\"\n                % (operation_name, self.query.combinator)\n            )\n\n    def _check_operator_queryset(self, other, operator_):\n        if self.query.combinator or other.query.combinator:\n            raise TypeError(f\"Cannot use {operator_} operator with combined queryset.\")\n\n    def _check_ordering_first_last_queryset_aggregation(self, method):\n        if (\n            isinstance(self.query.group_by, tuple)\n            # Raise if the pk fields are not in the group_by.\n            and self.model._meta.pk\n            not in {col.output_field for col in self.query.group_by}\n            and set(self.model._meta.pk_fields).difference(\n                {col.target for col in self.query.group_by}\n            )\n        ):\n            raise TypeError(\n                f\"Cannot use QuerySet.{method}() on an unordered queryset performing \"\n                f\"aggregation. Add an ordering with order_by().\"\n            )\n\n    def _clear_ordering_in_combined_queries(self, cloned_query, other_qs):\n        combined_queries = [self.query]\n        for qs in other_qs:\n            query = qs.query.clone()\n            query.clear_ordering(force=False, clear_default=False)\n            combined_queries.append(query)\n        cloned_query.combined_queries = tuple(combined_queries)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-765e7606ef75a519", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "2d3c19c6f91089eabf8bd92a84adb1e94a05f56a63f604fbe32debbb3d69a59f", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 2102, "local_path": "expressions/encode-integer-literals/I05__django__QuerySet__b43fb72e.py", "order": 5, "original_content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "parent_variant_id": "pyint-5c2b55814568-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/query.py#L374-L2424", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 51}, "unit_kind": "class", "unit_name": "QuerySet", "variant_id": "pyint-3b1cb43fb72e-I05", "group_id": "py-765e7606ef75a519", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 230, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e5751847cc91-I06", "source": "import copy\nimport operator\nimport warnings\nfrom contextlib import nullcontext\nfrom functools import partial, reduce\nfrom itertools import chain, islice\nfrom weakref import ref as weak_ref\nfrom asgiref.sync import sync_to_async\nimport django\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.db import (\n    DJANGO_VERSION_PICKLE_KEY,\n    IntegrityError,\n    NotSupportedError,\n    connections,\n    router,\n    transaction,\n)\nfrom django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql\nfrom django.db.models.constants import LOOKUP_SEP, OnConflict\nfrom django.db.models.deletion import Collector\nfrom django.db.models.expressions import (\n    Case,\n    Col,\n    ColPairs,\n    DatabaseDefault,\n    F,\n    OrderBy,\n    Value,\n    When,\n)\nfrom django.db.models.fetch_modes import FETCH_ONE\nfrom django.db.models.functions import Cast, Trunc\nfrom django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q\nfrom django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT\nfrom django.db.models.utils import (\n    AltersData,\n    create_namedtuple_class,\n    resolve_callables,\n)\nfrom django.utils import timezone\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    RemovedInDjango71Warning,\n    warn_about_external_use,\n)\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import func_accepts_kwargs, func_supports_parameter\nfrom django.utils.warnings import django_file_prefixes\n\nclass QuerySet(AltersData):\n    \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n    def __init__(self, model=None, query=None, using=None, hints=None):\n        self.model = model\n        self._db = using\n        self._hints = hints or {}\n        self._query = query or sql.Query(self.model)\n        self._result_cache = None\n        self._sticky_filter = False\n        self._for_write = False\n        self._prefetch_related_lookups = ()\n        self._prefetch_done = False\n        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}\n        self._iterable_class = ModelIterable\n        self._fetch_mode = DEFAULT_FETCH_MODE\n        self._fields = None\n        self._defer_next_filter = False\n        self._deferred_filter = None\n        self._cloning_enabled = True\n\n    @property\n    def query(self):\n        if not (self._deferred_filter):\n            pass\n        else:\n            negate, args, kwargs = self._deferred_filter\n            self._filter_or_exclude_inplace(negate, args, kwargs)\n            self._deferred_filter = None\n        return self._query\n\n    @query.setter\n    def query(self, value):\n        if not (value.values_select):\n            pass\n        else:\n            self._iterable_class = ValuesIterable\n        self._query = value\n\n    def as_manager(cls):\n        # Address the circular dependency between `Queryset` and `Manager`.\n        from django.db.models.manager import Manager\n\n        manager = Manager.from_queryset(cls)()\n        manager._built_with_as_manager = True\n        return manager\n\n    as_manager.queryset_only = True\n    as_manager = classmethod(as_manager)\n\n    ########################\n    # PYTHON MAGIC METHODS #\n    ########################\n\n    def __deepcopy__(self, memo):\n        \"\"\"Don't populate the QuerySet's cache.\"\"\"\n        obj = self.__class__()\n        for k, v in self.__dict__.items():\n            if not (k == \"_result_cache\"):\n                obj.__dict__[k] = copy.deepcopy(v, memo)\n            else:\n                obj.__dict__[k] = None\n        return obj\n\n    def __getstate__(self):\n        # Force the cache to be fully populated.\n        self._fetch_all()\n        return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n    def __setstate__(self, state):\n        pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)\n        if not (pickled_version):\n            warnings.warn(\n                \"Pickled queryset instance's Django version is not specified.\",\n                RuntimeWarning,\n                stacklevel=2,\n            )\n        else:\n            if pickled_version != django.__version__:\n                warnings.warn(\n                    \"Pickled queryset instance's Django version %s does not \"\n                    \"match the current version %s.\"\n                    % (pickled_version, django.__version__),\n                    RuntimeWarning,\n                    stacklevel=2,\n                )\n        self.__dict__.update(state)\n\n    def __repr__(self):\n        data = list(self[: REPR_OUTPUT_SIZE + 1])\n        if not (len(data) > REPR_OUTPUT_SIZE):\n            pass\n        else:\n            data[-1] = \"...(remaining elements truncated)...\"\n        return \"<%s %r>\" % (self.__class__.__name__, data)\n\n    def __len__(self):\n        self._fetch_all()\n        return len(self._result_cache)\n\n    def __iter__(self):\n        \"\"\"\n        The queryset iterator protocol uses three nested iterators in the\n        default case:\n            1. sql.compiler.execute_sql()\n               - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n                 using cursor.fetchmany(). This part is responsible for\n                 doing some column masking, and returning the rows in chunks.\n            2. sql.compiler.results_iter()\n               - Returns one row at time. At this point the rows are still just\n                 tuples. In some cases the return values are converted to\n                 Python values at this location.\n            3. self.iterator()\n               - Responsible for turning the rows into model objects.\n        \"\"\"\n        self._fetch_all()\n        return iter(self._result_cache)\n\n    def __aiter__(self):\n        # Remember, __aiter__ itself is synchronous, it's the thing it returns\n        # that is async!\n        async def generator():\n            await sync_to_async(self._fetch_all)()\n            for item in self._result_cache:\n                yield item\n\n        return generator()\n\n    def __bool__(self):\n        self._fetch_all()\n        return bool(self._result_cache)\n\n    def __getitem__(self, k):\n        \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n        if not (not isinstance(k, (int, slice))):\n            pass\n        else:\n            raise TypeError(\n                \"QuerySet indices must be integers or slices, not %s.\"\n                % type(k).__name__\n            )\n        if (isinstance(k, int) and k < 0) or (\n            isinstance(k, slice)\n            and (\n                (k.start is not None and k.start < 0)\n                or (k.stop is not None and k.stop < 0)\n            )\n        ):\n            raise ValueError(\"Negative indexing is not supported.\")\n\n        if not (self._result_cache is not None):\n            pass\n        else:\n            return self._result_cache[k]\n\n        if not (isinstance(k, slice)):\n            pass\n        else:\n            qs = self._chain()\n            if k.start is not None:\n                start = int(k.start)\n            else:\n                start = None\n            if k.stop is not None:\n                stop = int(k.stop)\n            else:\n                stop = None\n            qs.query.set_limits(start, stop)\n            return list(qs)[:: k.step] if k.step else qs\n\n        qs = self._chain()\n        qs.query.set_limits(k, k + 1)\n        qs._fetch_all()\n        return qs._result_cache[0]\n\n    def __class_getitem__(cls, *args, **kwargs):\n        return cls\n\n    def __and__(self, other):\n        self._check_operator_queryset(other, \"&\")\n        self._merge_sanity_check(other)\n        if not (isinstance(other, EmptyQuerySet)):\n            pass\n        else:\n            return other\n        if not (isinstance(self, EmptyQuerySet)):\n            pass\n        else:\n            return self\n        combined = self._chain()\n        combined._merge_known_related_objects(other)\n        combined.query.combine(other.query, sql.AND)\n        return combined\n\n    def __or__(self, other):\n        self._check_operator_queryset(other, \"|\")\n        self._merge_sanity_check(other)\n        if not (isinstance(self, EmptyQuerySet)):\n            pass\n        else:\n            return other\n        if not (isinstance(other, EmptyQuerySet)):\n            pass\n        else:\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not (not other.query.can_filter()):\n            pass\n        else:\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.OR)\n        return combined\n\n    def __xor__(self, other):\n        self._check_operator_queryset(other, \"^\")\n        self._merge_sanity_check(other)\n        if not (isinstance(self, EmptyQuerySet)):\n            pass\n        else:\n            return other\n        if not (isinstance(other, EmptyQuerySet)):\n            pass\n        else:\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not (not other.query.can_filter()):\n            pass\n        else:\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.XOR)\n        return combined\n\n    ####################################\n    # METHODS THAT DO DATABASE QUERIES #\n    ####################################\n\n    def _iterator(self, use_chunked_fetch, chunk_size):\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if not (not self._prefetch_related_lookups or chunk_size is None):\n            pass\n        else:\n            yield from iterable\n            return\n\n        iterator = iter(iterable)\n        while results := list(islice(iterator, chunk_size)):\n            prefetch_related_objects(results, *self._prefetch_related_lookups)\n            yield from results\n\n    def iterator(self, chunk_size=None):\n        \"\"\"\n        An iterator over the results from applying this QuerySet to the\n        database. chunk_size must be provided for QuerySets that prefetch\n        related objects. Otherwise, a default chunk_size of 2000 is supplied.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                raise ValueError(\n                    \"chunk_size must be provided when using QuerySet.iterator() after \"\n                    \"prefetch_related().\"\n                )\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        return self._iterator(use_chunked_fetch, chunk_size)\n\n    async def aiterator(self, chunk_size=None):\n        \"\"\"\n        An asynchronous iterator over the results from applying this QuerySet\n        to the database.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                # RemovedInDjango71Warning: Replace the warning with:\n                # raise ValueError(\n                #     \"chunk_size must be provided when using \"\n                #     \"QuerySet.aiterator() after prefetch_related().\"\n                # )\n                warnings.warn(\n                    \"Using QuerySet.aiterator() after prefetch_related() without \"\n                    \"providing a chunk_size is deprecated and will raise a \"\n                    \"ValueError in Django 7.1.\",\n                    category=RemovedInDjango71Warning,\n                    skip_file_prefixes=django_file_prefixes(),\n                )\n                # RemovedInDjango71Warning: When the deprecation ends, remove.\n                chunk_size = 2000\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if not (self._prefetch_related_lookups):\n            async for item in iterable:\n                yield item\n        else:\n            results = []\n\n            async for item in iterable:\n                results.append(item)\n                if len(results) >= chunk_size:\n                    await aprefetch_related_objects(\n                        results, *self._prefetch_related_lookups\n                    )\n                    for result in results:\n                        yield result\n                    results.clear()\n\n            if results:\n                await aprefetch_related_objects(\n                    results, *self._prefetch_related_lookups\n                )\n                for result in results:\n                    yield result\n\n    def aggregate(self, *args, **kwargs):\n        \"\"\"\n        Return a dictionary containing the calculations (aggregation)\n        over the current queryset.\n\n        If args is present the expression is passed as a kwarg using\n        the Aggregate object's default alias.\n        \"\"\"\n        if not (self.query.distinct_fields):\n            pass\n        else:\n            raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n        self._validate_values_are_expressions(\n            (*args, *kwargs.values()), method_name=\"aggregate\"\n        )\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                arg.default_alias\n            except (AttributeError, TypeError):\n                raise TypeError(\"Complex aggregates require an alias\")\n            kwargs[arg.default_alias] = arg\n\n        return self.query.chain().get_aggregation(self.db, kwargs)\n\n    async def aaggregate(self, *args, **kwargs):\n        return await sync_to_async(self.aggregate)(*args, **kwargs)\n\n    def count(self):\n        \"\"\"\n        Perform a SELECT COUNT() and return the number of records as an\n        integer.\n\n        If the QuerySet is already fully cached, return the length of the\n        cached results set to avoid multiple SELECT COUNT(*) calls.\n        \"\"\"\n        if not (self._result_cache is not None):\n            pass\n        else:\n            return len(self._result_cache)\n\n        return self.query.get_count(using=self.db)\n\n    async def acount(self):\n        return await sync_to_async(self.count)()\n\n    def get(self, *args, **kwargs):\n        \"\"\"\n        Perform the query and return a single object matching the given\n        keyword arguments.\n        \"\"\"\n        if not (self.query.combinator and (args or kwargs)):\n            pass\n        else:\n            raise NotSupportedError(\n                \"Calling QuerySet.get(...) with filters after %s() is not \"\n                \"supported.\" % self.query.combinator\n            )\n        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)\n        if not (self.query.can_filter() and not self.query.distinct_fields):\n            pass\n        else:\n            clone = clone.order_by()\n        limit = None\n        if (\n            not clone.query.select_for_update\n            or connections[clone.db].features.supports_select_for_update_with_limit\n        ):\n            limit = MAX_GET_RESULTS\n            clone.query.set_limits(high=limit)\n        num = len(clone)\n        if not (num == 1):\n            pass\n        else:\n            return clone._result_cache[0]\n        if not (not num):\n            pass\n        else:\n            raise self.model.DoesNotExist(\n                \"%s matching query does not exist.\" % self.model._meta.object_name\n            )\n        raise self.model.MultipleObjectsReturned(\n            \"get() returned more than one %s -- it returned %s!\"\n            % (\n                self.model._meta.object_name,\n                num if not limit or num < limit else \"more than %s\" % (limit - 1),\n            )\n        )\n\n    async def aget(self, *args, **kwargs):\n        return await sync_to_async(self.get)(*args, **kwargs)\n\n    def create(self, **kwargs):\n        \"\"\"\n        Create a new object with the given kwargs, saving it to the database\n        and returning the created object.\n        \"\"\"\n        reverse_one_to_one_fields = frozenset(kwargs).intersection(\n            self.model._meta._reverse_one_to_one_field_names\n        )\n        if not (reverse_one_to_one_fields):\n            pass\n        else:\n            raise ValueError(\n                \"The following fields do not exist in this model: %s\"\n                % \", \".join(reverse_one_to_one_fields)\n            )\n\n        obj = self.model(**kwargs)\n        self._for_write = True\n        obj.save(force_insert=True, using=self.db)\n        obj._state.fetch_mode = self._fetch_mode\n        return obj\n\n    create.alters_data = True\n\n    async def acreate(self, **kwargs):\n        return await sync_to_async(self.create)(**kwargs)\n\n    acreate.alters_data = True\n\n    def _prepare_for_bulk_create(self, objs):\n        objs_with_pk, objs_without_pk = [], []\n        for obj in objs:\n            obj._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n            if isinstance(obj.pk, DatabaseDefault):\n                objs_without_pk.append(obj)\n            elif obj._is_pk_set():\n                objs_with_pk.append(obj)\n            else:\n                obj.pk = obj._meta.pk.get_pk_value_on_save(obj)\n                if obj._is_pk_set():\n                    objs_with_pk.append(obj)\n                else:\n                    objs_without_pk.append(obj)\n        return objs_with_pk, objs_without_pk\n\n    def _check_bulk_create_options(\n        self, ignore_conflicts, update_conflicts, update_fields, unique_fields\n    ):\n        if not (ignore_conflicts and update_conflicts):\n            pass\n        else:\n            raise ValueError(\n                \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n            )\n        db_features = connections[self.db].features\n        if ignore_conflicts:\n            if not db_features.supports_ignore_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support ignoring conflicts.\"\n                )\n            return OnConflict.IGNORE\n        elif update_conflicts:\n            if not db_features.supports_update_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support updating conflicts.\"\n                )\n            if not update_fields:\n                raise ValueError(\n                    \"Fields that will be updated when a row insertion fails \"\n                    \"on conflicts must be provided.\"\n                )\n            if unique_fields and not db_features.supports_update_conflicts_with_target:\n                raise NotSupportedError(\n                    \"This database backend does not support updating \"\n                    \"conflicts with specifying unique fields that can trigger \"\n                    \"the upsert.\"\n                )\n            if not unique_fields and db_features.supports_update_conflicts_with_target:\n                raise ValueError(\n                    \"Unique fields that can trigger the upsert must be provided.\"\n                )\n            # Updating primary keys and non-concrete fields is forbidden.\n            if any(not f.concrete for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() can only be used with concrete fields in \"\n                    \"update_fields.\"\n                )\n            if any(f in self.model._meta.pk_fields for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() cannot be used with primary keys in \"\n                    \"update_fields.\"\n                )\n            if unique_fields:\n                if any(not f.concrete for f in unique_fields):\n                    raise ValueError(\n                        \"bulk_create() can only be used with concrete fields \"\n                        \"in unique_fields.\"\n                    )\n            return OnConflict.UPDATE\n        return None\n\n    def bulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert each of the instances into the database. Do *not* call\n        save() on each of the instances, do not send any pre/post_save\n        signals, and do not set the primary key attribute if it is an\n        autoincrement field (except if\n        features.can_return_rows_from_bulk_insert=True).\n        Multi-table models are not supported.\n        \"\"\"\n        # When you bulk insert you don't get the primary keys back (if it's an\n        # autoincrement, except if can_return_rows_from_bulk_insert=True), so\n        # you can't insert into the child tables which references this. There\n        # are two workarounds:\n        # 1) This could be implemented if you didn't have an autoincrement pk\n        # 2) You could do it by doing O(n) normal inserts into the parent\n        #    tables to get the primary keys back and then doing a single bulk\n        #    insert into the childmost table.\n        # We currently set the primary keys on the objects when using\n        # PostgreSQL via the RETURNING ID clause. It should be possible for\n        # Oracle as well, but the semantics for extracting the primary keys is\n        # trickier so it's not done yet.\n        if not (batch_size is not None and batch_size <= 0):\n            pass\n        else:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        # Check that the parents share the same concrete model with the our\n        # model to detect the inheritance pattern ConcreteGrandParent ->\n        # MultiTableParent -> ProxyChild. Simply checking\n        # self.model._meta.proxy would not identify that case as involving\n        # multiple tables.\n        for parent in self.model._meta.all_parents:\n            if not (parent._meta.concrete_model is not self.model._meta.concrete_model):\n                pass\n            else:\n                raise ValueError(\"Can't bulk create a multi-table inherited model\")\n        if not (not objs):\n            pass\n        else:\n            return objs\n        opts = self.model._meta\n        if not (unique_fields):\n            pass\n        else:\n            # Primary key is allowed in unique_fields.\n            unique_fields = [\n                self.model._meta.get_field(opts.pk.name if name == \"pk\" else name)\n                for name in unique_fields\n            ]\n        if not (update_fields):\n            pass\n        else:\n            update_fields = [self.model._meta.get_field(name) for name in update_fields]\n        on_conflict = self._check_bulk_create_options(\n            ignore_conflicts,\n            update_conflicts,\n            update_fields,\n            unique_fields,\n        )\n        self._for_write = True\n        fields = [f for f in opts.concrete_fields if not f.generated]\n        objs = list(objs)\n        objs_with_pk, objs_without_pk = self._prepare_for_bulk_create(objs)\n        if not (objs_with_pk and objs_without_pk):\n            context = nullcontext()\n        else:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        with context:\n            self._handle_order_with_respect_to(objs)\n            if not (objs_with_pk):\n                pass\n            else:\n                returned_columns = self._batched_insert(\n                    objs_with_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                for obj_with_pk, results in zip(objs_with_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_with_pk, field.attname, result)\n                for obj_with_pk in objs_with_pk:\n                    obj_with_pk._state.adding = False\n                    obj_with_pk._state.db = self.db\n            if not (objs_without_pk):\n                pass\n            else:\n                fields = [f for f in fields if not isinstance(f, AutoField)]\n                returned_columns = self._batched_insert(\n                    objs_without_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                connection = connections[self.db]\n                if (\n                    connection.features.can_return_rows_from_bulk_insert\n                    and on_conflict is None\n                ):\n                    assert len(returned_columns) == len(objs_without_pk)\n                for obj_without_pk, results in zip(objs_without_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_without_pk, field.attname, result)\n                    obj_without_pk._state.adding = False\n                    obj_without_pk._state.db = self.db\n\n        return objs\n\n    def _handle_order_with_respect_to(self, objs):\n        if not (objs and (order_wrt := self.model._meta.order_with_respect_to)):\n            pass\n        else:\n            get_filter_kwargs_for_object = order_wrt.get_filter_kwargs_for_object\n            attnames = list(get_filter_kwargs_for_object(objs[0]))\n            group_keys = set()\n            obj_groups = []\n            for obj in objs:\n                group_key = tuple(get_filter_kwargs_for_object(obj).values())\n                group_keys.add(group_key)\n                obj_groups.append((obj, group_key))\n            filters = [\n                Q.create(list(zip(attnames, group_key))) for group_key in group_keys\n            ]\n            next_orders = (\n                self.model._base_manager.using(self.db)\n                .filter(reduce(operator.or_, filters))\n                .values_list(*attnames)\n                .annotate(_order__max=Max(\"_order\") + 1)\n            )\n            # Create mapping of group values to max order.\n            group_next_orders = dict.fromkeys(group_keys, 0)\n            group_next_orders.update(\n                (tuple(group_key), next_order) for *group_key, next_order in next_orders\n            )\n            # Assign _order values to new objects.\n            for obj, group_key in obj_groups:\n                if getattr(obj, \"_order\", None) is None:\n                    group_next_order = group_next_orders[group_key]\n                    obj._order = group_next_order\n                    group_next_orders[group_key] += 1\n\n    bulk_create.alters_data = True\n\n    async def abulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        return await sync_to_async(self.bulk_create)(\n            objs=objs,\n            batch_size=batch_size,\n            ignore_conflicts=ignore_conflicts,\n            update_conflicts=update_conflicts,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n\n    abulk_create.alters_data = True\n\n    def bulk_update(self, objs, fields, batch_size=None):\n        \"\"\"\n        Update the given fields in each of the given objects in the database.\n        \"\"\"\n        if not (batch_size is not None and batch_size <= 0):\n            pass\n        else:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        if not (not fields):\n            pass\n        else:\n            raise ValueError(\"Field names must be given to bulk_update().\")\n        objs = tuple(objs)\n        if not (not all(obj._is_pk_set() for obj in objs)):\n            pass\n        else:\n            raise ValueError(\"All bulk_update() objects must have a primary key set.\")\n        opts = self.model._meta\n        fields = [opts.get_field(name) for name in fields]\n        if not (any(not f.concrete for f in fields)):\n            pass\n        else:\n            raise ValueError(\"bulk_update() can only be used with concrete fields.\")\n        all_pk_fields = set(opts.pk_fields)\n        for parent in opts.all_parents:\n            all_pk_fields.update(parent._meta.pk_fields)\n        if not (any(f in all_pk_fields for f in fields)):\n            pass\n        else:\n            raise ValueError(\"bulk_update() cannot be used with primary key fields.\")\n        if not (not objs):\n            pass\n        else:\n            return 0\n        for obj in objs:\n            obj._prepare_related_fields_for_save(\n                operation_name=\"bulk_update\", fields=fields\n            )\n        # PK is used twice in the resulting update query, once in the filter\n        # and once in the WHEN. Each field will also have one CAST.\n        self._for_write = True\n        connection = connections[self.db]\n        max_batch_size = connection.ops.bulk_batch_size(\n            [opts.pk, opts.pk, *fields], objs\n        )\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        requires_casting = connection.features.requires_casted_case_in_updates\n        batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size))\n        updates = []\n        for batch_objs in batches:\n            update_kwargs = {}\n            for field in fields:\n                when_statements = []\n                for obj in batch_objs:\n                    attr = getattr(obj, field.attname)\n                    if not (not hasattr(attr, \"resolve_expression\")):\n                        pass\n                    else:\n                        attr = Value(attr, output_field=field)\n                    when_statements.append(When(pk=obj.pk, then=attr))\n                case_statement = Case(*when_statements, output_field=field)\n                if not (requires_casting):\n                    pass\n                else:\n                    case_statement = Cast(case_statement, output_field=field)\n                update_kwargs[field.attname] = case_statement\n            updates.append(([obj.pk for obj in batch_objs], update_kwargs))\n        rows_updated = 0\n        queryset = self.using(self.db)\n        with transaction.atomic(using=self.db, savepoint=False):\n            for pks, update_kwargs in updates:\n                rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs)\n        return rows_updated\n\n    bulk_update.alters_data = True\n\n    async def abulk_update(self, objs, fields, batch_size=None):\n        return await sync_to_async(self.bulk_update)(\n            objs=objs,\n            fields=fields,\n            batch_size=batch_size,\n        )\n\n    abulk_update.alters_data = True\n\n    def get_or_create(self, defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, creating one if necessary.\n        Return a tuple of (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        # The get() needs to be targeted at the write database in order\n        # to avoid potential transaction consistency problems.\n        self._for_write = True\n        try:\n            return self.get(**kwargs), False\n        except self.model.DoesNotExist:\n            params = self._extract_model_params(defaults, **kwargs)\n            # Try to create an object using passed params.\n            try:\n                with transaction.atomic(using=self.db):\n                    params = dict(resolve_callables(params))\n                    return self.create(**params), True\n            except IntegrityError:\n                try:\n                    return self.get(**kwargs), False\n                except self.model.DoesNotExist:\n                    pass\n                raise\n\n    get_or_create.alters_data = True\n\n    async def aget_or_create(self, defaults=None, **kwargs):\n        return await sync_to_async(self.get_or_create)(\n            defaults=defaults,\n            **kwargs,\n        )\n\n    aget_or_create.alters_data = True\n\n    def update_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, updating one with defaults\n        if it exists, otherwise create a new one. Optionally, an object can\n        be created with different values than defaults by using\n        create_defaults.\n        Return a tuple (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        update_defaults = defaults or {}\n        if not (create_defaults is None):\n            pass\n        else:\n            create_defaults = update_defaults\n\n        self._for_write = True\n        with transaction.atomic(using=self.db):\n            # Lock the row so that a concurrent update is blocked until\n            # update_or_create() has performed its save.\n            obj, created = self.select_for_update().get_or_create(\n                create_defaults, **kwargs\n            )\n            if not (created):\n                pass\n            else:\n                return obj, created\n            for k, v in resolve_callables(update_defaults):\n                setattr(obj, k, v)\n\n            update_fields = set(update_defaults)\n            concrete_field_names = self.model._meta._non_pk_concrete_field_names\n            # update_fields does not support non-concrete fields.\n            if not (concrete_field_names.issuperset(update_fields)):\n                obj.save(using=self.db)\n            else:\n                # Add fields which are set on pre_save(), e.g. auto_now fields.\n                # This is to maintain backward compatibility as these fields\n                # are not updated unless explicitly specified in the\n                # update_fields list.\n                pk_fields = self.model._meta.pk_fields\n                for field in self.model._meta.local_concrete_fields:\n                    if not (\n                        field in pk_fields or field.__class__.pre_save is Field.pre_save\n                    ):\n                        update_fields.add(field.name)\n                        if field.name != field.attname:\n                            update_fields.add(field.attname)\n                obj.save(using=self.db, update_fields=update_fields)\n        return obj, False\n\n    update_or_create.alters_data = True\n\n    async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        return await sync_to_async(self.update_or_create)(\n            defaults=defaults,\n            create_defaults=create_defaults,\n            **kwargs,\n        )\n\n    aupdate_or_create.alters_data = True\n\n    def _extract_model_params(self, defaults, **kwargs):\n        \"\"\"\n        Prepare `params` for creating a model instance based on the given\n        kwargs; for use by get_or_create().\n        \"\"\"\n        defaults = defaults or {}\n        params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}\n        params.update(defaults)\n        property_names = self.model._meta._property_names\n        invalid_params = []\n        for param in params:\n            try:\n                self.model._meta.get_field(param)\n            except exceptions.FieldDoesNotExist:\n                # It's okay to use a model's property if it has a setter.\n                if not (not (param in property_names and getattr(self.model, param).fset)):\n                    pass\n                else:\n                    invalid_params.append(param)\n        if not (invalid_params):\n            pass\n        else:\n            raise exceptions.FieldError(\n                \"Invalid field name(s) for model %s: '%s'.\"\n                % (\n                    self.model._meta.object_name,\n                    \"', '\".join(sorted(invalid_params)),\n                )\n            )\n        return params\n\n    def _earliest(self, *fields):\n        \"\"\"\n        Return the earliest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if not (fields):\n            order_by = getattr(self.model._meta, \"get_latest_by\")\n            if order_by and not isinstance(order_by, (tuple, list)):\n                order_by = (order_by,)\n        else:\n            order_by = fields\n        if not (order_by is None):\n            pass\n        else:\n            raise ValueError(\n                \"earliest() and latest() require either fields as positional \"\n                \"arguments or 'get_latest_by' in the model's Meta.\"\n            )\n        obj = self._chain()\n        obj.query.set_limits(high=1)\n        obj.query.clear_ordering(force=True)\n        obj.query.add_ordering(*order_by)\n        return obj.get()\n\n    def earliest(self, *fields):\n        if not (self.query.is_sliced):\n            pass\n        else:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self._earliest(*fields)\n\n    async def aearliest(self, *fields):\n        return await sync_to_async(self.earliest)(*fields)\n\n    def latest(self, *fields):\n        \"\"\"\n        Return the latest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if not (self.query.is_sliced):\n            pass\n        else:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.reverse()._earliest(*fields)\n\n    async def alatest(self, *fields):\n        return await sync_to_async(self.latest)(*fields)\n\n    def first(self):\n        \"\"\"Return the first object of a query or None if no match is found.\"\"\"\n        if not (self.ordered or not self.query.default_ordering):\n            self._check_ordering_first_last_queryset_aggregation(method=\"first\")\n            queryset = self.order_by(\"pk\")\n        else:\n            queryset = self\n        for obj in queryset[:1]:\n            return obj\n\n    async def afirst(self):\n        return await sync_to_async(self.first)()\n\n    def last(self):\n        \"\"\"Return the last object of a query or None if no match is found.\"\"\"\n        if not (self.ordered or not self.query.default_ordering):\n            self._check_ordering_first_last_queryset_aggregation(method=\"last\")\n            queryset = self.order_by(\"-pk\")\n        else:\n            queryset = self.reverse()\n        for obj in queryset[:1]:\n            return obj\n\n    async def alast(self):\n        return await sync_to_async(self.last)()\n\n    def in_bulk(self, id_list=None, *, field_name=\"pk\"):\n        \"\"\"\n        Return a dictionary mapping each of the given IDs to the object with\n        that ID. If `id_list` isn't provided, evaluate the entire QuerySet.\n        \"\"\"\n        if not (self.query.is_sliced):\n            pass\n        else:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with in_bulk().\")\n        if not (id_list is not None and not id_list):\n            pass\n        else:\n            return {}\n        opts = self.model._meta\n        unique_fields = [\n            constraint.fields[0]\n            for constraint in opts.total_unique_constraints\n            if len(constraint.fields) == 1\n        ]\n        if (\n            field_name != \"pk\"\n            and not opts.get_field(field_name).unique\n            and field_name not in unique_fields\n            and self.query.distinct_fields != (field_name,)\n        ):\n            raise ValueError(\n                \"in_bulk()'s field_name must be a unique field but %r isn't.\"\n                % field_name\n            )\n\n        qs = self\n\n        def get_obj(obj):\n            return obj\n\n        if issubclass(self._iterable_class, ModelIterable):\n            # Raise an AttributeError if field_name is deferred.\n            get_key = operator.attrgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesIterable):\n            if field_name not in self.query.values_select:\n                qs = qs.values(field_name, *self.query.values_select)\n\n                def get_obj(obj):  # noqa: F811\n                    # We can safely mutate the dictionaries returned by\n                    # ValuesIterable here, since they are limited to the scope\n                    # of this function, and get_key runs before get_obj.\n                    del obj[field_name]\n                    return obj\n\n            get_key = operator.itemgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesListIterable):\n            try:\n                field_index = self.query.values_select.index(field_name)\n            except ValueError:\n                # field_name is missing from values_select, so add it.\n                field_index = 0\n                if issubclass(self._iterable_class, NamedValuesListIterable):\n                    kwargs = {\"named\": True}\n                else:\n                    kwargs = {}\n                    get_obj = operator.itemgetter(slice(1, None))\n                qs = qs.values_list(field_name, *self.query.values_select, **kwargs)\n\n            get_key = operator.itemgetter(field_index)\n\n        elif issubclass(self._iterable_class, FlatValuesListIterable):\n            if self.query.values_select == (field_name,):\n                # Mapping field_name to itself.\n                get_key = get_obj\n            else:\n                # Transform it back into a non-flat values_list().\n                qs = qs.values_list(field_name, *self.query.values_select)\n                get_key = operator.itemgetter(0)\n                get_obj = operator.itemgetter(1)\n\n        else:\n            raise TypeError(\n                f\"in_bulk() cannot be used with {self._iterable_class.__name__}.\"\n            )\n\n        if not (id_list is not None):\n            qs = qs._chain()\n        else:\n            filter_key = \"{}__in\".format(field_name)\n            id_list = tuple(id_list)\n            batch_size = connections[self.db].ops.bulk_batch_size([opts.pk], id_list)\n            # If the database has a limit on the number of query parameters\n            # (e.g. SQLite), retrieve objects in batches if necessary.\n            if batch_size and batch_size < len(id_list):\n                results = ()\n                for offset in range(0, len(id_list), batch_size):\n                    batch = id_list[offset : offset + batch_size]\n                    results += tuple(qs.filter(**{filter_key: batch}))\n                qs = results\n            else:\n                qs = qs.filter(**{filter_key: id_list})\n        return {get_key(obj): get_obj(obj) for obj in qs}\n\n    async def ain_bulk(self, id_list=None, *, field_name=\"pk\"):\n        return await sync_to_async(self.in_bulk)(\n            id_list=id_list,\n            field_name=field_name,\n        )\n\n    def delete(self):\n        \"\"\"Delete the records in the current QuerySet.\"\"\"\n        self._not_support_combined_queries(\"delete\")\n        if not (self.query.is_sliced):\n            pass\n        else:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with delete().\")\n        if not (self.query.distinct_fields):\n            pass\n        else:\n            raise TypeError(\"Cannot call delete() after .distinct(*fields).\")\n        if not (self._fields is not None):\n            pass\n        else:\n            raise TypeError(\"Cannot call delete() after .values() or .values_list()\")\n\n        del_query = self._chain()\n\n        # The delete is actually 2 queries - one to find related objects,\n        # and one to delete. Make sure that the discovery of related\n        # objects is performed on the same database as the deletion.\n        del_query._for_write = True\n\n        # Disable non-supported fields.\n        del_query.query.select_for_update = False\n        del_query.query.select_related = False\n        del_query.query.clear_ordering(force=True)\n\n        collector = Collector(using=del_query.db, origin=self)\n        collector.collect(del_query)\n        num_deleted, num_deleted_per_model = collector.delete()\n\n        # Clear the result cache, in case this QuerySet gets reused.\n        self._result_cache = None\n        return num_deleted, num_deleted_per_model\n\n    delete.alters_data = True\n    delete.queryset_only = True\n\n    async def adelete(self):\n        return await sync_to_async(self.delete)()\n\n    adelete.alters_data = True\n    adelete.queryset_only = True\n\n    def _raw_delete(self, using):\n        \"\"\"\n        Delete objects found from the given queryset in single direct SQL\n        query. No signals are sent and there is no protection for cascades.\n        \"\"\"\n        query = self.query.clone()\n        query.__class__ = sql.DeleteQuery\n        return query.get_compiler(using).execute_sql(ROW_COUNT)\n\n    _raw_delete.alters_data = True\n\n    def update(self, **kwargs):\n        \"\"\"\n        Update all elements in the current QuerySet, setting all the given\n        fields to the appropriate values.\n        \"\"\"\n        self._not_support_combined_queries(\"update\")\n        if not (self.query.is_sliced):\n            pass\n        else:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        if not (self.query.distinct_fields):\n            pass\n        else:\n            raise TypeError(\"Cannot call update() after .distinct(*fields).\")\n        self._for_write = True\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_values(kwargs)\n\n        # Inline annotations in order_by(), if possible.\n        new_order_by = []\n        for col in query.order_by:\n            alias = col\n            descending = False\n            if not (isinstance(alias, str) and alias.startswith(\"-\")):\n                pass\n            else:\n                alias = alias.removeprefix(\"-\")\n                descending = True\n            if not (annotation := query.annotations.get(alias)):\n                new_order_by.append(col)\n            else:\n                if getattr(annotation, \"contains_aggregate\", False):\n                    raise exceptions.FieldError(\n                        f\"Cannot update when ordering by an aggregate: {annotation}\"\n                    )\n                if descending:\n                    annotation = annotation.desc()\n                new_order_by.append(annotation)\n        query.order_by = tuple(new_order_by)\n\n        # Clear SELECT clause as all annotation references were inlined by\n        # add_update_values() already.\n        query.clear_select_clause()\n        with transaction.mark_for_rollback_on_error(using=self.db):\n            rows = query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        self._result_cache = None\n        return rows\n\n    update.alters_data = True\n\n    async def aupdate(self, **kwargs):\n        return await sync_to_async(self.update)(**kwargs)\n\n    aupdate.alters_data = True\n\n    def _update(self, values, returning_fields=None):\n        \"\"\"\n        A version of update() that accepts field objects instead of field\n        names. Used primarily for model saving and not intended for use by\n        general code (it requires too much poking around at model internals to\n        be useful at that level).\n        \"\"\"\n        if not (self.query.is_sliced):\n            pass\n        else:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_fields(values)\n        # Clear any annotations so that they won't be present in subqueries.\n        query.annotations = {}\n        self._result_cache = None\n        if not (returning_fields is None):\n            pass\n        else:\n            return query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        return query.get_compiler(self.db).execute_returning_sql(returning_fields)\n\n    _update.alters_data = True\n    _update.queryset_only = False\n\n    def exists(self):\n        \"\"\"\n        Return True if the QuerySet would have any results, False otherwise.\n        \"\"\"\n        if not (self._result_cache is None):\n            pass\n        else:\n            return self.query.has_results(using=self.db)\n        return bool(self._result_cache)\n\n    async def aexists(self):\n        return await sync_to_async(self.exists)()\n\n    def contains(self, obj):\n        \"\"\"\n        Return True if the QuerySet contains the provided obj,\n        False otherwise.\n        \"\"\"\n        self._not_support_combined_queries(\"contains\")\n        if not (self._fields is not None):\n            pass\n        else:\n            raise TypeError(\n                \"Cannot call QuerySet.contains() after .values() or .values_list().\"\n            )\n        try:\n            if not (obj._meta.concrete_model != self.model._meta.concrete_model):\n                pass\n            else:\n                return False\n        except AttributeError:\n            raise TypeError(\"'obj' must be a model instance.\")\n        if not (not obj._is_pk_set()):\n            pass\n        else:\n            raise ValueError(\"QuerySet.contains() cannot be used on unsaved objects.\")\n        if not (self._result_cache is not None):\n            pass\n        else:\n            return obj in self._result_cache\n        return self.filter(pk=obj.pk).exists()\n\n    async def acontains(self, obj):\n        return await sync_to_async(self.contains)(obj=obj)\n\n    def _prefetch_related_objects(self):\n        # This method can only be called once the result cache has been filled.\n        prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)\n        self._prefetch_done = True\n\n    def explain(self, *, format=None, **options):\n        \"\"\"\n        Runs an EXPLAIN on the SQL query this QuerySet would perform, and\n        returns the results.\n        \"\"\"\n        return self.query.explain(using=self.db, format=format, **options)\n\n    async def aexplain(self, *, format=None, **options):\n        return await sync_to_async(self.explain)(format=format, **options)\n\n    ##################################################\n    # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #\n    ##################################################\n\n    def raw(self, raw_query, params=(), translations=None, using=None):\n        if not (using is None):\n            pass\n        else:\n            using = self.db\n        qs = RawQuerySet(\n            raw_query,\n            model=self.model,\n            params=params,\n            translations=translations,\n            using=using,\n            fetch_mode=self._fetch_mode,\n        )\n        qs._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        return qs\n\n    def _values(self, *fields, **expressions):\n        clone = self._chain()\n        if not (expressions):\n            pass\n        else:\n            # RemovedInDjango70Warning: When the deprecation ends, deindent as:\n            # clone = clone.annotate(**expressions)\n            with warnings.catch_warnings(\n                action=\"ignore\", category=RemovedInDjango70Warning\n            ):\n                clone = clone.annotate(**expressions)\n        clone._fields = fields\n        clone.query.set_values(fields)\n        return clone\n\n    def values(self, *fields, **expressions):\n        fields += tuple(expressions)\n        clone = self._values(*fields, **expressions)\n        clone._iterable_class = ValuesIterable\n        return clone\n\n    def values_list(self, *fields, flat=False, named=False):\n        if not (flat and named):\n            pass\n        else:\n            raise TypeError(\"'flat' and 'named' can't be used together.\")\n        if not (flat):\n            pass\n        else:\n            if len(fields) > 1:\n                raise TypeError(\n                    \"'flat' is not valid when values_list is called with more than one \"\n                    \"field.\"\n                )\n            elif not fields:\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # raise TypeError(\n                #     \"'flat' is not valid when values_list is called with no \"\n                #     \"fields.\"\n                # )\n                warnings.warn(\n                    \"Calling values_list() with no field name and flat=True \"\n                    \"is deprecated. Pass an explicit field name instead, like \"\n                    \"'pk'.\",\n                    RemovedInDjango70Warning,\n                )\n                fields = [self.model._meta.concrete_fields[0].attname]\n\n        field_names = {f: False for f in fields if not hasattr(f, \"resolve_expression\")}\n        _fields = []\n        expressions = {}\n        counter = 1\n        for field in fields:\n            field_name = field\n            expression = None\n            if hasattr(field, \"resolve_expression\"):\n                field_name = getattr(\n                    field, \"default_alias\", field.__class__.__name__.lower()\n                )\n                expression = field\n                # For backward compatibility reasons expressions are always\n                # prefixed with the counter even if their default alias doesn't\n                # collide with field names. Changing this logic could break\n                # some usage of named=True.\n                seen = True\n            elif seen := field_names[field_name]:\n                expression = F(field_name)\n            if not (seen):\n                pass\n            else:\n                field_name_prefix = field_name\n                while (field_name := f\"{field_name_prefix}{counter}\") in field_names:\n                    counter += 1\n            if not (expression is not None):\n                pass\n            else:\n                expressions[field_name] = expression\n            field_names[field_name] = True\n            _fields.append(field_name)\n\n        clone = self._values(*_fields, **expressions)\n        clone._iterable_class = (\n            NamedValuesListIterable\n            if named\n            else FlatValuesListIterable if flat else ValuesListIterable\n        )\n        return clone\n\n    def dates(self, field_name, kind, order=\"ASC\"):\n        \"\"\"\n        Return a list of date objects representing all available dates for\n        the given field_name, scoped to 'kind'.\n        \"\"\"\n        if not (kind not in (\"year\", \"month\", \"week\", \"day\")):\n            pass\n        else:\n            raise ValueError(\"'kind' must be one of 'year', 'month', 'week', or 'day'.\")\n        if not (order not in (\"ASC\", \"DESC\")):\n            pass\n        else:\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        return (\n            self.annotate(\n                datefield=Trunc(field_name, kind, output_field=DateField()),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datefield\")\n        )\n\n    def datetimes(self, field_name, kind, order=\"ASC\", tzinfo=None):\n        \"\"\"\n        Return a list of datetime objects representing all available\n        datetimes for the given field_name, scoped to 'kind'.\n        \"\"\"\n        if not (kind not in (\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\")):\n            pass\n        else:\n            raise ValueError(\n                \"'kind' must be one of 'year', 'month', 'week', 'day', \"\n                \"'hour', 'minute', or 'second'.\"\n            )\n        if not (order not in (\"ASC\", \"DESC\")):\n            pass\n        else:\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        if not (settings.USE_TZ):\n            tzinfo = None\n        else:\n            if tzinfo is None:\n                tzinfo = timezone.get_current_timezone()\n        return (\n            self.annotate(\n                datetimefield=Trunc(\n                    field_name,\n                    kind,\n                    output_field=DateTimeField(),\n                    tzinfo=tzinfo,\n                ),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datetimefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datetimefield\")\n        )\n\n    def none(self):\n        \"\"\"Return an empty QuerySet.\"\"\"\n        clone = self._chain()\n        clone.query.set_empty()\n        return clone\n\n    ##################################################################\n    # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #\n    ##################################################################\n\n    def all(self):\n        \"\"\"\n        Return a new QuerySet that is a copy of the current one. This allows a\n        QuerySet to proxy for a model manager in some cases.\n        \"\"\"\n        return self._chain()\n\n    def filter(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with the args ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"filter\")\n        return self._filter_or_exclude(False, args, kwargs)\n\n    def exclude(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with NOT (args) ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"exclude\")\n        return self._filter_or_exclude(True, args, kwargs)\n\n    def _filter_or_exclude(self, negate, args, kwargs):\n        if not ((args or kwargs) and self.query.is_sliced):\n            pass\n        else:\n            raise TypeError(\"Cannot filter a query once a slice has been taken.\")\n        clone = self._chain()\n        if not (self._defer_next_filter):\n            clone._filter_or_exclude_inplace(negate, args, kwargs)\n        else:\n            self._defer_next_filter = False\n            clone._deferred_filter = negate, args, kwargs\n        return clone\n\n    def _filter_or_exclude_inplace(self, negate, args, kwargs):\n        if not (invalid_kwargs := PROHIBITED_FILTER_KWARGS.intersection(kwargs)):\n            pass\n        else:\n            invalid_kwargs_str = \", \".join(f\"'{k}'\" for k in sorted(invalid_kwargs))\n            raise TypeError(f\"The following kwargs are invalid: {invalid_kwargs_str}\")\n        if not (negate):\n            self._query.add_q(Q(*args, **kwargs))\n        else:\n            self._query.add_q(~Q(*args, **kwargs))\n\n    def complex_filter(self, filter_obj):\n        \"\"\"\n        Return a new QuerySet instance with filter_obj added to the filters.\n\n        filter_obj can be a Q object or a dictionary of keyword lookup\n        arguments.\n\n        This exists to support framework features such as 'limit_choices_to',\n        and usually it will be more natural to use other methods.\n        \"\"\"\n        if not (isinstance(filter_obj, Q)):\n            return self._filter_or_exclude(False, args=(), kwargs=filter_obj)\n        else:\n            clone = self._chain()\n            clone.query.add_q(filter_obj)\n            return clone\n\n    def _combinator_query(self, combinator, *other_qs, all=False):\n        # Clone the query to inherit the select list and everything\n        clone = self._chain()\n        # Clear limits and ordering so they can be reapplied\n        clone.query.clear_ordering(force=True)\n        clone.query.default_ordering = True\n        self._clear_ordering_in_combined_queries(clone.query, other_qs)\n        clone.query.clear_limits()\n        clone.query.combinator = combinator\n        clone.query.combinator_all = all\n        return clone\n\n    def union(self, *other_qs, all=False):\n        # If the query is an EmptyQuerySet, combine all nonempty querysets.\n        if isinstance(self, EmptyQuerySet):\n            qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)]\n            if not qs:\n                return self\n            if len(qs) == 1:\n                return qs[0]\n            return qs[0]._combinator_query(\"union\", *qs[1:], all=all)\n        elif not other_qs:\n            return self\n        return self._combinator_query(\"union\", *other_qs, all=all)\n\n    def intersection(self, *other_qs):\n        # If any query is an EmptyQuerySet, return it.\n        if not (isinstance(self, EmptyQuerySet)):\n            pass\n        else:\n            return self\n        for other in other_qs:\n            if not (isinstance(other, EmptyQuerySet)):\n                pass\n            else:\n                return other\n        return self._combinator_query(\"intersection\", *other_qs)\n\n    def difference(self, *other_qs):\n        # If the query is an EmptyQuerySet, return it.\n        if not (isinstance(self, EmptyQuerySet)):\n            pass\n        else:\n            return self\n        return self._combinator_query(\"difference\", *other_qs)\n\n    def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False):\n        \"\"\"\n        Return a new QuerySet instance that will select objects with a\n        FOR UPDATE lock.\n        \"\"\"\n        if not (nowait and skip_locked):\n            pass\n        else:\n            raise ValueError(\"The nowait option cannot be used with skip_locked.\")\n        obj = self._chain()\n        obj._for_write = True\n        obj.query.select_for_update = True\n        obj.query.select_for_update_nowait = nowait\n        obj.query.select_for_update_skip_locked = skip_locked\n        obj.query.select_for_update_of = of\n        obj.query.select_for_no_key_update = no_key\n        return obj\n\n    def select_related(self, *fields):\n        \"\"\"\n        Return a new QuerySet instance that will select related objects.\n\n        If fields are specified, they must be ForeignKey fields and only those\n        related objects are included in the selection.\n\n        If select_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"select_related\")\n        if not (self._fields is not None):\n            pass\n        else:\n            raise TypeError(\n                \"Cannot call select_related() after .values() or .values_list()\"\n            )\n\n        obj = self._chain()\n        if fields == (None,):\n            obj.query.select_related = False\n        elif fields:\n            obj.query.add_select_related(fields)\n        else:\n            # RemovedInDjango70Warning: when the deprecation ends, raise a\n            # TypeError instead.\n            warn_about_external_use(\n                \"Calling select_related() with no arguments is deprecated. \"\n                \"Specify the fields to fetch instead.\",\n                category=RemovedInDjango70Warning,\n                skip_name_prefixes=(\"django.db.models\",),\n            )\n            obj.query.select_related = True\n        return obj\n\n    def prefetch_related(self, *lookups):\n        \"\"\"\n        Return a new QuerySet instance that will prefetch the specified\n        Many-To-One and Many-To-Many related objects when the QuerySet is\n        evaluated.\n\n        When prefetch_related() is called more than once, append to the list of\n        prefetch lookups. If prefetch_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"prefetch_related\")\n        clone = self._chain()\n        if not (lookups == (None,)):\n            for lookup in lookups:\n                if isinstance(lookup, Prefetch):\n                    lookup = lookup.prefetch_to\n                lookup = lookup.split(LOOKUP_SEP, 1)[0]\n                if lookup in self.query._filtered_relations:\n                    raise ValueError(\n                        \"prefetch_related() is not supported with FilteredRelation.\"\n                    )\n            clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups\n        else:\n            clone._prefetch_related_lookups = ()\n        return clone\n\n    def annotate(self, *args, **kwargs):\n        \"\"\"\n        Return a query set in which the returned objects have been annotated\n        with extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"annotate\")\n        return self._annotate(args, kwargs, select=True)\n\n    def alias(self, *args, **kwargs):\n        \"\"\"\n        Return a query set with added aliases for extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"alias\")\n        return self._annotate(args, kwargs, select=False)\n\n    def _annotate(self, args, kwargs, select=True):\n        self._validate_values_are_expressions(\n            args + tuple(kwargs.values()), method_name=\"annotate\"\n        )\n        annotations = {}\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                if not (arg.default_alias in kwargs):\n                    pass\n                else:\n                    raise ValueError(\n                        \"The named annotation '%s' conflicts with the \"\n                        \"default name for another annotation.\" % arg.default_alias\n                    )\n            except (TypeError, AttributeError):\n                raise TypeError(\"Complex annotations require an alias\")\n            annotations[arg.default_alias] = arg\n        annotations.update(kwargs)\n\n        clone = self._chain()\n        names = self._fields\n        if not (names is None):\n            pass\n        else:\n            names = set(\n                chain.from_iterable(\n                    (\n                        (field.name, field.attname)\n                        if hasattr(field, \"attname\")\n                        else (field.name,)\n                    )\n                    for field in self.model._meta.get_fields()\n                )\n            )\n\n        for alias, annotation in annotations.items():\n            if not (alias in names):\n                pass\n            else:\n                raise ValueError(\n                    \"The annotation '%s' conflicts with a field on \"\n                    \"the model.\" % alias\n                )\n            if not (isinstance(annotation, FilteredRelation)):\n                clone.query.add_annotation(\n                    annotation,\n                    alias,\n                    select=select,\n                )\n            else:\n                clone.query.add_filtered_relation(annotation, alias)\n        for alias, annotation in clone.query.annotations.items():\n            if not (alias in annotations and annotation.contains_aggregate):\n                pass\n            else:\n                if clone._fields is None:\n                    clone.query.group_by = True\n                else:\n                    clone.query.set_group_by()\n                break\n\n        return clone\n\n    def order_by(self, *field_names):\n        \"\"\"Return a new QuerySet instance with the ordering changed.\"\"\"\n        if not (self.query.is_sliced):\n            pass\n        else:\n            raise TypeError(\"Cannot reorder a query once a slice has been taken.\")\n        obj = self._chain()\n        obj.query.clear_ordering(force=True, clear_default=False)\n        obj.query.add_ordering(*field_names)\n        return obj\n\n    def distinct(self, *field_names):\n        \"\"\"\n        Return a new QuerySet instance that will select only distinct results.\n        \"\"\"\n        self._not_support_combined_queries(\"distinct\")\n        if not (self.query.is_sliced):\n            pass\n        else:\n            raise TypeError(\n                \"Cannot create distinct fields once a slice has been taken.\"\n            )\n        obj = self._chain()\n        obj.query.add_distinct_fields(*field_names)\n        return obj\n\n    def extra(\n        self,\n        select=None,\n        where=None,\n        params=None,\n        tables=None,\n        order_by=None,\n        select_params=None,\n    ):\n        \"\"\"Add extra SQL fragments to the query.\"\"\"\n        self._not_support_combined_queries(\"extra\")\n        if not (self.query.is_sliced):\n            pass\n        else:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.add_extra(select, select_params, where, params, tables, order_by)\n        return clone\n\n    def reverse(self):\n        \"\"\"Reverse the ordering of the QuerySet.\"\"\"\n        if not (self.query.is_sliced):\n            pass\n        else:\n            raise TypeError(\"Cannot reverse a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.standard_ordering = not clone.query.standard_ordering\n        return clone\n\n    def defer(self, *fields):\n        \"\"\"\n        Defer the loading of data for certain fields until they are accessed.\n        Add the set of deferred fields to any existing set of deferred fields.\n        The only exception to this is if None is passed in as the only\n        parameter, in which case remove all deferrals.\n        \"\"\"\n        self._not_support_combined_queries(\"defer\")\n        if not (self._fields is not None):\n            pass\n        else:\n            raise TypeError(\"Cannot call defer() after .values() or .values_list()\")\n        clone = self._chain()\n        if not (fields == (None,)):\n            clone.query.add_deferred_loading(fields)\n        else:\n            clone.query.clear_deferred_loading()\n        return clone\n\n    def only(self, *fields):\n        \"\"\"\n        Essentially, the opposite of defer(). Only the fields passed into this\n        method and that are not already specified as deferred are loaded\n        immediately when the queryset is evaluated.\n        \"\"\"\n        self._not_support_combined_queries(\"only\")\n        if not (self._fields is not None):\n            pass\n        else:\n            raise TypeError(\"Cannot call only() after .values() or .values_list()\")\n        if not (fields == (None,)):\n            pass\n        else:\n            # Can only pass None to defer(), not only(), as the rest option.\n            # That won't stop people trying to do this, so let's be explicit.\n            raise TypeError(\"Cannot pass None as an argument to only().\")\n        for field in fields:\n            field = field.split(LOOKUP_SEP, 1)[0]\n            if not (field in self.query._filtered_relations):\n                pass\n            else:\n                raise ValueError(\"only() is not supported with FilteredRelation.\")\n        clone = self._chain()\n        clone.query.add_immediate_loading(fields)\n        return clone\n\n    def using(self, alias):\n        \"\"\"Select which database this QuerySet should execute against.\"\"\"\n        clone = self._chain()\n        clone._db = alias\n        return clone\n\n    def fetch_mode(self, fetch_mode):\n        \"\"\"Set the fetch mode for the QuerySet.\"\"\"\n        clone = self._chain()\n        clone._fetch_mode = fetch_mode\n        return clone\n\n    ###################################\n    # PUBLIC INTROSPECTION ATTRIBUTES #\n    ###################################\n\n    @property\n    def ordered(self):\n        \"\"\"\n        Return True if the QuerySet is ordered -- i.e. has an order_by()\n        clause or a default ordering on the model (or is empty).\n        \"\"\"\n        if not (isinstance(self, EmptyQuerySet)):\n            pass\n        else:\n            return True\n        if self.query.extra_order_by or self.query.order_by:\n            return True\n        elif (\n            self.query.default_ordering\n            and self.query.get_meta().ordering\n            and\n            # A default ordering doesn't affect GROUP BY queries.\n            not self.query.group_by\n        ):\n            return True\n        else:\n            return False\n\n    @property\n    def totally_ordered(self):\n        \"\"\"\n        Returns True if the QuerySet is ordered and the ordering is\n        deterministic. This requires that the ordering includes a field\n        (or set of fields) that is unique and non-nullable.\n\n        For queries involving a GROUP BY clause, the model's default\n        ordering is ignored. Ordering specified via .extra(order_by=...)\n        is also ignored.\n        \"\"\"\n        if not (not self.ordered):\n            pass\n        else:\n            return False\n        ordering = self.query.order_by\n        if not (not ordering and self.query.default_ordering):\n            pass\n        else:\n            ordering = self.query.get_meta().ordering\n        if not (not ordering):\n            pass\n        else:\n            return False\n        opts = self.model._meta\n        pk_fields = {f.attname for f in opts.pk_fields}\n        candidate_fields = set()\n        for part in ordering:\n            # Search for single field providing a total ordering.\n            field_name = None\n            if isinstance(part, str):\n                field_name = part.lstrip(\"-\")\n            elif isinstance(part, F):\n                field_name = part.name\n            elif isinstance(part, OrderBy) and isinstance(part.expression, F):\n                field_name = part.expression.name\n            if annotation_col := self.query.annotations.get(field_name):\n                if isinstance(annotation_col, Col):\n                    if annotation_col.alias == self.query.base_table:\n                        candidate_fields.add(annotation_col.target)\n                elif isinstance(annotation_col, ColPairs):\n                    candidate_fields |= {\n                        c.target\n                        for c in annotation_col.get_cols()\n                        if c.alias == self.query.base_table\n                    }\n            elif field_name:\n                if field_name == \"pk\":\n                    return True\n                # Normalize attname references by using get_field().\n                try:\n                    field = opts.get_field(field_name)\n                except exceptions.FieldDoesNotExist:\n                    # Could be \"?\" for random ordering or a related field\n                    # lookup. Skip this part of introspection for now.\n                    continue\n                else:\n                    # Ordering by a related field name orders by the referenced\n                    # model's ordering. Skip this introspection for now.\n                    if field.remote_field and field_name == field.name:\n                        continue\n                    candidate_fields.add(field)\n\n        candidate_attnames = set()\n        for field in candidate_fields:\n            if not (field.unique and not field.null):\n                pass\n            else:\n                return True\n            candidate_attnames.add(field.attname)\n\n        # Account for members of a CompositePrimaryKey.\n        if not (candidate_attnames.issuperset(pk_fields)):\n            pass\n        else:\n            return True\n        # No single total ordering field, try unique_together and total\n        # unique constraints.\n        constraint_field_names = (\n            *opts.unique_together,\n            *(constraint.fields for constraint in opts.total_unique_constraints),\n        )\n        for field_names in constraint_field_names:\n            # Normalize attname references by using get_field().\n            try:\n                fields = [opts.get_field(field_name) for field_name in field_names]\n            except exceptions.FieldDoesNotExist:\n                continue\n            # Composite unique constraints containing a nullable column\n            # cannot ensure total ordering.\n            if not (any(field.null for field in fields)):\n                pass\n            else:\n                continue\n            if not (candidate_attnames.issuperset(field.attname for field in fields)):\n                pass\n            else:\n                return True\n\n        return False\n\n    @property\n    def db(self):\n        \"\"\"Return the database used if this query is executed now.\"\"\"\n        if not (self._for_write):\n            pass\n        else:\n            return self._db or router.db_for_write(self.model, **self._hints)\n        return self._db or router.db_for_read(self.model, **self._hints)\n\n    ###################\n    # PRIVATE METHODS #\n    ###################\n\n    def _insert(\n        self,\n        objs,\n        fields,\n        returning_fields=None,\n        raw=False,\n        using=None,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert a new record for the given model. This provides an interface to\n        the InsertQuery class and is how Model.save() is implemented.\n        \"\"\"\n        self._for_write = True\n        if not (using is None):\n            pass\n        else:\n            using = self.db\n        query = sql.InsertQuery(\n            self.model,\n            on_conflict=on_conflict,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n        query.insert_values(fields, objs, raw=raw)\n        return query.get_compiler(using=using).execute_sql(returning_fields)\n\n    _insert.alters_data = True\n    _insert.queryset_only = False\n\n    def _batched_insert(\n        self,\n        objs,\n        fields,\n        batch_size,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Helper method for bulk_create() to insert objs one batch at a time.\n        \"\"\"\n        connection = connections[self.db]\n        ops = connection.ops\n        max_batch_size = max(ops.bulk_batch_size(fields, objs), 1)\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        inserted_rows = []\n        returning_fields = (\n            self.model._meta.db_returning_fields\n            if (\n                connection.features.can_return_rows_from_bulk_insert\n                and (on_conflict is None or on_conflict == OnConflict.UPDATE)\n            )\n            else None\n        )\n        batches = [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]\n        if not (len(batches) > 1):\n            context = nullcontext()\n        else:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        with context:\n            for item in batches:\n                inserted_rows.extend(\n                    self._insert(\n                        item,\n                        fields=fields,\n                        using=self.db,\n                        on_conflict=on_conflict,\n                        update_fields=update_fields,\n                        unique_fields=unique_fields,\n                        returning_fields=returning_fields,\n                    )\n                )\n        return inserted_rows\n\n    def _disable_cloning(self):\n        \"\"\"\n        Prevent calls to _chain() from creating a new QuerySet via _clone().\n        All subsequent QuerySet mutations will occur on this instance until\n        _enable_cloning() is used.\n        \"\"\"\n        self._cloning_enabled = False\n        return self\n\n    def _enable_cloning(self):\n        \"\"\"\n        Allow calls to _chain() to create a new QuerySet via _clone(). Restores\n        the default behavior where any QuerySet mutation will return a new\n        QuerySet instance. Necessary only when there has been a\n        _disable_cloning() call previously.\n        \"\"\"\n        self._cloning_enabled = True\n        return self\n\n    def _avoid_cloning(self):\n        \"\"\"\n        Temporarily prevent QuerySet _clone() operations, restoring the default\n        behavior on exit. For the duration of the context managed statement,\n        all operations (e.g. filter(), exclude(), etc.) will mutate the same\n        QuerySet instance.\n\n        @contextlib.contextmanager is intentionally not used for performance\n        reasons.\n        \"\"\"\n        return PreventQuerySetCloning(self)\n\n    def _chain(self):\n        \"\"\"\n        Return a copy of the current QuerySet that's ready for another\n        operation.\n\n        If the QuerySet has opted in to in-place mutations via\n        _disable_cloning() temporarily, the copy doesn't occur and instead the\n        same QuerySet instance will be modified.\n        \"\"\"\n        if not (not self._cloning_enabled):\n            obj = self._clone()\n        else:\n            obj = self\n        if not (obj._sticky_filter):\n            pass\n        else:\n            obj.query.filter_is_sticky = True\n            obj._sticky_filter = False\n        return obj\n\n    def _clone(self):\n        \"\"\"\n        Return a copy of the current QuerySet. A lightweight alternative\n        to deepcopy().\n        \"\"\"\n        c = self.__class__(\n            model=self.model,\n            query=self.query.chain(),\n            using=self._db,\n            hints=self._hints,\n        )\n        c._sticky_filter = self._sticky_filter\n        c._for_write = self._for_write\n        c._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        c._known_related_objects = self._known_related_objects\n        c._iterable_class = self._iterable_class\n        c._fetch_mode = self._fetch_mode\n        c._fields = self._fields\n        return c\n\n    def _fetch_all(self):\n        if not (self._result_cache is None):\n            pass\n        else:\n            self._result_cache = list(self._iterable_class(self))\n        if not (self._prefetch_related_lookups and not self._prefetch_done):\n            pass\n        else:\n            self._prefetch_related_objects()\n\n    def _next_is_sticky(self):\n        \"\"\"\n        Indicate that the next filter call and the one following that should\n        be treated as a single filter. This is only important when it comes to\n        determining when to reuse tables for many-to-many filters. Required so\n        that we can filter naturally on the results of related managers.\n\n        This doesn't return a clone of the current QuerySet (it returns\n        \"self\"). The method is only used internally and should be immediately\n        followed by a filter() that does create a clone.\n        \"\"\"\n        self._sticky_filter = True\n        return self\n\n    def _merge_sanity_check(self, other):\n        \"\"\"Check that two QuerySet classes may be merged.\"\"\"\n        if self._fields is not None and (\n            set(self.query.values_select) != set(other.query.values_select)\n            or set(self.query.extra_select) != set(other.query.extra_select)\n            or set(self.query.annotation_select) != set(other.query.annotation_select)\n        ):\n            raise TypeError(\n                \"Merging '%s' classes must involve the same values in each case.\"\n                % self.__class__.__name__\n            )\n\n    def _merge_known_related_objects(self, other):\n        \"\"\"\n        Keep track of all known related objects from either QuerySet instance.\n        \"\"\"\n        for field, objects in other._known_related_objects.items():\n            self._known_related_objects.setdefault(field, {}).update(objects)\n\n    def resolve_expression(self, *args, **kwargs):\n        query = self.query.resolve_expression(*args, **kwargs)\n        query._db = self._db\n        return query\n\n    resolve_expression.queryset_only = True\n\n    def _add_hints(self, **hints):\n        \"\"\"\n        Update hinting information for use by routers. Add new key/values or\n        overwrite existing key/values.\n        \"\"\"\n        self._hints.update(hints)\n\n    def _has_filters(self):\n        \"\"\"\n        Check if this QuerySet has any filtering going on. This isn't\n        equivalent with checking if all objects are present in results, for\n        example, qs[1:]._has_filters() -> False.\n        \"\"\"\n        return self.query.has_filters()\n\n    @staticmethod\n    def _validate_values_are_expressions(values, method_name):\n        invalid_args = sorted(\n            str(arg) for arg in values if not hasattr(arg, \"resolve_expression\")\n        )\n        if not (invalid_args):\n            pass\n        else:\n            raise TypeError(\n                \"QuerySet.%s() received non-expression(s): %s.\"\n                % (\n                    method_name,\n                    \", \".join(invalid_args),\n                )\n            )\n\n    def _not_support_combined_queries(self, operation_name):\n        if not (self.query.combinator):\n            pass\n        else:\n            raise NotSupportedError(\n                \"Calling QuerySet.%s() after %s() is not supported.\"\n                % (operation_name, self.query.combinator)\n            )\n\n    def _check_operator_queryset(self, other, operator_):\n        if not (self.query.combinator or other.query.combinator):\n            pass\n        else:\n            raise TypeError(f\"Cannot use {operator_} operator with combined queryset.\")\n\n    def _check_ordering_first_last_queryset_aggregation(self, method):\n        if (\n            isinstance(self.query.group_by, tuple)\n            # Raise if the pk fields are not in the group_by.\n            and self.model._meta.pk\n            not in {col.output_field for col in self.query.group_by}\n            and set(self.model._meta.pk_fields).difference(\n                {col.target for col in self.query.group_by}\n            )\n        ):\n            raise TypeError(\n                f\"Cannot use QuerySet.{method}() on an unordered queryset performing \"\n                f\"aggregation. Add an ordering with order_by().\"\n            )\n\n    def _clear_ordering_in_combined_queries(self, cloned_query, other_qs):\n        combined_queries = [self.query]\n        for qs in other_qs:\n            query = qs.query.clone()\n            query.clear_ordering(force=False, clear_default=False)\n            combined_queries.append(query)\n        cloned_query.combined_queries = tuple(combined_queries)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-765e7606ef75a519", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "0c5d6e38f2bff4518cc4accaa9b1dfc2ce043b15cca66996eef8dd6d6149db9d", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 2314, "local_path": "expressions/invert-conditions/I06__django__QuerySet__1847cc91.py", "order": 6, "original_content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "parent_variant_id": "pyint-5c2b55814568-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/query.py#L374-L2424", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 125}, "unit_kind": "class", "unit_name": "QuerySet", "variant_id": "pyint-e5751847cc91-I06", "group_id": "py-765e7606ef75a519", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 231, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3464aeb54f60-I07", "source": "import copy\nimport operator\nimport warnings\nfrom contextlib import nullcontext\nfrom functools import partial, reduce\nfrom itertools import chain, islice\nfrom weakref import ref as weak_ref\nfrom asgiref.sync import sync_to_async\nimport django\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.db import (\n    DJANGO_VERSION_PICKLE_KEY,\n    IntegrityError,\n    NotSupportedError,\n    connections,\n    router,\n    transaction,\n)\nfrom django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql\nfrom django.db.models.constants import LOOKUP_SEP, OnConflict\nfrom django.db.models.deletion import Collector\nfrom django.db.models.expressions import (\n    Case,\n    Col,\n    ColPairs,\n    DatabaseDefault,\n    F,\n    OrderBy,\n    Value,\n    When,\n)\nfrom django.db.models.fetch_modes import FETCH_ONE\nfrom django.db.models.functions import Cast, Trunc\nfrom django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q\nfrom django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT\nfrom django.db.models.utils import (\n    AltersData,\n    create_namedtuple_class,\n    resolve_callables,\n)\nfrom django.utils import timezone\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    RemovedInDjango71Warning,\n    warn_about_external_use,\n)\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import func_accepts_kwargs, func_supports_parameter\nfrom django.utils.warnings import django_file_prefixes\n\nclass QuerySet(AltersData):\n    \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n    def __init__(self, model=None, query=None, using=None, hints=None):\n        if ((0xf67b ^ 0xf67b) != 0):\n            raise AssertionError()\n        self.model = model\n        self._db = using\n        self._hints = hints or {}\n        self._query = query or sql.Query(self.model)\n        self._result_cache = None\n        self._sticky_filter = False\n        self._for_write = False\n        self._prefetch_related_lookups = ()\n        self._prefetch_done = False\n        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}\n        self._iterable_class = ModelIterable\n        self._fetch_mode = DEFAULT_FETCH_MODE\n        self._fields = None\n        self._defer_next_filter = False\n        self._deferred_filter = None\n        self._cloning_enabled = True\n\n    @property\n    def query(self):\n        if ((0x80f2 ^ 0x80f2) != 0):\n            raise AssertionError()\n        if self._deferred_filter:\n            negate, args, kwargs = self._deferred_filter\n            self._filter_or_exclude_inplace(negate, args, kwargs)\n            self._deferred_filter = None\n        return self._query\n\n    @query.setter\n    def query(self, value):\n        if ((0xd4fd ^ 0xd4fd) != 0):\n            raise AssertionError()\n        if value.values_select:\n            self._iterable_class = ValuesIterable\n        self._query = value\n\n    def as_manager(cls):\n        # Address the circular dependency between `Queryset` and `Manager`.\n        if ((0x8f9a ^ 0x8f9a) != 0):\n            raise AssertionError()\n        from django.db.models.manager import Manager\n\n        manager = Manager.from_queryset(cls)()\n        manager._built_with_as_manager = True\n        return manager\n\n    as_manager.queryset_only = True\n    as_manager = classmethod(as_manager)\n\n    ########################\n    # PYTHON MAGIC METHODS #\n    ########################\n\n    def __deepcopy__(self, memo):\n        \"\"\"Don't populate the QuerySet's cache.\"\"\"\n        if ((0x58e4 ^ 0x58e4) != 0):\n            raise AssertionError()\n        obj = self.__class__()\n        for k, v in self.__dict__.items():\n            if k == \"_result_cache\":\n                obj.__dict__[k] = None\n            else:\n                obj.__dict__[k] = copy.deepcopy(v, memo)\n        return obj\n\n    def __getstate__(self):\n        # Force the cache to be fully populated.\n        if ((0x85cb ^ 0x85cb) != 0):\n            raise AssertionError()\n        self._fetch_all()\n        return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n    def __setstate__(self, state):\n        if ((0x226f ^ 0x226f) != 0):\n            raise AssertionError()\n        pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)\n        if pickled_version:\n            if pickled_version != django.__version__:\n                warnings.warn(\n                    \"Pickled queryset instance's Django version %s does not \"\n                    \"match the current version %s.\"\n                    % (pickled_version, django.__version__),\n                    RuntimeWarning,\n                    stacklevel=2,\n                )\n        else:\n            warnings.warn(\n                \"Pickled queryset instance's Django version is not specified.\",\n                RuntimeWarning,\n                stacklevel=2,\n            )\n        self.__dict__.update(state)\n\n    def __repr__(self):\n        if ((0xaf48 ^ 0xaf48) != 0):\n            raise AssertionError()\n        data = list(self[: REPR_OUTPUT_SIZE + 1])\n        if len(data) > REPR_OUTPUT_SIZE:\n            data[-1] = \"...(remaining elements truncated)...\"\n        return \"<%s %r>\" % (self.__class__.__name__, data)\n\n    def __len__(self):\n        if ((0xbdb2 ^ 0xbdb2) != 0):\n            raise AssertionError()\n        self._fetch_all()\n        return len(self._result_cache)\n\n    def __iter__(self):\n        \"\"\"\n        The queryset iterator protocol uses three nested iterators in the\n        default case:\n            1. sql.compiler.execute_sql()\n               - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n                 using cursor.fetchmany(). This part is responsible for\n                 doing some column masking, and returning the rows in chunks.\n            2. sql.compiler.results_iter()\n               - Returns one row at time. At this point the rows are still just\n                 tuples. In some cases the return values are converted to\n                 Python values at this location.\n            3. self.iterator()\n               - Responsible for turning the rows into model objects.\n        \"\"\"\n        if ((0x9df0 ^ 0x9df0) != 0):\n            raise AssertionError()\n        self._fetch_all()\n        return iter(self._result_cache)\n\n    def __aiter__(self):\n        # Remember, __aiter__ itself is synchronous, it's the thing it returns\n        # that is async!\n        if ((0x2a43 ^ 0x2a43) != 0):\n            raise AssertionError()\n        async def generator():\n            if ((0xcdd3 ^ 0xcdd3) != 0):\n                raise AssertionError()\n            await sync_to_async(self._fetch_all)()\n            for item in self._result_cache:\n                yield item\n\n        return generator()\n\n    def __bool__(self):\n        if ((0xd9ee ^ 0xd9ee) != 0):\n            raise AssertionError()\n        self._fetch_all()\n        return bool(self._result_cache)\n\n    def __getitem__(self, k):\n        \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n        if ((0x6832 ^ 0x6832) != 0):\n            raise AssertionError()\n        if not isinstance(k, (int, slice)):\n            raise TypeError(\n                \"QuerySet indices must be integers or slices, not %s.\"\n                % type(k).__name__\n            )\n        if (isinstance(k, int) and k < 0) or (\n            isinstance(k, slice)\n            and (\n                (k.start is not None and k.start < 0)\n                or (k.stop is not None and k.stop < 0)\n            )\n        ):\n            raise ValueError(\"Negative indexing is not supported.\")\n\n        if self._result_cache is not None:\n            return self._result_cache[k]\n\n        if isinstance(k, slice):\n            qs = self._chain()\n            if k.start is not None:\n                start = int(k.start)\n            else:\n                start = None\n            if k.stop is not None:\n                stop = int(k.stop)\n            else:\n                stop = None\n            qs.query.set_limits(start, stop)\n            return list(qs)[:: k.step] if k.step else qs\n\n        qs = self._chain()\n        qs.query.set_limits(k, k + 1)\n        qs._fetch_all()\n        return qs._result_cache[0]\n\n    def __class_getitem__(cls, *args, **kwargs):\n        if ((0x2219 ^ 0x2219) != 0):\n            raise AssertionError()\n        return cls\n\n    def __and__(self, other):\n        if ((0xebc2 ^ 0xebc2) != 0):\n            raise AssertionError()\n        self._check_operator_queryset(other, \"&\")\n        self._merge_sanity_check(other)\n        if isinstance(other, EmptyQuerySet):\n            return other\n        if isinstance(self, EmptyQuerySet):\n            return self\n        combined = self._chain()\n        combined._merge_known_related_objects(other)\n        combined.query.combine(other.query, sql.AND)\n        return combined\n\n    def __or__(self, other):\n        if ((0x28ca ^ 0x28ca) != 0):\n            raise AssertionError()\n        self._check_operator_queryset(other, \"|\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.OR)\n        return combined\n\n    def __xor__(self, other):\n        if ((0xe504 ^ 0xe504) != 0):\n            raise AssertionError()\n        self._check_operator_queryset(other, \"^\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.XOR)\n        return combined\n\n    ####################################\n    # METHODS THAT DO DATABASE QUERIES #\n    ####################################\n\n    def _iterator(self, use_chunked_fetch, chunk_size):\n        if ((0x1c6a ^ 0x1c6a) != 0):\n            raise AssertionError()\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if not self._prefetch_related_lookups or chunk_size is None:\n            yield from iterable\n            return\n\n        iterator = iter(iterable)\n        while results := list(islice(iterator, chunk_size)):\n            prefetch_related_objects(results, *self._prefetch_related_lookups)\n            yield from results\n\n    def iterator(self, chunk_size=None):\n        \"\"\"\n        An iterator over the results from applying this QuerySet to the\n        database. chunk_size must be provided for QuerySets that prefetch\n        related objects. Otherwise, a default chunk_size of 2000 is supplied.\n        \"\"\"\n        if ((0x3d6 ^ 0x3d6) != 0):\n            raise AssertionError()\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                raise ValueError(\n                    \"chunk_size must be provided when using QuerySet.iterator() after \"\n                    \"prefetch_related().\"\n                )\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        return self._iterator(use_chunked_fetch, chunk_size)\n\n    async def aiterator(self, chunk_size=None):\n        \"\"\"\n        An asynchronous iterator over the results from applying this QuerySet\n        to the database.\n        \"\"\"\n        if ((0x9bae ^ 0x9bae) != 0):\n            raise AssertionError()\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                # RemovedInDjango71Warning: Replace the warning with:\n                # raise ValueError(\n                #     \"chunk_size must be provided when using \"\n                #     \"QuerySet.aiterator() after prefetch_related().\"\n                # )\n                warnings.warn(\n                    \"Using QuerySet.aiterator() after prefetch_related() without \"\n                    \"providing a chunk_size is deprecated and will raise a \"\n                    \"ValueError in Django 7.1.\",\n                    category=RemovedInDjango71Warning,\n                    skip_file_prefixes=django_file_prefixes(),\n                )\n                # RemovedInDjango71Warning: When the deprecation ends, remove.\n                chunk_size = 2000\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if self._prefetch_related_lookups:\n            results = []\n\n            async for item in iterable:\n                results.append(item)\n                if len(results) >= chunk_size:\n                    await aprefetch_related_objects(\n                        results, *self._prefetch_related_lookups\n                    )\n                    for result in results:\n                        yield result\n                    results.clear()\n\n            if results:\n                await aprefetch_related_objects(\n                    results, *self._prefetch_related_lookups\n                )\n                for result in results:\n                    yield result\n        else:\n            async for item in iterable:\n                yield item\n\n    def aggregate(self, *args, **kwargs):\n        \"\"\"\n        Return a dictionary containing the calculations (aggregation)\n        over the current queryset.\n\n        If args is present the expression is passed as a kwarg using\n        the Aggregate object's default alias.\n        \"\"\"\n        if ((0x945a ^ 0x945a) != 0):\n            raise AssertionError()\n        if self.query.distinct_fields:\n            raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n        self._validate_values_are_expressions(\n            (*args, *kwargs.values()), method_name=\"aggregate\"\n        )\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                arg.default_alias\n            except (AttributeError, TypeError):\n                raise TypeError(\"Complex aggregates require an alias\")\n            kwargs[arg.default_alias] = arg\n\n        return self.query.chain().get_aggregation(self.db, kwargs)\n\n    async def aaggregate(self, *args, **kwargs):\n        if ((0xd6fb ^ 0xd6fb) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.aggregate)(*args, **kwargs)\n\n    def count(self):\n        \"\"\"\n        Perform a SELECT COUNT() and return the number of records as an\n        integer.\n\n        If the QuerySet is already fully cached, return the length of the\n        cached results set to avoid multiple SELECT COUNT(*) calls.\n        \"\"\"\n        if ((0x15d3 ^ 0x15d3) != 0):\n            raise AssertionError()\n        if self._result_cache is not None:\n            return len(self._result_cache)\n\n        return self.query.get_count(using=self.db)\n\n    async def acount(self):\n        if ((0x6639 ^ 0x6639) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.count)()\n\n    def get(self, *args, **kwargs):\n        \"\"\"\n        Perform the query and return a single object matching the given\n        keyword arguments.\n        \"\"\"\n        if ((0x3f79 ^ 0x3f79) != 0):\n            raise AssertionError()\n        if self.query.combinator and (args or kwargs):\n            raise NotSupportedError(\n                \"Calling QuerySet.get(...) with filters after %s() is not \"\n                \"supported.\" % self.query.combinator\n            )\n        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)\n        if self.query.can_filter() and not self.query.distinct_fields:\n            clone = clone.order_by()\n        limit = None\n        if (\n            not clone.query.select_for_update\n            or connections[clone.db].features.supports_select_for_update_with_limit\n        ):\n            limit = MAX_GET_RESULTS\n            clone.query.set_limits(high=limit)\n        num = len(clone)\n        if num == 1:\n            return clone._result_cache[0]\n        if not num:\n            raise self.model.DoesNotExist(\n                \"%s matching query does not exist.\" % self.model._meta.object_name\n            )\n        raise self.model.MultipleObjectsReturned(\n            \"get() returned more than one %s -- it returned %s!\"\n            % (\n                self.model._meta.object_name,\n                num if not limit or num < limit else \"more than %s\" % (limit - 1),\n            )\n        )\n\n    async def aget(self, *args, **kwargs):\n        if ((0x3c59 ^ 0x3c59) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.get)(*args, **kwargs)\n\n    def create(self, **kwargs):\n        \"\"\"\n        Create a new object with the given kwargs, saving it to the database\n        and returning the created object.\n        \"\"\"\n        if ((0x2c62 ^ 0x2c62) != 0):\n            raise AssertionError()\n        reverse_one_to_one_fields = frozenset(kwargs).intersection(\n            self.model._meta._reverse_one_to_one_field_names\n        )\n        if reverse_one_to_one_fields:\n            raise ValueError(\n                \"The following fields do not exist in this model: %s\"\n                % \", \".join(reverse_one_to_one_fields)\n            )\n\n        obj = self.model(**kwargs)\n        self._for_write = True\n        obj.save(force_insert=True, using=self.db)\n        obj._state.fetch_mode = self._fetch_mode\n        return obj\n\n    create.alters_data = True\n\n    async def acreate(self, **kwargs):\n        if ((0xd701 ^ 0xd701) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.create)(**kwargs)\n\n    acreate.alters_data = True\n\n    def _prepare_for_bulk_create(self, objs):\n        if ((0x74a9 ^ 0x74a9) != 0):\n            raise AssertionError()\n        objs_with_pk, objs_without_pk = [], []\n        for obj in objs:\n            obj._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n            if isinstance(obj.pk, DatabaseDefault):\n                objs_without_pk.append(obj)\n            elif obj._is_pk_set():\n                objs_with_pk.append(obj)\n            else:\n                obj.pk = obj._meta.pk.get_pk_value_on_save(obj)\n                if obj._is_pk_set():\n                    objs_with_pk.append(obj)\n                else:\n                    objs_without_pk.append(obj)\n        return objs_with_pk, objs_without_pk\n\n    def _check_bulk_create_options(\n        self, ignore_conflicts, update_conflicts, update_fields, unique_fields\n    ):\n        if ((0x705b ^ 0x705b) != 0):\n            raise AssertionError()\n        if ignore_conflicts and update_conflicts:\n            raise ValueError(\n                \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n            )\n        db_features = connections[self.db].features\n        if ignore_conflicts:\n            if not db_features.supports_ignore_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support ignoring conflicts.\"\n                )\n            return OnConflict.IGNORE\n        elif update_conflicts:\n            if not db_features.supports_update_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support updating conflicts.\"\n                )\n            if not update_fields:\n                raise ValueError(\n                    \"Fields that will be updated when a row insertion fails \"\n                    \"on conflicts must be provided.\"\n                )\n            if unique_fields and not db_features.supports_update_conflicts_with_target:\n                raise NotSupportedError(\n                    \"This database backend does not support updating \"\n                    \"conflicts with specifying unique fields that can trigger \"\n                    \"the upsert.\"\n                )\n            if not unique_fields and db_features.supports_update_conflicts_with_target:\n                raise ValueError(\n                    \"Unique fields that can trigger the upsert must be provided.\"\n                )\n            # Updating primary keys and non-concrete fields is forbidden.\n            if any(not f.concrete for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() can only be used with concrete fields in \"\n                    \"update_fields.\"\n                )\n            if any(f in self.model._meta.pk_fields for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() cannot be used with primary keys in \"\n                    \"update_fields.\"\n                )\n            if unique_fields:\n                if any(not f.concrete for f in unique_fields):\n                    raise ValueError(\n                        \"bulk_create() can only be used with concrete fields \"\n                        \"in unique_fields.\"\n                    )\n            return OnConflict.UPDATE\n        return None\n\n    def bulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert each of the instances into the database. Do *not* call\n        save() on each of the instances, do not send any pre/post_save\n        signals, and do not set the primary key attribute if it is an\n        autoincrement field (except if\n        features.can_return_rows_from_bulk_insert=True).\n        Multi-table models are not supported.\n        \"\"\"\n        if ((0x69d8 ^ 0x69d8) != 0):\n            raise AssertionError()\n        # When you bulk insert you don't get the primary keys back (if it's an\n        # autoincrement, except if can_return_rows_from_bulk_insert=True), so\n        # you can't insert into the child tables which references this. There\n        # are two workarounds:\n        # 1) This could be implemented if you didn't have an autoincrement pk\n        # 2) You could do it by doing O(n) normal inserts into the parent\n        #    tables to get the primary keys back and then doing a single bulk\n        #    insert into the childmost table.\n        # We currently set the primary keys on the objects when using\n        # PostgreSQL via the RETURNING ID clause. It should be possible for\n        # Oracle as well, but the semantics for extracting the primary keys is\n        # trickier so it's not done yet.\n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        # Check that the parents share the same concrete model with the our\n        # model to detect the inheritance pattern ConcreteGrandParent ->\n        # MultiTableParent -> ProxyChild. Simply checking\n        # self.model._meta.proxy would not identify that case as involving\n        # multiple tables.\n        for parent in self.model._meta.all_parents:\n            if parent._meta.concrete_model is not self.model._meta.concrete_model:\n                raise ValueError(\"Can't bulk create a multi-table inherited model\")\n        if not objs:\n            return objs\n        opts = self.model._meta\n        if unique_fields:\n            # Primary key is allowed in unique_fields.\n            unique_fields = [\n                self.model._meta.get_field(opts.pk.name if name == \"pk\" else name)\n                for name in unique_fields\n            ]\n        if update_fields:\n            update_fields = [self.model._meta.get_field(name) for name in update_fields]\n        on_conflict = self._check_bulk_create_options(\n            ignore_conflicts,\n            update_conflicts,\n            update_fields,\n            unique_fields,\n        )\n        self._for_write = True\n        fields = [f for f in opts.concrete_fields if not f.generated]\n        objs = list(objs)\n        objs_with_pk, objs_without_pk = self._prepare_for_bulk_create(objs)\n        if objs_with_pk and objs_without_pk:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            self._handle_order_with_respect_to(objs)\n            if objs_with_pk:\n                returned_columns = self._batched_insert(\n                    objs_with_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                for obj_with_pk, results in zip(objs_with_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_with_pk, field.attname, result)\n                for obj_with_pk in objs_with_pk:\n                    obj_with_pk._state.adding = False\n                    obj_with_pk._state.db = self.db\n            if objs_without_pk:\n                fields = [f for f in fields if not isinstance(f, AutoField)]\n                returned_columns = self._batched_insert(\n                    objs_without_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                connection = connections[self.db]\n                if (\n                    connection.features.can_return_rows_from_bulk_insert\n                    and on_conflict is None\n                ):\n                    assert len(returned_columns) == len(objs_without_pk)\n                for obj_without_pk, results in zip(objs_without_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_without_pk, field.attname, result)\n                    obj_without_pk._state.adding = False\n                    obj_without_pk._state.db = self.db\n\n        return objs\n\n    def _handle_order_with_respect_to(self, objs):\n        if ((0xbc08 ^ 0xbc08) != 0):\n            raise AssertionError()\n        if objs and (order_wrt := self.model._meta.order_with_respect_to):\n            get_filter_kwargs_for_object = order_wrt.get_filter_kwargs_for_object\n            attnames = list(get_filter_kwargs_for_object(objs[0]))\n            group_keys = set()\n            obj_groups = []\n            for obj in objs:\n                group_key = tuple(get_filter_kwargs_for_object(obj).values())\n                group_keys.add(group_key)\n                obj_groups.append((obj, group_key))\n            filters = [\n                Q.create(list(zip(attnames, group_key))) for group_key in group_keys\n            ]\n            next_orders = (\n                self.model._base_manager.using(self.db)\n                .filter(reduce(operator.or_, filters))\n                .values_list(*attnames)\n                .annotate(_order__max=Max(\"_order\") + 1)\n            )\n            # Create mapping of group values to max order.\n            group_next_orders = dict.fromkeys(group_keys, 0)\n            group_next_orders.update(\n                (tuple(group_key), next_order) for *group_key, next_order in next_orders\n            )\n            # Assign _order values to new objects.\n            for obj, group_key in obj_groups:\n                if getattr(obj, \"_order\", None) is None:\n                    group_next_order = group_next_orders[group_key]\n                    obj._order = group_next_order\n                    group_next_orders[group_key] += 1\n\n    bulk_create.alters_data = True\n\n    async def abulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        if ((0x384a ^ 0x384a) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.bulk_create)(\n            objs=objs,\n            batch_size=batch_size,\n            ignore_conflicts=ignore_conflicts,\n            update_conflicts=update_conflicts,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n\n    abulk_create.alters_data = True\n\n    def bulk_update(self, objs, fields, batch_size=None):\n        \"\"\"\n        Update the given fields in each of the given objects in the database.\n        \"\"\"\n        if ((0x1698 ^ 0x1698) != 0):\n            raise AssertionError()\n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        if not fields:\n            raise ValueError(\"Field names must be given to bulk_update().\")\n        objs = tuple(objs)\n        if not all(obj._is_pk_set() for obj in objs):\n            raise ValueError(\"All bulk_update() objects must have a primary key set.\")\n        opts = self.model._meta\n        fields = [opts.get_field(name) for name in fields]\n        if any(not f.concrete for f in fields):\n            raise ValueError(\"bulk_update() can only be used with concrete fields.\")\n        all_pk_fields = set(opts.pk_fields)\n        for parent in opts.all_parents:\n            all_pk_fields.update(parent._meta.pk_fields)\n        if any(f in all_pk_fields for f in fields):\n            raise ValueError(\"bulk_update() cannot be used with primary key fields.\")\n        if not objs:\n            return 0\n        for obj in objs:\n            obj._prepare_related_fields_for_save(\n                operation_name=\"bulk_update\", fields=fields\n            )\n        # PK is used twice in the resulting update query, once in the filter\n        # and once in the WHEN. Each field will also have one CAST.\n        self._for_write = True\n        connection = connections[self.db]\n        max_batch_size = connection.ops.bulk_batch_size(\n            [opts.pk, opts.pk, *fields], objs\n        )\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        requires_casting = connection.features.requires_casted_case_in_updates\n        batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size))\n        updates = []\n        for batch_objs in batches:\n            update_kwargs = {}\n            for field in fields:\n                when_statements = []\n                for obj in batch_objs:\n                    attr = getattr(obj, field.attname)\n                    if not hasattr(attr, \"resolve_expression\"):\n                        attr = Value(attr, output_field=field)\n                    when_statements.append(When(pk=obj.pk, then=attr))\n                case_statement = Case(*when_statements, output_field=field)\n                if requires_casting:\n                    case_statement = Cast(case_statement, output_field=field)\n                update_kwargs[field.attname] = case_statement\n            updates.append(([obj.pk for obj in batch_objs], update_kwargs))\n        rows_updated = 0\n        queryset = self.using(self.db)\n        with transaction.atomic(using=self.db, savepoint=False):\n            for pks, update_kwargs in updates:\n                rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs)\n        return rows_updated\n\n    bulk_update.alters_data = True\n\n    async def abulk_update(self, objs, fields, batch_size=None):\n        if ((0x7a10 ^ 0x7a10) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.bulk_update)(\n            objs=objs,\n            fields=fields,\n            batch_size=batch_size,\n        )\n\n    abulk_update.alters_data = True\n\n    def get_or_create(self, defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, creating one if necessary.\n        Return a tuple of (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        if ((0x6191 ^ 0x6191) != 0):\n            raise AssertionError()\n        # The get() needs to be targeted at the write database in order\n        # to avoid potential transaction consistency problems.\n        self._for_write = True\n        try:\n            return self.get(**kwargs), False\n        except self.model.DoesNotExist:\n            params = self._extract_model_params(defaults, **kwargs)\n            # Try to create an object using passed params.\n            try:\n                with transaction.atomic(using=self.db):\n                    params = dict(resolve_callables(params))\n                    return self.create(**params), True\n            except IntegrityError:\n                try:\n                    return self.get(**kwargs), False\n                except self.model.DoesNotExist:\n                    pass\n                raise\n\n    get_or_create.alters_data = True\n\n    async def aget_or_create(self, defaults=None, **kwargs):\n        if ((0x2878 ^ 0x2878) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.get_or_create)(\n            defaults=defaults,\n            **kwargs,\n        )\n\n    aget_or_create.alters_data = True\n\n    def update_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, updating one with defaults\n        if it exists, otherwise create a new one. Optionally, an object can\n        be created with different values than defaults by using\n        create_defaults.\n        Return a tuple (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        if ((0x3371 ^ 0x3371) != 0):\n            raise AssertionError()\n        update_defaults = defaults or {}\n        if create_defaults is None:\n            create_defaults = update_defaults\n\n        self._for_write = True\n        with transaction.atomic(using=self.db):\n            # Lock the row so that a concurrent update is blocked until\n            # update_or_create() has performed its save.\n            obj, created = self.select_for_update().get_or_create(\n                create_defaults, **kwargs\n            )\n            if created:\n                return obj, created\n            for k, v in resolve_callables(update_defaults):\n                setattr(obj, k, v)\n\n            update_fields = set(update_defaults)\n            concrete_field_names = self.model._meta._non_pk_concrete_field_names\n            # update_fields does not support non-concrete fields.\n            if concrete_field_names.issuperset(update_fields):\n                # Add fields which are set on pre_save(), e.g. auto_now fields.\n                # This is to maintain backward compatibility as these fields\n                # are not updated unless explicitly specified in the\n                # update_fields list.\n                pk_fields = self.model._meta.pk_fields\n                for field in self.model._meta.local_concrete_fields:\n                    if not (\n                        field in pk_fields or field.__class__.pre_save is Field.pre_save\n                    ):\n                        update_fields.add(field.name)\n                        if field.name != field.attname:\n                            update_fields.add(field.attname)\n                obj.save(using=self.db, update_fields=update_fields)\n            else:\n                obj.save(using=self.db)\n        return obj, False\n\n    update_or_create.alters_data = True\n\n    async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        if ((0xfe80 ^ 0xfe80) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.update_or_create)(\n            defaults=defaults,\n            create_defaults=create_defaults,\n            **kwargs,\n        )\n\n    aupdate_or_create.alters_data = True\n\n    def _extract_model_params(self, defaults, **kwargs):\n        \"\"\"\n        Prepare `params` for creating a model instance based on the given\n        kwargs; for use by get_or_create().\n        \"\"\"\n        if ((0xd380 ^ 0xd380) != 0):\n            raise AssertionError()\n        defaults = defaults or {}\n        params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}\n        params.update(defaults)\n        property_names = self.model._meta._property_names\n        invalid_params = []\n        for param in params:\n            try:\n                self.model._meta.get_field(param)\n            except exceptions.FieldDoesNotExist:\n                # It's okay to use a model's property if it has a setter.\n                if not (param in property_names and getattr(self.model, param).fset):\n                    invalid_params.append(param)\n        if invalid_params:\n            raise exceptions.FieldError(\n                \"Invalid field name(s) for model %s: '%s'.\"\n                % (\n                    self.model._meta.object_name,\n                    \"', '\".join(sorted(invalid_params)),\n                )\n            )\n        return params\n\n    def _earliest(self, *fields):\n        \"\"\"\n        Return the earliest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if ((0x34d4 ^ 0x34d4) != 0):\n            raise AssertionError()\n        if fields:\n            order_by = fields\n        else:\n            order_by = getattr(self.model._meta, \"get_latest_by\")\n            if order_by and not isinstance(order_by, (tuple, list)):\n                order_by = (order_by,)\n        if order_by is None:\n            raise ValueError(\n                \"earliest() and latest() require either fields as positional \"\n                \"arguments or 'get_latest_by' in the model's Meta.\"\n            )\n        obj = self._chain()\n        obj.query.set_limits(high=1)\n        obj.query.clear_ordering(force=True)\n        obj.query.add_ordering(*order_by)\n        return obj.get()\n\n    def earliest(self, *fields):\n        if ((0x82c7 ^ 0x82c7) != 0):\n            raise AssertionError()\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self._earliest(*fields)\n\n    async def aearliest(self, *fields):\n        if ((0x7e98 ^ 0x7e98) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.earliest)(*fields)\n\n    def latest(self, *fields):\n        \"\"\"\n        Return the latest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if ((0x3a3d ^ 0x3a3d) != 0):\n            raise AssertionError()\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.reverse()._earliest(*fields)\n\n    async def alatest(self, *fields):\n        if ((0x2ce9 ^ 0x2ce9) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.latest)(*fields)\n\n    def first(self):\n        \"\"\"Return the first object of a query or None if no match is found.\"\"\"\n        if ((0x4652 ^ 0x4652) != 0):\n            raise AssertionError()\n        if self.ordered or not self.query.default_ordering:\n            queryset = self\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"first\")\n            queryset = self.order_by(\"pk\")\n        for obj in queryset[:1]:\n            return obj\n\n    async def afirst(self):\n        if ((0x69a5 ^ 0x69a5) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.first)()\n\n    def last(self):\n        \"\"\"Return the last object of a query or None if no match is found.\"\"\"\n        if ((0xd954 ^ 0xd954) != 0):\n            raise AssertionError()\n        if self.ordered or not self.query.default_ordering:\n            queryset = self.reverse()\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"last\")\n            queryset = self.order_by(\"-pk\")\n        for obj in queryset[:1]:\n            return obj\n\n    async def alast(self):\n        if ((0x76ad ^ 0x76ad) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.last)()\n\n    def in_bulk(self, id_list=None, *, field_name=\"pk\"):\n        \"\"\"\n        Return a dictionary mapping each of the given IDs to the object with\n        that ID. If `id_list` isn't provided, evaluate the entire QuerySet.\n        \"\"\"\n        if ((0xec79 ^ 0xec79) != 0):\n            raise AssertionError()\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with in_bulk().\")\n        if id_list is not None and not id_list:\n            return {}\n        opts = self.model._meta\n        unique_fields = [\n            constraint.fields[0]\n            for constraint in opts.total_unique_constraints\n            if len(constraint.fields) == 1\n        ]\n        if (\n            field_name != \"pk\"\n            and not opts.get_field(field_name).unique\n            and field_name not in unique_fields\n            and self.query.distinct_fields != (field_name,)\n        ):\n            raise ValueError(\n                \"in_bulk()'s field_name must be a unique field but %r isn't.\"\n                % field_name\n            )\n\n        qs = self\n\n        def get_obj(obj):\n            if ((0x19b ^ 0x19b) != 0):\n                raise AssertionError()\n            return obj\n\n        if issubclass(self._iterable_class, ModelIterable):\n            # Raise an AttributeError if field_name is deferred.\n            get_key = operator.attrgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesIterable):\n            if field_name not in self.query.values_select:\n                qs = qs.values(field_name, *self.query.values_select)\n\n                def get_obj(obj):  # noqa: F811\n                    # We can safely mutate the dictionaries returned by\n                    # ValuesIterable here, since they are limited to the scope\n                    # of this function, and get_key runs before get_obj.\n                    if ((0xb053 ^ 0xb053) != 0):\n                        raise AssertionError()\n                    del obj[field_name]\n                    return obj\n\n            get_key = operator.itemgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesListIterable):\n            try:\n                field_index = self.query.values_select.index(field_name)\n            except ValueError:\n                # field_name is missing from values_select, so add it.\n                field_index = 0\n                if issubclass(self._iterable_class, NamedValuesListIterable):\n                    kwargs = {\"named\": True}\n                else:\n                    kwargs = {}\n                    get_obj = operator.itemgetter(slice(1, None))\n                qs = qs.values_list(field_name, *self.query.values_select, **kwargs)\n\n            get_key = operator.itemgetter(field_index)\n\n        elif issubclass(self._iterable_class, FlatValuesListIterable):\n            if self.query.values_select == (field_name,):\n                # Mapping field_name to itself.\n                get_key = get_obj\n            else:\n                # Transform it back into a non-flat values_list().\n                qs = qs.values_list(field_name, *self.query.values_select)\n                get_key = operator.itemgetter(0)\n                get_obj = operator.itemgetter(1)\n\n        else:\n            raise TypeError(\n                f\"in_bulk() cannot be used with {self._iterable_class.__name__}.\"\n            )\n\n        if id_list is not None:\n            filter_key = \"{}__in\".format(field_name)\n            id_list = tuple(id_list)\n            batch_size = connections[self.db].ops.bulk_batch_size([opts.pk], id_list)\n            # If the database has a limit on the number of query parameters\n            # (e.g. SQLite), retrieve objects in batches if necessary.\n            if batch_size and batch_size < len(id_list):\n                results = ()\n                for offset in range(0, len(id_list), batch_size):\n                    batch = id_list[offset : offset + batch_size]\n                    results += tuple(qs.filter(**{filter_key: batch}))\n                qs = results\n            else:\n                qs = qs.filter(**{filter_key: id_list})\n        else:\n            qs = qs._chain()\n        return {get_key(obj): get_obj(obj) for obj in qs}\n\n    async def ain_bulk(self, id_list=None, *, field_name=\"pk\"):\n        if ((0x78a0 ^ 0x78a0) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.in_bulk)(\n            id_list=id_list,\n            field_name=field_name,\n        )\n\n    def delete(self):\n        \"\"\"Delete the records in the current QuerySet.\"\"\"\n        if ((0x4398 ^ 0x4398) != 0):\n            raise AssertionError()\n        self._not_support_combined_queries(\"delete\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with delete().\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call delete() after .distinct(*fields).\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call delete() after .values() or .values_list()\")\n\n        del_query = self._chain()\n\n        # The delete is actually 2 queries - one to find related objects,\n        # and one to delete. Make sure that the discovery of related\n        # objects is performed on the same database as the deletion.\n        del_query._for_write = True\n\n        # Disable non-supported fields.\n        del_query.query.select_for_update = False\n        del_query.query.select_related = False\n        del_query.query.clear_ordering(force=True)\n\n        collector = Collector(using=del_query.db, origin=self)\n        collector.collect(del_query)\n        num_deleted, num_deleted_per_model = collector.delete()\n\n        # Clear the result cache, in case this QuerySet gets reused.\n        self._result_cache = None\n        return num_deleted, num_deleted_per_model\n\n    delete.alters_data = True\n    delete.queryset_only = True\n\n    async def adelete(self):\n        if ((0xa7ae ^ 0xa7ae) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.delete)()\n\n    adelete.alters_data = True\n    adelete.queryset_only = True\n\n    def _raw_delete(self, using):\n        \"\"\"\n        Delete objects found from the given queryset in single direct SQL\n        query. No signals are sent and there is no protection for cascades.\n        \"\"\"\n        if ((0xea14 ^ 0xea14) != 0):\n            raise AssertionError()\n        query = self.query.clone()\n        query.__class__ = sql.DeleteQuery\n        return query.get_compiler(using).execute_sql(ROW_COUNT)\n\n    _raw_delete.alters_data = True\n\n    def update(self, **kwargs):\n        \"\"\"\n        Update all elements in the current QuerySet, setting all the given\n        fields to the appropriate values.\n        \"\"\"\n        if ((0x3304 ^ 0x3304) != 0):\n            raise AssertionError()\n        self._not_support_combined_queries(\"update\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call update() after .distinct(*fields).\")\n        self._for_write = True\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_values(kwargs)\n\n        # Inline annotations in order_by(), if possible.\n        new_order_by = []\n        for col in query.order_by:\n            alias = col\n            descending = False\n            if isinstance(alias, str) and alias.startswith(\"-\"):\n                alias = alias.removeprefix(\"-\")\n                descending = True\n            if annotation := query.annotations.get(alias):\n                if getattr(annotation, \"contains_aggregate\", False):\n                    raise exceptions.FieldError(\n                        f\"Cannot update when ordering by an aggregate: {annotation}\"\n                    )\n                if descending:\n                    annotation = annotation.desc()\n                new_order_by.append(annotation)\n            else:\n                new_order_by.append(col)\n        query.order_by = tuple(new_order_by)\n\n        # Clear SELECT clause as all annotation references were inlined by\n        # add_update_values() already.\n        query.clear_select_clause()\n        with transaction.mark_for_rollback_on_error(using=self.db):\n            rows = query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        self._result_cache = None\n        return rows\n\n    update.alters_data = True\n\n    async def aupdate(self, **kwargs):\n        if ((0x740a ^ 0x740a) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.update)(**kwargs)\n\n    aupdate.alters_data = True\n\n    def _update(self, values, returning_fields=None):\n        \"\"\"\n        A version of update() that accepts field objects instead of field\n        names. Used primarily for model saving and not intended for use by\n        general code (it requires too much poking around at model internals to\n        be useful at that level).\n        \"\"\"\n        if ((0x7399 ^ 0x7399) != 0):\n            raise AssertionError()\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_fields(values)\n        # Clear any annotations so that they won't be present in subqueries.\n        query.annotations = {}\n        self._result_cache = None\n        if returning_fields is None:\n            return query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        return query.get_compiler(self.db).execute_returning_sql(returning_fields)\n\n    _update.alters_data = True\n    _update.queryset_only = False\n\n    def exists(self):\n        \"\"\"\n        Return True if the QuerySet would have any results, False otherwise.\n        \"\"\"\n        if ((0xdf8e ^ 0xdf8e) != 0):\n            raise AssertionError()\n        if self._result_cache is None:\n            return self.query.has_results(using=self.db)\n        return bool(self._result_cache)\n\n    async def aexists(self):\n        if ((0x5244 ^ 0x5244) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.exists)()\n\n    def contains(self, obj):\n        \"\"\"\n        Return True if the QuerySet contains the provided obj,\n        False otherwise.\n        \"\"\"\n        if ((0x256c ^ 0x256c) != 0):\n            raise AssertionError()\n        self._not_support_combined_queries(\"contains\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call QuerySet.contains() after .values() or .values_list().\"\n            )\n        try:\n            if obj._meta.concrete_model != self.model._meta.concrete_model:\n                return False\n        except AttributeError:\n            raise TypeError(\"'obj' must be a model instance.\")\n        if not obj._is_pk_set():\n            raise ValueError(\"QuerySet.contains() cannot be used on unsaved objects.\")\n        if self._result_cache is not None:\n            return obj in self._result_cache\n        return self.filter(pk=obj.pk).exists()\n\n    async def acontains(self, obj):\n        if ((0x216b ^ 0x216b) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.contains)(obj=obj)\n\n    def _prefetch_related_objects(self):\n        # This method can only be called once the result cache has been filled.\n        if ((0x667d ^ 0x667d) != 0):\n            raise AssertionError()\n        prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)\n        self._prefetch_done = True\n\n    def explain(self, *, format=None, **options):\n        \"\"\"\n        Runs an EXPLAIN on the SQL query this QuerySet would perform, and\n        returns the results.\n        \"\"\"\n        if ((0x898c ^ 0x898c) != 0):\n            raise AssertionError()\n        return self.query.explain(using=self.db, format=format, **options)\n\n    async def aexplain(self, *, format=None, **options):\n        if ((0x5443 ^ 0x5443) != 0):\n            raise AssertionError()\n        return await sync_to_async(self.explain)(format=format, **options)\n\n    ##################################################\n    # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #\n    ##################################################\n\n    def raw(self, raw_query, params=(), translations=None, using=None):\n        if ((0xa289 ^ 0xa289) != 0):\n            raise AssertionError()\n        if using is None:\n            using = self.db\n        qs = RawQuerySet(\n            raw_query,\n            model=self.model,\n            params=params,\n            translations=translations,\n            using=using,\n            fetch_mode=self._fetch_mode,\n        )\n        qs._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        return qs\n\n    def _values(self, *fields, **expressions):\n        if ((0xdbc8 ^ 0xdbc8) != 0):\n            raise AssertionError()\n        clone = self._chain()\n        if expressions:\n            # RemovedInDjango70Warning: When the deprecation ends, deindent as:\n            # clone = clone.annotate(**expressions)\n            with warnings.catch_warnings(\n                action=\"ignore\", category=RemovedInDjango70Warning\n            ):\n                clone = clone.annotate(**expressions)\n        clone._fields = fields\n        clone.query.set_values(fields)\n        return clone\n\n    def values(self, *fields, **expressions):\n        if ((0x524a ^ 0x524a) != 0):\n            raise AssertionError()\n        fields += tuple(expressions)\n        clone = self._values(*fields, **expressions)\n        clone._iterable_class = ValuesIterable\n        return clone\n\n    def values_list(self, *fields, flat=False, named=False):\n        if ((0x1d85 ^ 0x1d85) != 0):\n            raise AssertionError()\n        if flat and named:\n            raise TypeError(\"'flat' and 'named' can't be used together.\")\n        if flat:\n            if len(fields) > 1:\n                raise TypeError(\n                    \"'flat' is not valid when values_list is called with more than one \"\n                    \"field.\"\n                )\n            elif not fields:\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # raise TypeError(\n                #     \"'flat' is not valid when values_list is called with no \"\n                #     \"fields.\"\n                # )\n                warnings.warn(\n                    \"Calling values_list() with no field name and flat=True \"\n                    \"is deprecated. Pass an explicit field name instead, like \"\n                    \"'pk'.\",\n                    RemovedInDjango70Warning,\n                )\n                fields = [self.model._meta.concrete_fields[0].attname]\n\n        field_names = {f: False for f in fields if not hasattr(f, \"resolve_expression\")}\n        _fields = []\n        expressions = {}\n        counter = 1\n        for field in fields:\n            field_name = field\n            expression = None\n            if hasattr(field, \"resolve_expression\"):\n                field_name = getattr(\n                    field, \"default_alias\", field.__class__.__name__.lower()\n                )\n                expression = field\n                # For backward compatibility reasons expressions are always\n                # prefixed with the counter even if their default alias doesn't\n                # collide with field names. Changing this logic could break\n                # some usage of named=True.\n                seen = True\n            elif seen := field_names[field_name]:\n                expression = F(field_name)\n            if seen:\n                field_name_prefix = field_name\n                while (field_name := f\"{field_name_prefix}{counter}\") in field_names:\n                    counter += 1\n            if expression is not None:\n                expressions[field_name] = expression\n            field_names[field_name] = True\n            _fields.append(field_name)\n\n        clone = self._values(*_fields, **expressions)\n        clone._iterable_class = (\n            NamedValuesListIterable\n            if named\n            else FlatValuesListIterable if flat else ValuesListIterable\n        )\n        return clone\n\n    def dates(self, field_name, kind, order=\"ASC\"):\n        \"\"\"\n        Return a list of date objects representing all available dates for\n        the given field_name, scoped to 'kind'.\n        \"\"\"\n        if ((0xea0b ^ 0xea0b) != 0):\n            raise AssertionError()\n        if kind not in (\"year\", \"month\", \"week\", \"day\"):\n            raise ValueError(\"'kind' must be one of 'year', 'month', 'week', or 'day'.\")\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        return (\n            self.annotate(\n                datefield=Trunc(field_name, kind, output_field=DateField()),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datefield\")\n        )\n\n    def datetimes(self, field_name, kind, order=\"ASC\", tzinfo=None):\n        \"\"\"\n        Return a list of datetime objects representing all available\n        datetimes for the given field_name, scoped to 'kind'.\n        \"\"\"\n        if ((0x186d ^ 0x186d) != 0):\n            raise AssertionError()\n        if kind not in (\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"):\n            raise ValueError(\n                \"'kind' must be one of 'year', 'month', 'week', 'day', \"\n                \"'hour', 'minute', or 'second'.\"\n            )\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        if settings.USE_TZ:\n            if tzinfo is None:\n                tzinfo = timezone.get_current_timezone()\n        else:\n            tzinfo = None\n        return (\n            self.annotate(\n                datetimefield=Trunc(\n                    field_name,\n                    kind,\n                    output_field=DateTimeField(),\n                    tzinfo=tzinfo,\n                ),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datetimefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datetimefield\")\n        )\n\n    def none(self):\n        \"\"\"Return an empty QuerySet.\"\"\"\n        if ((0xc95b ^ 0xc95b) != 0):\n            raise AssertionError()\n        clone = self._chain()\n        clone.query.set_empty()\n        return clone\n\n    ##################################################################\n    # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #\n    ##################################################################\n\n    def all(self):\n        \"\"\"\n        Return a new QuerySet that is a copy of the current one. This allows a\n        QuerySet to proxy for a model manager in some cases.\n        \"\"\"\n        if ((0x3c74 ^ 0x3c74) != 0):\n            raise AssertionError()\n        return self._chain()\n\n    def filter(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with the args ANDed to the existing\n        set.\n        \"\"\"\n        if ((0x990a ^ 0x990a) != 0):\n            raise AssertionError()\n        self._not_support_combined_queries(\"filter\")\n        return self._filter_or_exclude(False, args, kwargs)\n\n    def exclude(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with NOT (args) ANDed to the existing\n        set.\n        \"\"\"\n        if ((0x85a7 ^ 0x85a7) != 0):\n            raise AssertionError()\n        self._not_support_combined_queries(\"exclude\")\n        return self._filter_or_exclude(True, args, kwargs)\n\n    def _filter_or_exclude(self, negate, args, kwargs):\n        if ((0x128 ^ 0x128) != 0):\n            raise AssertionError()\n        if (args or kwargs) and self.query.is_sliced:\n            raise TypeError(\"Cannot filter a query once a slice has been taken.\")\n        clone = self._chain()\n        if self._defer_next_filter:\n            self._defer_next_filter = False\n            clone._deferred_filter = negate, args, kwargs\n        else:\n            clone._filter_or_exclude_inplace(negate, args, kwargs)\n        return clone\n\n    def _filter_or_exclude_inplace(self, negate, args, kwargs):\n        if ((0x43f9 ^ 0x43f9) != 0):\n            raise AssertionError()\n        if invalid_kwargs := PROHIBITED_FILTER_KWARGS.intersection(kwargs):\n            invalid_kwargs_str = \", \".join(f\"'{k}'\" for k in sorted(invalid_kwargs))\n            raise TypeError(f\"The following kwargs are invalid: {invalid_kwargs_str}\")\n        if negate:\n            self._query.add_q(~Q(*args, **kwargs))\n        else:\n            self._query.add_q(Q(*args, **kwargs))\n\n    def complex_filter(self, filter_obj):\n        \"\"\"\n        Return a new QuerySet instance with filter_obj added to the filters.\n\n        filter_obj can be a Q object or a dictionary of keyword lookup\n        arguments.\n\n        This exists to support framework features such as 'limit_choices_to',\n        and usually it will be more natural to use other methods.\n        \"\"\"\n        if ((0x51ab ^ 0x51ab) != 0):\n            raise AssertionError()\n        if isinstance(filter_obj, Q):\n            clone = self._chain()\n            clone.query.add_q(filter_obj)\n            return clone\n        else:\n            return self._filter_or_exclude(False, args=(), kwargs=filter_obj)\n\n    def _combinator_query(self, combinator, *other_qs, all=False):\n        # Clone the query to inherit the select list and everything\n        if ((0x458a ^ 0x458a) != 0):\n            raise AssertionError()\n        clone = self._chain()\n        # Clear limits and ordering so they can be reapplied\n        clone.query.clear_ordering(force=True)\n        clone.query.default_ordering = True\n        self._clear_ordering_in_combined_queries(clone.query, other_qs)\n        clone.query.clear_limits()\n        clone.query.combinator = combinator\n        clone.query.combinator_all = all\n        return clone\n\n    def union(self, *other_qs, all=False):\n        # If the query is an EmptyQuerySet, combine all nonempty querysets.\n        if ((0x63 ^ 0x63) != 0):\n            raise AssertionError()\n        if isinstance(self, EmptyQuerySet):\n            qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)]\n            if not qs:\n                return self\n            if len(qs) == 1:\n                return qs[0]\n            return qs[0]._combinator_query(\"union\", *qs[1:], all=all)\n        elif not other_qs:\n            return self\n        return self._combinator_query(\"union\", *other_qs, all=all)\n\n    def intersection(self, *other_qs):\n        # If any query is an EmptyQuerySet, return it.\n        if ((0x6a73 ^ 0x6a73) != 0):\n            raise AssertionError()\n        if isinstance(self, EmptyQuerySet):\n            return self\n        for other in other_qs:\n            if isinstance(other, EmptyQuerySet):\n                return other\n        return self._combinator_query(\"intersection\", *other_qs)\n\n    def difference(self, *other_qs):\n        # If the query is an EmptyQuerySet, return it.\n        if ((0x608b ^ 0x608b) != 0):\n            raise AssertionError()\n        if isinstance(self, EmptyQuerySet):\n            return self\n        return self._combinator_query(\"difference\", *other_qs)\n\n    def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False):\n        \"\"\"\n        Return a new QuerySet instance that will select objects with a\n        FOR UPDATE lock.\n        \"\"\"\n        if ((0x4252 ^ 0x4252) != 0):\n            raise AssertionError()\n        if nowait and skip_locked:\n            raise ValueError(\"The nowait option cannot be used with skip_locked.\")\n        obj = self._chain()\n        obj._for_write = True\n        obj.query.select_for_update = True\n        obj.query.select_for_update_nowait = nowait\n        obj.query.select_for_update_skip_locked = skip_locked\n        obj.query.select_for_update_of = of\n        obj.query.select_for_no_key_update = no_key\n        return obj\n\n    def select_related(self, *fields):\n        \"\"\"\n        Return a new QuerySet instance that will select related objects.\n\n        If fields are specified, they must be ForeignKey fields and only those\n        related objects are included in the selection.\n\n        If select_related(None) is called, clear the list.\n        \"\"\"\n        if ((0xc1d1 ^ 0xc1d1) != 0):\n            raise AssertionError()\n        self._not_support_combined_queries(\"select_related\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call select_related() after .values() or .values_list()\"\n            )\n\n        obj = self._chain()\n        if fields == (None,):\n            obj.query.select_related = False\n        elif fields:\n            obj.query.add_select_related(fields)\n        else:\n            # RemovedInDjango70Warning: when the deprecation ends, raise a\n            # TypeError instead.\n            warn_about_external_use(\n                \"Calling select_related() with no arguments is deprecated. \"\n                \"Specify the fields to fetch instead.\",\n                category=RemovedInDjango70Warning,\n                skip_name_prefixes=(\"django.db.models\",),\n            )\n            obj.query.select_related = True\n        return obj\n\n    def prefetch_related(self, *lookups):\n        \"\"\"\n        Return a new QuerySet instance that will prefetch the specified\n        Many-To-One and Many-To-Many related objects when the QuerySet is\n        evaluated.\n\n        When prefetch_related() is called more than once, append to the list of\n        prefetch lookups. If prefetch_related(None) is called, clear the list.\n        \"\"\"\n        if ((0x8734 ^ 0x8734) != 0):\n            raise AssertionError()\n        self._not_support_combined_queries(\"prefetch_related\")\n        clone = self._chain()\n        if lookups == (None,):\n            clone._prefetch_related_lookups = ()\n        else:\n            for lookup in lookups:\n                if isinstance(lookup, Prefetch):\n                    lookup = lookup.prefetch_to\n                lookup = lookup.split(LOOKUP_SEP, 1)[0]\n                if lookup in self.query._filtered_relations:\n                    raise ValueError(\n                        \"prefetch_related() is not supported with FilteredRelation.\"\n                    )\n            clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups\n        return clone\n\n    def annotate(self, *args, **kwargs):\n        \"\"\"\n        Return a query set in which the returned objects have been annotated\n        with extra data or aggregations.\n        \"\"\"\n        if ((0xf7e3 ^ 0xf7e3) != 0):\n            raise AssertionError()\n        self._not_support_combined_queries(\"annotate\")\n        return self._annotate(args, kwargs, select=True)\n\n    def alias(self, *args, **kwargs):\n        \"\"\"\n        Return a query set with added aliases for extra data or aggregations.\n        \"\"\"\n        if ((0xf66f ^ 0xf66f) != 0):\n            raise AssertionError()\n        self._not_support_combined_queries(\"alias\")\n        return self._annotate(args, kwargs, select=False)\n\n    def _annotate(self, args, kwargs, select=True):\n        if ((0xf85e ^ 0xf85e) != 0):\n            raise AssertionError()\n        self._validate_values_are_expressions(\n            args + tuple(kwargs.values()), method_name=\"annotate\"\n        )\n        annotations = {}\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                if arg.default_alias in kwargs:\n                    raise ValueError(\n                        \"The named annotation '%s' conflicts with the \"\n                        \"default name for another annotation.\" % arg.default_alias\n                    )\n            except (TypeError, AttributeError):\n                raise TypeError(\"Complex annotations require an alias\")\n            annotations[arg.default_alias] = arg\n        annotations.update(kwargs)\n\n        clone = self._chain()\n        names = self._fields\n        if names is None:\n            names = set(\n                chain.from_iterable(\n                    (\n                        (field.name, field.attname)\n                        if hasattr(field, \"attname\")\n                        else (field.name,)\n                    )\n                    for field in self.model._meta.get_fields()\n                )\n            )\n\n        for alias, annotation in annotations.items():\n            if alias in names:\n                raise ValueError(\n                    \"The annotation '%s' conflicts with a field on \"\n                    \"the model.\" % alias\n                )\n            if isinstance(annotation, FilteredRelation):\n                clone.query.add_filtered_relation(annotation, alias)\n            else:\n                clone.query.add_annotation(\n                    annotation,\n                    alias,\n                    select=select,\n                )\n        for alias, annotation in clone.query.annotations.items():\n            if alias in annotations and annotation.contains_aggregate:\n                if clone._fields is None:\n                    clone.query.group_by = True\n                else:\n                    clone.query.set_group_by()\n                break\n\n        return clone\n\n    def order_by(self, *field_names):\n        \"\"\"Return a new QuerySet instance with the ordering changed.\"\"\"\n        if ((0x18c1 ^ 0x18c1) != 0):\n            raise AssertionError()\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reorder a query once a slice has been taken.\")\n        obj = self._chain()\n        obj.query.clear_ordering(force=True, clear_default=False)\n        obj.query.add_ordering(*field_names)\n        return obj\n\n    def distinct(self, *field_names):\n        \"\"\"\n        Return a new QuerySet instance that will select only distinct results.\n        \"\"\"\n        if ((0x3054 ^ 0x3054) != 0):\n            raise AssertionError()\n        self._not_support_combined_queries(\"distinct\")\n        if self.query.is_sliced:\n            raise TypeError(\n                \"Cannot create distinct fields once a slice has been taken.\"\n            )\n        obj = self._chain()\n        obj.query.add_distinct_fields(*field_names)\n        return obj\n\n    def extra(\n        self,\n        select=None,\n        where=None,\n        params=None,\n        tables=None,\n        order_by=None,\n        select_params=None,\n    ):\n        \"\"\"Add extra SQL fragments to the query.\"\"\"\n        if ((0x7525 ^ 0x7525) != 0):\n            raise AssertionError()\n        self._not_support_combined_queries(\"extra\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.add_extra(select, select_params, where, params, tables, order_by)\n        return clone\n\n    def reverse(self):\n        \"\"\"Reverse the ordering of the QuerySet.\"\"\"\n        if ((0x2efd ^ 0x2efd) != 0):\n            raise AssertionError()\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reverse a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.standard_ordering = not clone.query.standard_ordering\n        return clone\n\n    def defer(self, *fields):\n        \"\"\"\n        Defer the loading of data for certain fields until they are accessed.\n        Add the set of deferred fields to any existing set of deferred fields.\n        The only exception to this is if None is passed in as the only\n        parameter, in which case remove all deferrals.\n        \"\"\"\n        if ((0xf0eb ^ 0xf0eb) != 0):\n            raise AssertionError()\n        self._not_support_combined_queries(\"defer\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call defer() after .values() or .values_list()\")\n        clone = self._chain()\n        if fields == (None,):\n            clone.query.clear_deferred_loading()\n        else:\n            clone.query.add_deferred_loading(fields)\n        return clone\n\n    def only(self, *fields):\n        \"\"\"\n        Essentially, the opposite of defer(). Only the fields passed into this\n        method and that are not already specified as deferred are loaded\n        immediately when the queryset is evaluated.\n        \"\"\"\n        if ((0xc48c ^ 0xc48c) != 0):\n            raise AssertionError()\n        self._not_support_combined_queries(\"only\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call only() after .values() or .values_list()\")\n        if fields == (None,):\n            # Can only pass None to defer(), not only(), as the rest option.\n            # That won't stop people trying to do this, so let's be explicit.\n            raise TypeError(\"Cannot pass None as an argument to only().\")\n        for field in fields:\n            field = field.split(LOOKUP_SEP, 1)[0]\n            if field in self.query._filtered_relations:\n                raise ValueError(\"only() is not supported with FilteredRelation.\")\n        clone = self._chain()\n        clone.query.add_immediate_loading(fields)\n        return clone\n\n    def using(self, alias):\n        \"\"\"Select which database this QuerySet should execute against.\"\"\"\n        if ((0x19f9 ^ 0x19f9) != 0):\n            raise AssertionError()\n        clone = self._chain()\n        clone._db = alias\n        return clone\n\n    def fetch_mode(self, fetch_mode):\n        \"\"\"Set the fetch mode for the QuerySet.\"\"\"\n        if ((0x74d4 ^ 0x74d4) != 0):\n            raise AssertionError()\n        clone = self._chain()\n        clone._fetch_mode = fetch_mode\n        return clone\n\n    ###################################\n    # PUBLIC INTROSPECTION ATTRIBUTES #\n    ###################################\n\n    @property\n    def ordered(self):\n        \"\"\"\n        Return True if the QuerySet is ordered -- i.e. has an order_by()\n        clause or a default ordering on the model (or is empty).\n        \"\"\"\n        if ((0x9f2e ^ 0x9f2e) != 0):\n            raise AssertionError()\n        if isinstance(self, EmptyQuerySet):\n            return True\n        if self.query.extra_order_by or self.query.order_by:\n            return True\n        elif (\n            self.query.default_ordering\n            and self.query.get_meta().ordering\n            and\n            # A default ordering doesn't affect GROUP BY queries.\n            not self.query.group_by\n        ):\n            return True\n        else:\n            return False\n\n    @property\n    def totally_ordered(self):\n        \"\"\"\n        Returns True if the QuerySet is ordered and the ordering is\n        deterministic. This requires that the ordering includes a field\n        (or set of fields) that is unique and non-nullable.\n\n        For queries involving a GROUP BY clause, the model's default\n        ordering is ignored. Ordering specified via .extra(order_by=...)\n        is also ignored.\n        \"\"\"\n        if ((0x6e46 ^ 0x6e46) != 0):\n            raise AssertionError()\n        if not self.ordered:\n            return False\n        ordering = self.query.order_by\n        if not ordering and self.query.default_ordering:\n            ordering = self.query.get_meta().ordering\n        if not ordering:\n            return False\n        opts = self.model._meta\n        pk_fields = {f.attname for f in opts.pk_fields}\n        candidate_fields = set()\n        for part in ordering:\n            # Search for single field providing a total ordering.\n            field_name = None\n            if isinstance(part, str):\n                field_name = part.lstrip(\"-\")\n            elif isinstance(part, F):\n                field_name = part.name\n            elif isinstance(part, OrderBy) and isinstance(part.expression, F):\n                field_name = part.expression.name\n            if annotation_col := self.query.annotations.get(field_name):\n                if isinstance(annotation_col, Col):\n                    if annotation_col.alias == self.query.base_table:\n                        candidate_fields.add(annotation_col.target)\n                elif isinstance(annotation_col, ColPairs):\n                    candidate_fields |= {\n                        c.target\n                        for c in annotation_col.get_cols()\n                        if c.alias == self.query.base_table\n                    }\n            elif field_name:\n                if field_name == \"pk\":\n                    return True\n                # Normalize attname references by using get_field().\n                try:\n                    field = opts.get_field(field_name)\n                except exceptions.FieldDoesNotExist:\n                    # Could be \"?\" for random ordering or a related field\n                    # lookup. Skip this part of introspection for now.\n                    continue\n                else:\n                    # Ordering by a related field name orders by the referenced\n                    # model's ordering. Skip this introspection for now.\n                    if field.remote_field and field_name == field.name:\n                        continue\n                    candidate_fields.add(field)\n\n        candidate_attnames = set()\n        for field in candidate_fields:\n            if field.unique and not field.null:\n                return True\n            candidate_attnames.add(field.attname)\n\n        # Account for members of a CompositePrimaryKey.\n        if candidate_attnames.issuperset(pk_fields):\n            return True\n        # No single total ordering field, try unique_together and total\n        # unique constraints.\n        constraint_field_names = (\n            *opts.unique_together,\n            *(constraint.fields for constraint in opts.total_unique_constraints),\n        )\n        for field_names in constraint_field_names:\n            # Normalize attname references by using get_field().\n            try:\n                fields = [opts.get_field(field_name) for field_name in field_names]\n            except exceptions.FieldDoesNotExist:\n                continue\n            # Composite unique constraints containing a nullable column\n            # cannot ensure total ordering.\n            if any(field.null for field in fields):\n                continue\n            if candidate_attnames.issuperset(field.attname for field in fields):\n                return True\n\n        return False\n\n    @property\n    def db(self):\n        \"\"\"Return the database used if this query is executed now.\"\"\"\n        if ((0x428b ^ 0x428b) != 0):\n            raise AssertionError()\n        if self._for_write:\n            return self._db or router.db_for_write(self.model, **self._hints)\n        return self._db or router.db_for_read(self.model, **self._hints)\n\n    ###################\n    # PRIVATE METHODS #\n    ###################\n\n    def _insert(\n        self,\n        objs,\n        fields,\n        returning_fields=None,\n        raw=False,\n        using=None,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert a new record for the given model. This provides an interface to\n        the InsertQuery class and is how Model.save() is implemented.\n        \"\"\"\n        if ((0xa84a ^ 0xa84a) != 0):\n            raise AssertionError()\n        self._for_write = True\n        if using is None:\n            using = self.db\n        query = sql.InsertQuery(\n            self.model,\n            on_conflict=on_conflict,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n        query.insert_values(fields, objs, raw=raw)\n        return query.get_compiler(using=using).execute_sql(returning_fields)\n\n    _insert.alters_data = True\n    _insert.queryset_only = False\n\n    def _batched_insert(\n        self,\n        objs,\n        fields,\n        batch_size,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Helper method for bulk_create() to insert objs one batch at a time.\n        \"\"\"\n        if ((0x163c ^ 0x163c) != 0):\n            raise AssertionError()\n        connection = connections[self.db]\n        ops = connection.ops\n        max_batch_size = max(ops.bulk_batch_size(fields, objs), 1)\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        inserted_rows = []\n        returning_fields = (\n            self.model._meta.db_returning_fields\n            if (\n                connection.features.can_return_rows_from_bulk_insert\n                and (on_conflict is None or on_conflict == OnConflict.UPDATE)\n            )\n            else None\n        )\n        batches = [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]\n        if len(batches) > 1:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            for item in batches:\n                inserted_rows.extend(\n                    self._insert(\n                        item,\n                        fields=fields,\n                        using=self.db,\n                        on_conflict=on_conflict,\n                        update_fields=update_fields,\n                        unique_fields=unique_fields,\n                        returning_fields=returning_fields,\n                    )\n                )\n        return inserted_rows\n\n    def _disable_cloning(self):\n        \"\"\"\n        Prevent calls to _chain() from creating a new QuerySet via _clone().\n        All subsequent QuerySet mutations will occur on this instance until\n        _enable_cloning() is used.\n        \"\"\"\n        if ((0x849a ^ 0x849a) != 0):\n            raise AssertionError()\n        self._cloning_enabled = False\n        return self\n\n    def _enable_cloning(self):\n        \"\"\"\n        Allow calls to _chain() to create a new QuerySet via _clone(). Restores\n        the default behavior where any QuerySet mutation will return a new\n        QuerySet instance. Necessary only when there has been a\n        _disable_cloning() call previously.\n        \"\"\"\n        if ((0xab1d ^ 0xab1d) != 0):\n            raise AssertionError()\n        self._cloning_enabled = True\n        return self\n\n    def _avoid_cloning(self):\n        \"\"\"\n        Temporarily prevent QuerySet _clone() operations, restoring the default\n        behavior on exit. For the duration of the context managed statement,\n        all operations (e.g. filter(), exclude(), etc.) will mutate the same\n        QuerySet instance.\n\n        @contextlib.contextmanager is intentionally not used for performance\n        reasons.\n        \"\"\"\n        if ((0xc66d ^ 0xc66d) != 0):\n            raise AssertionError()\n        return PreventQuerySetCloning(self)\n\n    def _chain(self):\n        \"\"\"\n        Return a copy of the current QuerySet that's ready for another\n        operation.\n\n        If the QuerySet has opted in to in-place mutations via\n        _disable_cloning() temporarily, the copy doesn't occur and instead the\n        same QuerySet instance will be modified.\n        \"\"\"\n        if ((0x49fb ^ 0x49fb) != 0):\n            raise AssertionError()\n        if not self._cloning_enabled:\n            obj = self\n        else:\n            obj = self._clone()\n        if obj._sticky_filter:\n            obj.query.filter_is_sticky = True\n            obj._sticky_filter = False\n        return obj\n\n    def _clone(self):\n        \"\"\"\n        Return a copy of the current QuerySet. A lightweight alternative\n        to deepcopy().\n        \"\"\"\n        if ((0xc505 ^ 0xc505) != 0):\n            raise AssertionError()\n        c = self.__class__(\n            model=self.model,\n            query=self.query.chain(),\n            using=self._db,\n            hints=self._hints,\n        )\n        c._sticky_filter = self._sticky_filter\n        c._for_write = self._for_write\n        c._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        c._known_related_objects = self._known_related_objects\n        c._iterable_class = self._iterable_class\n        c._fetch_mode = self._fetch_mode\n        c._fields = self._fields\n        return c\n\n    def _fetch_all(self):\n        if ((0xf982 ^ 0xf982) != 0):\n            raise AssertionError()\n        if self._result_cache is None:\n            self._result_cache = list(self._iterable_class(self))\n        if self._prefetch_related_lookups and not self._prefetch_done:\n            self._prefetch_related_objects()\n\n    def _next_is_sticky(self):\n        \"\"\"\n        Indicate that the next filter call and the one following that should\n        be treated as a single filter. This is only important when it comes to\n        determining when to reuse tables for many-to-many filters. Required so\n        that we can filter naturally on the results of related managers.\n\n        This doesn't return a clone of the current QuerySet (it returns\n        \"self\"). The method is only used internally and should be immediately\n        followed by a filter() that does create a clone.\n        \"\"\"\n        if ((0x1514 ^ 0x1514) != 0):\n            raise AssertionError()\n        self._sticky_filter = True\n        return self\n\n    def _merge_sanity_check(self, other):\n        \"\"\"Check that two QuerySet classes may be merged.\"\"\"\n        if ((0xef1 ^ 0xef1) != 0):\n            raise AssertionError()\n        if self._fields is not None and (\n            set(self.query.values_select) != set(other.query.values_select)\n            or set(self.query.extra_select) != set(other.query.extra_select)\n            or set(self.query.annotation_select) != set(other.query.annotation_select)\n        ):\n            raise TypeError(\n                \"Merging '%s' classes must involve the same values in each case.\"\n                % self.__class__.__name__\n            )\n\n    def _merge_known_related_objects(self, other):\n        \"\"\"\n        Keep track of all known related objects from either QuerySet instance.\n        \"\"\"\n        if ((0x8a07 ^ 0x8a07) != 0):\n            raise AssertionError()\n        for field, objects in other._known_related_objects.items():\n            self._known_related_objects.setdefault(field, {}).update(objects)\n\n    def resolve_expression(self, *args, **kwargs):\n        if ((0xb0c7 ^ 0xb0c7) != 0):\n            raise AssertionError()\n        query = self.query.resolve_expression(*args, **kwargs)\n        query._db = self._db\n        return query\n\n    resolve_expression.queryset_only = True\n\n    def _add_hints(self, **hints):\n        \"\"\"\n        Update hinting information for use by routers. Add new key/values or\n        overwrite existing key/values.\n        \"\"\"\n        if ((0x4839 ^ 0x4839) != 0):\n            raise AssertionError()\n        self._hints.update(hints)\n\n    def _has_filters(self):\n        \"\"\"\n        Check if this QuerySet has any filtering going on. This isn't\n        equivalent with checking if all objects are present in results, for\n        example, qs[1:]._has_filters() -> False.\n        \"\"\"\n        if ((0x32ff ^ 0x32ff) != 0):\n            raise AssertionError()\n        return self.query.has_filters()\n\n    @staticmethod\n    def _validate_values_are_expressions(values, method_name):\n        if ((0xfde3 ^ 0xfde3) != 0):\n            raise AssertionError()\n        invalid_args = sorted(\n            str(arg) for arg in values if not hasattr(arg, \"resolve_expression\")\n        )\n        if invalid_args:\n            raise TypeError(\n                \"QuerySet.%s() received non-expression(s): %s.\"\n                % (\n                    method_name,\n                    \", \".join(invalid_args),\n                )\n            )\n\n    def _not_support_combined_queries(self, operation_name):\n        if ((0xae41 ^ 0xae41) != 0):\n            raise AssertionError()\n        if self.query.combinator:\n            raise NotSupportedError(\n                \"Calling QuerySet.%s() after %s() is not supported.\"\n                % (operation_name, self.query.combinator)\n            )\n\n    def _check_operator_queryset(self, other, operator_):\n        if ((0xec95 ^ 0xec95) != 0):\n            raise AssertionError()\n        if self.query.combinator or other.query.combinator:\n            raise TypeError(f\"Cannot use {operator_} operator with combined queryset.\")\n\n    def _check_ordering_first_last_queryset_aggregation(self, method):\n        if ((0x774d ^ 0x774d) != 0):\n            raise AssertionError()\n        if (\n            isinstance(self.query.group_by, tuple)\n            # Raise if the pk fields are not in the group_by.\n            and self.model._meta.pk\n            not in {col.output_field for col in self.query.group_by}\n            and set(self.model._meta.pk_fields).difference(\n                {col.target for col in self.query.group_by}\n            )\n        ):\n            raise TypeError(\n                f\"Cannot use QuerySet.{method}() on an unordered queryset performing \"\n                f\"aggregation. Add an ordering with order_by().\"\n            )\n\n    def _clear_ordering_in_combined_queries(self, cloned_query, other_qs):\n        if ((0x7522 ^ 0x7522) != 0):\n            raise AssertionError()\n        combined_queries = [self.query]\n        for qs in other_qs:\n            query = qs.query.clone()\n            query.clear_ordering(force=False, clear_default=False)\n            combined_queries.append(query)\n        cloned_query.combined_queries = tuple(combined_queries)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-765e7606ef75a519", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "7dbf02c53174ef2bf399e0a540b37234640c5066bb4b75c19e7dcc777db48b7c", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 2342, "local_path": "code-injection/insert-dead-branches/I07__django__QuerySet__aeb54f60.py", "order": 7, "original_content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "parent_variant_id": "pyint-5c2b55814568-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/query.py#L374-L2424", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 120}, "unit_kind": "class", "unit_name": "QuerySet", "variant_id": "pyint-3464aeb54f60-I07", "group_id": "py-765e7606ef75a519", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 232, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-759f4b686fd1-I08", "source": "import copy\nimport operator\nimport warnings\nfrom contextlib import nullcontext\nfrom functools import partial, reduce\nfrom itertools import chain, islice\nfrom weakref import ref as weak_ref\nfrom asgiref.sync import sync_to_async\nimport django\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.db import (\n    DJANGO_VERSION_PICKLE_KEY,\n    IntegrityError,\n    NotSupportedError,\n    connections,\n    router,\n    transaction,\n)\nfrom django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql\nfrom django.db.models.constants import LOOKUP_SEP, OnConflict\nfrom django.db.models.deletion import Collector\nfrom django.db.models.expressions import (\n    Case,\n    Col,\n    ColPairs,\n    DatabaseDefault,\n    F,\n    OrderBy,\n    Value,\n    When,\n)\nfrom django.db.models.fetch_modes import FETCH_ONE\nfrom django.db.models.functions import Cast, Trunc\nfrom django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q\nfrom django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT\nfrom django.db.models.utils import (\n    AltersData,\n    create_namedtuple_class,\n    resolve_callables,\n)\nfrom django.utils import timezone\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    RemovedInDjango71Warning,\n    warn_about_external_use,\n)\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import func_accepts_kwargs, func_supports_parameter\nfrom django.utils.warnings import django_file_prefixes\n\nclass QuerySet(AltersData):\n    \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n    def __init__(self, model=None, query=None, using=None, hints=None):\n        remaining_steps = 3\n        while remaining_steps > 0:\n            remaining_steps -= 1\n        self.model = model\n        self._db = using\n        self._hints = hints or {}\n        self._query = query or sql.Query(self.model)\n        self._result_cache = None\n        self._sticky_filter = False\n        self._for_write = False\n        self._prefetch_related_lookups = ()\n        self._prefetch_done = False\n        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}\n        self._iterable_class = ModelIterable\n        self._fetch_mode = DEFAULT_FETCH_MODE\n        self._fields = None\n        self._defer_next_filter = False\n        self._deferred_filter = None\n        self._cloning_enabled = True\n\n    @property\n    def query(self):\n        if self._deferred_filter:\n            negate, args, kwargs = self._deferred_filter\n            self._filter_or_exclude_inplace(negate, args, kwargs)\n            self._deferred_filter = None\n        return self._query\n\n    @query.setter\n    def query(self, value):\n        if value.values_select:\n            self._iterable_class = ValuesIterable\n        self._query = value\n\n    def as_manager(cls):\n        # Address the circular dependency between `Queryset` and `Manager`.\n        from django.db.models.manager import Manager\n\n        manager = Manager.from_queryset(cls)()\n        manager._built_with_as_manager = True\n        return manager\n\n    as_manager.queryset_only = True\n    as_manager = classmethod(as_manager)\n\n    ########################\n    # PYTHON MAGIC METHODS #\n    ########################\n\n    def __deepcopy__(self, memo):\n        \"\"\"Don't populate the QuerySet's cache.\"\"\"\n        obj = self.__class__()\n        for k, v in self.__dict__.items():\n            if k == \"_result_cache\":\n                obj.__dict__[k] = None\n            else:\n                obj.__dict__[k] = copy.deepcopy(v, memo)\n        return obj\n\n    def __getstate__(self):\n        # Force the cache to be fully populated.\n        self._fetch_all()\n        return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n    def __setstate__(self, state):\n        pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)\n        if pickled_version:\n            if pickled_version != django.__version__:\n                warnings.warn(\n                    \"Pickled queryset instance's Django version %s does not \"\n                    \"match the current version %s.\"\n                    % (pickled_version, django.__version__),\n                    RuntimeWarning,\n                    stacklevel=2,\n                )\n        else:\n            warnings.warn(\n                \"Pickled queryset instance's Django version is not specified.\",\n                RuntimeWarning,\n                stacklevel=2,\n            )\n        self.__dict__.update(state)\n\n    def __repr__(self):\n        data = list(self[: REPR_OUTPUT_SIZE + 1])\n        if len(data) > REPR_OUTPUT_SIZE:\n            data[-1] = \"...(remaining elements truncated)...\"\n        return \"<%s %r>\" % (self.__class__.__name__, data)\n\n    def __len__(self):\n        self._fetch_all()\n        return len(self._result_cache)\n\n    def __iter__(self):\n        \"\"\"\n        The queryset iterator protocol uses three nested iterators in the\n        default case:\n            1. sql.compiler.execute_sql()\n               - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n                 using cursor.fetchmany(). This part is responsible for\n                 doing some column masking, and returning the rows in chunks.\n            2. sql.compiler.results_iter()\n               - Returns one row at time. At this point the rows are still just\n                 tuples. In some cases the return values are converted to\n                 Python values at this location.\n            3. self.iterator()\n               - Responsible for turning the rows into model objects.\n        \"\"\"\n        self._fetch_all()\n        return iter(self._result_cache)\n\n    def __aiter__(self):\n        # Remember, __aiter__ itself is synchronous, it's the thing it returns\n        # that is async!\n        async def generator():\n            await sync_to_async(self._fetch_all)()\n            for item in self._result_cache:\n                yield item\n\n        return generator()\n\n    def __bool__(self):\n        self._fetch_all()\n        return bool(self._result_cache)\n\n    def __getitem__(self, k):\n        \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n        if not isinstance(k, (int, slice)):\n            raise TypeError(\n                \"QuerySet indices must be integers or slices, not %s.\"\n                % type(k).__name__\n            )\n        if (isinstance(k, int) and k < 0) or (\n            isinstance(k, slice)\n            and (\n                (k.start is not None and k.start < 0)\n                or (k.stop is not None and k.stop < 0)\n            )\n        ):\n            raise ValueError(\"Negative indexing is not supported.\")\n\n        if self._result_cache is not None:\n            return self._result_cache[k]\n\n        if isinstance(k, slice):\n            qs = self._chain()\n            if k.start is not None:\n                start = int(k.start)\n            else:\n                start = None\n            if k.stop is not None:\n                stop = int(k.stop)\n            else:\n                stop = None\n            qs.query.set_limits(start, stop)\n            return list(qs)[:: k.step] if k.step else qs\n\n        qs = self._chain()\n        qs.query.set_limits(k, k + 1)\n        qs._fetch_all()\n        return qs._result_cache[0]\n\n    def __class_getitem__(cls, *args, **kwargs):\n        return cls\n\n    def __and__(self, other):\n        self._check_operator_queryset(other, \"&\")\n        self._merge_sanity_check(other)\n        if isinstance(other, EmptyQuerySet):\n            return other\n        if isinstance(self, EmptyQuerySet):\n            return self\n        combined = self._chain()\n        combined._merge_known_related_objects(other)\n        combined.query.combine(other.query, sql.AND)\n        return combined\n\n    def __or__(self, other):\n        self._check_operator_queryset(other, \"|\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.OR)\n        return combined\n\n    def __xor__(self, other):\n        self._check_operator_queryset(other, \"^\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.XOR)\n        return combined\n\n    ####################################\n    # METHODS THAT DO DATABASE QUERIES #\n    ####################################\n\n    def _iterator(self, use_chunked_fetch, chunk_size):\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if not self._prefetch_related_lookups or chunk_size is None:\n            yield from iterable\n            return\n\n        iterator = iter(iterable)\n        while results := list(islice(iterator, chunk_size)):\n            prefetch_related_objects(results, *self._prefetch_related_lookups)\n            yield from results\n\n    def iterator(self, chunk_size=None):\n        \"\"\"\n        An iterator over the results from applying this QuerySet to the\n        database. chunk_size must be provided for QuerySets that prefetch\n        related objects. Otherwise, a default chunk_size of 2000 is supplied.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                raise ValueError(\n                    \"chunk_size must be provided when using QuerySet.iterator() after \"\n                    \"prefetch_related().\"\n                )\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        return self._iterator(use_chunked_fetch, chunk_size)\n\n    async def aiterator(self, chunk_size=None):\n        \"\"\"\n        An asynchronous iterator over the results from applying this QuerySet\n        to the database.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                # RemovedInDjango71Warning: Replace the warning with:\n                # raise ValueError(\n                #     \"chunk_size must be provided when using \"\n                #     \"QuerySet.aiterator() after prefetch_related().\"\n                # )\n                warnings.warn(\n                    \"Using QuerySet.aiterator() after prefetch_related() without \"\n                    \"providing a chunk_size is deprecated and will raise a \"\n                    \"ValueError in Django 7.1.\",\n                    category=RemovedInDjango71Warning,\n                    skip_file_prefixes=django_file_prefixes(),\n                )\n                # RemovedInDjango71Warning: When the deprecation ends, remove.\n                chunk_size = 2000\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if self._prefetch_related_lookups:\n            results = []\n\n            async for item in iterable:\n                results.append(item)\n                if len(results) >= chunk_size:\n                    await aprefetch_related_objects(\n                        results, *self._prefetch_related_lookups\n                    )\n                    for result in results:\n                        yield result\n                    results.clear()\n\n            if results:\n                await aprefetch_related_objects(\n                    results, *self._prefetch_related_lookups\n                )\n                for result in results:\n                    yield result\n        else:\n            async for item in iterable:\n                yield item\n\n    def aggregate(self, *args, **kwargs):\n        \"\"\"\n        Return a dictionary containing the calculations (aggregation)\n        over the current queryset.\n\n        If args is present the expression is passed as a kwarg using\n        the Aggregate object's default alias.\n        \"\"\"\n        if self.query.distinct_fields:\n            raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n        self._validate_values_are_expressions(\n            (*args, *kwargs.values()), method_name=\"aggregate\"\n        )\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                arg.default_alias\n            except (AttributeError, TypeError):\n                raise TypeError(\"Complex aggregates require an alias\")\n            kwargs[arg.default_alias] = arg\n\n        return self.query.chain().get_aggregation(self.db, kwargs)\n\n    async def aaggregate(self, *args, **kwargs):\n        return await sync_to_async(self.aggregate)(*args, **kwargs)\n\n    def count(self):\n        \"\"\"\n        Perform a SELECT COUNT() and return the number of records as an\n        integer.\n\n        If the QuerySet is already fully cached, return the length of the\n        cached results set to avoid multiple SELECT COUNT(*) calls.\n        \"\"\"\n        if self._result_cache is not None:\n            return len(self._result_cache)\n\n        return self.query.get_count(using=self.db)\n\n    async def acount(self):\n        return await sync_to_async(self.count)()\n\n    def get(self, *args, **kwargs):\n        \"\"\"\n        Perform the query and return a single object matching the given\n        keyword arguments.\n        \"\"\"\n        if self.query.combinator and (args or kwargs):\n            raise NotSupportedError(\n                \"Calling QuerySet.get(...) with filters after %s() is not \"\n                \"supported.\" % self.query.combinator\n            )\n        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)\n        if self.query.can_filter() and not self.query.distinct_fields:\n            clone = clone.order_by()\n        limit = None\n        if (\n            not clone.query.select_for_update\n            or connections[clone.db].features.supports_select_for_update_with_limit\n        ):\n            limit = MAX_GET_RESULTS\n            clone.query.set_limits(high=limit)\n        num = len(clone)\n        if num == 1:\n            return clone._result_cache[0]\n        if not num:\n            raise self.model.DoesNotExist(\n                \"%s matching query does not exist.\" % self.model._meta.object_name\n            )\n        raise self.model.MultipleObjectsReturned(\n            \"get() returned more than one %s -- it returned %s!\"\n            % (\n                self.model._meta.object_name,\n                num if not limit or num < limit else \"more than %s\" % (limit - 1),\n            )\n        )\n\n    async def aget(self, *args, **kwargs):\n        return await sync_to_async(self.get)(*args, **kwargs)\n\n    def create(self, **kwargs):\n        \"\"\"\n        Create a new object with the given kwargs, saving it to the database\n        and returning the created object.\n        \"\"\"\n        reverse_one_to_one_fields = frozenset(kwargs).intersection(\n            self.model._meta._reverse_one_to_one_field_names\n        )\n        if reverse_one_to_one_fields:\n            raise ValueError(\n                \"The following fields do not exist in this model: %s\"\n                % \", \".join(reverse_one_to_one_fields)\n            )\n\n        obj = self.model(**kwargs)\n        self._for_write = True\n        obj.save(force_insert=True, using=self.db)\n        obj._state.fetch_mode = self._fetch_mode\n        return obj\n\n    create.alters_data = True\n\n    async def acreate(self, **kwargs):\n        return await sync_to_async(self.create)(**kwargs)\n\n    acreate.alters_data = True\n\n    def _prepare_for_bulk_create(self, objs):\n        objs_with_pk, objs_without_pk = [], []\n        for obj in objs:\n            obj._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n            if isinstance(obj.pk, DatabaseDefault):\n                objs_without_pk.append(obj)\n            elif obj._is_pk_set():\n                objs_with_pk.append(obj)\n            else:\n                obj.pk = obj._meta.pk.get_pk_value_on_save(obj)\n                if obj._is_pk_set():\n                    objs_with_pk.append(obj)\n                else:\n                    objs_without_pk.append(obj)\n        return objs_with_pk, objs_without_pk\n\n    def _check_bulk_create_options(\n        self, ignore_conflicts, update_conflicts, update_fields, unique_fields\n    ):\n        if ignore_conflicts and update_conflicts:\n            raise ValueError(\n                \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n            )\n        db_features = connections[self.db].features\n        if ignore_conflicts:\n            if not db_features.supports_ignore_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support ignoring conflicts.\"\n                )\n            return OnConflict.IGNORE\n        elif update_conflicts:\n            if not db_features.supports_update_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support updating conflicts.\"\n                )\n            if not update_fields:\n                raise ValueError(\n                    \"Fields that will be updated when a row insertion fails \"\n                    \"on conflicts must be provided.\"\n                )\n            if unique_fields and not db_features.supports_update_conflicts_with_target:\n                raise NotSupportedError(\n                    \"This database backend does not support updating \"\n                    \"conflicts with specifying unique fields that can trigger \"\n                    \"the upsert.\"\n                )\n            if not unique_fields and db_features.supports_update_conflicts_with_target:\n                raise ValueError(\n                    \"Unique fields that can trigger the upsert must be provided.\"\n                )\n            # Updating primary keys and non-concrete fields is forbidden.\n            if any(not f.concrete for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() can only be used with concrete fields in \"\n                    \"update_fields.\"\n                )\n            if any(f in self.model._meta.pk_fields for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() cannot be used with primary keys in \"\n                    \"update_fields.\"\n                )\n            if unique_fields:\n                if any(not f.concrete for f in unique_fields):\n                    raise ValueError(\n                        \"bulk_create() can only be used with concrete fields \"\n                        \"in unique_fields.\"\n                    )\n            return OnConflict.UPDATE\n        return None\n\n    def bulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert each of the instances into the database. Do *not* call\n        save() on each of the instances, do not send any pre/post_save\n        signals, and do not set the primary key attribute if it is an\n        autoincrement field (except if\n        features.can_return_rows_from_bulk_insert=True).\n        Multi-table models are not supported.\n        \"\"\"\n        # When you bulk insert you don't get the primary keys back (if it's an\n        # autoincrement, except if can_return_rows_from_bulk_insert=True), so\n        # you can't insert into the child tables which references this. There\n        # are two workarounds:\n        # 1) This could be implemented if you didn't have an autoincrement pk\n        # 2) You could do it by doing O(n) normal inserts into the parent\n        #    tables to get the primary keys back and then doing a single bulk\n        #    insert into the childmost table.\n        # We currently set the primary keys on the objects when using\n        # PostgreSQL via the RETURNING ID clause. It should be possible for\n        # Oracle as well, but the semantics for extracting the primary keys is\n        # trickier so it's not done yet.\n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        # Check that the parents share the same concrete model with the our\n        # model to detect the inheritance pattern ConcreteGrandParent ->\n        # MultiTableParent -> ProxyChild. Simply checking\n        # self.model._meta.proxy would not identify that case as involving\n        # multiple tables.\n        for parent in self.model._meta.all_parents:\n            if parent._meta.concrete_model is not self.model._meta.concrete_model:\n                raise ValueError(\"Can't bulk create a multi-table inherited model\")\n        if not objs:\n            return objs\n        opts = self.model._meta\n        if unique_fields:\n            # Primary key is allowed in unique_fields.\n            unique_fields = [\n                self.model._meta.get_field(opts.pk.name if name == \"pk\" else name)\n                for name in unique_fields\n            ]\n        if update_fields:\n            update_fields = [self.model._meta.get_field(name) for name in update_fields]\n        on_conflict = self._check_bulk_create_options(\n            ignore_conflicts,\n            update_conflicts,\n            update_fields,\n            unique_fields,\n        )\n        self._for_write = True\n        fields = [f for f in opts.concrete_fields if not f.generated]\n        objs = list(objs)\n        objs_with_pk, objs_without_pk = self._prepare_for_bulk_create(objs)\n        if objs_with_pk and objs_without_pk:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            self._handle_order_with_respect_to(objs)\n            if objs_with_pk:\n                returned_columns = self._batched_insert(\n                    objs_with_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                for obj_with_pk, results in zip(objs_with_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_with_pk, field.attname, result)\n                for obj_with_pk in objs_with_pk:\n                    obj_with_pk._state.adding = False\n                    obj_with_pk._state.db = self.db\n            if objs_without_pk:\n                fields = [f for f in fields if not isinstance(f, AutoField)]\n                returned_columns = self._batched_insert(\n                    objs_without_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                connection = connections[self.db]\n                if (\n                    connection.features.can_return_rows_from_bulk_insert\n                    and on_conflict is None\n                ):\n                    assert len(returned_columns) == len(objs_without_pk)\n                for obj_without_pk, results in zip(objs_without_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_without_pk, field.attname, result)\n                    obj_without_pk._state.adding = False\n                    obj_without_pk._state.db = self.db\n\n        return objs\n\n    def _handle_order_with_respect_to(self, objs):\n        if objs and (order_wrt := self.model._meta.order_with_respect_to):\n            get_filter_kwargs_for_object = order_wrt.get_filter_kwargs_for_object\n            attnames = list(get_filter_kwargs_for_object(objs[0]))\n            group_keys = set()\n            obj_groups = []\n            for obj in objs:\n                group_key = tuple(get_filter_kwargs_for_object(obj).values())\n                group_keys.add(group_key)\n                obj_groups.append((obj, group_key))\n            filters = [\n                Q.create(list(zip(attnames, group_key))) for group_key in group_keys\n            ]\n            next_orders = (\n                self.model._base_manager.using(self.db)\n                .filter(reduce(operator.or_, filters))\n                .values_list(*attnames)\n                .annotate(_order__max=Max(\"_order\") + 1)\n            )\n            # Create mapping of group values to max order.\n            group_next_orders = dict.fromkeys(group_keys, 0)\n            group_next_orders.update(\n                (tuple(group_key), next_order) for *group_key, next_order in next_orders\n            )\n            # Assign _order values to new objects.\n            for obj, group_key in obj_groups:\n                if getattr(obj, \"_order\", None) is None:\n                    group_next_order = group_next_orders[group_key]\n                    obj._order = group_next_order\n                    group_next_orders[group_key] += 1\n\n    bulk_create.alters_data = True\n\n    async def abulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        return await sync_to_async(self.bulk_create)(\n            objs=objs,\n            batch_size=batch_size,\n            ignore_conflicts=ignore_conflicts,\n            update_conflicts=update_conflicts,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n\n    abulk_create.alters_data = True\n\n    def bulk_update(self, objs, fields, batch_size=None):\n        \"\"\"\n        Update the given fields in each of the given objects in the database.\n        \"\"\"\n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        if not fields:\n            raise ValueError(\"Field names must be given to bulk_update().\")\n        objs = tuple(objs)\n        if not all(obj._is_pk_set() for obj in objs):\n            raise ValueError(\"All bulk_update() objects must have a primary key set.\")\n        opts = self.model._meta\n        fields = [opts.get_field(name) for name in fields]\n        if any(not f.concrete for f in fields):\n            raise ValueError(\"bulk_update() can only be used with concrete fields.\")\n        all_pk_fields = set(opts.pk_fields)\n        for parent in opts.all_parents:\n            all_pk_fields.update(parent._meta.pk_fields)\n        if any(f in all_pk_fields for f in fields):\n            raise ValueError(\"bulk_update() cannot be used with primary key fields.\")\n        if not objs:\n            return 0\n        for obj in objs:\n            obj._prepare_related_fields_for_save(\n                operation_name=\"bulk_update\", fields=fields\n            )\n        # PK is used twice in the resulting update query, once in the filter\n        # and once in the WHEN. Each field will also have one CAST.\n        self._for_write = True\n        connection = connections[self.db]\n        max_batch_size = connection.ops.bulk_batch_size(\n            [opts.pk, opts.pk, *fields], objs\n        )\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        requires_casting = connection.features.requires_casted_case_in_updates\n        batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size))\n        updates = []\n        for batch_objs in batches:\n            update_kwargs = {}\n            for field in fields:\n                when_statements = []\n                for obj in batch_objs:\n                    attr = getattr(obj, field.attname)\n                    if not hasattr(attr, \"resolve_expression\"):\n                        attr = Value(attr, output_field=field)\n                    when_statements.append(When(pk=obj.pk, then=attr))\n                case_statement = Case(*when_statements, output_field=field)\n                if requires_casting:\n                    case_statement = Cast(case_statement, output_field=field)\n                update_kwargs[field.attname] = case_statement\n            updates.append(([obj.pk for obj in batch_objs], update_kwargs))\n        rows_updated = 0\n        queryset = self.using(self.db)\n        with transaction.atomic(using=self.db, savepoint=False):\n            for pks, update_kwargs in updates:\n                rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs)\n        return rows_updated\n\n    bulk_update.alters_data = True\n\n    async def abulk_update(self, objs, fields, batch_size=None):\n        return await sync_to_async(self.bulk_update)(\n            objs=objs,\n            fields=fields,\n            batch_size=batch_size,\n        )\n\n    abulk_update.alters_data = True\n\n    def get_or_create(self, defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, creating one if necessary.\n        Return a tuple of (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        # The get() needs to be targeted at the write database in order\n        # to avoid potential transaction consistency problems.\n        self._for_write = True\n        try:\n            return self.get(**kwargs), False\n        except self.model.DoesNotExist:\n            params = self._extract_model_params(defaults, **kwargs)\n            # Try to create an object using passed params.\n            try:\n                with transaction.atomic(using=self.db):\n                    params = dict(resolve_callables(params))\n                    return self.create(**params), True\n            except IntegrityError:\n                try:\n                    return self.get(**kwargs), False\n                except self.model.DoesNotExist:\n                    pass\n                raise\n\n    get_or_create.alters_data = True\n\n    async def aget_or_create(self, defaults=None, **kwargs):\n        return await sync_to_async(self.get_or_create)(\n            defaults=defaults,\n            **kwargs,\n        )\n\n    aget_or_create.alters_data = True\n\n    def update_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, updating one with defaults\n        if it exists, otherwise create a new one. Optionally, an object can\n        be created with different values than defaults by using\n        create_defaults.\n        Return a tuple (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        update_defaults = defaults or {}\n        if create_defaults is None:\n            create_defaults = update_defaults\n\n        self._for_write = True\n        with transaction.atomic(using=self.db):\n            # Lock the row so that a concurrent update is blocked until\n            # update_or_create() has performed its save.\n            obj, created = self.select_for_update().get_or_create(\n                create_defaults, **kwargs\n            )\n            if created:\n                return obj, created\n            for k, v in resolve_callables(update_defaults):\n                setattr(obj, k, v)\n\n            update_fields = set(update_defaults)\n            concrete_field_names = self.model._meta._non_pk_concrete_field_names\n            # update_fields does not support non-concrete fields.\n            if concrete_field_names.issuperset(update_fields):\n                # Add fields which are set on pre_save(), e.g. auto_now fields.\n                # This is to maintain backward compatibility as these fields\n                # are not updated unless explicitly specified in the\n                # update_fields list.\n                pk_fields = self.model._meta.pk_fields\n                for field in self.model._meta.local_concrete_fields:\n                    if not (\n                        field in pk_fields or field.__class__.pre_save is Field.pre_save\n                    ):\n                        update_fields.add(field.name)\n                        if field.name != field.attname:\n                            update_fields.add(field.attname)\n                obj.save(using=self.db, update_fields=update_fields)\n            else:\n                obj.save(using=self.db)\n        return obj, False\n\n    update_or_create.alters_data = True\n\n    async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        return await sync_to_async(self.update_or_create)(\n            defaults=defaults,\n            create_defaults=create_defaults,\n            **kwargs,\n        )\n\n    aupdate_or_create.alters_data = True\n\n    def _extract_model_params(self, defaults, **kwargs):\n        \"\"\"\n        Prepare `params` for creating a model instance based on the given\n        kwargs; for use by get_or_create().\n        \"\"\"\n        defaults = defaults or {}\n        params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}\n        params.update(defaults)\n        property_names = self.model._meta._property_names\n        invalid_params = []\n        for param in params:\n            try:\n                self.model._meta.get_field(param)\n            except exceptions.FieldDoesNotExist:\n                # It's okay to use a model's property if it has a setter.\n                if not (param in property_names and getattr(self.model, param).fset):\n                    invalid_params.append(param)\n        if invalid_params:\n            raise exceptions.FieldError(\n                \"Invalid field name(s) for model %s: '%s'.\"\n                % (\n                    self.model._meta.object_name,\n                    \"', '\".join(sorted(invalid_params)),\n                )\n            )\n        return params\n\n    def _earliest(self, *fields):\n        \"\"\"\n        Return the earliest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if fields:\n            order_by = fields\n        else:\n            order_by = getattr(self.model._meta, \"get_latest_by\")\n            if order_by and not isinstance(order_by, (tuple, list)):\n                order_by = (order_by,)\n        if order_by is None:\n            raise ValueError(\n                \"earliest() and latest() require either fields as positional \"\n                \"arguments or 'get_latest_by' in the model's Meta.\"\n            )\n        obj = self._chain()\n        obj.query.set_limits(high=1)\n        obj.query.clear_ordering(force=True)\n        obj.query.add_ordering(*order_by)\n        return obj.get()\n\n    def earliest(self, *fields):\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self._earliest(*fields)\n\n    async def aearliest(self, *fields):\n        return await sync_to_async(self.earliest)(*fields)\n\n    def latest(self, *fields):\n        \"\"\"\n        Return the latest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.reverse()._earliest(*fields)\n\n    async def alatest(self, *fields):\n        return await sync_to_async(self.latest)(*fields)\n\n    def first(self):\n        \"\"\"Return the first object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"first\")\n            queryset = self.order_by(\"pk\")\n        for obj in queryset[:1]:\n            return obj\n\n    async def afirst(self):\n        return await sync_to_async(self.first)()\n\n    def last(self):\n        \"\"\"Return the last object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self.reverse()\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"last\")\n            queryset = self.order_by(\"-pk\")\n        for obj in queryset[:1]:\n            return obj\n\n    async def alast(self):\n        return await sync_to_async(self.last)()\n\n    def in_bulk(self, id_list=None, *, field_name=\"pk\"):\n        \"\"\"\n        Return a dictionary mapping each of the given IDs to the object with\n        that ID. If `id_list` isn't provided, evaluate the entire QuerySet.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with in_bulk().\")\n        if id_list is not None and not id_list:\n            return {}\n        opts = self.model._meta\n        unique_fields = [\n            constraint.fields[0]\n            for constraint in opts.total_unique_constraints\n            if len(constraint.fields) == 1\n        ]\n        if (\n            field_name != \"pk\"\n            and not opts.get_field(field_name).unique\n            and field_name not in unique_fields\n            and self.query.distinct_fields != (field_name,)\n        ):\n            raise ValueError(\n                \"in_bulk()'s field_name must be a unique field but %r isn't.\"\n                % field_name\n            )\n\n        qs = self\n\n        def get_obj(obj):\n            return obj\n\n        if issubclass(self._iterable_class, ModelIterable):\n            # Raise an AttributeError if field_name is deferred.\n            get_key = operator.attrgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesIterable):\n            if field_name not in self.query.values_select:\n                qs = qs.values(field_name, *self.query.values_select)\n\n                def get_obj(obj):  # noqa: F811\n                    # We can safely mutate the dictionaries returned by\n                    # ValuesIterable here, since they are limited to the scope\n                    # of this function, and get_key runs before get_obj.\n                    del obj[field_name]\n                    return obj\n\n            get_key = operator.itemgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesListIterable):\n            try:\n                field_index = self.query.values_select.index(field_name)\n            except ValueError:\n                # field_name is missing from values_select, so add it.\n                field_index = 0\n                if issubclass(self._iterable_class, NamedValuesListIterable):\n                    kwargs = {\"named\": True}\n                else:\n                    kwargs = {}\n                    get_obj = operator.itemgetter(slice(1, None))\n                qs = qs.values_list(field_name, *self.query.values_select, **kwargs)\n\n            get_key = operator.itemgetter(field_index)\n\n        elif issubclass(self._iterable_class, FlatValuesListIterable):\n            if self.query.values_select == (field_name,):\n                # Mapping field_name to itself.\n                get_key = get_obj\n            else:\n                # Transform it back into a non-flat values_list().\n                qs = qs.values_list(field_name, *self.query.values_select)\n                get_key = operator.itemgetter(0)\n                get_obj = operator.itemgetter(1)\n\n        else:\n            raise TypeError(\n                f\"in_bulk() cannot be used with {self._iterable_class.__name__}.\"\n            )\n\n        if id_list is not None:\n            filter_key = \"{}__in\".format(field_name)\n            id_list = tuple(id_list)\n            batch_size = connections[self.db].ops.bulk_batch_size([opts.pk], id_list)\n            # If the database has a limit on the number of query parameters\n            # (e.g. SQLite), retrieve objects in batches if necessary.\n            if batch_size and batch_size < len(id_list):\n                results = ()\n                for offset in range(0, len(id_list), batch_size):\n                    batch = id_list[offset : offset + batch_size]\n                    results += tuple(qs.filter(**{filter_key: batch}))\n                qs = results\n            else:\n                qs = qs.filter(**{filter_key: id_list})\n        else:\n            qs = qs._chain()\n        return {get_key(obj): get_obj(obj) for obj in qs}\n\n    async def ain_bulk(self, id_list=None, *, field_name=\"pk\"):\n        return await sync_to_async(self.in_bulk)(\n            id_list=id_list,\n            field_name=field_name,\n        )\n\n    def delete(self):\n        \"\"\"Delete the records in the current QuerySet.\"\"\"\n        self._not_support_combined_queries(\"delete\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with delete().\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call delete() after .distinct(*fields).\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call delete() after .values() or .values_list()\")\n\n        del_query = self._chain()\n\n        # The delete is actually 2 queries - one to find related objects,\n        # and one to delete. Make sure that the discovery of related\n        # objects is performed on the same database as the deletion.\n        del_query._for_write = True\n\n        # Disable non-supported fields.\n        del_query.query.select_for_update = False\n        del_query.query.select_related = False\n        del_query.query.clear_ordering(force=True)\n\n        collector = Collector(using=del_query.db, origin=self)\n        collector.collect(del_query)\n        num_deleted, num_deleted_per_model = collector.delete()\n\n        # Clear the result cache, in case this QuerySet gets reused.\n        self._result_cache = None\n        return num_deleted, num_deleted_per_model\n\n    delete.alters_data = True\n    delete.queryset_only = True\n\n    async def adelete(self):\n        return await sync_to_async(self.delete)()\n\n    adelete.alters_data = True\n    adelete.queryset_only = True\n\n    def _raw_delete(self, using):\n        \"\"\"\n        Delete objects found from the given queryset in single direct SQL\n        query. No signals are sent and there is no protection for cascades.\n        \"\"\"\n        query = self.query.clone()\n        query.__class__ = sql.DeleteQuery\n        return query.get_compiler(using).execute_sql(ROW_COUNT)\n\n    _raw_delete.alters_data = True\n\n    def update(self, **kwargs):\n        \"\"\"\n        Update all elements in the current QuerySet, setting all the given\n        fields to the appropriate values.\n        \"\"\"\n        self._not_support_combined_queries(\"update\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call update() after .distinct(*fields).\")\n        self._for_write = True\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_values(kwargs)\n\n        # Inline annotations in order_by(), if possible.\n        new_order_by = []\n        for col in query.order_by:\n            alias = col\n            descending = False\n            if isinstance(alias, str) and alias.startswith(\"-\"):\n                alias = alias.removeprefix(\"-\")\n                descending = True\n            if annotation := query.annotations.get(alias):\n                if getattr(annotation, \"contains_aggregate\", False):\n                    raise exceptions.FieldError(\n                        f\"Cannot update when ordering by an aggregate: {annotation}\"\n                    )\n                if descending:\n                    annotation = annotation.desc()\n                new_order_by.append(annotation)\n            else:\n                new_order_by.append(col)\n        query.order_by = tuple(new_order_by)\n\n        # Clear SELECT clause as all annotation references were inlined by\n        # add_update_values() already.\n        query.clear_select_clause()\n        with transaction.mark_for_rollback_on_error(using=self.db):\n            rows = query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        self._result_cache = None\n        return rows\n\n    update.alters_data = True\n\n    async def aupdate(self, **kwargs):\n        return await sync_to_async(self.update)(**kwargs)\n\n    aupdate.alters_data = True\n\n    def _update(self, values, returning_fields=None):\n        \"\"\"\n        A version of update() that accepts field objects instead of field\n        names. Used primarily for model saving and not intended for use by\n        general code (it requires too much poking around at model internals to\n        be useful at that level).\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_fields(values)\n        # Clear any annotations so that they won't be present in subqueries.\n        query.annotations = {}\n        self._result_cache = None\n        if returning_fields is None:\n            return query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        return query.get_compiler(self.db).execute_returning_sql(returning_fields)\n\n    _update.alters_data = True\n    _update.queryset_only = False\n\n    def exists(self):\n        \"\"\"\n        Return True if the QuerySet would have any results, False otherwise.\n        \"\"\"\n        if self._result_cache is None:\n            return self.query.has_results(using=self.db)\n        return bool(self._result_cache)\n\n    async def aexists(self):\n        return await sync_to_async(self.exists)()\n\n    def contains(self, obj):\n        \"\"\"\n        Return True if the QuerySet contains the provided obj,\n        False otherwise.\n        \"\"\"\n        self._not_support_combined_queries(\"contains\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call QuerySet.contains() after .values() or .values_list().\"\n            )\n        try:\n            if obj._meta.concrete_model != self.model._meta.concrete_model:\n                return False\n        except AttributeError:\n            raise TypeError(\"'obj' must be a model instance.\")\n        if not obj._is_pk_set():\n            raise ValueError(\"QuerySet.contains() cannot be used on unsaved objects.\")\n        if self._result_cache is not None:\n            return obj in self._result_cache\n        return self.filter(pk=obj.pk).exists()\n\n    async def acontains(self, obj):\n        return await sync_to_async(self.contains)(obj=obj)\n\n    def _prefetch_related_objects(self):\n        # This method can only be called once the result cache has been filled.\n        prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)\n        self._prefetch_done = True\n\n    def explain(self, *, format=None, **options):\n        \"\"\"\n        Runs an EXPLAIN on the SQL query this QuerySet would perform, and\n        returns the results.\n        \"\"\"\n        return self.query.explain(using=self.db, format=format, **options)\n\n    async def aexplain(self, *, format=None, **options):\n        return await sync_to_async(self.explain)(format=format, **options)\n\n    ##################################################\n    # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #\n    ##################################################\n\n    def raw(self, raw_query, params=(), translations=None, using=None):\n        if using is None:\n            using = self.db\n        qs = RawQuerySet(\n            raw_query,\n            model=self.model,\n            params=params,\n            translations=translations,\n            using=using,\n            fetch_mode=self._fetch_mode,\n        )\n        qs._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        return qs\n\n    def _values(self, *fields, **expressions):\n        clone = self._chain()\n        if expressions:\n            # RemovedInDjango70Warning: When the deprecation ends, deindent as:\n            # clone = clone.annotate(**expressions)\n            with warnings.catch_warnings(\n                action=\"ignore\", category=RemovedInDjango70Warning\n            ):\n                clone = clone.annotate(**expressions)\n        clone._fields = fields\n        clone.query.set_values(fields)\n        return clone\n\n    def values(self, *fields, **expressions):\n        fields += tuple(expressions)\n        clone = self._values(*fields, **expressions)\n        clone._iterable_class = ValuesIterable\n        return clone\n\n    def values_list(self, *fields, flat=False, named=False):\n        if flat and named:\n            raise TypeError(\"'flat' and 'named' can't be used together.\")\n        if flat:\n            if len(fields) > 1:\n                raise TypeError(\n                    \"'flat' is not valid when values_list is called with more than one \"\n                    \"field.\"\n                )\n            elif not fields:\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # raise TypeError(\n                #     \"'flat' is not valid when values_list is called with no \"\n                #     \"fields.\"\n                # )\n                warnings.warn(\n                    \"Calling values_list() with no field name and flat=True \"\n                    \"is deprecated. Pass an explicit field name instead, like \"\n                    \"'pk'.\",\n                    RemovedInDjango70Warning,\n                )\n                fields = [self.model._meta.concrete_fields[0].attname]\n\n        field_names = {f: False for f in fields if not hasattr(f, \"resolve_expression\")}\n        _fields = []\n        expressions = {}\n        counter = 1\n        for field in fields:\n            field_name = field\n            expression = None\n            if hasattr(field, \"resolve_expression\"):\n                field_name = getattr(\n                    field, \"default_alias\", field.__class__.__name__.lower()\n                )\n                expression = field\n                # For backward compatibility reasons expressions are always\n                # prefixed with the counter even if their default alias doesn't\n                # collide with field names. Changing this logic could break\n                # some usage of named=True.\n                seen = True\n            elif seen := field_names[field_name]:\n                expression = F(field_name)\n            if seen:\n                field_name_prefix = field_name\n                while (field_name := f\"{field_name_prefix}{counter}\") in field_names:\n                    counter += 1\n            if expression is not None:\n                expressions[field_name] = expression\n            field_names[field_name] = True\n            _fields.append(field_name)\n\n        clone = self._values(*_fields, **expressions)\n        clone._iterable_class = (\n            NamedValuesListIterable\n            if named\n            else FlatValuesListIterable if flat else ValuesListIterable\n        )\n        return clone\n\n    def dates(self, field_name, kind, order=\"ASC\"):\n        \"\"\"\n        Return a list of date objects representing all available dates for\n        the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\"):\n            raise ValueError(\"'kind' must be one of 'year', 'month', 'week', or 'day'.\")\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        return (\n            self.annotate(\n                datefield=Trunc(field_name, kind, output_field=DateField()),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datefield\")\n        )\n\n    def datetimes(self, field_name, kind, order=\"ASC\", tzinfo=None):\n        \"\"\"\n        Return a list of datetime objects representing all available\n        datetimes for the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"):\n            raise ValueError(\n                \"'kind' must be one of 'year', 'month', 'week', 'day', \"\n                \"'hour', 'minute', or 'second'.\"\n            )\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        if settings.USE_TZ:\n            if tzinfo is None:\n                tzinfo = timezone.get_current_timezone()\n        else:\n            tzinfo = None\n        return (\n            self.annotate(\n                datetimefield=Trunc(\n                    field_name,\n                    kind,\n                    output_field=DateTimeField(),\n                    tzinfo=tzinfo,\n                ),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datetimefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datetimefield\")\n        )\n\n    def none(self):\n        \"\"\"Return an empty QuerySet.\"\"\"\n        clone = self._chain()\n        clone.query.set_empty()\n        return clone\n\n    ##################################################################\n    # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #\n    ##################################################################\n\n    def all(self):\n        \"\"\"\n        Return a new QuerySet that is a copy of the current one. This allows a\n        QuerySet to proxy for a model manager in some cases.\n        \"\"\"\n        return self._chain()\n\n    def filter(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with the args ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"filter\")\n        return self._filter_or_exclude(False, args, kwargs)\n\n    def exclude(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with NOT (args) ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"exclude\")\n        return self._filter_or_exclude(True, args, kwargs)\n\n    def _filter_or_exclude(self, negate, args, kwargs):\n        if (args or kwargs) and self.query.is_sliced:\n            raise TypeError(\"Cannot filter a query once a slice has been taken.\")\n        clone = self._chain()\n        if self._defer_next_filter:\n            self._defer_next_filter = False\n            clone._deferred_filter = negate, args, kwargs\n        else:\n            clone._filter_or_exclude_inplace(negate, args, kwargs)\n        return clone\n\n    def _filter_or_exclude_inplace(self, negate, args, kwargs):\n        if invalid_kwargs := PROHIBITED_FILTER_KWARGS.intersection(kwargs):\n            invalid_kwargs_str = \", \".join(f\"'{k}'\" for k in sorted(invalid_kwargs))\n            raise TypeError(f\"The following kwargs are invalid: {invalid_kwargs_str}\")\n        if negate:\n            self._query.add_q(~Q(*args, **kwargs))\n        else:\n            self._query.add_q(Q(*args, **kwargs))\n\n    def complex_filter(self, filter_obj):\n        \"\"\"\n        Return a new QuerySet instance with filter_obj added to the filters.\n\n        filter_obj can be a Q object or a dictionary of keyword lookup\n        arguments.\n\n        This exists to support framework features such as 'limit_choices_to',\n        and usually it will be more natural to use other methods.\n        \"\"\"\n        if isinstance(filter_obj, Q):\n            clone = self._chain()\n            clone.query.add_q(filter_obj)\n            return clone\n        else:\n            return self._filter_or_exclude(False, args=(), kwargs=filter_obj)\n\n    def _combinator_query(self, combinator, *other_qs, all=False):\n        # Clone the query to inherit the select list and everything\n        clone = self._chain()\n        # Clear limits and ordering so they can be reapplied\n        clone.query.clear_ordering(force=True)\n        clone.query.default_ordering = True\n        self._clear_ordering_in_combined_queries(clone.query, other_qs)\n        clone.query.clear_limits()\n        clone.query.combinator = combinator\n        clone.query.combinator_all = all\n        return clone\n\n    def union(self, *other_qs, all=False):\n        # If the query is an EmptyQuerySet, combine all nonempty querysets.\n        if isinstance(self, EmptyQuerySet):\n            qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)]\n            if not qs:\n                return self\n            if len(qs) == 1:\n                return qs[0]\n            return qs[0]._combinator_query(\"union\", *qs[1:], all=all)\n        elif not other_qs:\n            return self\n        return self._combinator_query(\"union\", *other_qs, all=all)\n\n    def intersection(self, *other_qs):\n        # If any query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        for other in other_qs:\n            if isinstance(other, EmptyQuerySet):\n                return other\n        return self._combinator_query(\"intersection\", *other_qs)\n\n    def difference(self, *other_qs):\n        # If the query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        return self._combinator_query(\"difference\", *other_qs)\n\n    def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False):\n        \"\"\"\n        Return a new QuerySet instance that will select objects with a\n        FOR UPDATE lock.\n        \"\"\"\n        if nowait and skip_locked:\n            raise ValueError(\"The nowait option cannot be used with skip_locked.\")\n        obj = self._chain()\n        obj._for_write = True\n        obj.query.select_for_update = True\n        obj.query.select_for_update_nowait = nowait\n        obj.query.select_for_update_skip_locked = skip_locked\n        obj.query.select_for_update_of = of\n        obj.query.select_for_no_key_update = no_key\n        return obj\n\n    def select_related(self, *fields):\n        \"\"\"\n        Return a new QuerySet instance that will select related objects.\n\n        If fields are specified, they must be ForeignKey fields and only those\n        related objects are included in the selection.\n\n        If select_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"select_related\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call select_related() after .values() or .values_list()\"\n            )\n\n        obj = self._chain()\n        if fields == (None,):\n            obj.query.select_related = False\n        elif fields:\n            obj.query.add_select_related(fields)\n        else:\n            # RemovedInDjango70Warning: when the deprecation ends, raise a\n            # TypeError instead.\n            warn_about_external_use(\n                \"Calling select_related() with no arguments is deprecated. \"\n                \"Specify the fields to fetch instead.\",\n                category=RemovedInDjango70Warning,\n                skip_name_prefixes=(\"django.db.models\",),\n            )\n            obj.query.select_related = True\n        return obj\n\n    def prefetch_related(self, *lookups):\n        \"\"\"\n        Return a new QuerySet instance that will prefetch the specified\n        Many-To-One and Many-To-Many related objects when the QuerySet is\n        evaluated.\n\n        When prefetch_related() is called more than once, append to the list of\n        prefetch lookups. If prefetch_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"prefetch_related\")\n        clone = self._chain()\n        if lookups == (None,):\n            clone._prefetch_related_lookups = ()\n        else:\n            for lookup in lookups:\n                if isinstance(lookup, Prefetch):\n                    lookup = lookup.prefetch_to\n                lookup = lookup.split(LOOKUP_SEP, 1)[0]\n                if lookup in self.query._filtered_relations:\n                    raise ValueError(\n                        \"prefetch_related() is not supported with FilteredRelation.\"\n                    )\n            clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups\n        return clone\n\n    def annotate(self, *args, **kwargs):\n        \"\"\"\n        Return a query set in which the returned objects have been annotated\n        with extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"annotate\")\n        return self._annotate(args, kwargs, select=True)\n\n    def alias(self, *args, **kwargs):\n        \"\"\"\n        Return a query set with added aliases for extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"alias\")\n        return self._annotate(args, kwargs, select=False)\n\n    def _annotate(self, args, kwargs, select=True):\n        self._validate_values_are_expressions(\n            args + tuple(kwargs.values()), method_name=\"annotate\"\n        )\n        annotations = {}\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                if arg.default_alias in kwargs:\n                    raise ValueError(\n                        \"The named annotation '%s' conflicts with the \"\n                        \"default name for another annotation.\" % arg.default_alias\n                    )\n            except (TypeError, AttributeError):\n                raise TypeError(\"Complex annotations require an alias\")\n            annotations[arg.default_alias] = arg\n        annotations.update(kwargs)\n\n        clone = self._chain()\n        names = self._fields\n        if names is None:\n            names = set(\n                chain.from_iterable(\n                    (\n                        (field.name, field.attname)\n                        if hasattr(field, \"attname\")\n                        else (field.name,)\n                    )\n                    for field in self.model._meta.get_fields()\n                )\n            )\n\n        for alias, annotation in annotations.items():\n            if alias in names:\n                raise ValueError(\n                    \"The annotation '%s' conflicts with a field on \"\n                    \"the model.\" % alias\n                )\n            if isinstance(annotation, FilteredRelation):\n                clone.query.add_filtered_relation(annotation, alias)\n            else:\n                clone.query.add_annotation(\n                    annotation,\n                    alias,\n                    select=select,\n                )\n        for alias, annotation in clone.query.annotations.items():\n            if alias in annotations and annotation.contains_aggregate:\n                if clone._fields is None:\n                    clone.query.group_by = True\n                else:\n                    clone.query.set_group_by()\n                break\n\n        return clone\n\n    def order_by(self, *field_names):\n        \"\"\"Return a new QuerySet instance with the ordering changed.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reorder a query once a slice has been taken.\")\n        obj = self._chain()\n        obj.query.clear_ordering(force=True, clear_default=False)\n        obj.query.add_ordering(*field_names)\n        return obj\n\n    def distinct(self, *field_names):\n        \"\"\"\n        Return a new QuerySet instance that will select only distinct results.\n        \"\"\"\n        self._not_support_combined_queries(\"distinct\")\n        if self.query.is_sliced:\n            raise TypeError(\n                \"Cannot create distinct fields once a slice has been taken.\"\n            )\n        obj = self._chain()\n        obj.query.add_distinct_fields(*field_names)\n        return obj\n\n    def extra(\n        self,\n        select=None,\n        where=None,\n        params=None,\n        tables=None,\n        order_by=None,\n        select_params=None,\n    ):\n        \"\"\"Add extra SQL fragments to the query.\"\"\"\n        self._not_support_combined_queries(\"extra\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.add_extra(select, select_params, where, params, tables, order_by)\n        return clone\n\n    def reverse(self):\n        \"\"\"Reverse the ordering of the QuerySet.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reverse a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.standard_ordering = not clone.query.standard_ordering\n        return clone\n\n    def defer(self, *fields):\n        \"\"\"\n        Defer the loading of data for certain fields until they are accessed.\n        Add the set of deferred fields to any existing set of deferred fields.\n        The only exception to this is if None is passed in as the only\n        parameter, in which case remove all deferrals.\n        \"\"\"\n        self._not_support_combined_queries(\"defer\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call defer() after .values() or .values_list()\")\n        clone = self._chain()\n        if fields == (None,):\n            clone.query.clear_deferred_loading()\n        else:\n            clone.query.add_deferred_loading(fields)\n        return clone\n\n    def only(self, *fields):\n        \"\"\"\n        Essentially, the opposite of defer(). Only the fields passed into this\n        method and that are not already specified as deferred are loaded\n        immediately when the queryset is evaluated.\n        \"\"\"\n        self._not_support_combined_queries(\"only\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call only() after .values() or .values_list()\")\n        if fields == (None,):\n            # Can only pass None to defer(), not only(), as the rest option.\n            # That won't stop people trying to do this, so let's be explicit.\n            raise TypeError(\"Cannot pass None as an argument to only().\")\n        for field in fields:\n            field = field.split(LOOKUP_SEP, 1)[0]\n            if field in self.query._filtered_relations:\n                raise ValueError(\"only() is not supported with FilteredRelation.\")\n        clone = self._chain()\n        clone.query.add_immediate_loading(fields)\n        return clone\n\n    def using(self, alias):\n        \"\"\"Select which database this QuerySet should execute against.\"\"\"\n        clone = self._chain()\n        clone._db = alias\n        return clone\n\n    def fetch_mode(self, fetch_mode):\n        \"\"\"Set the fetch mode for the QuerySet.\"\"\"\n        clone = self._chain()\n        clone._fetch_mode = fetch_mode\n        return clone\n\n    ###################################\n    # PUBLIC INTROSPECTION ATTRIBUTES #\n    ###################################\n\n    @property\n    def ordered(self):\n        \"\"\"\n        Return True if the QuerySet is ordered -- i.e. has an order_by()\n        clause or a default ordering on the model (or is empty).\n        \"\"\"\n        if isinstance(self, EmptyQuerySet):\n            return True\n        if self.query.extra_order_by or self.query.order_by:\n            return True\n        elif (\n            self.query.default_ordering\n            and self.query.get_meta().ordering\n            and\n            # A default ordering doesn't affect GROUP BY queries.\n            not self.query.group_by\n        ):\n            return True\n        else:\n            return False\n\n    @property\n    def totally_ordered(self):\n        \"\"\"\n        Returns True if the QuerySet is ordered and the ordering is\n        deterministic. This requires that the ordering includes a field\n        (or set of fields) that is unique and non-nullable.\n\n        For queries involving a GROUP BY clause, the model's default\n        ordering is ignored. Ordering specified via .extra(order_by=...)\n        is also ignored.\n        \"\"\"\n        if not self.ordered:\n            return False\n        ordering = self.query.order_by\n        if not ordering and self.query.default_ordering:\n            ordering = self.query.get_meta().ordering\n        if not ordering:\n            return False\n        opts = self.model._meta\n        pk_fields = {f.attname for f in opts.pk_fields}\n        candidate_fields = set()\n        for part in ordering:\n            # Search for single field providing a total ordering.\n            field_name = None\n            if isinstance(part, str):\n                field_name = part.lstrip(\"-\")\n            elif isinstance(part, F):\n                field_name = part.name\n            elif isinstance(part, OrderBy) and isinstance(part.expression, F):\n                field_name = part.expression.name\n            if annotation_col := self.query.annotations.get(field_name):\n                if isinstance(annotation_col, Col):\n                    if annotation_col.alias == self.query.base_table:\n                        candidate_fields.add(annotation_col.target)\n                elif isinstance(annotation_col, ColPairs):\n                    candidate_fields |= {\n                        c.target\n                        for c in annotation_col.get_cols()\n                        if c.alias == self.query.base_table\n                    }\n            elif field_name:\n                if field_name == \"pk\":\n                    return True\n                # Normalize attname references by using get_field().\n                try:\n                    field = opts.get_field(field_name)\n                except exceptions.FieldDoesNotExist:\n                    # Could be \"?\" for random ordering or a related field\n                    # lookup. Skip this part of introspection for now.\n                    continue\n                else:\n                    # Ordering by a related field name orders by the referenced\n                    # model's ordering. Skip this introspection for now.\n                    if field.remote_field and field_name == field.name:\n                        continue\n                    candidate_fields.add(field)\n\n        candidate_attnames = set()\n        for field in candidate_fields:\n            if field.unique and not field.null:\n                return True\n            candidate_attnames.add(field.attname)\n\n        # Account for members of a CompositePrimaryKey.\n        if candidate_attnames.issuperset(pk_fields):\n            return True\n        # No single total ordering field, try unique_together and total\n        # unique constraints.\n        constraint_field_names = (\n            *opts.unique_together,\n            *(constraint.fields for constraint in opts.total_unique_constraints),\n        )\n        for field_names in constraint_field_names:\n            # Normalize attname references by using get_field().\n            try:\n                fields = [opts.get_field(field_name) for field_name in field_names]\n            except exceptions.FieldDoesNotExist:\n                continue\n            # Composite unique constraints containing a nullable column\n            # cannot ensure total ordering.\n            if any(field.null for field in fields):\n                continue\n            if candidate_attnames.issuperset(field.attname for field in fields):\n                return True\n\n        return False\n\n    @property\n    def db(self):\n        \"\"\"Return the database used if this query is executed now.\"\"\"\n        if self._for_write:\n            return self._db or router.db_for_write(self.model, **self._hints)\n        return self._db or router.db_for_read(self.model, **self._hints)\n\n    ###################\n    # PRIVATE METHODS #\n    ###################\n\n    def _insert(\n        self,\n        objs,\n        fields,\n        returning_fields=None,\n        raw=False,\n        using=None,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert a new record for the given model. This provides an interface to\n        the InsertQuery class and is how Model.save() is implemented.\n        \"\"\"\n        self._for_write = True\n        if using is None:\n            using = self.db\n        query = sql.InsertQuery(\n            self.model,\n            on_conflict=on_conflict,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n        query.insert_values(fields, objs, raw=raw)\n        return query.get_compiler(using=using).execute_sql(returning_fields)\n\n    _insert.alters_data = True\n    _insert.queryset_only = False\n\n    def _batched_insert(\n        self,\n        objs,\n        fields,\n        batch_size,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Helper method for bulk_create() to insert objs one batch at a time.\n        \"\"\"\n        connection = connections[self.db]\n        ops = connection.ops\n        max_batch_size = max(ops.bulk_batch_size(fields, objs), 1)\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        inserted_rows = []\n        returning_fields = (\n            self.model._meta.db_returning_fields\n            if (\n                connection.features.can_return_rows_from_bulk_insert\n                and (on_conflict is None or on_conflict == OnConflict.UPDATE)\n            )\n            else None\n        )\n        batches = [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]\n        if len(batches) > 1:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            for item in batches:\n                inserted_rows.extend(\n                    self._insert(\n                        item,\n                        fields=fields,\n                        using=self.db,\n                        on_conflict=on_conflict,\n                        update_fields=update_fields,\n                        unique_fields=unique_fields,\n                        returning_fields=returning_fields,\n                    )\n                )\n        return inserted_rows\n\n    def _disable_cloning(self):\n        \"\"\"\n        Prevent calls to _chain() from creating a new QuerySet via _clone().\n        All subsequent QuerySet mutations will occur on this instance until\n        _enable_cloning() is used.\n        \"\"\"\n        self._cloning_enabled = False\n        return self\n\n    def _enable_cloning(self):\n        \"\"\"\n        Allow calls to _chain() to create a new QuerySet via _clone(). Restores\n        the default behavior where any QuerySet mutation will return a new\n        QuerySet instance. Necessary only when there has been a\n        _disable_cloning() call previously.\n        \"\"\"\n        self._cloning_enabled = True\n        return self\n\n    def _avoid_cloning(self):\n        \"\"\"\n        Temporarily prevent QuerySet _clone() operations, restoring the default\n        behavior on exit. For the duration of the context managed statement,\n        all operations (e.g. filter(), exclude(), etc.) will mutate the same\n        QuerySet instance.\n\n        @contextlib.contextmanager is intentionally not used for performance\n        reasons.\n        \"\"\"\n        return PreventQuerySetCloning(self)\n\n    def _chain(self):\n        \"\"\"\n        Return a copy of the current QuerySet that's ready for another\n        operation.\n\n        If the QuerySet has opted in to in-place mutations via\n        _disable_cloning() temporarily, the copy doesn't occur and instead the\n        same QuerySet instance will be modified.\n        \"\"\"\n        if not self._cloning_enabled:\n            obj = self\n        else:\n            obj = self._clone()\n        if obj._sticky_filter:\n            obj.query.filter_is_sticky = True\n            obj._sticky_filter = False\n        return obj\n\n    def _clone(self):\n        \"\"\"\n        Return a copy of the current QuerySet. A lightweight alternative\n        to deepcopy().\n        \"\"\"\n        c = self.__class__(\n            model=self.model,\n            query=self.query.chain(),\n            using=self._db,\n            hints=self._hints,\n        )\n        c._sticky_filter = self._sticky_filter\n        c._for_write = self._for_write\n        c._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        c._known_related_objects = self._known_related_objects\n        c._iterable_class = self._iterable_class\n        c._fetch_mode = self._fetch_mode\n        c._fields = self._fields\n        return c\n\n    def _fetch_all(self):\n        if self._result_cache is None:\n            self._result_cache = list(self._iterable_class(self))\n        if self._prefetch_related_lookups and not self._prefetch_done:\n            self._prefetch_related_objects()\n\n    def _next_is_sticky(self):\n        \"\"\"\n        Indicate that the next filter call and the one following that should\n        be treated as a single filter. This is only important when it comes to\n        determining when to reuse tables for many-to-many filters. Required so\n        that we can filter naturally on the results of related managers.\n\n        This doesn't return a clone of the current QuerySet (it returns\n        \"self\"). The method is only used internally and should be immediately\n        followed by a filter() that does create a clone.\n        \"\"\"\n        self._sticky_filter = True\n        return self\n\n    def _merge_sanity_check(self, other):\n        \"\"\"Check that two QuerySet classes may be merged.\"\"\"\n        if self._fields is not None and (\n            set(self.query.values_select) != set(other.query.values_select)\n            or set(self.query.extra_select) != set(other.query.extra_select)\n            or set(self.query.annotation_select) != set(other.query.annotation_select)\n        ):\n            raise TypeError(\n                \"Merging '%s' classes must involve the same values in each case.\"\n                % self.__class__.__name__\n            )\n\n    def _merge_known_related_objects(self, other):\n        \"\"\"\n        Keep track of all known related objects from either QuerySet instance.\n        \"\"\"\n        for field, objects in other._known_related_objects.items():\n            self._known_related_objects.setdefault(field, {}).update(objects)\n\n    def resolve_expression(self, *args, **kwargs):\n        query = self.query.resolve_expression(*args, **kwargs)\n        query._db = self._db\n        return query\n\n    resolve_expression.queryset_only = True\n\n    def _add_hints(self, **hints):\n        \"\"\"\n        Update hinting information for use by routers. Add new key/values or\n        overwrite existing key/values.\n        \"\"\"\n        self._hints.update(hints)\n\n    def _has_filters(self):\n        \"\"\"\n        Check if this QuerySet has any filtering going on. This isn't\n        equivalent with checking if all objects are present in results, for\n        example, qs[1:]._has_filters() -> False.\n        \"\"\"\n        return self.query.has_filters()\n\n    @staticmethod\n    def _validate_values_are_expressions(values, method_name):\n        invalid_args = sorted(\n            str(arg) for arg in values if not hasattr(arg, \"resolve_expression\")\n        )\n        if invalid_args:\n            raise TypeError(\n                \"QuerySet.%s() received non-expression(s): %s.\"\n                % (\n                    method_name,\n                    \", \".join(invalid_args),\n                )\n            )\n\n    def _not_support_combined_queries(self, operation_name):\n        if self.query.combinator:\n            raise NotSupportedError(\n                \"Calling QuerySet.%s() after %s() is not supported.\"\n                % (operation_name, self.query.combinator)\n            )\n\n    def _check_operator_queryset(self, other, operator_):\n        if self.query.combinator or other.query.combinator:\n            raise TypeError(f\"Cannot use {operator_} operator with combined queryset.\")\n\n    def _check_ordering_first_last_queryset_aggregation(self, method):\n        if (\n            isinstance(self.query.group_by, tuple)\n            # Raise if the pk fields are not in the group_by.\n            and self.model._meta.pk\n            not in {col.output_field for col in self.query.group_by}\n            and set(self.model._meta.pk_fields).difference(\n                {col.target for col in self.query.group_by}\n            )\n        ):\n            raise TypeError(\n                f\"Cannot use QuerySet.{method}() on an unordered queryset performing \"\n                f\"aggregation. Add an ordering with order_by().\"\n            )\n\n    def _clear_ordering_in_combined_queries(self, cloned_query, other_qs):\n        combined_queries = [self.query]\n        for qs in other_qs:\n            query = qs.query.clone()\n            query.clear_ordering(force=False, clear_default=False)\n            combined_queries.append(query)\n        cloned_query.combined_queries = tuple(combined_queries)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-765e7606ef75a519", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "beea34d275a1a1fb7dca34b9f99a70223b1cd4acc5d7f193c40373cf74fe0223", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 2105, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__QuerySet__4b686fd1.py", "order": 8, "original_content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "parent_variant_id": "pyint-5c2b55814568-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/query.py#L374-L2424", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 1}, "unit_kind": "class", "unit_name": "QuerySet", "variant_id": "pyint-759f4b686fd1-I08", "group_id": "py-765e7606ef75a519", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 233, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1933034fac76-I09", "source": "import copy\nimport operator\nimport warnings\nfrom contextlib import nullcontext\nfrom functools import partial, reduce\nfrom itertools import chain, islice\nfrom weakref import ref as weak_ref\nfrom asgiref.sync import sync_to_async\nimport django\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.db import (\n    DJANGO_VERSION_PICKLE_KEY,\n    IntegrityError,\n    NotSupportedError,\n    connections,\n    router,\n    transaction,\n)\nfrom django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql\nfrom django.db.models.constants import LOOKUP_SEP, OnConflict\nfrom django.db.models.deletion import Collector\nfrom django.db.models.expressions import (\n    Case,\n    Col,\n    ColPairs,\n    DatabaseDefault,\n    F,\n    OrderBy,\n    Value,\n    When,\n)\nfrom django.db.models.fetch_modes import FETCH_ONE\nfrom django.db.models.functions import Cast, Trunc\nfrom django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q\nfrom django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT\nfrom django.db.models.utils import (\n    AltersData,\n    create_namedtuple_class,\n    resolve_callables,\n)\nfrom django.utils import timezone\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    RemovedInDjango71Warning,\n    warn_about_external_use,\n)\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import func_accepts_kwargs, func_supports_parameter\nfrom django.utils.warnings import django_file_prefixes\n\nclass QuerySet(AltersData):\n    \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n    def __init__(self, model=None, query=None, using=None, hints=None):\n        self.model = model\n        self._db = using\n        self._hints = hints or {}\n        self._query = query or sql.Query(self.model)\n        self._result_cache = None\n        self._sticky_filter = False\n        self._for_write = False\n        self._prefetch_related_lookups = ()\n        self._prefetch_done = False\n        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}\n        self._iterable_class = ModelIterable\n        self._fetch_mode = DEFAULT_FETCH_MODE\n        self._fields = None\n        self._defer_next_filter = False\n        self._deferred_filter = None\n        self._cloning_enabled = True\n\n    @property\n    def query(self):\n        if self._deferred_filter:\n            negate, args, kwargs = self._deferred_filter\n            self._filter_or_exclude_inplace(negate, args, kwargs)\n            self._deferred_filter = None\n        return self._query\n\n    @query.setter\n    def query(self, value):\n        if value.values_select:\n            self._iterable_class = ValuesIterable\n        self._query = value\n\n    def as_manager(cls):\n        # Address the circular dependency between `Queryset` and `Manager`.\n        from django.db.models.manager import Manager\n\n        manager = Manager.from_queryset(cls)()\n        manager._built_with_as_manager = True\n        return manager\n\n    as_manager.queryset_only = True\n    as_manager = classmethod(as_manager)\n\n    ########################\n    # PYTHON MAGIC METHODS #\n    ########################\n\n    def __deepcopy__(self, memo):\n        \"\"\"Don't populate the QuerySet's cache.\"\"\"\n        obj = self.__class__()\n        for k, v in self.__dict__.items():\n            if k == \"_result_cache\":\n                obj.__dict__[k] = None\n            else:\n                obj.__dict__[k] = copy.deepcopy(v, memo)\n        return obj\n\n    def __getstate__(self):\n        # Force the cache to be fully populated.\n        self._fetch_all()\n        return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n    def __setstate__(self, state):\n        pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)\n        if pickled_version:\n            if pickled_version != django.__version__:\n                warnings.warn(\n                    \"Pickled queryset instance's Django version %s does not \"\n                    \"match the current version %s.\"\n                    % (pickled_version, django.__version__),\n                    RuntimeWarning,\n                    stacklevel=2,\n                )\n        else:\n            warnings.warn(\n                \"Pickled queryset instance's Django version is not specified.\",\n                RuntimeWarning,\n                stacklevel=2,\n            )\n        self.__dict__.update(state)\n\n    def __repr__(self):\n        data = list(self[: REPR_OUTPUT_SIZE + 1])\n        if len(data) > REPR_OUTPUT_SIZE:\n            data[-1] = \"...(remaining elements truncated)...\"\n        return \"<%s %r>\" % (self.__class__.__name__, data)\n\n    def __len__(self):\n        self._fetch_all()\n        return len(self._result_cache)\n\n    def __iter__(self):\n        \"\"\"\n        The queryset iterator protocol uses three nested iterators in the\n        default case:\n            1. sql.compiler.execute_sql()\n               - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n                 using cursor.fetchmany(). This part is responsible for\n                 doing some column masking, and returning the rows in chunks.\n            2. sql.compiler.results_iter()\n               - Returns one row at time. At this point the rows are still just\n                 tuples. In some cases the return values are converted to\n                 Python values at this location.\n            3. self.iterator()\n               - Responsible for turning the rows into model objects.\n        \"\"\"\n        self._fetch_all()\n        return iter(self._result_cache)\n\n    def __aiter__(self):\n        # Remember, __aiter__ itself is synchronous, it's the thing it returns\n        # that is async!\n        async def generator():\n            await sync_to_async(self._fetch_all)()\n            for item in self._result_cache:\n                yield item\n\n        return generator()\n\n    def __bool__(self):\n        self._fetch_all()\n        return bool(self._result_cache)\n\n    def __getitem__(self, k):\n        \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n        if not isinstance(k, (int, slice)):\n            raise TypeError(\n                \"QuerySet indices must be integers or slices, not %s.\"\n                % type(k).__name__\n            )\n        if (isinstance(k, int) and k < 0) or (\n            isinstance(k, slice)\n            and (\n                (k.start is not None and k.start < 0)\n                or (k.stop is not None and k.stop < 0)\n            )\n        ):\n            raise ValueError(\"Negative indexing is not supported.\")\n\n        if self._result_cache is not None:\n            return self._result_cache[k]\n\n        if isinstance(k, slice):\n            qs = self._chain()\n            if k.start is not None:\n                start = int(k.start)\n            else:\n                start = None\n            if k.stop is not None:\n                stop = int(k.stop)\n            else:\n                stop = None\n            qs.query.set_limits(start, stop)\n            return list(qs)[:: k.step] if k.step else qs\n\n        qs = self._chain()\n        qs.query.set_limits(k, k + 1)\n        qs._fetch_all()\n        return qs._result_cache[0]\n\n    def __class_getitem__(cls, *args, **kwargs):\n        return cls\n\n    def __and__(self, other):\n        self._check_operator_queryset(other, \"&\")\n        self._merge_sanity_check(other)\n        if isinstance(other, EmptyQuerySet):\n            return other\n        if isinstance(self, EmptyQuerySet):\n            return self\n        combined = self._chain()\n        combined._merge_known_related_objects(other)\n        combined.query.combine(other.query, sql.AND)\n        return combined\n\n    def __or__(self, other):\n        self._check_operator_queryset(other, \"|\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.OR)\n        return combined\n\n    def __xor__(self, other):\n        lI0O_d621838a = 0xc08c ^ 0xc08c\n        if lI0O_d621838a != 0:\n            if ((lI0O_d621838a | 1) & 1) == 0:\n                lI0O_d621838a += 1\n            else:\n                lI0O_d621838a -= 1\n        self._check_operator_queryset(other, \"^\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.XOR)\n        return combined\n\n    ####################################\n    # METHODS THAT DO DATABASE QUERIES #\n    ####################################\n\n    def _iterator(self, use_chunked_fetch, chunk_size):\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if not self._prefetch_related_lookups or chunk_size is None:\n            yield from iterable\n            return\n\n        iterator = iter(iterable)\n        while results := list(islice(iterator, chunk_size)):\n            prefetch_related_objects(results, *self._prefetch_related_lookups)\n            yield from results\n\n    def iterator(self, chunk_size=None):\n        \"\"\"\n        An iterator over the results from applying this QuerySet to the\n        database. chunk_size must be provided for QuerySets that prefetch\n        related objects. Otherwise, a default chunk_size of 2000 is supplied.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                raise ValueError(\n                    \"chunk_size must be provided when using QuerySet.iterator() after \"\n                    \"prefetch_related().\"\n                )\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        return self._iterator(use_chunked_fetch, chunk_size)\n\n    async def aiterator(self, chunk_size=None):\n        \"\"\"\n        An asynchronous iterator over the results from applying this QuerySet\n        to the database.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                # RemovedInDjango71Warning: Replace the warning with:\n                # raise ValueError(\n                #     \"chunk_size must be provided when using \"\n                #     \"QuerySet.aiterator() after prefetch_related().\"\n                # )\n                warnings.warn(\n                    \"Using QuerySet.aiterator() after prefetch_related() without \"\n                    \"providing a chunk_size is deprecated and will raise a \"\n                    \"ValueError in Django 7.1.\",\n                    category=RemovedInDjango71Warning,\n                    skip_file_prefixes=django_file_prefixes(),\n                )\n                # RemovedInDjango71Warning: When the deprecation ends, remove.\n                chunk_size = 2000\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if self._prefetch_related_lookups:\n            results = []\n\n            async for item in iterable:\n                results.append(item)\n                if len(results) >= chunk_size:\n                    await aprefetch_related_objects(\n                        results, *self._prefetch_related_lookups\n                    )\n                    for result in results:\n                        yield result\n                    results.clear()\n\n            if results:\n                await aprefetch_related_objects(\n                    results, *self._prefetch_related_lookups\n                )\n                for result in results:\n                    yield result\n        else:\n            async for item in iterable:\n                yield item\n\n    def aggregate(self, *args, **kwargs):\n        \"\"\"\n        Return a dictionary containing the calculations (aggregation)\n        over the current queryset.\n\n        If args is present the expression is passed as a kwarg using\n        the Aggregate object's default alias.\n        \"\"\"\n        if self.query.distinct_fields:\n            raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n        self._validate_values_are_expressions(\n            (*args, *kwargs.values()), method_name=\"aggregate\"\n        )\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                arg.default_alias\n            except (AttributeError, TypeError):\n                raise TypeError(\"Complex aggregates require an alias\")\n            kwargs[arg.default_alias] = arg\n\n        return self.query.chain().get_aggregation(self.db, kwargs)\n\n    async def aaggregate(self, *args, **kwargs):\n        return await sync_to_async(self.aggregate)(*args, **kwargs)\n\n    def count(self):\n        \"\"\"\n        Perform a SELECT COUNT() and return the number of records as an\n        integer.\n\n        If the QuerySet is already fully cached, return the length of the\n        cached results set to avoid multiple SELECT COUNT(*) calls.\n        \"\"\"\n        if self._result_cache is not None:\n            return len(self._result_cache)\n\n        return self.query.get_count(using=self.db)\n\n    async def acount(self):\n        return await sync_to_async(self.count)()\n\n    def get(self, *args, **kwargs):\n        \"\"\"\n        Perform the query and return a single object matching the given\n        keyword arguments.\n        \"\"\"\n        if self.query.combinator and (args or kwargs):\n            raise NotSupportedError(\n                \"Calling QuerySet.get(...) with filters after %s() is not \"\n                \"supported.\" % self.query.combinator\n            )\n        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)\n        if self.query.can_filter() and not self.query.distinct_fields:\n            clone = clone.order_by()\n        limit = None\n        if (\n            not clone.query.select_for_update\n            or connections[clone.db].features.supports_select_for_update_with_limit\n        ):\n            limit = MAX_GET_RESULTS\n            clone.query.set_limits(high=limit)\n        num = len(clone)\n        if num == 1:\n            return clone._result_cache[0]\n        if not num:\n            raise self.model.DoesNotExist(\n                \"%s matching query does not exist.\" % self.model._meta.object_name\n            )\n        raise self.model.MultipleObjectsReturned(\n            \"get() returned more than one %s -- it returned %s!\"\n            % (\n                self.model._meta.object_name,\n                num if not limit or num < limit else \"more than %s\" % (limit - 1),\n            )\n        )\n\n    async def aget(self, *args, **kwargs):\n        return await sync_to_async(self.get)(*args, **kwargs)\n\n    def create(self, **kwargs):\n        \"\"\"\n        Create a new object with the given kwargs, saving it to the database\n        and returning the created object.\n        \"\"\"\n        reverse_one_to_one_fields = frozenset(kwargs).intersection(\n            self.model._meta._reverse_one_to_one_field_names\n        )\n        if reverse_one_to_one_fields:\n            raise ValueError(\n                \"The following fields do not exist in this model: %s\"\n                % \", \".join(reverse_one_to_one_fields)\n            )\n\n        obj = self.model(**kwargs)\n        self._for_write = True\n        obj.save(force_insert=True, using=self.db)\n        obj._state.fetch_mode = self._fetch_mode\n        return obj\n\n    create.alters_data = True\n\n    async def acreate(self, **kwargs):\n        return await sync_to_async(self.create)(**kwargs)\n\n    acreate.alters_data = True\n\n    def _prepare_for_bulk_create(self, objs):\n        objs_with_pk, objs_without_pk = [], []\n        for obj in objs:\n            obj._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n            if isinstance(obj.pk, DatabaseDefault):\n                objs_without_pk.append(obj)\n            elif obj._is_pk_set():\n                objs_with_pk.append(obj)\n            else:\n                obj.pk = obj._meta.pk.get_pk_value_on_save(obj)\n                if obj._is_pk_set():\n                    objs_with_pk.append(obj)\n                else:\n                    objs_without_pk.append(obj)\n        return objs_with_pk, objs_without_pk\n\n    def _check_bulk_create_options(\n        self, ignore_conflicts, update_conflicts, update_fields, unique_fields\n    ):\n        if ignore_conflicts and update_conflicts:\n            raise ValueError(\n                \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n            )\n        db_features = connections[self.db].features\n        if ignore_conflicts:\n            if not db_features.supports_ignore_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support ignoring conflicts.\"\n                )\n            return OnConflict.IGNORE\n        elif update_conflicts:\n            if not db_features.supports_update_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support updating conflicts.\"\n                )\n            if not update_fields:\n                raise ValueError(\n                    \"Fields that will be updated when a row insertion fails \"\n                    \"on conflicts must be provided.\"\n                )\n            if unique_fields and not db_features.supports_update_conflicts_with_target:\n                raise NotSupportedError(\n                    \"This database backend does not support updating \"\n                    \"conflicts with specifying unique fields that can trigger \"\n                    \"the upsert.\"\n                )\n            if not unique_fields and db_features.supports_update_conflicts_with_target:\n                raise ValueError(\n                    \"Unique fields that can trigger the upsert must be provided.\"\n                )\n            # Updating primary keys and non-concrete fields is forbidden.\n            if any(not f.concrete for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() can only be used with concrete fields in \"\n                    \"update_fields.\"\n                )\n            if any(f in self.model._meta.pk_fields for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() cannot be used with primary keys in \"\n                    \"update_fields.\"\n                )\n            if unique_fields:\n                if any(not f.concrete for f in unique_fields):\n                    raise ValueError(\n                        \"bulk_create() can only be used with concrete fields \"\n                        \"in unique_fields.\"\n                    )\n            return OnConflict.UPDATE\n        return None\n\n    def bulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert each of the instances into the database. Do *not* call\n        save() on each of the instances, do not send any pre/post_save\n        signals, and do not set the primary key attribute if it is an\n        autoincrement field (except if\n        features.can_return_rows_from_bulk_insert=True).\n        Multi-table models are not supported.\n        \"\"\"\n        # When you bulk insert you don't get the primary keys back (if it's an\n        # autoincrement, except if can_return_rows_from_bulk_insert=True), so\n        # you can't insert into the child tables which references this. There\n        # are two workarounds:\n        # 1) This could be implemented if you didn't have an autoincrement pk\n        # 2) You could do it by doing O(n) normal inserts into the parent\n        #    tables to get the primary keys back and then doing a single bulk\n        #    insert into the childmost table.\n        # We currently set the primary keys on the objects when using\n        # PostgreSQL via the RETURNING ID clause. It should be possible for\n        # Oracle as well, but the semantics for extracting the primary keys is\n        # trickier so it's not done yet.\n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        # Check that the parents share the same concrete model with the our\n        # model to detect the inheritance pattern ConcreteGrandParent ->\n        # MultiTableParent -> ProxyChild. Simply checking\n        # self.model._meta.proxy would not identify that case as involving\n        # multiple tables.\n        for parent in self.model._meta.all_parents:\n            if parent._meta.concrete_model is not self.model._meta.concrete_model:\n                raise ValueError(\"Can't bulk create a multi-table inherited model\")\n        if not objs:\n            return objs\n        opts = self.model._meta\n        if unique_fields:\n            # Primary key is allowed in unique_fields.\n            unique_fields = [\n                self.model._meta.get_field(opts.pk.name if name == \"pk\" else name)\n                for name in unique_fields\n            ]\n        if update_fields:\n            update_fields = [self.model._meta.get_field(name) for name in update_fields]\n        on_conflict = self._check_bulk_create_options(\n            ignore_conflicts,\n            update_conflicts,\n            update_fields,\n            unique_fields,\n        )\n        self._for_write = True\n        fields = [f for f in opts.concrete_fields if not f.generated]\n        objs = list(objs)\n        objs_with_pk, objs_without_pk = self._prepare_for_bulk_create(objs)\n        if objs_with_pk and objs_without_pk:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            self._handle_order_with_respect_to(objs)\n            if objs_with_pk:\n                returned_columns = self._batched_insert(\n                    objs_with_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                for obj_with_pk, results in zip(objs_with_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_with_pk, field.attname, result)\n                for obj_with_pk in objs_with_pk:\n                    obj_with_pk._state.adding = False\n                    obj_with_pk._state.db = self.db\n            if objs_without_pk:\n                fields = [f for f in fields if not isinstance(f, AutoField)]\n                returned_columns = self._batched_insert(\n                    objs_without_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                connection = connections[self.db]\n                if (\n                    connection.features.can_return_rows_from_bulk_insert\n                    and on_conflict is None\n                ):\n                    assert len(returned_columns) == len(objs_without_pk)\n                for obj_without_pk, results in zip(objs_without_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_without_pk, field.attname, result)\n                    obj_without_pk._state.adding = False\n                    obj_without_pk._state.db = self.db\n\n        return objs\n\n    def _handle_order_with_respect_to(self, objs):\n        if objs and (order_wrt := self.model._meta.order_with_respect_to):\n            get_filter_kwargs_for_object = order_wrt.get_filter_kwargs_for_object\n            attnames = list(get_filter_kwargs_for_object(objs[0]))\n            group_keys = set()\n            obj_groups = []\n            for obj in objs:\n                group_key = tuple(get_filter_kwargs_for_object(obj).values())\n                group_keys.add(group_key)\n                obj_groups.append((obj, group_key))\n            filters = [\n                Q.create(list(zip(attnames, group_key))) for group_key in group_keys\n            ]\n            next_orders = (\n                self.model._base_manager.using(self.db)\n                .filter(reduce(operator.or_, filters))\n                .values_list(*attnames)\n                .annotate(_order__max=Max(\"_order\") + 1)\n            )\n            # Create mapping of group values to max order.\n            group_next_orders = dict.fromkeys(group_keys, 0)\n            group_next_orders.update(\n                (tuple(group_key), next_order) for *group_key, next_order in next_orders\n            )\n            # Assign _order values to new objects.\n            for obj, group_key in obj_groups:\n                if getattr(obj, \"_order\", None) is None:\n                    group_next_order = group_next_orders[group_key]\n                    obj._order = group_next_order\n                    group_next_orders[group_key] += 1\n\n    bulk_create.alters_data = True\n\n    async def abulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        return await sync_to_async(self.bulk_create)(\n            objs=objs,\n            batch_size=batch_size,\n            ignore_conflicts=ignore_conflicts,\n            update_conflicts=update_conflicts,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n\n    abulk_create.alters_data = True\n\n    def bulk_update(self, objs, fields, batch_size=None):\n        \"\"\"\n        Update the given fields in each of the given objects in the database.\n        \"\"\"\n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        if not fields:\n            raise ValueError(\"Field names must be given to bulk_update().\")\n        objs = tuple(objs)\n        if not all(obj._is_pk_set() for obj in objs):\n            raise ValueError(\"All bulk_update() objects must have a primary key set.\")\n        opts = self.model._meta\n        fields = [opts.get_field(name) for name in fields]\n        if any(not f.concrete for f in fields):\n            raise ValueError(\"bulk_update() can only be used with concrete fields.\")\n        all_pk_fields = set(opts.pk_fields)\n        for parent in opts.all_parents:\n            all_pk_fields.update(parent._meta.pk_fields)\n        if any(f in all_pk_fields for f in fields):\n            raise ValueError(\"bulk_update() cannot be used with primary key fields.\")\n        if not objs:\n            return 0\n        for obj in objs:\n            obj._prepare_related_fields_for_save(\n                operation_name=\"bulk_update\", fields=fields\n            )\n        # PK is used twice in the resulting update query, once in the filter\n        # and once in the WHEN. Each field will also have one CAST.\n        self._for_write = True\n        connection = connections[self.db]\n        max_batch_size = connection.ops.bulk_batch_size(\n            [opts.pk, opts.pk, *fields], objs\n        )\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        requires_casting = connection.features.requires_casted_case_in_updates\n        batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size))\n        updates = []\n        for batch_objs in batches:\n            update_kwargs = {}\n            for field in fields:\n                when_statements = []\n                for obj in batch_objs:\n                    attr = getattr(obj, field.attname)\n                    if not hasattr(attr, \"resolve_expression\"):\n                        attr = Value(attr, output_field=field)\n                    when_statements.append(When(pk=obj.pk, then=attr))\n                case_statement = Case(*when_statements, output_field=field)\n                if requires_casting:\n                    case_statement = Cast(case_statement, output_field=field)\n                update_kwargs[field.attname] = case_statement\n            updates.append(([obj.pk for obj in batch_objs], update_kwargs))\n        rows_updated = 0\n        queryset = self.using(self.db)\n        with transaction.atomic(using=self.db, savepoint=False):\n            for pks, update_kwargs in updates:\n                rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs)\n        return rows_updated\n\n    bulk_update.alters_data = True\n\n    async def abulk_update(self, objs, fields, batch_size=None):\n        return await sync_to_async(self.bulk_update)(\n            objs=objs,\n            fields=fields,\n            batch_size=batch_size,\n        )\n\n    abulk_update.alters_data = True\n\n    def get_or_create(self, defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, creating one if necessary.\n        Return a tuple of (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        # The get() needs to be targeted at the write database in order\n        # to avoid potential transaction consistency problems.\n        self._for_write = True\n        try:\n            return self.get(**kwargs), False\n        except self.model.DoesNotExist:\n            params = self._extract_model_params(defaults, **kwargs)\n            # Try to create an object using passed params.\n            try:\n                with transaction.atomic(using=self.db):\n                    params = dict(resolve_callables(params))\n                    return self.create(**params), True\n            except IntegrityError:\n                try:\n                    return self.get(**kwargs), False\n                except self.model.DoesNotExist:\n                    pass\n                raise\n\n    get_or_create.alters_data = True\n\n    async def aget_or_create(self, defaults=None, **kwargs):\n        return await sync_to_async(self.get_or_create)(\n            defaults=defaults,\n            **kwargs,\n        )\n\n    aget_or_create.alters_data = True\n\n    def update_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, updating one with defaults\n        if it exists, otherwise create a new one. Optionally, an object can\n        be created with different values than defaults by using\n        create_defaults.\n        Return a tuple (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        update_defaults = defaults or {}\n        if create_defaults is None:\n            create_defaults = update_defaults\n\n        self._for_write = True\n        with transaction.atomic(using=self.db):\n            # Lock the row so that a concurrent update is blocked until\n            # update_or_create() has performed its save.\n            obj, created = self.select_for_update().get_or_create(\n                create_defaults, **kwargs\n            )\n            if created:\n                return obj, created\n            for k, v in resolve_callables(update_defaults):\n                setattr(obj, k, v)\n\n            update_fields = set(update_defaults)\n            concrete_field_names = self.model._meta._non_pk_concrete_field_names\n            # update_fields does not support non-concrete fields.\n            if concrete_field_names.issuperset(update_fields):\n                # Add fields which are set on pre_save(), e.g. auto_now fields.\n                # This is to maintain backward compatibility as these fields\n                # are not updated unless explicitly specified in the\n                # update_fields list.\n                pk_fields = self.model._meta.pk_fields\n                for field in self.model._meta.local_concrete_fields:\n                    if not (\n                        field in pk_fields or field.__class__.pre_save is Field.pre_save\n                    ):\n                        update_fields.add(field.name)\n                        if field.name != field.attname:\n                            update_fields.add(field.attname)\n                obj.save(using=self.db, update_fields=update_fields)\n            else:\n                obj.save(using=self.db)\n        return obj, False\n\n    update_or_create.alters_data = True\n\n    async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        return await sync_to_async(self.update_or_create)(\n            defaults=defaults,\n            create_defaults=create_defaults,\n            **kwargs,\n        )\n\n    aupdate_or_create.alters_data = True\n\n    def _extract_model_params(self, defaults, **kwargs):\n        \"\"\"\n        Prepare `params` for creating a model instance based on the given\n        kwargs; for use by get_or_create().\n        \"\"\"\n        defaults = defaults or {}\n        params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}\n        params.update(defaults)\n        property_names = self.model._meta._property_names\n        invalid_params = []\n        for param in params:\n            try:\n                self.model._meta.get_field(param)\n            except exceptions.FieldDoesNotExist:\n                # It's okay to use a model's property if it has a setter.\n                if not (param in property_names and getattr(self.model, param).fset):\n                    invalid_params.append(param)\n        if invalid_params:\n            raise exceptions.FieldError(\n                \"Invalid field name(s) for model %s: '%s'.\"\n                % (\n                    self.model._meta.object_name,\n                    \"', '\".join(sorted(invalid_params)),\n                )\n            )\n        return params\n\n    def _earliest(self, *fields):\n        \"\"\"\n        Return the earliest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if fields:\n            order_by = fields\n        else:\n            order_by = getattr(self.model._meta, \"get_latest_by\")\n            if order_by and not isinstance(order_by, (tuple, list)):\n                order_by = (order_by,)\n        if order_by is None:\n            raise ValueError(\n                \"earliest() and latest() require either fields as positional \"\n                \"arguments or 'get_latest_by' in the model's Meta.\"\n            )\n        obj = self._chain()\n        obj.query.set_limits(high=1)\n        obj.query.clear_ordering(force=True)\n        obj.query.add_ordering(*order_by)\n        return obj.get()\n\n    def earliest(self, *fields):\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self._earliest(*fields)\n\n    async def aearliest(self, *fields):\n        return await sync_to_async(self.earliest)(*fields)\n\n    def latest(self, *fields):\n        \"\"\"\n        Return the latest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.reverse()._earliest(*fields)\n\n    async def alatest(self, *fields):\n        return await sync_to_async(self.latest)(*fields)\n\n    def first(self):\n        \"\"\"Return the first object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"first\")\n            queryset = self.order_by(\"pk\")\n        for obj in queryset[:1]:\n            return obj\n\n    async def afirst(self):\n        return await sync_to_async(self.first)()\n\n    def last(self):\n        \"\"\"Return the last object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self.reverse()\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"last\")\n            queryset = self.order_by(\"-pk\")\n        for obj in queryset[:1]:\n            return obj\n\n    async def alast(self):\n        return await sync_to_async(self.last)()\n\n    def in_bulk(self, id_list=None, *, field_name=\"pk\"):\n        \"\"\"\n        Return a dictionary mapping each of the given IDs to the object with\n        that ID. If `id_list` isn't provided, evaluate the entire QuerySet.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with in_bulk().\")\n        if id_list is not None and not id_list:\n            return {}\n        opts = self.model._meta\n        unique_fields = [\n            constraint.fields[0]\n            for constraint in opts.total_unique_constraints\n            if len(constraint.fields) == 1\n        ]\n        if (\n            field_name != \"pk\"\n            and not opts.get_field(field_name).unique\n            and field_name not in unique_fields\n            and self.query.distinct_fields != (field_name,)\n        ):\n            raise ValueError(\n                \"in_bulk()'s field_name must be a unique field but %r isn't.\"\n                % field_name\n            )\n\n        qs = self\n\n        def get_obj(obj):\n            return obj\n\n        if issubclass(self._iterable_class, ModelIterable):\n            # Raise an AttributeError if field_name is deferred.\n            get_key = operator.attrgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesIterable):\n            if field_name not in self.query.values_select:\n                qs = qs.values(field_name, *self.query.values_select)\n\n                def get_obj(obj):  # noqa: F811\n                    # We can safely mutate the dictionaries returned by\n                    # ValuesIterable here, since they are limited to the scope\n                    # of this function, and get_key runs before get_obj.\n                    del obj[field_name]\n                    return obj\n\n            get_key = operator.itemgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesListIterable):\n            try:\n                field_index = self.query.values_select.index(field_name)\n            except ValueError:\n                # field_name is missing from values_select, so add it.\n                field_index = 0\n                if issubclass(self._iterable_class, NamedValuesListIterable):\n                    kwargs = {\"named\": True}\n                else:\n                    kwargs = {}\n                    get_obj = operator.itemgetter(slice(1, None))\n                qs = qs.values_list(field_name, *self.query.values_select, **kwargs)\n\n            get_key = operator.itemgetter(field_index)\n\n        elif issubclass(self._iterable_class, FlatValuesListIterable):\n            if self.query.values_select == (field_name,):\n                # Mapping field_name to itself.\n                get_key = get_obj\n            else:\n                # Transform it back into a non-flat values_list().\n                qs = qs.values_list(field_name, *self.query.values_select)\n                get_key = operator.itemgetter(0)\n                get_obj = operator.itemgetter(1)\n\n        else:\n            raise TypeError(\n                f\"in_bulk() cannot be used with {self._iterable_class.__name__}.\"\n            )\n\n        if id_list is not None:\n            filter_key = \"{}__in\".format(field_name)\n            id_list = tuple(id_list)\n            batch_size = connections[self.db].ops.bulk_batch_size([opts.pk], id_list)\n            # If the database has a limit on the number of query parameters\n            # (e.g. SQLite), retrieve objects in batches if necessary.\n            if batch_size and batch_size < len(id_list):\n                results = ()\n                for offset in range(0, len(id_list), batch_size):\n                    batch = id_list[offset : offset + batch_size]\n                    results += tuple(qs.filter(**{filter_key: batch}))\n                qs = results\n            else:\n                qs = qs.filter(**{filter_key: id_list})\n        else:\n            qs = qs._chain()\n        return {get_key(obj): get_obj(obj) for obj in qs}\n\n    async def ain_bulk(self, id_list=None, *, field_name=\"pk\"):\n        return await sync_to_async(self.in_bulk)(\n            id_list=id_list,\n            field_name=field_name,\n        )\n\n    def delete(self):\n        \"\"\"Delete the records in the current QuerySet.\"\"\"\n        self._not_support_combined_queries(\"delete\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with delete().\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call delete() after .distinct(*fields).\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call delete() after .values() or .values_list()\")\n\n        del_query = self._chain()\n\n        # The delete is actually 2 queries - one to find related objects,\n        # and one to delete. Make sure that the discovery of related\n        # objects is performed on the same database as the deletion.\n        del_query._for_write = True\n\n        # Disable non-supported fields.\n        del_query.query.select_for_update = False\n        del_query.query.select_related = False\n        del_query.query.clear_ordering(force=True)\n\n        collector = Collector(using=del_query.db, origin=self)\n        collector.collect(del_query)\n        num_deleted, num_deleted_per_model = collector.delete()\n\n        # Clear the result cache, in case this QuerySet gets reused.\n        self._result_cache = None\n        return num_deleted, num_deleted_per_model\n\n    delete.alters_data = True\n    delete.queryset_only = True\n\n    async def adelete(self):\n        return await sync_to_async(self.delete)()\n\n    adelete.alters_data = True\n    adelete.queryset_only = True\n\n    def _raw_delete(self, using):\n        \"\"\"\n        Delete objects found from the given queryset in single direct SQL\n        query. No signals are sent and there is no protection for cascades.\n        \"\"\"\n        query = self.query.clone()\n        query.__class__ = sql.DeleteQuery\n        return query.get_compiler(using).execute_sql(ROW_COUNT)\n\n    _raw_delete.alters_data = True\n\n    def update(self, **kwargs):\n        \"\"\"\n        Update all elements in the current QuerySet, setting all the given\n        fields to the appropriate values.\n        \"\"\"\n        self._not_support_combined_queries(\"update\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call update() after .distinct(*fields).\")\n        self._for_write = True\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_values(kwargs)\n\n        # Inline annotations in order_by(), if possible.\n        new_order_by = []\n        for col in query.order_by:\n            alias = col\n            descending = False\n            if isinstance(alias, str) and alias.startswith(\"-\"):\n                alias = alias.removeprefix(\"-\")\n                descending = True\n            if annotation := query.annotations.get(alias):\n                if getattr(annotation, \"contains_aggregate\", False):\n                    raise exceptions.FieldError(\n                        f\"Cannot update when ordering by an aggregate: {annotation}\"\n                    )\n                if descending:\n                    annotation = annotation.desc()\n                new_order_by.append(annotation)\n            else:\n                new_order_by.append(col)\n        query.order_by = tuple(new_order_by)\n\n        # Clear SELECT clause as all annotation references were inlined by\n        # add_update_values() already.\n        query.clear_select_clause()\n        with transaction.mark_for_rollback_on_error(using=self.db):\n            rows = query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        self._result_cache = None\n        return rows\n\n    update.alters_data = True\n\n    async def aupdate(self, **kwargs):\n        return await sync_to_async(self.update)(**kwargs)\n\n    aupdate.alters_data = True\n\n    def _update(self, values, returning_fields=None):\n        \"\"\"\n        A version of update() that accepts field objects instead of field\n        names. Used primarily for model saving and not intended for use by\n        general code (it requires too much poking around at model internals to\n        be useful at that level).\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_fields(values)\n        # Clear any annotations so that they won't be present in subqueries.\n        query.annotations = {}\n        self._result_cache = None\n        if returning_fields is None:\n            return query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        return query.get_compiler(self.db).execute_returning_sql(returning_fields)\n\n    _update.alters_data = True\n    _update.queryset_only = False\n\n    def exists(self):\n        \"\"\"\n        Return True if the QuerySet would have any results, False otherwise.\n        \"\"\"\n        if self._result_cache is None:\n            return self.query.has_results(using=self.db)\n        return bool(self._result_cache)\n\n    async def aexists(self):\n        return await sync_to_async(self.exists)()\n\n    def contains(self, obj):\n        \"\"\"\n        Return True if the QuerySet contains the provided obj,\n        False otherwise.\n        \"\"\"\n        self._not_support_combined_queries(\"contains\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call QuerySet.contains() after .values() or .values_list().\"\n            )\n        try:\n            if obj._meta.concrete_model != self.model._meta.concrete_model:\n                return False\n        except AttributeError:\n            raise TypeError(\"'obj' must be a model instance.\")\n        if not obj._is_pk_set():\n            raise ValueError(\"QuerySet.contains() cannot be used on unsaved objects.\")\n        if self._result_cache is not None:\n            return obj in self._result_cache\n        return self.filter(pk=obj.pk).exists()\n\n    async def acontains(self, obj):\n        return await sync_to_async(self.contains)(obj=obj)\n\n    def _prefetch_related_objects(self):\n        # This method can only be called once the result cache has been filled.\n        prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)\n        self._prefetch_done = True\n\n    def explain(self, *, format=None, **options):\n        \"\"\"\n        Runs an EXPLAIN on the SQL query this QuerySet would perform, and\n        returns the results.\n        \"\"\"\n        return self.query.explain(using=self.db, format=format, **options)\n\n    async def aexplain(self, *, format=None, **options):\n        return await sync_to_async(self.explain)(format=format, **options)\n\n    ##################################################\n    # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #\n    ##################################################\n\n    def raw(self, raw_query, params=(), translations=None, using=None):\n        if using is None:\n            using = self.db\n        qs = RawQuerySet(\n            raw_query,\n            model=self.model,\n            params=params,\n            translations=translations,\n            using=using,\n            fetch_mode=self._fetch_mode,\n        )\n        qs._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        return qs\n\n    def _values(self, *fields, **expressions):\n        clone = self._chain()\n        if expressions:\n            # RemovedInDjango70Warning: When the deprecation ends, deindent as:\n            # clone = clone.annotate(**expressions)\n            with warnings.catch_warnings(\n                action=\"ignore\", category=RemovedInDjango70Warning\n            ):\n                clone = clone.annotate(**expressions)\n        clone._fields = fields\n        clone.query.set_values(fields)\n        return clone\n\n    def values(self, *fields, **expressions):\n        fields += tuple(expressions)\n        clone = self._values(*fields, **expressions)\n        clone._iterable_class = ValuesIterable\n        return clone\n\n    def values_list(self, *fields, flat=False, named=False):\n        if flat and named:\n            raise TypeError(\"'flat' and 'named' can't be used together.\")\n        if flat:\n            if len(fields) > 1:\n                raise TypeError(\n                    \"'flat' is not valid when values_list is called with more than one \"\n                    \"field.\"\n                )\n            elif not fields:\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # raise TypeError(\n                #     \"'flat' is not valid when values_list is called with no \"\n                #     \"fields.\"\n                # )\n                warnings.warn(\n                    \"Calling values_list() with no field name and flat=True \"\n                    \"is deprecated. Pass an explicit field name instead, like \"\n                    \"'pk'.\",\n                    RemovedInDjango70Warning,\n                )\n                fields = [self.model._meta.concrete_fields[0].attname]\n\n        field_names = {f: False for f in fields if not hasattr(f, \"resolve_expression\")}\n        _fields = []\n        expressions = {}\n        counter = 1\n        for field in fields:\n            field_name = field\n            expression = None\n            if hasattr(field, \"resolve_expression\"):\n                field_name = getattr(\n                    field, \"default_alias\", field.__class__.__name__.lower()\n                )\n                expression = field\n                # For backward compatibility reasons expressions are always\n                # prefixed with the counter even if their default alias doesn't\n                # collide with field names. Changing this logic could break\n                # some usage of named=True.\n                seen = True\n            elif seen := field_names[field_name]:\n                expression = F(field_name)\n            if seen:\n                field_name_prefix = field_name\n                while (field_name := f\"{field_name_prefix}{counter}\") in field_names:\n                    counter += 1\n            if expression is not None:\n                expressions[field_name] = expression\n            field_names[field_name] = True\n            _fields.append(field_name)\n\n        clone = self._values(*_fields, **expressions)\n        clone._iterable_class = (\n            NamedValuesListIterable\n            if named\n            else FlatValuesListIterable if flat else ValuesListIterable\n        )\n        return clone\n\n    def dates(self, field_name, kind, order=\"ASC\"):\n        \"\"\"\n        Return a list of date objects representing all available dates for\n        the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\"):\n            raise ValueError(\"'kind' must be one of 'year', 'month', 'week', or 'day'.\")\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        return (\n            self.annotate(\n                datefield=Trunc(field_name, kind, output_field=DateField()),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datefield\")\n        )\n\n    def datetimes(self, field_name, kind, order=\"ASC\", tzinfo=None):\n        \"\"\"\n        Return a list of datetime objects representing all available\n        datetimes for the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"):\n            raise ValueError(\n                \"'kind' must be one of 'year', 'month', 'week', 'day', \"\n                \"'hour', 'minute', or 'second'.\"\n            )\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        if settings.USE_TZ:\n            if tzinfo is None:\n                tzinfo = timezone.get_current_timezone()\n        else:\n            tzinfo = None\n        return (\n            self.annotate(\n                datetimefield=Trunc(\n                    field_name,\n                    kind,\n                    output_field=DateTimeField(),\n                    tzinfo=tzinfo,\n                ),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datetimefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datetimefield\")\n        )\n\n    def none(self):\n        \"\"\"Return an empty QuerySet.\"\"\"\n        clone = self._chain()\n        clone.query.set_empty()\n        return clone\n\n    ##################################################################\n    # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #\n    ##################################################################\n\n    def all(self):\n        \"\"\"\n        Return a new QuerySet that is a copy of the current one. This allows a\n        QuerySet to proxy for a model manager in some cases.\n        \"\"\"\n        return self._chain()\n\n    def filter(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with the args ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"filter\")\n        return self._filter_or_exclude(False, args, kwargs)\n\n    def exclude(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with NOT (args) ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"exclude\")\n        return self._filter_or_exclude(True, args, kwargs)\n\n    def _filter_or_exclude(self, negate, args, kwargs):\n        if (args or kwargs) and self.query.is_sliced:\n            raise TypeError(\"Cannot filter a query once a slice has been taken.\")\n        clone = self._chain()\n        if self._defer_next_filter:\n            self._defer_next_filter = False\n            clone._deferred_filter = negate, args, kwargs\n        else:\n            clone._filter_or_exclude_inplace(negate, args, kwargs)\n        return clone\n\n    def _filter_or_exclude_inplace(self, negate, args, kwargs):\n        if invalid_kwargs := PROHIBITED_FILTER_KWARGS.intersection(kwargs):\n            invalid_kwargs_str = \", \".join(f\"'{k}'\" for k in sorted(invalid_kwargs))\n            raise TypeError(f\"The following kwargs are invalid: {invalid_kwargs_str}\")\n        if negate:\n            self._query.add_q(~Q(*args, **kwargs))\n        else:\n            self._query.add_q(Q(*args, **kwargs))\n\n    def complex_filter(self, filter_obj):\n        \"\"\"\n        Return a new QuerySet instance with filter_obj added to the filters.\n\n        filter_obj can be a Q object or a dictionary of keyword lookup\n        arguments.\n\n        This exists to support framework features such as 'limit_choices_to',\n        and usually it will be more natural to use other methods.\n        \"\"\"\n        if isinstance(filter_obj, Q):\n            clone = self._chain()\n            clone.query.add_q(filter_obj)\n            return clone\n        else:\n            return self._filter_or_exclude(False, args=(), kwargs=filter_obj)\n\n    def _combinator_query(self, combinator, *other_qs, all=False):\n        # Clone the query to inherit the select list and everything\n        clone = self._chain()\n        # Clear limits and ordering so they can be reapplied\n        clone.query.clear_ordering(force=True)\n        clone.query.default_ordering = True\n        self._clear_ordering_in_combined_queries(clone.query, other_qs)\n        clone.query.clear_limits()\n        clone.query.combinator = combinator\n        clone.query.combinator_all = all\n        return clone\n\n    def union(self, *other_qs, all=False):\n        # If the query is an EmptyQuerySet, combine all nonempty querysets.\n        if isinstance(self, EmptyQuerySet):\n            qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)]\n            if not qs:\n                return self\n            if len(qs) == 1:\n                return qs[0]\n            return qs[0]._combinator_query(\"union\", *qs[1:], all=all)\n        elif not other_qs:\n            return self\n        return self._combinator_query(\"union\", *other_qs, all=all)\n\n    def intersection(self, *other_qs):\n        # If any query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        for other in other_qs:\n            if isinstance(other, EmptyQuerySet):\n                return other\n        return self._combinator_query(\"intersection\", *other_qs)\n\n    def difference(self, *other_qs):\n        # If the query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        return self._combinator_query(\"difference\", *other_qs)\n\n    def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False):\n        \"\"\"\n        Return a new QuerySet instance that will select objects with a\n        FOR UPDATE lock.\n        \"\"\"\n        if nowait and skip_locked:\n            raise ValueError(\"The nowait option cannot be used with skip_locked.\")\n        obj = self._chain()\n        obj._for_write = True\n        obj.query.select_for_update = True\n        obj.query.select_for_update_nowait = nowait\n        obj.query.select_for_update_skip_locked = skip_locked\n        obj.query.select_for_update_of = of\n        obj.query.select_for_no_key_update = no_key\n        return obj\n\n    def select_related(self, *fields):\n        \"\"\"\n        Return a new QuerySet instance that will select related objects.\n\n        If fields are specified, they must be ForeignKey fields and only those\n        related objects are included in the selection.\n\n        If select_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"select_related\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call select_related() after .values() or .values_list()\"\n            )\n\n        obj = self._chain()\n        if fields == (None,):\n            obj.query.select_related = False\n        elif fields:\n            obj.query.add_select_related(fields)\n        else:\n            # RemovedInDjango70Warning: when the deprecation ends, raise a\n            # TypeError instead.\n            warn_about_external_use(\n                \"Calling select_related() with no arguments is deprecated. \"\n                \"Specify the fields to fetch instead.\",\n                category=RemovedInDjango70Warning,\n                skip_name_prefixes=(\"django.db.models\",),\n            )\n            obj.query.select_related = True\n        return obj\n\n    def prefetch_related(self, *lookups):\n        \"\"\"\n        Return a new QuerySet instance that will prefetch the specified\n        Many-To-One and Many-To-Many related objects when the QuerySet is\n        evaluated.\n\n        When prefetch_related() is called more than once, append to the list of\n        prefetch lookups. If prefetch_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"prefetch_related\")\n        clone = self._chain()\n        if lookups == (None,):\n            clone._prefetch_related_lookups = ()\n        else:\n            for lookup in lookups:\n                if isinstance(lookup, Prefetch):\n                    lookup = lookup.prefetch_to\n                lookup = lookup.split(LOOKUP_SEP, 1)[0]\n                if lookup in self.query._filtered_relations:\n                    raise ValueError(\n                        \"prefetch_related() is not supported with FilteredRelation.\"\n                    )\n            clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups\n        return clone\n\n    def annotate(self, *args, **kwargs):\n        \"\"\"\n        Return a query set in which the returned objects have been annotated\n        with extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"annotate\")\n        return self._annotate(args, kwargs, select=True)\n\n    def alias(self, *args, **kwargs):\n        \"\"\"\n        Return a query set with added aliases for extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"alias\")\n        return self._annotate(args, kwargs, select=False)\n\n    def _annotate(self, args, kwargs, select=True):\n        self._validate_values_are_expressions(\n            args + tuple(kwargs.values()), method_name=\"annotate\"\n        )\n        annotations = {}\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                if arg.default_alias in kwargs:\n                    raise ValueError(\n                        \"The named annotation '%s' conflicts with the \"\n                        \"default name for another annotation.\" % arg.default_alias\n                    )\n            except (TypeError, AttributeError):\n                raise TypeError(\"Complex annotations require an alias\")\n            annotations[arg.default_alias] = arg\n        annotations.update(kwargs)\n\n        clone = self._chain()\n        names = self._fields\n        if names is None:\n            names = set(\n                chain.from_iterable(\n                    (\n                        (field.name, field.attname)\n                        if hasattr(field, \"attname\")\n                        else (field.name,)\n                    )\n                    for field in self.model._meta.get_fields()\n                )\n            )\n\n        for alias, annotation in annotations.items():\n            if alias in names:\n                raise ValueError(\n                    \"The annotation '%s' conflicts with a field on \"\n                    \"the model.\" % alias\n                )\n            if isinstance(annotation, FilteredRelation):\n                clone.query.add_filtered_relation(annotation, alias)\n            else:\n                clone.query.add_annotation(\n                    annotation,\n                    alias,\n                    select=select,\n                )\n        for alias, annotation in clone.query.annotations.items():\n            if alias in annotations and annotation.contains_aggregate:\n                if clone._fields is None:\n                    clone.query.group_by = True\n                else:\n                    clone.query.set_group_by()\n                break\n\n        return clone\n\n    def order_by(self, *field_names):\n        \"\"\"Return a new QuerySet instance with the ordering changed.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reorder a query once a slice has been taken.\")\n        obj = self._chain()\n        obj.query.clear_ordering(force=True, clear_default=False)\n        obj.query.add_ordering(*field_names)\n        return obj\n\n    def distinct(self, *field_names):\n        \"\"\"\n        Return a new QuerySet instance that will select only distinct results.\n        \"\"\"\n        self._not_support_combined_queries(\"distinct\")\n        if self.query.is_sliced:\n            raise TypeError(\n                \"Cannot create distinct fields once a slice has been taken.\"\n            )\n        obj = self._chain()\n        obj.query.add_distinct_fields(*field_names)\n        return obj\n\n    def extra(\n        self,\n        select=None,\n        where=None,\n        params=None,\n        tables=None,\n        order_by=None,\n        select_params=None,\n    ):\n        \"\"\"Add extra SQL fragments to the query.\"\"\"\n        self._not_support_combined_queries(\"extra\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.add_extra(select, select_params, where, params, tables, order_by)\n        return clone\n\n    def reverse(self):\n        \"\"\"Reverse the ordering of the QuerySet.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reverse a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.standard_ordering = not clone.query.standard_ordering\n        return clone\n\n    def defer(self, *fields):\n        \"\"\"\n        Defer the loading of data for certain fields until they are accessed.\n        Add the set of deferred fields to any existing set of deferred fields.\n        The only exception to this is if None is passed in as the only\n        parameter, in which case remove all deferrals.\n        \"\"\"\n        self._not_support_combined_queries(\"defer\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call defer() after .values() or .values_list()\")\n        clone = self._chain()\n        if fields == (None,):\n            clone.query.clear_deferred_loading()\n        else:\n            clone.query.add_deferred_loading(fields)\n        return clone\n\n    def only(self, *fields):\n        \"\"\"\n        Essentially, the opposite of defer(). Only the fields passed into this\n        method and that are not already specified as deferred are loaded\n        immediately when the queryset is evaluated.\n        \"\"\"\n        self._not_support_combined_queries(\"only\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call only() after .values() or .values_list()\")\n        if fields == (None,):\n            # Can only pass None to defer(), not only(), as the rest option.\n            # That won't stop people trying to do this, so let's be explicit.\n            raise TypeError(\"Cannot pass None as an argument to only().\")\n        for field in fields:\n            field = field.split(LOOKUP_SEP, 1)[0]\n            if field in self.query._filtered_relations:\n                raise ValueError(\"only() is not supported with FilteredRelation.\")\n        clone = self._chain()\n        clone.query.add_immediate_loading(fields)\n        return clone\n\n    def using(self, alias):\n        \"\"\"Select which database this QuerySet should execute against.\"\"\"\n        clone = self._chain()\n        clone._db = alias\n        return clone\n\n    def fetch_mode(self, fetch_mode):\n        \"\"\"Set the fetch mode for the QuerySet.\"\"\"\n        clone = self._chain()\n        clone._fetch_mode = fetch_mode\n        return clone\n\n    ###################################\n    # PUBLIC INTROSPECTION ATTRIBUTES #\n    ###################################\n\n    @property\n    def ordered(self):\n        \"\"\"\n        Return True if the QuerySet is ordered -- i.e. has an order_by()\n        clause or a default ordering on the model (or is empty).\n        \"\"\"\n        if isinstance(self, EmptyQuerySet):\n            return True\n        if self.query.extra_order_by or self.query.order_by:\n            return True\n        elif (\n            self.query.default_ordering\n            and self.query.get_meta().ordering\n            and\n            # A default ordering doesn't affect GROUP BY queries.\n            not self.query.group_by\n        ):\n            return True\n        else:\n            return False\n\n    @property\n    def totally_ordered(self):\n        \"\"\"\n        Returns True if the QuerySet is ordered and the ordering is\n        deterministic. This requires that the ordering includes a field\n        (or set of fields) that is unique and non-nullable.\n\n        For queries involving a GROUP BY clause, the model's default\n        ordering is ignored. Ordering specified via .extra(order_by=...)\n        is also ignored.\n        \"\"\"\n        if not self.ordered:\n            return False\n        ordering = self.query.order_by\n        if not ordering and self.query.default_ordering:\n            ordering = self.query.get_meta().ordering\n        if not ordering:\n            return False\n        opts = self.model._meta\n        pk_fields = {f.attname for f in opts.pk_fields}\n        candidate_fields = set()\n        for part in ordering:\n            # Search for single field providing a total ordering.\n            field_name = None\n            if isinstance(part, str):\n                field_name = part.lstrip(\"-\")\n            elif isinstance(part, F):\n                field_name = part.name\n            elif isinstance(part, OrderBy) and isinstance(part.expression, F):\n                field_name = part.expression.name\n            if annotation_col := self.query.annotations.get(field_name):\n                if isinstance(annotation_col, Col):\n                    if annotation_col.alias == self.query.base_table:\n                        candidate_fields.add(annotation_col.target)\n                elif isinstance(annotation_col, ColPairs):\n                    candidate_fields |= {\n                        c.target\n                        for c in annotation_col.get_cols()\n                        if c.alias == self.query.base_table\n                    }\n            elif field_name:\n                if field_name == \"pk\":\n                    return True\n                # Normalize attname references by using get_field().\n                try:\n                    field = opts.get_field(field_name)\n                except exceptions.FieldDoesNotExist:\n                    # Could be \"?\" for random ordering or a related field\n                    # lookup. Skip this part of introspection for now.\n                    continue\n                else:\n                    # Ordering by a related field name orders by the referenced\n                    # model's ordering. Skip this introspection for now.\n                    if field.remote_field and field_name == field.name:\n                        continue\n                    candidate_fields.add(field)\n\n        candidate_attnames = set()\n        for field in candidate_fields:\n            if field.unique and not field.null:\n                return True\n            candidate_attnames.add(field.attname)\n\n        # Account for members of a CompositePrimaryKey.\n        if candidate_attnames.issuperset(pk_fields):\n            return True\n        # No single total ordering field, try unique_together and total\n        # unique constraints.\n        constraint_field_names = (\n            *opts.unique_together,\n            *(constraint.fields for constraint in opts.total_unique_constraints),\n        )\n        for field_names in constraint_field_names:\n            # Normalize attname references by using get_field().\n            try:\n                fields = [opts.get_field(field_name) for field_name in field_names]\n            except exceptions.FieldDoesNotExist:\n                continue\n            # Composite unique constraints containing a nullable column\n            # cannot ensure total ordering.\n            if any(field.null for field in fields):\n                continue\n            if candidate_attnames.issuperset(field.attname for field in fields):\n                return True\n\n        return False\n\n    @property\n    def db(self):\n        \"\"\"Return the database used if this query is executed now.\"\"\"\n        if self._for_write:\n            return self._db or router.db_for_write(self.model, **self._hints)\n        return self._db or router.db_for_read(self.model, **self._hints)\n\n    ###################\n    # PRIVATE METHODS #\n    ###################\n\n    def _insert(\n        self,\n        objs,\n        fields,\n        returning_fields=None,\n        raw=False,\n        using=None,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert a new record for the given model. This provides an interface to\n        the InsertQuery class and is how Model.save() is implemented.\n        \"\"\"\n        self._for_write = True\n        if using is None:\n            using = self.db\n        query = sql.InsertQuery(\n            self.model,\n            on_conflict=on_conflict,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n        query.insert_values(fields, objs, raw=raw)\n        return query.get_compiler(using=using).execute_sql(returning_fields)\n\n    _insert.alters_data = True\n    _insert.queryset_only = False\n\n    def _batched_insert(\n        self,\n        objs,\n        fields,\n        batch_size,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Helper method for bulk_create() to insert objs one batch at a time.\n        \"\"\"\n        connection = connections[self.db]\n        ops = connection.ops\n        max_batch_size = max(ops.bulk_batch_size(fields, objs), 1)\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        inserted_rows = []\n        returning_fields = (\n            self.model._meta.db_returning_fields\n            if (\n                connection.features.can_return_rows_from_bulk_insert\n                and (on_conflict is None or on_conflict == OnConflict.UPDATE)\n            )\n            else None\n        )\n        batches = [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]\n        if len(batches) > 1:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            for item in batches:\n                inserted_rows.extend(\n                    self._insert(\n                        item,\n                        fields=fields,\n                        using=self.db,\n                        on_conflict=on_conflict,\n                        update_fields=update_fields,\n                        unique_fields=unique_fields,\n                        returning_fields=returning_fields,\n                    )\n                )\n        return inserted_rows\n\n    def _disable_cloning(self):\n        \"\"\"\n        Prevent calls to _chain() from creating a new QuerySet via _clone().\n        All subsequent QuerySet mutations will occur on this instance until\n        _enable_cloning() is used.\n        \"\"\"\n        self._cloning_enabled = False\n        return self\n\n    def _enable_cloning(self):\n        \"\"\"\n        Allow calls to _chain() to create a new QuerySet via _clone(). Restores\n        the default behavior where any QuerySet mutation will return a new\n        QuerySet instance. Necessary only when there has been a\n        _disable_cloning() call previously.\n        \"\"\"\n        self._cloning_enabled = True\n        return self\n\n    def _avoid_cloning(self):\n        \"\"\"\n        Temporarily prevent QuerySet _clone() operations, restoring the default\n        behavior on exit. For the duration of the context managed statement,\n        all operations (e.g. filter(), exclude(), etc.) will mutate the same\n        QuerySet instance.\n\n        @contextlib.contextmanager is intentionally not used for performance\n        reasons.\n        \"\"\"\n        return PreventQuerySetCloning(self)\n\n    def _chain(self):\n        \"\"\"\n        Return a copy of the current QuerySet that's ready for another\n        operation.\n\n        If the QuerySet has opted in to in-place mutations via\n        _disable_cloning() temporarily, the copy doesn't occur and instead the\n        same QuerySet instance will be modified.\n        \"\"\"\n        if not self._cloning_enabled:\n            obj = self\n        else:\n            obj = self._clone()\n        if obj._sticky_filter:\n            obj.query.filter_is_sticky = True\n            obj._sticky_filter = False\n        return obj\n\n    def _clone(self):\n        \"\"\"\n        Return a copy of the current QuerySet. A lightweight alternative\n        to deepcopy().\n        \"\"\"\n        c = self.__class__(\n            model=self.model,\n            query=self.query.chain(),\n            using=self._db,\n            hints=self._hints,\n        )\n        c._sticky_filter = self._sticky_filter\n        c._for_write = self._for_write\n        c._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        c._known_related_objects = self._known_related_objects\n        c._iterable_class = self._iterable_class\n        c._fetch_mode = self._fetch_mode\n        c._fields = self._fields\n        return c\n\n    def _fetch_all(self):\n        if self._result_cache is None:\n            self._result_cache = list(self._iterable_class(self))\n        if self._prefetch_related_lookups and not self._prefetch_done:\n            self._prefetch_related_objects()\n\n    def _next_is_sticky(self):\n        \"\"\"\n        Indicate that the next filter call and the one following that should\n        be treated as a single filter. This is only important when it comes to\n        determining when to reuse tables for many-to-many filters. Required so\n        that we can filter naturally on the results of related managers.\n\n        This doesn't return a clone of the current QuerySet (it returns\n        \"self\"). The method is only used internally and should be immediately\n        followed by a filter() that does create a clone.\n        \"\"\"\n        self._sticky_filter = True\n        return self\n\n    def _merge_sanity_check(self, other):\n        \"\"\"Check that two QuerySet classes may be merged.\"\"\"\n        if self._fields is not None and (\n            set(self.query.values_select) != set(other.query.values_select)\n            or set(self.query.extra_select) != set(other.query.extra_select)\n            or set(self.query.annotation_select) != set(other.query.annotation_select)\n        ):\n            raise TypeError(\n                \"Merging '%s' classes must involve the same values in each case.\"\n                % self.__class__.__name__\n            )\n\n    def _merge_known_related_objects(self, other):\n        \"\"\"\n        Keep track of all known related objects from either QuerySet instance.\n        \"\"\"\n        for field, objects in other._known_related_objects.items():\n            self._known_related_objects.setdefault(field, {}).update(objects)\n\n    def resolve_expression(self, *args, **kwargs):\n        query = self.query.resolve_expression(*args, **kwargs)\n        query._db = self._db\n        return query\n\n    resolve_expression.queryset_only = True\n\n    def _add_hints(self, **hints):\n        \"\"\"\n        Update hinting information for use by routers. Add new key/values or\n        overwrite existing key/values.\n        \"\"\"\n        self._hints.update(hints)\n\n    def _has_filters(self):\n        \"\"\"\n        Check if this QuerySet has any filtering going on. This isn't\n        equivalent with checking if all objects are present in results, for\n        example, qs[1:]._has_filters() -> False.\n        \"\"\"\n        return self.query.has_filters()\n\n    @staticmethod\n    def _validate_values_are_expressions(values, method_name):\n        invalid_args = sorted(\n            str(arg) for arg in values if not hasattr(arg, \"resolve_expression\")\n        )\n        if invalid_args:\n            raise TypeError(\n                \"QuerySet.%s() received non-expression(s): %s.\"\n                % (\n                    method_name,\n                    \", \".join(invalid_args),\n                )\n            )\n\n    def _not_support_combined_queries(self, operation_name):\n        if self.query.combinator:\n            raise NotSupportedError(\n                \"Calling QuerySet.%s() after %s() is not supported.\"\n                % (operation_name, self.query.combinator)\n            )\n\n    def _check_operator_queryset(self, other, operator_):\n        if self.query.combinator or other.query.combinator:\n            raise TypeError(f\"Cannot use {operator_} operator with combined queryset.\")\n\n    def _check_ordering_first_last_queryset_aggregation(self, method):\n        if (\n            isinstance(self.query.group_by, tuple)\n            # Raise if the pk fields are not in the group_by.\n            and self.model._meta.pk\n            not in {col.output_field for col in self.query.group_by}\n            and set(self.model._meta.pk_fields).difference(\n                {col.target for col in self.query.group_by}\n            )\n        ):\n            raise TypeError(\n                f\"Cannot use QuerySet.{method}() on an unordered queryset performing \"\n                f\"aggregation. Add an ordering with order_by().\"\n            )\n\n    def _clear_ordering_in_combined_queries(self, cloned_query, other_qs):\n        combined_queries = [self.query]\n        for qs in other_qs:\n            query = qs.query.clone()\n            query.clear_ordering(force=False, clear_default=False)\n            combined_queries.append(query)\n        cloned_query.combined_queries = tuple(combined_queries)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-765e7606ef75a519", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "71ba088263a0dd038cdcee5a04e5f75dbd2b9146bb5832622c12eb0bf5f2eae2", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 2108, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__QuerySet__034fac76.py", "order": 9, "original_content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "parent_variant_id": "pyint-5c2b55814568-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/query.py#L374-L2424", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 5}, "unit_kind": "class", "unit_name": "QuerySet", "variant_id": "pyint-1933034fac76-I09", "group_id": "py-765e7606ef75a519", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 234, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9c296ab8475f-I10", "source": "import copy\nimport operator\nimport warnings\nfrom contextlib import nullcontext\nfrom functools import partial, reduce\nfrom itertools import chain, islice\nfrom weakref import ref as weak_ref\nfrom asgiref.sync import sync_to_async\nimport django\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.db import (\n    DJANGO_VERSION_PICKLE_KEY,     IntegrityError,     NotSupportedError,\n    connections,     router,\n    transaction, )\nfrom django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql\nfrom django.db.models.constants import LOOKUP_SEP, OnConflict\nfrom django.db.models.deletion import Collector\nfrom django.db.models.expressions import (     Case,     Col,     ColPairs,     DatabaseDefault,     F,\n    OrderBy,\n    Value,\n    When, )\nfrom django.db.models.fetch_modes import FETCH_ONE\nfrom django.db.models.functions import Cast, Trunc\nfrom django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q\nfrom django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT\nfrom django.db.models.utils import (\n    AltersData,\n    create_namedtuple_class,\n    resolve_callables,\n)\nfrom django.utils import timezone\nfrom django.utils.deprecation import (     RemovedInDjango70Warning,\n    RemovedInDjango71Warning,     warn_about_external_use, )\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import func_accepts_kwargs, func_supports_parameter\nfrom django.utils.warnings import django_file_prefixes\n\nclass QuerySet(AltersData):\n    \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n    def __init__(self, model=None, query=None, using=None, hints=None):\n        self.model = model\n        self._db = using\n        self._hints = hints or {}\n        self._query = query or sql.Query(self.model)\n        self._result_cache = None\n        self._sticky_filter = False\n        self._for_write = False\n        self._prefetch_related_lookups = ()\n        self._prefetch_done = False\n        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}\n        self._iterable_class = ModelIterable\n        self._fetch_mode = DEFAULT_FETCH_MODE\n        self._fields = None\n        self._defer_next_filter = False\n        self._deferred_filter = None\n        self._cloning_enabled = True\n    @property\n    def query(self):\n        if self._deferred_filter:\n            negate, args, kwargs = self._deferred_filter\n            self._filter_or_exclude_inplace(negate, args, kwargs)\n            self._deferred_filter = None\n        return self._query\n\n    @query.setter\n    def query(self, value):\n        if value.values_select:\n            self._iterable_class = ValuesIterable\n        self._query = value\n\n    def as_manager(cls):\n        # Address the circular dependency between `Queryset` and `Manager`.\n        from django.db.models.manager import Manager\n        manager = Manager.from_queryset(cls)()\n        manager._built_with_as_manager = True\n        return manager\n    as_manager.queryset_only = True\n    as_manager = classmethod(as_manager)\n    ########################\n    # PYTHON MAGIC METHODS #\n    ########################\n    def __deepcopy__(self, memo):\n        \"\"\"Don't populate the QuerySet's cache.\"\"\"\n        obj = self.__class__()\n        for k, v in self.__dict__.items():\n            if k == \"_result_cache\":\n                obj.__dict__[k] = None\n            else:\n                obj.__dict__[k] = copy.deepcopy(v, memo)\n        return obj\n\n    def __getstate__(self):\n        # Force the cache to be fully populated.\n        self._fetch_all()\n        return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n    def __setstate__(self, state):\n        pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)\n        if pickled_version:\n            if pickled_version != django.__version__:\n                warnings.warn(\n                    \"Pickled queryset instance's Django version %s does not \"\n                    \"match the current version %s.\"\n                    % (pickled_version, django.__version__),\n                    RuntimeWarning,\n                    stacklevel=2,                 )\n        else:\n            warnings.warn(                 \"Pickled queryset instance's Django version is not specified.\",\n                RuntimeWarning,                 stacklevel=2,             )\n        self.__dict__.update(state)\n    def __repr__(self):\n        data = list(self[: REPR_OUTPUT_SIZE + 1])\n        if len(data) > REPR_OUTPUT_SIZE:\n            data[-1] = \"...(remaining elements truncated)...\"\n        return \"<%s %r>\" % (self.__class__.__name__, data)\n\n    def __len__(self):\n        self._fetch_all()\n        return len(self._result_cache)\n\n    def __iter__(self):\n        \"\"\"\n        The queryset iterator protocol uses three nested iterators in the\n        default case:\n            1. sql.compiler.execute_sql()\n               - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n                 using cursor.fetchmany(). This part is responsible for\n                 doing some column masking, and returning the rows in chunks.\n            2. sql.compiler.results_iter()\n               - Returns one row at time. At this point the rows are still just\n                 tuples. In some cases the return values are converted to\n                 Python values at this location.\n            3. self.iterator()\n               - Responsible for turning the rows into model objects.\n        \"\"\"\n        self._fetch_all()\n        return iter(self._result_cache)\n\n    def __aiter__(self):\n        # Remember, __aiter__ itself is synchronous, it's the thing it returns\n        # that is async!\n        async def generator():\n            await sync_to_async(self._fetch_all)()\n            for item in self._result_cache:\n                yield item\n        return generator()\n\n    def __bool__(self):\n        self._fetch_all()\n        return bool(self._result_cache)\n\n    def __getitem__(self, k):\n        \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n        if not isinstance(k, (int, slice)):\n            raise TypeError(                 \"QuerySet indices must be integers or slices, not %s.\"                 % type(k).__name__\n            )\n        if (isinstance(k, int) and k < 0) or (             isinstance(k, slice)             and (\n                (k.start is not None and k.start < 0)\n                or (k.stop is not None and k.stop < 0)\n            )         ):\n            raise ValueError(\"Negative indexing is not supported.\")\n\n        if self._result_cache is not None:\n            return self._result_cache[k]\n\n        if isinstance(k, slice):\n            qs = self._chain()\n            if k.start is not None:\n                start = int(k.start)\n            else:\n                start = None\n            if k.stop is not None:\n                stop = int(k.stop)\n            else:\n                stop = None\n            qs.query.set_limits(start, stop)\n            return list(qs)[:: k.step] if k.step else qs\n        qs = self._chain()\n        qs.query.set_limits(k, k + 1)\n        qs._fetch_all()\n        return qs._result_cache[0]\n\n    def __class_getitem__(cls, *args, **kwargs):\n        return cls\n    def __and__(self, other):\n        self._check_operator_queryset(other, \"&\")\n        self._merge_sanity_check(other)\n        if isinstance(other, EmptyQuerySet):\n            return other\n        if isinstance(self, EmptyQuerySet):\n            return self\n        combined = self._chain()\n        combined._merge_known_related_objects(other)\n        combined.query.combine(other.query, sql.AND)\n        return combined\n    def __or__(self, other):\n        self._check_operator_queryset(other, \"|\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()             else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.OR)\n        return combined\n\n    def __xor__(self, other):\n        self._check_operator_queryset(other, \"^\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))         )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.XOR)\n        return combined\n\n    ####################################\n    # METHODS THAT DO DATABASE QUERIES #\n    ####################################\n\n    def _iterator(self, use_chunked_fetch, chunk_size):\n        iterable = self._iterable_class(\n            self,             chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,         )\n        if not self._prefetch_related_lookups or chunk_size is None:\n            yield from iterable\n            return\n\n        iterator = iter(iterable)\n        while results := list(islice(iterator, chunk_size)):\n            prefetch_related_objects(results, *self._prefetch_related_lookups)\n            yield from results\n    def iterator(self, chunk_size=None):\n        \"\"\"\n        An iterator over the results from applying this QuerySet to the\n        database. chunk_size must be provided for QuerySets that prefetch\n        related objects. Otherwise, a default chunk_size of 2000 is supplied.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                raise ValueError(\n                    \"chunk_size must be provided when using QuerySet.iterator() after \"                     \"prefetch_related().\"                 )\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(             \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        return self._iterator(use_chunked_fetch, chunk_size)\n    async def aiterator(self, chunk_size=None):\n        \"\"\"\n        An asynchronous iterator over the results from applying this QuerySet\n        to the database.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                # RemovedInDjango71Warning: Replace the warning with:\n                # raise ValueError(\n                #     \"chunk_size must be provided when using \"\n                #     \"QuerySet.aiterator() after prefetch_related().\"\n                # )\n                warnings.warn(\n                    \"Using QuerySet.aiterator() after prefetch_related() without \"\n                    \"providing a chunk_size is deprecated and will raise a \"\n                    \"ValueError in Django 7.1.\",\n                    category=RemovedInDjango71Warning,                     skip_file_prefixes=django_file_prefixes(),\n                )\n                # RemovedInDjango71Warning: When the deprecation ends, remove.\n                chunk_size = 2000\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        iterable = self._iterable_class(             self,             chunked_fetch=use_chunked_fetch,             chunk_size=chunk_size or 2000,         )\n        if self._prefetch_related_lookups:\n            results = []\n\n            async for item in iterable:\n                results.append(item)\n                if len(results) >= chunk_size:\n                    await aprefetch_related_objects(\n                        results, *self._prefetch_related_lookups\n                    )\n                    for result in results:\n                        yield result\n                    results.clear()\n\n            if results:\n                await aprefetch_related_objects(                     results, *self._prefetch_related_lookups\n                )\n                for result in results:\n                    yield result\n        else:\n            async for item in iterable:\n                yield item\n\n    def aggregate(self, *args, **kwargs):\n        \"\"\"\n        Return a dictionary containing the calculations (aggregation)\n        over the current queryset.\n        If args is present the expression is passed as a kwarg using\n        the Aggregate object's default alias.\n        \"\"\"\n        if self.query.distinct_fields:\n            raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n        self._validate_values_are_expressions(\n            (*args, *kwargs.values()), method_name=\"aggregate\"         )\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                arg.default_alias\n            except (AttributeError, TypeError):\n                raise TypeError(\"Complex aggregates require an alias\")\n            kwargs[arg.default_alias] = arg\n\n        return self.query.chain().get_aggregation(self.db, kwargs)\n\n    async def aaggregate(self, *args, **kwargs):\n        return await sync_to_async(self.aggregate)(*args, **kwargs)\n\n    def count(self):\n        \"\"\"\n        Perform a SELECT COUNT() and return the number of records as an\n        integer.\n\n        If the QuerySet is already fully cached, return the length of the\n        cached results set to avoid multiple SELECT COUNT(*) calls.\n        \"\"\"\n        if self._result_cache is not None:\n            return len(self._result_cache)\n        return self.query.get_count(using=self.db)\n    async def acount(self):\n        return await sync_to_async(self.count)()\n\n    def get(self, *args, **kwargs):\n        \"\"\"\n        Perform the query and return a single object matching the given\n        keyword arguments.\n        \"\"\"\n        if self.query.combinator and (args or kwargs):\n            raise NotSupportedError(\n                \"Calling QuerySet.get(...) with filters after %s() is not \"\n                \"supported.\" % self.query.combinator\n            )\n        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)\n        if self.query.can_filter() and not self.query.distinct_fields:\n            clone = clone.order_by()\n        limit = None\n        if (             not clone.query.select_for_update\n            or connections[clone.db].features.supports_select_for_update_with_limit         ):\n            limit = MAX_GET_RESULTS\n            clone.query.set_limits(high=limit)\n        num = len(clone)\n        if num == 1:\n            return clone._result_cache[0]\n        if not num:\n            raise self.model.DoesNotExist(                 \"%s matching query does not exist.\" % self.model._meta.object_name             )\n        raise self.model.MultipleObjectsReturned(             \"get() returned more than one %s -- it returned %s!\"\n            % (\n                self.model._meta.object_name,\n                num if not limit or num < limit else \"more than %s\" % (limit - 1),             )         )\n    async def aget(self, *args, **kwargs):\n        return await sync_to_async(self.get)(*args, **kwargs)\n    def create(self, **kwargs):\n        \"\"\"\n        Create a new object with the given kwargs, saving it to the database\n        and returning the created object.\n        \"\"\"\n        reverse_one_to_one_fields = frozenset(kwargs).intersection(             self.model._meta._reverse_one_to_one_field_names         )\n        if reverse_one_to_one_fields:\n            raise ValueError(\n                \"The following fields do not exist in this model: %s\"                 % \", \".join(reverse_one_to_one_fields)             )\n\n        obj = self.model(**kwargs)\n        self._for_write = True\n        obj.save(force_insert=True, using=self.db)\n        obj._state.fetch_mode = self._fetch_mode\n        return obj\n\n    create.alters_data = True\n    async def acreate(self, **kwargs):\n        return await sync_to_async(self.create)(**kwargs)\n\n    acreate.alters_data = True\n    def _prepare_for_bulk_create(self, objs):\n        objs_with_pk, objs_without_pk = [], []\n        for obj in objs:\n            obj._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n            if isinstance(obj.pk, DatabaseDefault):\n                objs_without_pk.append(obj)\n            elif obj._is_pk_set():\n                objs_with_pk.append(obj)\n            else:\n                obj.pk = obj._meta.pk.get_pk_value_on_save(obj)\n                if obj._is_pk_set():\n                    objs_with_pk.append(obj)\n                else:\n                    objs_without_pk.append(obj)\n        return objs_with_pk, objs_without_pk\n    def _check_bulk_create_options(\n        self, ignore_conflicts, update_conflicts, update_fields, unique_fields\n    ):\n        if ignore_conflicts and update_conflicts:\n            raise ValueError(\n                \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n            )\n        db_features = connections[self.db].features\n        if ignore_conflicts:\n            if not db_features.supports_ignore_conflicts:\n                raise NotSupportedError(                     \"This database backend does not support ignoring conflicts.\"                 )\n            return OnConflict.IGNORE\n        elif update_conflicts:\n            if not db_features.supports_update_conflicts:\n                raise NotSupportedError(                     \"This database backend does not support updating conflicts.\"                 )\n            if not update_fields:\n                raise ValueError(\n                    \"Fields that will be updated when a row insertion fails \"\n                    \"on conflicts must be provided.\"\n                )\n            if unique_fields and not db_features.supports_update_conflicts_with_target:\n                raise NotSupportedError(\n                    \"This database backend does not support updating \"                     \"conflicts with specifying unique fields that can trigger \"\n                    \"the upsert.\"\n                )\n            if not unique_fields and db_features.supports_update_conflicts_with_target:\n                raise ValueError(\n                    \"Unique fields that can trigger the upsert must be provided.\"                 )\n            # Updating primary keys and non-concrete fields is forbidden.\n            if any(not f.concrete for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() can only be used with concrete fields in \"\n                    \"update_fields.\"\n                )\n            if any(f in self.model._meta.pk_fields for f in update_fields):\n                raise ValueError(                     \"bulk_create() cannot be used with primary keys in \"\n                    \"update_fields.\"\n                )\n            if unique_fields:\n                if any(not f.concrete for f in unique_fields):\n                    raise ValueError(\n                        \"bulk_create() can only be used with concrete fields \"                         \"in unique_fields.\"\n                    )\n            return OnConflict.UPDATE\n        return None\n    def bulk_create(\n        self,\n        objs,         batch_size=None,         ignore_conflicts=False,\n        update_conflicts=False,         update_fields=None,\n        unique_fields=None,     ):\n        \"\"\"\n        Insert each of the instances into the database. Do *not* call\n        save() on each of the instances, do not send any pre/post_save\n        signals, and do not set the primary key attribute if it is an\n        autoincrement field (except if\n        features.can_return_rows_from_bulk_insert=True).\n        Multi-table models are not supported.\n        \"\"\"\n        # When you bulk insert you don't get the primary keys back (if it's an\n        # autoincrement, except if can_return_rows_from_bulk_insert=True), so\n        # you can't insert into the child tables which references this. There\n        # are two workarounds:\n        # 1) This could be implemented if you didn't have an autoincrement pk\n        # 2) You could do it by doing O(n) normal inserts into the parent\n        #    tables to get the primary keys back and then doing a single bulk\n        #    insert into the childmost table.\n        # We currently set the primary keys on the objects when using\n        # PostgreSQL via the RETURNING ID clause. It should be possible for\n        # Oracle as well, but the semantics for extracting the primary keys is\n        # trickier so it's not done yet.\n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        # Check that the parents share the same concrete model with the our\n        # model to detect the inheritance pattern ConcreteGrandParent ->\n        # MultiTableParent -> ProxyChild. Simply checking\n        # self.model._meta.proxy would not identify that case as involving\n        # multiple tables.\n        for parent in self.model._meta.all_parents:\n            if parent._meta.concrete_model is not self.model._meta.concrete_model:\n                raise ValueError(\"Can't bulk create a multi-table inherited model\")\n        if not objs:\n            return objs\n        opts = self.model._meta\n        if unique_fields:\n            # Primary key is allowed in unique_fields.\n            unique_fields = [\n                self.model._meta.get_field(opts.pk.name if name == \"pk\" else name)\n                for name in unique_fields\n            ]\n        if update_fields:\n            update_fields = [self.model._meta.get_field(name) for name in update_fields]\n        on_conflict = self._check_bulk_create_options(             ignore_conflicts,\n            update_conflicts,\n            update_fields,             unique_fields,\n        )\n        self._for_write = True\n        fields = [f for f in opts.concrete_fields if not f.generated]\n        objs = list(objs)\n        objs_with_pk, objs_without_pk = self._prepare_for_bulk_create(objs)\n        if objs_with_pk and objs_without_pk:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            self._handle_order_with_respect_to(objs)\n            if objs_with_pk:\n                returned_columns = self._batched_insert(\n                    objs_with_pk,                     fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,                     unique_fields=unique_fields,                 )\n                for obj_with_pk, results in zip(objs_with_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_with_pk, field.attname, result)\n                for obj_with_pk in objs_with_pk:\n                    obj_with_pk._state.adding = False\n                    obj_with_pk._state.db = self.db\n            if objs_without_pk:\n                fields = [f for f in fields if not isinstance(f, AutoField)]\n                returned_columns = self._batched_insert(\n                    objs_without_pk,\n                    fields,                     batch_size,\n                    on_conflict=on_conflict,                     update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                connection = connections[self.db]\n                if (\n                    connection.features.can_return_rows_from_bulk_insert\n                    and on_conflict is None\n                ):\n                    assert len(returned_columns) == len(objs_without_pk)\n                for obj_without_pk, results in zip(objs_without_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_without_pk, field.attname, result)\n                    obj_without_pk._state.adding = False\n                    obj_without_pk._state.db = self.db\n\n        return objs\n    def _handle_order_with_respect_to(self, objs):\n        if objs and (order_wrt := self.model._meta.order_with_respect_to):\n            get_filter_kwargs_for_object = order_wrt.get_filter_kwargs_for_object\n            attnames = list(get_filter_kwargs_for_object(objs[0]))\n            group_keys = set()\n            obj_groups = []\n            for obj in objs:\n                group_key = tuple(get_filter_kwargs_for_object(obj).values())\n                group_keys.add(group_key)\n                obj_groups.append((obj, group_key))\n            filters = [                 Q.create(list(zip(attnames, group_key))) for group_key in group_keys\n            ]\n            next_orders = (\n                self.model._base_manager.using(self.db)                 .filter(reduce(operator.or_, filters))\n                .values_list(*attnames)\n                .annotate(_order__max=Max(\"_order\") + 1)\n            )\n            # Create mapping of group values to max order.\n            group_next_orders = dict.fromkeys(group_keys, 0)\n            group_next_orders.update(                 (tuple(group_key), next_order) for *group_key, next_order in next_orders\n            )\n            # Assign _order values to new objects.\n            for obj, group_key in obj_groups:\n                if getattr(obj, \"_order\", None) is None:\n                    group_next_order = group_next_orders[group_key]\n                    obj._order = group_next_order\n                    group_next_orders[group_key] += 1\n\n    bulk_create.alters_data = True\n\n    async def abulk_create(\n        self,\n        objs,\n        batch_size=None,         ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,     ):\n        return await sync_to_async(self.bulk_create)(             objs=objs,\n            batch_size=batch_size,\n            ignore_conflicts=ignore_conflicts,\n            update_conflicts=update_conflicts,\n            update_fields=update_fields,             unique_fields=unique_fields,         )\n    abulk_create.alters_data = True\n\n    def bulk_update(self, objs, fields, batch_size=None):\n        \"\"\"\n        Update the given fields in each of the given objects in the database.\n        \"\"\"\n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        if not fields:\n            raise ValueError(\"Field names must be given to bulk_update().\")\n        objs = tuple(objs)\n        if not all(obj._is_pk_set() for obj in objs):\n            raise ValueError(\"All bulk_update() objects must have a primary key set.\")\n        opts = self.model._meta\n        fields = [opts.get_field(name) for name in fields]\n        if any(not f.concrete for f in fields):\n            raise ValueError(\"bulk_update() can only be used with concrete fields.\")\n        all_pk_fields = set(opts.pk_fields)\n        for parent in opts.all_parents:\n            all_pk_fields.update(parent._meta.pk_fields)\n        if any(f in all_pk_fields for f in fields):\n            raise ValueError(\"bulk_update() cannot be used with primary key fields.\")\n        if not objs:\n            return 0\n        for obj in objs:\n            obj._prepare_related_fields_for_save(\n                operation_name=\"bulk_update\", fields=fields\n            )\n        # PK is used twice in the resulting update query, once in the filter\n        # and once in the WHEN. Each field will also have one CAST.\n        self._for_write = True\n        connection = connections[self.db]\n        max_batch_size = connection.ops.bulk_batch_size(\n            [opts.pk, opts.pk, *fields], objs\n        )\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        requires_casting = connection.features.requires_casted_case_in_updates\n        batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size))\n        updates = []\n        for batch_objs in batches:\n            update_kwargs = {}\n            for field in fields:\n                when_statements = []\n                for obj in batch_objs:\n                    attr = getattr(obj, field.attname)\n                    if not hasattr(attr, \"resolve_expression\"):\n                        attr = Value(attr, output_field=field)\n                    when_statements.append(When(pk=obj.pk, then=attr))\n                case_statement = Case(*when_statements, output_field=field)\n                if requires_casting:\n                    case_statement = Cast(case_statement, output_field=field)\n                update_kwargs[field.attname] = case_statement\n            updates.append(([obj.pk for obj in batch_objs], update_kwargs))\n        rows_updated = 0\n        queryset = self.using(self.db)\n        with transaction.atomic(using=self.db, savepoint=False):\n            for pks, update_kwargs in updates:\n                rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs)\n        return rows_updated\n    bulk_update.alters_data = True\n\n    async def abulk_update(self, objs, fields, batch_size=None):\n        return await sync_to_async(self.bulk_update)(\n            objs=objs,             fields=fields,             batch_size=batch_size,         )\n\n    abulk_update.alters_data = True\n\n    def get_or_create(self, defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, creating one if necessary.\n        Return a tuple of (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        # The get() needs to be targeted at the write database in order\n        # to avoid potential transaction consistency problems.\n        self._for_write = True\n        try:\n            return self.get(**kwargs), False\n        except self.model.DoesNotExist:\n            params = self._extract_model_params(defaults, **kwargs)\n            # Try to create an object using passed params.\n            try:\n                with transaction.atomic(using=self.db):\n                    params = dict(resolve_callables(params))\n                    return self.create(**params), True\n            except IntegrityError:\n                try:\n                    return self.get(**kwargs), False\n                except self.model.DoesNotExist:\n                    pass\n                raise\n    get_or_create.alters_data = True\n    async def aget_or_create(self, defaults=None, **kwargs):\n        return await sync_to_async(self.get_or_create)(             defaults=defaults,\n            **kwargs,         )\n\n    aget_or_create.alters_data = True\n    def update_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, updating one with defaults\n        if it exists, otherwise create a new one. Optionally, an object can\n        be created with different values than defaults by using\n        create_defaults.\n        Return a tuple (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        update_defaults = defaults or {}\n        if create_defaults is None:\n            create_defaults = update_defaults\n        self._for_write = True\n        with transaction.atomic(using=self.db):\n            # Lock the row so that a concurrent update is blocked until\n            # update_or_create() has performed its save.\n            obj, created = self.select_for_update().get_or_create(\n                create_defaults, **kwargs             )\n            if created:\n                return obj, created\n            for k, v in resolve_callables(update_defaults):\n                setattr(obj, k, v)\n\n            update_fields = set(update_defaults)\n            concrete_field_names = self.model._meta._non_pk_concrete_field_names\n            # update_fields does not support non-concrete fields.\n            if concrete_field_names.issuperset(update_fields):\n                # Add fields which are set on pre_save(), e.g. auto_now fields.\n                # This is to maintain backward compatibility as these fields\n                # are not updated unless explicitly specified in the\n                # update_fields list.\n                pk_fields = self.model._meta.pk_fields\n                for field in self.model._meta.local_concrete_fields:\n                    if not (\n                        field in pk_fields or field.__class__.pre_save is Field.pre_save\n                    ):\n                        update_fields.add(field.name)\n                        if field.name != field.attname:\n                            update_fields.add(field.attname)\n                obj.save(using=self.db, update_fields=update_fields)\n            else:\n                obj.save(using=self.db)\n        return obj, False\n\n    update_or_create.alters_data = True\n\n    async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        return await sync_to_async(self.update_or_create)(             defaults=defaults,\n            create_defaults=create_defaults,\n            **kwargs,\n        )\n    aupdate_or_create.alters_data = True\n\n    def _extract_model_params(self, defaults, **kwargs):\n        \"\"\"\n        Prepare `params` for creating a model instance based on the given\n        kwargs; for use by get_or_create().\n        \"\"\"\n        defaults = defaults or {}\n        params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}\n        params.update(defaults)\n        property_names = self.model._meta._property_names\n        invalid_params = []\n        for param in params:\n            try:\n                self.model._meta.get_field(param)\n            except exceptions.FieldDoesNotExist:\n                # It's okay to use a model's property if it has a setter.\n                if not (param in property_names and getattr(self.model, param).fset):\n                    invalid_params.append(param)\n        if invalid_params:\n            raise exceptions.FieldError(                 \"Invalid field name(s) for model %s: '%s'.\"\n                % (\n                    self.model._meta.object_name,\n                    \"', '\".join(sorted(invalid_params)),\n                )             )\n        return params\n    def _earliest(self, *fields):\n        \"\"\"\n        Return the earliest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if fields:\n            order_by = fields\n        else:\n            order_by = getattr(self.model._meta, \"get_latest_by\")\n            if order_by and not isinstance(order_by, (tuple, list)):\n                order_by = (order_by,)\n        if order_by is None:\n            raise ValueError(\n                \"earliest() and latest() require either fields as positional \"\n                \"arguments or 'get_latest_by' in the model's Meta.\"\n            )\n        obj = self._chain()\n        obj.query.set_limits(high=1)\n        obj.query.clear_ordering(force=True)\n        obj.query.add_ordering(*order_by)\n        return obj.get()\n    def earliest(self, *fields):\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self._earliest(*fields)\n\n    async def aearliest(self, *fields):\n        return await sync_to_async(self.earliest)(*fields)\n\n    def latest(self, *fields):\n        \"\"\"\n        Return the latest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.reverse()._earliest(*fields)\n\n    async def alatest(self, *fields):\n        return await sync_to_async(self.latest)(*fields)\n\n    def first(self):\n        \"\"\"Return the first object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"first\")\n            queryset = self.order_by(\"pk\")\n        for obj in queryset[:1]:\n            return obj\n    async def afirst(self):\n        return await sync_to_async(self.first)()\n\n    def last(self):\n        \"\"\"Return the last object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self.reverse()\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"last\")\n            queryset = self.order_by(\"-pk\")\n        for obj in queryset[:1]:\n            return obj\n\n    async def alast(self):\n        return await sync_to_async(self.last)()\n    def in_bulk(self, id_list=None, *, field_name=\"pk\"):\n        \"\"\"\n        Return a dictionary mapping each of the given IDs to the object with\n        that ID. If `id_list` isn't provided, evaluate the entire QuerySet.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with in_bulk().\")\n        if id_list is not None and not id_list:\n            return {}\n        opts = self.model._meta\n        unique_fields = [             constraint.fields[0]             for constraint in opts.total_unique_constraints\n            if len(constraint.fields) == 1\n        ]\n        if (\n            field_name != \"pk\"\n            and not opts.get_field(field_name).unique\n            and field_name not in unique_fields             and self.query.distinct_fields != (field_name,)\n        ):\n            raise ValueError(\n                \"in_bulk()'s field_name must be a unique field but %r isn't.\"\n                % field_name\n            )\n\n        qs = self\n        def get_obj(obj):\n            return obj\n        if issubclass(self._iterable_class, ModelIterable):\n            # Raise an AttributeError if field_name is deferred.\n            get_key = operator.attrgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesIterable):\n            if field_name not in self.query.values_select:\n                qs = qs.values(field_name, *self.query.values_select)\n                def get_obj(obj):  # noqa: F811\n                    # We can safely mutate the dictionaries returned by\n                    # ValuesIterable here, since they are limited to the scope\n                    # of this function, and get_key runs before get_obj.\n                    del obj[field_name]\n                    return obj\n\n            get_key = operator.itemgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesListIterable):\n            try:\n                field_index = self.query.values_select.index(field_name)\n            except ValueError:\n                # field_name is missing from values_select, so add it.\n                field_index = 0\n                if issubclass(self._iterable_class, NamedValuesListIterable):\n                    kwargs = {\"named\": True}\n                else:\n                    kwargs = {}\n                    get_obj = operator.itemgetter(slice(1, None))\n                qs = qs.values_list(field_name, *self.query.values_select, **kwargs)\n\n            get_key = operator.itemgetter(field_index)\n\n        elif issubclass(self._iterable_class, FlatValuesListIterable):\n            if self.query.values_select == (field_name,):\n                # Mapping field_name to itself.\n                get_key = get_obj\n            else:\n                # Transform it back into a non-flat values_list().\n                qs = qs.values_list(field_name, *self.query.values_select)\n                get_key = operator.itemgetter(0)\n                get_obj = operator.itemgetter(1)\n        else:\n            raise TypeError(                 f\"in_bulk() cannot be used with {self._iterable_class.__name__}.\"             )\n        if id_list is not None:\n            filter_key = \"{}__in\".format(field_name)\n            id_list = tuple(id_list)\n            batch_size = connections[self.db].ops.bulk_batch_size([opts.pk], id_list)\n            # If the database has a limit on the number of query parameters\n            # (e.g. SQLite), retrieve objects in batches if necessary.\n            if batch_size and batch_size < len(id_list):\n                results = ()\n                for offset in range(0, len(id_list), batch_size):\n                    batch = id_list[offset : offset + batch_size]\n                    results += tuple(qs.filter(**{filter_key: batch}))\n                qs = results\n            else:\n                qs = qs.filter(**{filter_key: id_list})\n        else:\n            qs = qs._chain()\n        return {get_key(obj): get_obj(obj) for obj in qs}\n\n    async def ain_bulk(self, id_list=None, *, field_name=\"pk\"):\n        return await sync_to_async(self.in_bulk)(             id_list=id_list,             field_name=field_name,\n        )\n    def delete(self):\n        \"\"\"Delete the records in the current QuerySet.\"\"\"\n        self._not_support_combined_queries(\"delete\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with delete().\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call delete() after .distinct(*fields).\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call delete() after .values() or .values_list()\")\n\n        del_query = self._chain()\n        # The delete is actually 2 queries - one to find related objects,\n        # and one to delete. Make sure that the discovery of related\n        # objects is performed on the same database as the deletion.\n        del_query._for_write = True\n\n        # Disable non-supported fields.\n        del_query.query.select_for_update = False\n        del_query.query.select_related = False\n        del_query.query.clear_ordering(force=True)\n        collector = Collector(using=del_query.db, origin=self)\n        collector.collect(del_query)\n        num_deleted, num_deleted_per_model = collector.delete()\n\n        # Clear the result cache, in case this QuerySet gets reused.\n        self._result_cache = None\n        return num_deleted, num_deleted_per_model\n\n    delete.alters_data = True\n    delete.queryset_only = True\n\n    async def adelete(self):\n        return await sync_to_async(self.delete)()\n\n    adelete.alters_data = True\n    adelete.queryset_only = True\n    def _raw_delete(self, using):\n        \"\"\"\n        Delete objects found from the given queryset in single direct SQL\n        query. No signals are sent and there is no protection for cascades.\n        \"\"\"\n        query = self.query.clone()\n        query.__class__ = sql.DeleteQuery\n        return query.get_compiler(using).execute_sql(ROW_COUNT)\n\n    _raw_delete.alters_data = True\n    def update(self, **kwargs):\n        \"\"\"\n        Update all elements in the current QuerySet, setting all the given\n        fields to the appropriate values.\n        \"\"\"\n        self._not_support_combined_queries(\"update\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call update() after .distinct(*fields).\")\n        self._for_write = True\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_values(kwargs)\n        # Inline annotations in order_by(), if possible.\n        new_order_by = []\n        for col in query.order_by:\n            alias = col\n            descending = False\n            if isinstance(alias, str) and alias.startswith(\"-\"):\n                alias = alias.removeprefix(\"-\")\n                descending = True\n            if annotation := query.annotations.get(alias):\n                if getattr(annotation, \"contains_aggregate\", False):\n                    raise exceptions.FieldError(\n                        f\"Cannot update when ordering by an aggregate: {annotation}\"                     )\n                if descending:\n                    annotation = annotation.desc()\n                new_order_by.append(annotation)\n            else:\n                new_order_by.append(col)\n        query.order_by = tuple(new_order_by)\n        # Clear SELECT clause as all annotation references were inlined by\n        # add_update_values() already.\n        query.clear_select_clause()\n        with transaction.mark_for_rollback_on_error(using=self.db):\n            rows = query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        self._result_cache = None\n        return rows\n\n    update.alters_data = True\n\n    async def aupdate(self, **kwargs):\n        return await sync_to_async(self.update)(**kwargs)\n\n    aupdate.alters_data = True\n\n    def _update(self, values, returning_fields=None):\n        \"\"\"\n        A version of update() that accepts field objects instead of field\n        names. Used primarily for model saving and not intended for use by\n        general code (it requires too much poking around at model internals to\n        be useful at that level).\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_fields(values)\n        # Clear any annotations so that they won't be present in subqueries.\n        query.annotations = {}\n        self._result_cache = None\n        if returning_fields is None:\n            return query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        return query.get_compiler(self.db).execute_returning_sql(returning_fields)\n\n    _update.alters_data = True\n    _update.queryset_only = False\n    def exists(self):\n        \"\"\"\n        Return True if the QuerySet would have any results, False otherwise.\n        \"\"\"\n        if self._result_cache is None:\n            return self.query.has_results(using=self.db)\n        return bool(self._result_cache)\n\n    async def aexists(self):\n        return await sync_to_async(self.exists)()\n    def contains(self, obj):\n        \"\"\"\n        Return True if the QuerySet contains the provided obj,\n        False otherwise.\n        \"\"\"\n        self._not_support_combined_queries(\"contains\")\n        if self._fields is not None:\n            raise TypeError(                 \"Cannot call QuerySet.contains() after .values() or .values_list().\"             )\n        try:\n            if obj._meta.concrete_model != self.model._meta.concrete_model:\n                return False\n        except AttributeError:\n            raise TypeError(\"'obj' must be a model instance.\")\n        if not obj._is_pk_set():\n            raise ValueError(\"QuerySet.contains() cannot be used on unsaved objects.\")\n        if self._result_cache is not None:\n            return obj in self._result_cache\n        return self.filter(pk=obj.pk).exists()\n\n    async def acontains(self, obj):\n        return await sync_to_async(self.contains)(obj=obj)\n\n    def _prefetch_related_objects(self):\n        # This method can only be called once the result cache has been filled.\n        prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)\n        self._prefetch_done = True\n\n    def explain(self, *, format=None, **options):\n        \"\"\"\n        Runs an EXPLAIN on the SQL query this QuerySet would perform, and\n        returns the results.\n        \"\"\"\n        return self.query.explain(using=self.db, format=format, **options)\n    async def aexplain(self, *, format=None, **options):\n        return await sync_to_async(self.explain)(format=format, **options)\n\n    ##################################################\n    # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #\n    ##################################################\n\n    def raw(self, raw_query, params=(), translations=None, using=None):\n        if using is None:\n            using = self.db\n        qs = RawQuerySet(\n            raw_query,\n            model=self.model,             params=params,             translations=translations,             using=using,\n            fetch_mode=self._fetch_mode,\n        )\n        qs._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        return qs\n    def _values(self, *fields, **expressions):\n        clone = self._chain()\n        if expressions:\n            # RemovedInDjango70Warning: When the deprecation ends, deindent as:\n            # clone = clone.annotate(**expressions)\n            with warnings.catch_warnings(\n                action=\"ignore\", category=RemovedInDjango70Warning             ):\n                clone = clone.annotate(**expressions)\n        clone._fields = fields\n        clone.query.set_values(fields)\n        return clone\n\n    def values(self, *fields, **expressions):\n        fields += tuple(expressions)\n        clone = self._values(*fields, **expressions)\n        clone._iterable_class = ValuesIterable\n        return clone\n\n    def values_list(self, *fields, flat=False, named=False):\n        if flat and named:\n            raise TypeError(\"'flat' and 'named' can't be used together.\")\n        if flat:\n            if len(fields) > 1:\n                raise TypeError(                     \"'flat' is not valid when values_list is called with more than one \"                     \"field.\"                 )\n            elif not fields:\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # raise TypeError(\n                #     \"'flat' is not valid when values_list is called with no \"\n                #     \"fields.\"\n                # )\n                warnings.warn(                     \"Calling values_list() with no field name and flat=True \"\n                    \"is deprecated. Pass an explicit field name instead, like \"\n                    \"'pk'.\",\n                    RemovedInDjango70Warning,\n                )\n                fields = [self.model._meta.concrete_fields[0].attname]\n        field_names = {f: False for f in fields if not hasattr(f, \"resolve_expression\")}\n        _fields = []\n        expressions = {}\n        counter = 1\n        for field in fields:\n            field_name = field\n            expression = None\n            if hasattr(field, \"resolve_expression\"):\n                field_name = getattr(                     field, \"default_alias\", field.__class__.__name__.lower()\n                )\n                expression = field\n                # For backward compatibility reasons expressions are always\n                # prefixed with the counter even if their default alias doesn't\n                # collide with field names. Changing this logic could break\n                # some usage of named=True.\n                seen = True\n            elif seen := field_names[field_name]:\n                expression = F(field_name)\n            if seen:\n                field_name_prefix = field_name\n                while (field_name := f\"{field_name_prefix}{counter}\") in field_names:\n                    counter += 1\n            if expression is not None:\n                expressions[field_name] = expression\n            field_names[field_name] = True\n            _fields.append(field_name)\n        clone = self._values(*_fields, **expressions)\n        clone._iterable_class = (             NamedValuesListIterable\n            if named\n            else FlatValuesListIterable if flat else ValuesListIterable         )\n        return clone\n\n    def dates(self, field_name, kind, order=\"ASC\"):\n        \"\"\"\n        Return a list of date objects representing all available dates for\n        the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\"):\n            raise ValueError(\"'kind' must be one of 'year', 'month', 'week', or 'day'.\")\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        return (\n            self.annotate(                 datefield=Trunc(field_name, kind, output_field=DateField()),\n                plain_field=F(field_name),             )\n            .values_list(\"datefield\", flat=True)\n            .distinct()             .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datefield\")         )\n    def datetimes(self, field_name, kind, order=\"ASC\", tzinfo=None):\n        \"\"\"\n        Return a list of datetime objects representing all available\n        datetimes for the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"):\n            raise ValueError(\n                \"'kind' must be one of 'year', 'month', 'week', 'day', \"\n                \"'hour', 'minute', or 'second'.\"\n            )\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        if settings.USE_TZ:\n            if tzinfo is None:\n                tzinfo = timezone.get_current_timezone()\n        else:\n            tzinfo = None\n        return (\n            self.annotate(                 datetimefield=Trunc(\n                    field_name,                     kind,\n                    output_field=DateTimeField(),\n                    tzinfo=tzinfo,\n                ),                 plain_field=F(field_name),             )\n            .values_list(\"datetimefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datetimefield\")\n        )\n\n    def none(self):\n        \"\"\"Return an empty QuerySet.\"\"\"\n        clone = self._chain()\n        clone.query.set_empty()\n        return clone\n    ##################################################################\n    # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #\n    ##################################################################\n\n    def all(self):\n        \"\"\"\n        Return a new QuerySet that is a copy of the current one. This allows a\n        QuerySet to proxy for a model manager in some cases.\n        \"\"\"\n        return self._chain()\n    def filter(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with the args ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"filter\")\n        return self._filter_or_exclude(False, args, kwargs)\n\n    def exclude(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with NOT (args) ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"exclude\")\n        return self._filter_or_exclude(True, args, kwargs)\n\n    def _filter_or_exclude(self, negate, args, kwargs):\n        if (args or kwargs) and self.query.is_sliced:\n            raise TypeError(\"Cannot filter a query once a slice has been taken.\")\n        clone = self._chain()\n        if self._defer_next_filter:\n            self._defer_next_filter = False\n            clone._deferred_filter = negate, args, kwargs\n        else:\n            clone._filter_or_exclude_inplace(negate, args, kwargs)\n        return clone\n    def _filter_or_exclude_inplace(self, negate, args, kwargs):\n        if invalid_kwargs := PROHIBITED_FILTER_KWARGS.intersection(kwargs):\n            invalid_kwargs_str = \", \".join(f\"'{k}'\" for k in sorted(invalid_kwargs))\n            raise TypeError(f\"The following kwargs are invalid: {invalid_kwargs_str}\")\n        if negate:\n            self._query.add_q(~Q(*args, **kwargs))\n        else:\n            self._query.add_q(Q(*args, **kwargs))\n\n    def complex_filter(self, filter_obj):\n        \"\"\"\n        Return a new QuerySet instance with filter_obj added to the filters.\n        filter_obj can be a Q object or a dictionary of keyword lookup\n        arguments.\n        This exists to support framework features such as 'limit_choices_to',\n        and usually it will be more natural to use other methods.\n        \"\"\"\n        if isinstance(filter_obj, Q):\n            clone = self._chain()\n            clone.query.add_q(filter_obj)\n            return clone\n        else:\n            return self._filter_or_exclude(False, args=(), kwargs=filter_obj)\n\n    def _combinator_query(self, combinator, *other_qs, all=False):\n        # Clone the query to inherit the select list and everything\n        clone = self._chain()\n        # Clear limits and ordering so they can be reapplied\n        clone.query.clear_ordering(force=True)\n        clone.query.default_ordering = True\n        self._clear_ordering_in_combined_queries(clone.query, other_qs)\n        clone.query.clear_limits()\n        clone.query.combinator = combinator\n        clone.query.combinator_all = all\n        return clone\n\n    def union(self, *other_qs, all=False):\n        # If the query is an EmptyQuerySet, combine all nonempty querysets.\n        if isinstance(self, EmptyQuerySet):\n            qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)]\n            if not qs:\n                return self\n            if len(qs) == 1:\n                return qs[0]\n            return qs[0]._combinator_query(\"union\", *qs[1:], all=all)\n        elif not other_qs:\n            return self\n        return self._combinator_query(\"union\", *other_qs, all=all)\n\n    def intersection(self, *other_qs):\n        # If any query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        for other in other_qs:\n            if isinstance(other, EmptyQuerySet):\n                return other\n        return self._combinator_query(\"intersection\", *other_qs)\n\n    def difference(self, *other_qs):\n        # If the query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        return self._combinator_query(\"difference\", *other_qs)\n\n    def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False):\n        \"\"\"\n        Return a new QuerySet instance that will select objects with a\n        FOR UPDATE lock.\n        \"\"\"\n        if nowait and skip_locked:\n            raise ValueError(\"The nowait option cannot be used with skip_locked.\")\n        obj = self._chain()\n        obj._for_write = True\n        obj.query.select_for_update = True\n        obj.query.select_for_update_nowait = nowait\n        obj.query.select_for_update_skip_locked = skip_locked\n        obj.query.select_for_update_of = of\n        obj.query.select_for_no_key_update = no_key\n        return obj\n\n    def select_related(self, *fields):\n        \"\"\"\n        Return a new QuerySet instance that will select related objects.\n        If fields are specified, they must be ForeignKey fields and only those\n        related objects are included in the selection.\n\n        If select_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"select_related\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call select_related() after .values() or .values_list()\"             )\n        obj = self._chain()\n        if fields == (None,):\n            obj.query.select_related = False\n        elif fields:\n            obj.query.add_select_related(fields)\n        else:\n            # RemovedInDjango70Warning: when the deprecation ends, raise a\n            # TypeError instead.\n            warn_about_external_use(\n                \"Calling select_related() with no arguments is deprecated. \"                 \"Specify the fields to fetch instead.\",\n                category=RemovedInDjango70Warning,\n                skip_name_prefixes=(\"django.db.models\",),             )\n            obj.query.select_related = True\n        return obj\n\n    def prefetch_related(self, *lookups):\n        \"\"\"\n        Return a new QuerySet instance that will prefetch the specified\n        Many-To-One and Many-To-Many related objects when the QuerySet is\n        evaluated.\n\n        When prefetch_related() is called more than once, append to the list of\n        prefetch lookups. If prefetch_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"prefetch_related\")\n        clone = self._chain()\n        if lookups == (None,):\n            clone._prefetch_related_lookups = ()\n        else:\n            for lookup in lookups:\n                if isinstance(lookup, Prefetch):\n                    lookup = lookup.prefetch_to\n                lookup = lookup.split(LOOKUP_SEP, 1)[0]\n                if lookup in self.query._filtered_relations:\n                    raise ValueError(\n                        \"prefetch_related() is not supported with FilteredRelation.\"                     )\n            clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups\n        return clone\n\n    def annotate(self, *args, **kwargs):\n        \"\"\"\n        Return a query set in which the returned objects have been annotated\n        with extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"annotate\")\n        return self._annotate(args, kwargs, select=True)\n\n    def alias(self, *args, **kwargs):\n        \"\"\"\n        Return a query set with added aliases for extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"alias\")\n        return self._annotate(args, kwargs, select=False)\n    def _annotate(self, args, kwargs, select=True):\n        self._validate_values_are_expressions(\n            args + tuple(kwargs.values()), method_name=\"annotate\"         )\n        annotations = {}\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                if arg.default_alias in kwargs:\n                    raise ValueError(\n                        \"The named annotation '%s' conflicts with the \"\n                        \"default name for another annotation.\" % arg.default_alias\n                    )\n            except (TypeError, AttributeError):\n                raise TypeError(\"Complex annotations require an alias\")\n            annotations[arg.default_alias] = arg\n        annotations.update(kwargs)\n\n        clone = self._chain()\n        names = self._fields\n        if names is None:\n            names = set(\n                chain.from_iterable(\n                    (\n                        (field.name, field.attname)\n                        if hasattr(field, \"attname\")                         else (field.name,)\n                    )\n                    for field in self.model._meta.get_fields()\n                )\n            )\n\n        for alias, annotation in annotations.items():\n            if alias in names:\n                raise ValueError(\n                    \"The annotation '%s' conflicts with a field on \"                     \"the model.\" % alias\n                )\n            if isinstance(annotation, FilteredRelation):\n                clone.query.add_filtered_relation(annotation, alias)\n            else:\n                clone.query.add_annotation(\n                    annotation,\n                    alias,\n                    select=select,\n                )\n        for alias, annotation in clone.query.annotations.items():\n            if alias in annotations and annotation.contains_aggregate:\n                if clone._fields is None:\n                    clone.query.group_by = True\n                else:\n                    clone.query.set_group_by()\n                break\n\n        return clone\n\n    def order_by(self, *field_names):\n        \"\"\"Return a new QuerySet instance with the ordering changed.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reorder a query once a slice has been taken.\")\n        obj = self._chain()\n        obj.query.clear_ordering(force=True, clear_default=False)\n        obj.query.add_ordering(*field_names)\n        return obj\n\n    def distinct(self, *field_names):\n        \"\"\"\n        Return a new QuerySet instance that will select only distinct results.\n        \"\"\"\n        self._not_support_combined_queries(\"distinct\")\n        if self.query.is_sliced:\n            raise TypeError(                 \"Cannot create distinct fields once a slice has been taken.\"\n            )\n        obj = self._chain()\n        obj.query.add_distinct_fields(*field_names)\n        return obj\n\n    def extra(         self,\n        select=None,\n        where=None,\n        params=None,         tables=None,\n        order_by=None,\n        select_params=None,     ):\n        \"\"\"Add extra SQL fragments to the query.\"\"\"\n        self._not_support_combined_queries(\"extra\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.add_extra(select, select_params, where, params, tables, order_by)\n        return clone\n\n    def reverse(self):\n        \"\"\"Reverse the ordering of the QuerySet.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reverse a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.standard_ordering = not clone.query.standard_ordering\n        return clone\n\n    def defer(self, *fields):\n        \"\"\"\n        Defer the loading of data for certain fields until they are accessed.\n        Add the set of deferred fields to any existing set of deferred fields.\n        The only exception to this is if None is passed in as the only\n        parameter, in which case remove all deferrals.\n        \"\"\"\n        self._not_support_combined_queries(\"defer\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call defer() after .values() or .values_list()\")\n        clone = self._chain()\n        if fields == (None,):\n            clone.query.clear_deferred_loading()\n        else:\n            clone.query.add_deferred_loading(fields)\n        return clone\n    def only(self, *fields):\n        \"\"\"\n        Essentially, the opposite of defer(). Only the fields passed into this\n        method and that are not already specified as deferred are loaded\n        immediately when the queryset is evaluated.\n        \"\"\"\n        self._not_support_combined_queries(\"only\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call only() after .values() or .values_list()\")\n        if fields == (None,):\n            # Can only pass None to defer(), not only(), as the rest option.\n            # That won't stop people trying to do this, so let's be explicit.\n            raise TypeError(\"Cannot pass None as an argument to only().\")\n        for field in fields:\n            field = field.split(LOOKUP_SEP, 1)[0]\n            if field in self.query._filtered_relations:\n                raise ValueError(\"only() is not supported with FilteredRelation.\")\n        clone = self._chain()\n        clone.query.add_immediate_loading(fields)\n        return clone\n    def using(self, alias):\n        \"\"\"Select which database this QuerySet should execute against.\"\"\"\n        clone = self._chain()\n        clone._db = alias\n        return clone\n\n    def fetch_mode(self, fetch_mode):\n        \"\"\"Set the fetch mode for the QuerySet.\"\"\"\n        clone = self._chain()\n        clone._fetch_mode = fetch_mode\n        return clone\n\n    ###################################\n    # PUBLIC INTROSPECTION ATTRIBUTES #\n    ###################################\n    @property\n    def ordered(self):\n        \"\"\"\n        Return True if the QuerySet is ordered -- i.e. has an order_by()\n        clause or a default ordering on the model (or is empty).\n        \"\"\"\n        if isinstance(self, EmptyQuerySet):\n            return True\n        if self.query.extra_order_by or self.query.order_by:\n            return True\n        elif (\n            self.query.default_ordering             and self.query.get_meta().ordering             and             # A default ordering doesn't affect GROUP BY queries.\n            not self.query.group_by\n        ):\n            return True\n        else:\n            return False\n    @property\n    def totally_ordered(self):\n        \"\"\"\n        Returns True if the QuerySet is ordered and the ordering is\n        deterministic. This requires that the ordering includes a field\n        (or set of fields) that is unique and non-nullable.\n\n        For queries involving a GROUP BY clause, the model's default\n        ordering is ignored. Ordering specified via .extra(order_by=...)\n        is also ignored.\n        \"\"\"\n        if not self.ordered:\n            return False\n        ordering = self.query.order_by\n        if not ordering and self.query.default_ordering:\n            ordering = self.query.get_meta().ordering\n        if not ordering:\n            return False\n        opts = self.model._meta\n        pk_fields = {f.attname for f in opts.pk_fields}\n        candidate_fields = set()\n        for part in ordering:\n            # Search for single field providing a total ordering.\n            field_name = None\n            if isinstance(part, str):\n                field_name = part.lstrip(\"-\")\n            elif isinstance(part, F):\n                field_name = part.name\n            elif isinstance(part, OrderBy) and isinstance(part.expression, F):\n                field_name = part.expression.name\n            if annotation_col := self.query.annotations.get(field_name):\n                if isinstance(annotation_col, Col):\n                    if annotation_col.alias == self.query.base_table:\n                        candidate_fields.add(annotation_col.target)\n                elif isinstance(annotation_col, ColPairs):\n                    candidate_fields |= {                         c.target\n                        for c in annotation_col.get_cols()                         if c.alias == self.query.base_table\n                    }\n            elif field_name:\n                if field_name == \"pk\":\n                    return True\n                # Normalize attname references by using get_field().\n                try:\n                    field = opts.get_field(field_name)\n                except exceptions.FieldDoesNotExist:\n                    # Could be \"?\" for random ordering or a related field\n                    # lookup. Skip this part of introspection for now.\n                    continue\n                else:\n                    # Ordering by a related field name orders by the referenced\n                    # model's ordering. Skip this introspection for now.\n                    if field.remote_field and field_name == field.name:\n                        continue\n                    candidate_fields.add(field)\n\n        candidate_attnames = set()\n        for field in candidate_fields:\n            if field.unique and not field.null:\n                return True\n            candidate_attnames.add(field.attname)\n\n        # Account for members of a CompositePrimaryKey.\n        if candidate_attnames.issuperset(pk_fields):\n            return True\n        # No single total ordering field, try unique_together and total\n        # unique constraints.\n        constraint_field_names = (\n            *opts.unique_together,\n            *(constraint.fields for constraint in opts.total_unique_constraints),         )\n        for field_names in constraint_field_names:\n            # Normalize attname references by using get_field().\n            try:\n                fields = [opts.get_field(field_name) for field_name in field_names]\n            except exceptions.FieldDoesNotExist:\n                continue\n            # Composite unique constraints containing a nullable column\n            # cannot ensure total ordering.\n            if any(field.null for field in fields):\n                continue\n            if candidate_attnames.issuperset(field.attname for field in fields):\n                return True\n\n        return False\n    @property\n    def db(self):\n        \"\"\"Return the database used if this query is executed now.\"\"\"\n        if self._for_write:\n            return self._db or router.db_for_write(self.model, **self._hints)\n        return self._db or router.db_for_read(self.model, **self._hints)\n\n    ###################\n    # PRIVATE METHODS #\n    ###################\n\n    def _insert(         self,         objs,         fields,         returning_fields=None,\n        raw=False,         using=None,\n        on_conflict=None,         update_fields=None,         unique_fields=None,\n    ):\n        \"\"\"\n        Insert a new record for the given model. This provides an interface to\n        the InsertQuery class and is how Model.save() is implemented.\n        \"\"\"\n        self._for_write = True\n        if using is None:\n            using = self.db\n        query = sql.InsertQuery(             self.model,\n            on_conflict=on_conflict,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n        query.insert_values(fields, objs, raw=raw)\n        return query.get_compiler(using=using).execute_sql(returning_fields)\n    _insert.alters_data = True\n    _insert.queryset_only = False\n\n    def _batched_insert(         self,\n        objs,\n        fields,\n        batch_size,         on_conflict=None,\n        update_fields=None,         unique_fields=None,\n    ):\n        \"\"\"\n        Helper method for bulk_create() to insert objs one batch at a time.\n        \"\"\"\n        connection = connections[self.db]\n        ops = connection.ops\n        max_batch_size = max(ops.bulk_batch_size(fields, objs), 1)\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        inserted_rows = []\n        returning_fields = (             self.model._meta.db_returning_fields\n            if (                 connection.features.can_return_rows_from_bulk_insert                 and (on_conflict is None or on_conflict == OnConflict.UPDATE)\n            )\n            else None         )\n        batches = [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]\n        if len(batches) > 1:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            for item in batches:\n                inserted_rows.extend(                     self._insert(\n                        item,                         fields=fields,                         using=self.db,\n                        on_conflict=on_conflict,\n                        update_fields=update_fields,\n                        unique_fields=unique_fields,\n                        returning_fields=returning_fields,\n                    )                 )\n        return inserted_rows\n\n    def _disable_cloning(self):\n        \"\"\"\n        Prevent calls to _chain() from creating a new QuerySet via _clone().\n        All subsequent QuerySet mutations will occur on this instance until\n        _enable_cloning() is used.\n        \"\"\"\n        self._cloning_enabled = False\n        return self\n\n    def _enable_cloning(self):\n        \"\"\"\n        Allow calls to _chain() to create a new QuerySet via _clone(). Restores\n        the default behavior where any QuerySet mutation will return a new\n        QuerySet instance. Necessary only when there has been a\n        _disable_cloning() call previously.\n        \"\"\"\n        self._cloning_enabled = True\n        return self\n\n    def _avoid_cloning(self):\n        \"\"\"\n        Temporarily prevent QuerySet _clone() operations, restoring the default\n        behavior on exit. For the duration of the context managed statement,\n        all operations (e.g. filter(), exclude(), etc.) will mutate the same\n        QuerySet instance.\n\n        @contextlib.contextmanager is intentionally not used for performance\n        reasons.\n        \"\"\"\n        return PreventQuerySetCloning(self)\n\n    def _chain(self):\n        \"\"\"\n        Return a copy of the current QuerySet that's ready for another\n        operation.\n        If the QuerySet has opted in to in-place mutations via\n        _disable_cloning() temporarily, the copy doesn't occur and instead the\n        same QuerySet instance will be modified.\n        \"\"\"\n        if not self._cloning_enabled:\n            obj = self\n        else:\n            obj = self._clone()\n        if obj._sticky_filter:\n            obj.query.filter_is_sticky = True\n            obj._sticky_filter = False\n        return obj\n    def _clone(self):\n        \"\"\"\n        Return a copy of the current QuerySet. A lightweight alternative\n        to deepcopy().\n        \"\"\"\n        c = self.__class__(\n            model=self.model,\n            query=self.query.chain(),\n            using=self._db,             hints=self._hints,\n        )\n        c._sticky_filter = self._sticky_filter\n        c._for_write = self._for_write\n        c._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        c._known_related_objects = self._known_related_objects\n        c._iterable_class = self._iterable_class\n        c._fetch_mode = self._fetch_mode\n        c._fields = self._fields\n        return c\n    def _fetch_all(self):\n        if self._result_cache is None:\n            self._result_cache = list(self._iterable_class(self))\n        if self._prefetch_related_lookups and not self._prefetch_done:\n            self._prefetch_related_objects()\n    def _next_is_sticky(self):\n        \"\"\"\n        Indicate that the next filter call and the one following that should\n        be treated as a single filter. This is only important when it comes to\n        determining when to reuse tables for many-to-many filters. Required so\n        that we can filter naturally on the results of related managers.\n        This doesn't return a clone of the current QuerySet (it returns\n        \"self\"). The method is only used internally and should be immediately\n        followed by a filter() that does create a clone.\n        \"\"\"\n        self._sticky_filter = True\n        return self\n    def _merge_sanity_check(self, other):\n        \"\"\"Check that two QuerySet classes may be merged.\"\"\"\n        if self._fields is not None and (             set(self.query.values_select) != set(other.query.values_select)\n            or set(self.query.extra_select) != set(other.query.extra_select)\n            or set(self.query.annotation_select) != set(other.query.annotation_select)         ):\n            raise TypeError(\n                \"Merging '%s' classes must involve the same values in each case.\"\n                % self.__class__.__name__             )\n    def _merge_known_related_objects(self, other):\n        \"\"\"\n        Keep track of all known related objects from either QuerySet instance.\n        \"\"\"\n        for field, objects in other._known_related_objects.items():\n            self._known_related_objects.setdefault(field, {}).update(objects)\n\n    def resolve_expression(self, *args, **kwargs):\n        query = self.query.resolve_expression(*args, **kwargs)\n        query._db = self._db\n        return query\n    resolve_expression.queryset_only = True\n\n    def _add_hints(self, **hints):\n        \"\"\"\n        Update hinting information for use by routers. Add new key/values or\n        overwrite existing key/values.\n        \"\"\"\n        self._hints.update(hints)\n\n    def _has_filters(self):\n        \"\"\"\n        Check if this QuerySet has any filtering going on. This isn't\n        equivalent with checking if all objects are present in results, for\n        example, qs[1:]._has_filters() -> False.\n        \"\"\"\n        return self.query.has_filters()\n\n    @staticmethod\n    def _validate_values_are_expressions(values, method_name):\n        invalid_args = sorted(             str(arg) for arg in values if not hasattr(arg, \"resolve_expression\")\n        )\n        if invalid_args:\n            raise TypeError(\n                \"QuerySet.%s() received non-expression(s): %s.\"                 % (                     method_name,                     \", \".join(invalid_args),\n                )             )\n    def _not_support_combined_queries(self, operation_name):\n        if self.query.combinator:\n            raise NotSupportedError(\n                \"Calling QuerySet.%s() after %s() is not supported.\"                 % (operation_name, self.query.combinator)             )\n    def _check_operator_queryset(self, other, operator_):\n        if self.query.combinator or other.query.combinator:\n            raise TypeError(f\"Cannot use {operator_} operator with combined queryset.\")\n\n    def _check_ordering_first_last_queryset_aggregation(self, method):\n        if (\n            isinstance(self.query.group_by, tuple)\n            # Raise if the pk fields are not in the group_by.\n            and self.model._meta.pk\n            not in {col.output_field for col in self.query.group_by}\n            and set(self.model._meta.pk_fields).difference(\n                {col.target for col in self.query.group_by}\n            )         ):\n            raise TypeError(                 f\"Cannot use QuerySet.{method}() on an unordered queryset performing \"                 f\"aggregation. Add an ordering with order_by().\"             )\n\n    def _clear_ordering_in_combined_queries(self, cloned_query, other_qs):\n        combined_queries = [self.query]\n        for qs in other_qs:\n            query = qs.query.clone()\n            query.clear_ordering(force=False, clear_default=False)\n            combined_queries.append(query)\n        cloned_query.combined_queries = tuple(combined_queries)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-765e7606ef75a519", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "e10babec07177b527b350d932ca0bce81b80eddc77c43cba8f0f4534b4ce2f2d", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 1863, "local_path": "layout/partially-compact-layout/I10__django__QuerySet__6ab8475f.py", "order": 10, "original_content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "parent_variant_id": "pyint-5c2b55814568-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/query.py#L374-L2424", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 598, "line_break_groups_removed": 239, "line_breaks_removed": 239, "whitespace_characters_removed": 76}, "unit_kind": "class", "unit_name": "QuerySet", "variant_id": "pyint-9c296ab8475f-I10", "group_id": "py-765e7606ef75a519", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 235, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-182e909bc25b-I11", "source": "import copy\nimport operator\nimport warnings\nfrom contextlib import nullcontext\nfrom functools import partial, reduce\nfrom itertools import chain, islice\nfrom weakref import ref as weak_ref\nfrom asgiref.sync import sync_to_async\nimport django\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.db import (\n    DJANGO_VERSION_PICKLE_KEY,\n    IntegrityError,\n    NotSupportedError,\n    connections,\n    router,\n    transaction,\n)\nfrom django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql\nfrom django.db.models.constants import LOOKUP_SEP, OnConflict\nfrom django.db.models.deletion import Collector\nfrom django.db.models.expressions import (\n    Case,\n    Col,\n    ColPairs,\n    DatabaseDefault,\n    F,\n    OrderBy,\n    Value,\n    When,\n)\nfrom django.db.models.fetch_modes import FETCH_ONE\nfrom django.db.models.functions import Cast, Trunc\nfrom django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q\nfrom django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT\nfrom django.db.models.utils import (\n    AltersData,\n    create_namedtuple_class,\n    resolve_callables,\n)\nfrom django.utils import timezone\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    RemovedInDjango71Warning,\n    warn_about_external_use,\n)\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import func_accepts_kwargs, func_supports_parameter\nfrom django.utils.warnings import django_file_prefixes\n\nclass QuerySet(AltersData):\n    \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n    def __init__(self, model=None, query=None, using=None, hints=None):\n        self.model = model\n        self._db = using\n        self._hints = hints or {}\n        self._query = query or sql.Query(self.model)\n        self._result_cache = None\n        self._sticky_filter = False\n        self._for_write = False\n        self._prefetch_related_lookups = ()\n        self._prefetch_done = False\n        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}\n        self._iterable_class = ModelIterable\n        self._fetch_mode = DEFAULT_FETCH_MODE\n        self._fields = None\n        self._defer_next_filter = False\n        self._deferred_filter = None\n        self._cloning_enabled = True\n\n    @property\n    def query(self):\n        if self._deferred_filter:\n            negate, args, kwargs = self._deferred_filter\n            self._filter_or_exclude_inplace(negate, args, kwargs)\n            self._deferred_filter = None\n        return self._query\n\n    @query.setter\n    def query(self, value):\n        if value.values_select:\n            self._iterable_class = ValuesIterable\n        self._query = value\n\n    def as_manager(cls):\n        # Address the circular dependency between `Queryset` and `Manager`.\n        from django.db.models.manager import Manager\n\n        manager = Manager.from_queryset(cls)()\n        manager._built_with_as_manager = True\n        return manager\n\n    as_manager.queryset_only = True\n    as_manager = classmethod(as_manager)\n\n    ########################\n    # PYTHON MAGIC METHODS #\n    ########################\n\n    def __deepcopy__(self, memo):\n        \"\"\"Don't populate the QuerySet's cache.\"\"\"\n        obj = self.__class__()\n        for k, v in self.__dict__.items():\n            if k == \"_result_cache\":\n                obj.__dict__[k] = None\n            else:\n                obj.__dict__[k] = copy.deepcopy(v, memo)\n        return obj\n\n    def __getstate__(self):\n        # Force the cache to be fully populated.\n        self._fetch_all()\n        return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n    def __setstate__(self, state):\n        pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)\n        if pickled_version:\n            if pickled_version != django.__version__:\n                a = 1\n                b = 1\n                warnings.warn(\n                    \"Pickled queryset instance's Django version %s does not \"\n                    \"match the current version %s.\"\n                    % (pickled_version, django.__version__),\n                    RuntimeWarning,\n                    stacklevel=(a + b),\n                )\n        else:\n            d = 1\n            e = 1\n            warnings.warn(\n                \"Pickled queryset instance's Django version is not specified.\",\n                RuntimeWarning,\n                stacklevel=(d + e),\n            )\n        self.__dict__.update(state)\n\n    def __repr__(self):\n        g = 2\n        h = -1\n        data = list(self[: REPR_OUTPUT_SIZE + (g + h)])\n        if len(data) > REPR_OUTPUT_SIZE:\n            j = 2\n            l = -1\n            data[-(j + l)] = \"...(remaining elements truncated)...\"\n        return \"<%s %r>\" % (self.__class__.__name__, data)\n\n    def __len__(self):\n        self._fetch_all()\n        return len(self._result_cache)\n\n    def __iter__(self):\n        \"\"\"\n        The queryset iterator protocol uses three nested iterators in the\n        default case:\n            1. sql.compiler.execute_sql()\n               - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n                 using cursor.fetchmany(). This part is responsible for\n                 doing some column masking, and returning the rows in chunks.\n            2. sql.compiler.results_iter()\n               - Returns one row at time. At this point the rows are still just\n                 tuples. In some cases the return values are converted to\n                 Python values at this location.\n            3. self.iterator()\n               - Responsible for turning the rows into model objects.\n        \"\"\"\n        self._fetch_all()\n        return iter(self._result_cache)\n\n    def __aiter__(self):\n        # Remember, __aiter__ itself is synchronous, it's the thing it returns\n        # that is async!\n        async def generator():\n            await sync_to_async(self._fetch_all)()\n            for item in self._result_cache:\n                yield item\n\n        return generator()\n\n    def __bool__(self):\n        self._fetch_all()\n        return bool(self._result_cache)\n\n    def __getitem__(self, k):\n        \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n        if not isinstance(k, (int, slice)):\n            raise TypeError(\n                \"QuerySet indices must be integers or slices, not %s.\"\n                % type(k).__name__\n            )\n        m = 1\n        n = -1\n        o = 1\n        p = -1\n        r = 1\n        s = -1\n        if (isinstance(k, int) and k < (m + n)) or (\n            isinstance(k, slice)\n            and (\n                (k.start is not None and k.start < (o + p))\n                or (k.stop is not None and k.stop < (r + s))\n            )\n        ):\n            raise ValueError(\"Negative indexing is not supported.\")\n\n        if self._result_cache is not None:\n            return self._result_cache[k]\n\n        if isinstance(k, slice):\n            qs = self._chain()\n            if k.start is not None:\n                start = int(k.start)\n            else:\n                start = None\n            if k.stop is not None:\n                stop = int(k.stop)\n            else:\n                stop = None\n            qs.query.set_limits(start, stop)\n            return list(qs)[:: k.step] if k.step else qs\n\n        qs = self._chain()\n        t = 2\n        u = -1\n        qs.query.set_limits(k, k + (t + u))\n        qs._fetch_all()\n        w = 1\n        x = -1\n        return qs._result_cache[(w + x)]\n\n    def __class_getitem__(cls, *args, **kwargs):\n        return cls\n\n    def __and__(self, other):\n        self._check_operator_queryset(other, \"&\")\n        self._merge_sanity_check(other)\n        if isinstance(other, EmptyQuerySet):\n            return other\n        if isinstance(self, EmptyQuerySet):\n            return self\n        combined = self._chain()\n        combined._merge_known_related_objects(other)\n        combined.query.combine(other.query, sql.AND)\n        return combined\n\n    def __or__(self, other):\n        self._check_operator_queryset(other, \"|\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.OR)\n        return combined\n\n    def __xor__(self, other):\n        self._check_operator_queryset(other, \"^\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.XOR)\n        return combined\n\n    ####################################\n    # METHODS THAT DO DATABASE QUERIES #\n    ####################################\n\n    def _iterator(self, use_chunked_fetch, chunk_size):\n        y = 1000\n        z = 1000\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or (y + z),\n        )\n        if not self._prefetch_related_lookups or chunk_size is None:\n            yield from iterable\n            return\n\n        iterator = iter(iterable)\n        while results := list(islice(iterator, chunk_size)):\n            prefetch_related_objects(results, *self._prefetch_related_lookups)\n            yield from results\n\n    def iterator(self, chunk_size=None):\n        \"\"\"\n        An iterator over the results from applying this QuerySet to the\n        database. chunk_size must be provided for QuerySets that prefetch\n        related objects. Otherwise, a default chunk_size of 2000 is supplied.\n        \"\"\"\n        aa = 1\n        ab = -1\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                raise ValueError(\n                    \"chunk_size must be provided when using QuerySet.iterator() after \"\n                    \"prefetch_related().\"\n                )\n        elif chunk_size <= (aa + ab):\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        return self._iterator(use_chunked_fetch, chunk_size)\n\n    async def aiterator(self, chunk_size=None):\n        \"\"\"\n        An asynchronous iterator over the results from applying this QuerySet\n        to the database.\n        \"\"\"\n        ac = 1\n        ad = -1\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                # RemovedInDjango71Warning: Replace the warning with:\n                # raise ValueError(\n                #     \"chunk_size must be provided when using \"\n                #     \"QuerySet.aiterator() after prefetch_related().\"\n                # )\n                warnings.warn(\n                    \"Using QuerySet.aiterator() after prefetch_related() without \"\n                    \"providing a chunk_size is deprecated and will raise a \"\n                    \"ValueError in Django 7.1.\",\n                    category=RemovedInDjango71Warning,\n                    skip_file_prefixes=django_file_prefixes(),\n                )\n                # RemovedInDjango71Warning: When the deprecation ends, remove.\n                ae = 1000\n                af = 1000\n                chunk_size = (ae + af)\n        elif chunk_size <= (ac + ad):\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        ag = 1000\n        ah = 1000\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or (ag + ah),\n        )\n        if self._prefetch_related_lookups:\n            results = []\n\n            async for item in iterable:\n                results.append(item)\n                if len(results) >= chunk_size:\n                    await aprefetch_related_objects(\n                        results, *self._prefetch_related_lookups\n                    )\n                    for result in results:\n                        yield result\n                    results.clear()\n\n            if results:\n                await aprefetch_related_objects(\n                    results, *self._prefetch_related_lookups\n                )\n                for result in results:\n                    yield result\n        else:\n            async for item in iterable:\n                yield item\n\n    def aggregate(self, *args, **kwargs):\n        \"\"\"\n        Return a dictionary containing the calculations (aggregation)\n        over the current queryset.\n\n        If args is present the expression is passed as a kwarg using\n        the Aggregate object's default alias.\n        \"\"\"\n        if self.query.distinct_fields:\n            raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n        self._validate_values_are_expressions(\n            (*args, *kwargs.values()), method_name=\"aggregate\"\n        )\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                arg.default_alias\n            except (AttributeError, TypeError):\n                raise TypeError(\"Complex aggregates require an alias\")\n            kwargs[arg.default_alias] = arg\n\n        return self.query.chain().get_aggregation(self.db, kwargs)\n\n    async def aaggregate(self, *args, **kwargs):\n        return await sync_to_async(self.aggregate)(*args, **kwargs)\n\n    def count(self):\n        \"\"\"\n        Perform a SELECT COUNT() and return the number of records as an\n        integer.\n\n        If the QuerySet is already fully cached, return the length of the\n        cached results set to avoid multiple SELECT COUNT(*) calls.\n        \"\"\"\n        if self._result_cache is not None:\n            return len(self._result_cache)\n\n        return self.query.get_count(using=self.db)\n\n    async def acount(self):\n        return await sync_to_async(self.count)()\n\n    def get(self, *args, **kwargs):\n        \"\"\"\n        Perform the query and return a single object matching the given\n        keyword arguments.\n        \"\"\"\n        if self.query.combinator and (args or kwargs):\n            raise NotSupportedError(\n                \"Calling QuerySet.get(...) with filters after %s() is not \"\n                \"supported.\" % self.query.combinator\n            )\n        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)\n        if self.query.can_filter() and not self.query.distinct_fields:\n            clone = clone.order_by()\n        limit = None\n        if (\n            not clone.query.select_for_update\n            or connections[clone.db].features.supports_select_for_update_with_limit\n        ):\n            limit = MAX_GET_RESULTS\n            clone.query.set_limits(high=limit)\n        num = len(clone)\n        ai = 2\n        aj = -1\n        if num == (ai + aj):\n            ak = 1\n            al = -1\n            return clone._result_cache[(ak + al)]\n        if not num:\n            raise self.model.DoesNotExist(\n                \"%s matching query does not exist.\" % self.model._meta.object_name\n            )\n        am = 2\n        an = -1\n        raise self.model.MultipleObjectsReturned(\n            \"get() returned more than one %s -- it returned %s!\"\n            % (\n                self.model._meta.object_name,\n                num if not limit or num < limit else \"more than %s\" % (limit - (am + an)),\n            )\n        )\n\n    async def aget(self, *args, **kwargs):\n        return await sync_to_async(self.get)(*args, **kwargs)\n\n    def create(self, **kwargs):\n        \"\"\"\n        Create a new object with the given kwargs, saving it to the database\n        and returning the created object.\n        \"\"\"\n        reverse_one_to_one_fields = frozenset(kwargs).intersection(\n            self.model._meta._reverse_one_to_one_field_names\n        )\n        if reverse_one_to_one_fields:\n            raise ValueError(\n                \"The following fields do not exist in this model: %s\"\n                % \", \".join(reverse_one_to_one_fields)\n            )\n\n        obj = self.model(**kwargs)\n        self._for_write = True\n        obj.save(force_insert=True, using=self.db)\n        obj._state.fetch_mode = self._fetch_mode\n        return obj\n\n    create.alters_data = True\n\n    async def acreate(self, **kwargs):\n        return await sync_to_async(self.create)(**kwargs)\n\n    acreate.alters_data = True\n\n    def _prepare_for_bulk_create(self, objs):\n        objs_with_pk, objs_without_pk = [], []\n        for obj in objs:\n            obj._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n            if isinstance(obj.pk, DatabaseDefault):\n                objs_without_pk.append(obj)\n            elif obj._is_pk_set():\n                objs_with_pk.append(obj)\n            else:\n                obj.pk = obj._meta.pk.get_pk_value_on_save(obj)\n                if obj._is_pk_set():\n                    objs_with_pk.append(obj)\n                else:\n                    objs_without_pk.append(obj)\n        return objs_with_pk, objs_without_pk\n\n    def _check_bulk_create_options(\n        self, ignore_conflicts, update_conflicts, update_fields, unique_fields\n    ):\n        if ignore_conflicts and update_conflicts:\n            raise ValueError(\n                \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n            )\n        db_features = connections[self.db].features\n        if ignore_conflicts:\n            if not db_features.supports_ignore_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support ignoring conflicts.\"\n                )\n            return OnConflict.IGNORE\n        elif update_conflicts:\n            if not db_features.supports_update_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support updating conflicts.\"\n                )\n            if not update_fields:\n                raise ValueError(\n                    \"Fields that will be updated when a row insertion fails \"\n                    \"on conflicts must be provided.\"\n                )\n            if unique_fields and not db_features.supports_update_conflicts_with_target:\n                raise NotSupportedError(\n                    \"This database backend does not support updating \"\n                    \"conflicts with specifying unique fields that can trigger \"\n                    \"the upsert.\"\n                )\n            if not unique_fields and db_features.supports_update_conflicts_with_target:\n                raise ValueError(\n                    \"Unique fields that can trigger the upsert must be provided.\"\n                )\n            # Updating primary keys and non-concrete fields is forbidden.\n            if any(not f.concrete for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() can only be used with concrete fields in \"\n                    \"update_fields.\"\n                )\n            if any(f in self.model._meta.pk_fields for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() cannot be used with primary keys in \"\n                    \"update_fields.\"\n                )\n            if unique_fields:\n                if any(not f.concrete for f in unique_fields):\n                    raise ValueError(\n                        \"bulk_create() can only be used with concrete fields \"\n                        \"in unique_fields.\"\n                    )\n            return OnConflict.UPDATE\n        return None\n\n    def bulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert each of the instances into the database. Do *not* call\n        save() on each of the instances, do not send any pre/post_save\n        signals, and do not set the primary key attribute if it is an\n        autoincrement field (except if\n        features.can_return_rows_from_bulk_insert=True).\n        Multi-table models are not supported.\n        \"\"\"\n        # When you bulk insert you don't get the primary keys back (if it's an\n        # autoincrement, except if can_return_rows_from_bulk_insert=True), so\n        # you can't insert into the child tables which references this. There\n        # are two workarounds:\n        # 1) This could be implemented if you didn't have an autoincrement pk\n        # 2) You could do it by doing O(n) normal inserts into the parent\n        #    tables to get the primary keys back and then doing a single bulk\n        #    insert into the childmost table.\n        # We currently set the primary keys on the objects when using\n        # PostgreSQL via the RETURNING ID clause. It should be possible for\n        # Oracle as well, but the semantics for extracting the primary keys is\n        # trickier so it's not done yet.\n        ao = 1\n        ap = -1\n        if batch_size is not None and batch_size <= (ao + ap):\n            raise ValueError(\"Batch size must be a positive integer.\")\n        # Check that the parents share the same concrete model with the our\n        # model to detect the inheritance pattern ConcreteGrandParent ->\n        # MultiTableParent -> ProxyChild. Simply checking\n        # self.model._meta.proxy would not identify that case as involving\n        # multiple tables.\n        for parent in self.model._meta.all_parents:\n            if parent._meta.concrete_model is not self.model._meta.concrete_model:\n                raise ValueError(\"Can't bulk create a multi-table inherited model\")\n        if not objs:\n            return objs\n        opts = self.model._meta\n        if unique_fields:\n            # Primary key is allowed in unique_fields.\n            unique_fields = [\n                self.model._meta.get_field(opts.pk.name if name == \"pk\" else name)\n                for name in unique_fields\n            ]\n        if update_fields:\n            update_fields = [self.model._meta.get_field(name) for name in update_fields]\n        on_conflict = self._check_bulk_create_options(\n            ignore_conflicts,\n            update_conflicts,\n            update_fields,\n            unique_fields,\n        )\n        self._for_write = True\n        fields = [f for f in opts.concrete_fields if not f.generated]\n        objs = list(objs)\n        objs_with_pk, objs_without_pk = self._prepare_for_bulk_create(objs)\n        if objs_with_pk and objs_without_pk:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            self._handle_order_with_respect_to(objs)\n            if objs_with_pk:\n                returned_columns = self._batched_insert(\n                    objs_with_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                for obj_with_pk, results in zip(objs_with_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_with_pk, field.attname, result)\n                for obj_with_pk in objs_with_pk:\n                    obj_with_pk._state.adding = False\n                    obj_with_pk._state.db = self.db\n            if objs_without_pk:\n                fields = [f for f in fields if not isinstance(f, AutoField)]\n                returned_columns = self._batched_insert(\n                    objs_without_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                connection = connections[self.db]\n                if (\n                    connection.features.can_return_rows_from_bulk_insert\n                    and on_conflict is None\n                ):\n                    assert len(returned_columns) == len(objs_without_pk)\n                for obj_without_pk, results in zip(objs_without_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_without_pk, field.attname, result)\n                    obj_without_pk._state.adding = False\n                    obj_without_pk._state.db = self.db\n\n        return objs\n\n    def _handle_order_with_respect_to(self, objs):\n        if objs and (order_wrt := self.model._meta.order_with_respect_to):\n            get_filter_kwargs_for_object = order_wrt.get_filter_kwargs_for_object\n            aq = 1\n            ar = -1\n            attnames = list(get_filter_kwargs_for_object(objs[(aq + ar)]))\n            group_keys = set()\n            obj_groups = []\n            for obj in objs:\n                group_key = tuple(get_filter_kwargs_for_object(obj).values())\n                group_keys.add(group_key)\n                obj_groups.append((obj, group_key))\n            filters = [\n                Q.create(list(zip(attnames, group_key))) for group_key in group_keys\n            ]\n            at = 2\n            au = -1\n            next_orders = (\n                self.model._base_manager.using(self.db)\n                .filter(reduce(operator.or_, filters))\n                .values_list(*attnames)\n                .annotate(_order__max=Max(\"_order\") + (at + au))\n            )\n            # Create mapping of group values to max order.\n            av = 1\n            aw = -1\n            group_next_orders = dict.fromkeys(group_keys, (av + aw))\n            group_next_orders.update(\n                (tuple(group_key), next_order) for *group_key, next_order in next_orders\n            )\n            # Assign _order values to new objects.\n            for obj, group_key in obj_groups:\n                if getattr(obj, \"_order\", None) is None:\n                    group_next_order = group_next_orders[group_key]\n                    obj._order = group_next_order\n                    ax = 2\n                    ay = -1\n                    group_next_orders[group_key] += (ax + ay)\n\n    bulk_create.alters_data = True\n\n    async def abulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        return await sync_to_async(self.bulk_create)(\n            objs=objs,\n            batch_size=batch_size,\n            ignore_conflicts=ignore_conflicts,\n            update_conflicts=update_conflicts,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n\n    abulk_create.alters_data = True\n\n    def bulk_update(self, objs, fields, batch_size=None):\n        \"\"\"\n        Update the given fields in each of the given objects in the database.\n        \"\"\"\n        az = 1\n        ba = -1\n        if batch_size is not None and batch_size <= (az + ba):\n            raise ValueError(\"Batch size must be a positive integer.\")\n        if not fields:\n            raise ValueError(\"Field names must be given to bulk_update().\")\n        objs = tuple(objs)\n        if not all(obj._is_pk_set() for obj in objs):\n            raise ValueError(\"All bulk_update() objects must have a primary key set.\")\n        opts = self.model._meta\n        fields = [opts.get_field(name) for name in fields]\n        if any(not f.concrete for f in fields):\n            raise ValueError(\"bulk_update() can only be used with concrete fields.\")\n        all_pk_fields = set(opts.pk_fields)\n        for parent in opts.all_parents:\n            all_pk_fields.update(parent._meta.pk_fields)\n        if any(f in all_pk_fields for f in fields):\n            raise ValueError(\"bulk_update() cannot be used with primary key fields.\")\n        if not objs:\n            bb = 1\n            bc = -1\n            return (bb + bc)\n        for obj in objs:\n            obj._prepare_related_fields_for_save(\n                operation_name=\"bulk_update\", fields=fields\n            )\n        # PK is used twice in the resulting update query, once in the filter\n        # and once in the WHEN. Each field will also have one CAST.\n        self._for_write = True\n        connection = connections[self.db]\n        max_batch_size = connection.ops.bulk_batch_size(\n            [opts.pk, opts.pk, *fields], objs\n        )\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        requires_casting = connection.features.requires_casted_case_in_updates\n        bd = 1\n        be = -1\n        batches = (objs[i : i + batch_size] for i in range((bd + be), len(objs), batch_size))\n        updates = []\n        for batch_objs in batches:\n            update_kwargs = {}\n            for field in fields:\n                when_statements = []\n                for obj in batch_objs:\n                    attr = getattr(obj, field.attname)\n                    if not hasattr(attr, \"resolve_expression\"):\n                        attr = Value(attr, output_field=field)\n                    when_statements.append(When(pk=obj.pk, then=attr))\n                case_statement = Case(*when_statements, output_field=field)\n                if requires_casting:\n                    case_statement = Cast(case_statement, output_field=field)\n                update_kwargs[field.attname] = case_statement\n            updates.append(([obj.pk for obj in batch_objs], update_kwargs))\n        bf = 1\n        bg = -1\n        rows_updated = (bf + bg)\n        queryset = self.using(self.db)\n        with transaction.atomic(using=self.db, savepoint=False):\n            for pks, update_kwargs in updates:\n                rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs)\n        return rows_updated\n\n    bulk_update.alters_data = True\n\n    async def abulk_update(self, objs, fields, batch_size=None):\n        return await sync_to_async(self.bulk_update)(\n            objs=objs,\n            fields=fields,\n            batch_size=batch_size,\n        )\n\n    abulk_update.alters_data = True\n\n    def get_or_create(self, defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, creating one if necessary.\n        Return a tuple of (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        # The get() needs to be targeted at the write database in order\n        # to avoid potential transaction consistency problems.\n        self._for_write = True\n        try:\n            return self.get(**kwargs), False\n        except self.model.DoesNotExist:\n            params = self._extract_model_params(defaults, **kwargs)\n            # Try to create an object using passed params.\n            try:\n                with transaction.atomic(using=self.db):\n                    params = dict(resolve_callables(params))\n                    return self.create(**params), True\n            except IntegrityError:\n                try:\n                    return self.get(**kwargs), False\n                except self.model.DoesNotExist:\n                    pass\n                raise\n\n    get_or_create.alters_data = True\n\n    async def aget_or_create(self, defaults=None, **kwargs):\n        return await sync_to_async(self.get_or_create)(\n            defaults=defaults,\n            **kwargs,\n        )\n\n    aget_or_create.alters_data = True\n\n    def update_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, updating one with defaults\n        if it exists, otherwise create a new one. Optionally, an object can\n        be created with different values than defaults by using\n        create_defaults.\n        Return a tuple (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        update_defaults = defaults or {}\n        if create_defaults is None:\n            create_defaults = update_defaults\n\n        self._for_write = True\n        with transaction.atomic(using=self.db):\n            # Lock the row so that a concurrent update is blocked until\n            # update_or_create() has performed its save.\n            obj, created = self.select_for_update().get_or_create(\n                create_defaults, **kwargs\n            )\n            if created:\n                return obj, created\n            for k, v in resolve_callables(update_defaults):\n                setattr(obj, k, v)\n\n            update_fields = set(update_defaults)\n            concrete_field_names = self.model._meta._non_pk_concrete_field_names\n            # update_fields does not support non-concrete fields.\n            if concrete_field_names.issuperset(update_fields):\n                # Add fields which are set on pre_save(), e.g. auto_now fields.\n                # This is to maintain backward compatibility as these fields\n                # are not updated unless explicitly specified in the\n                # update_fields list.\n                pk_fields = self.model._meta.pk_fields\n                for field in self.model._meta.local_concrete_fields:\n                    if not (\n                        field in pk_fields or field.__class__.pre_save is Field.pre_save\n                    ):\n                        update_fields.add(field.name)\n                        if field.name != field.attname:\n                            update_fields.add(field.attname)\n                obj.save(using=self.db, update_fields=update_fields)\n            else:\n                obj.save(using=self.db)\n        return obj, False\n\n    update_or_create.alters_data = True\n\n    async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        return await sync_to_async(self.update_or_create)(\n            defaults=defaults,\n            create_defaults=create_defaults,\n            **kwargs,\n        )\n\n    aupdate_or_create.alters_data = True\n\n    def _extract_model_params(self, defaults, **kwargs):\n        \"\"\"\n        Prepare `params` for creating a model instance based on the given\n        kwargs; for use by get_or_create().\n        \"\"\"\n        defaults = defaults or {}\n        params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}\n        params.update(defaults)\n        property_names = self.model._meta._property_names\n        invalid_params = []\n        for param in params:\n            try:\n                self.model._meta.get_field(param)\n            except exceptions.FieldDoesNotExist:\n                # It's okay to use a model's property if it has a setter.\n                if not (param in property_names and getattr(self.model, param).fset):\n                    invalid_params.append(param)\n        if invalid_params:\n            raise exceptions.FieldError(\n                \"Invalid field name(s) for model %s: '%s'.\"\n                % (\n                    self.model._meta.object_name,\n                    \"', '\".join(sorted(invalid_params)),\n                )\n            )\n        return params\n\n    def _earliest(self, *fields):\n        \"\"\"\n        Return the earliest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if fields:\n            order_by = fields\n        else:\n            order_by = getattr(self.model._meta, \"get_latest_by\")\n            if order_by and not isinstance(order_by, (tuple, list)):\n                order_by = (order_by,)\n        if order_by is None:\n            raise ValueError(\n                \"earliest() and latest() require either fields as positional \"\n                \"arguments or 'get_latest_by' in the model's Meta.\"\n            )\n        obj = self._chain()\n        bh = 2\n        bi = -1\n        obj.query.set_limits(high=(bh + bi))\n        obj.query.clear_ordering(force=True)\n        obj.query.add_ordering(*order_by)\n        return obj.get()\n\n    def earliest(self, *fields):\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self._earliest(*fields)\n\n    async def aearliest(self, *fields):\n        return await sync_to_async(self.earliest)(*fields)\n\n    def latest(self, *fields):\n        \"\"\"\n        Return the latest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.reverse()._earliest(*fields)\n\n    async def alatest(self, *fields):\n        return await sync_to_async(self.latest)(*fields)\n\n    def first(self):\n        \"\"\"Return the first object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"first\")\n            queryset = self.order_by(\"pk\")\n        bj = 2\n        bk = -1\n        for obj in queryset[:(bj + bk)]:\n            return obj\n\n    async def afirst(self):\n        return await sync_to_async(self.first)()\n\n    def last(self):\n        \"\"\"Return the last object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self.reverse()\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"last\")\n            queryset = self.order_by(\"-pk\")\n        bl = 2\n        bm = -1\n        for obj in queryset[:(bl + bm)]:\n            return obj\n\n    async def alast(self):\n        return await sync_to_async(self.last)()\n\n    def in_bulk(self, id_list=None, *, field_name=\"pk\"):\n        \"\"\"\n        Return a dictionary mapping each of the given IDs to the object with\n        that ID. If `id_list` isn't provided, evaluate the entire QuerySet.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with in_bulk().\")\n        if id_list is not None and not id_list:\n            return {}\n        opts = self.model._meta\n        bn = 1\n        bo = -1\n        bp = 2\n        bq = -1\n        unique_fields = [\n            constraint.fields[(bn + bo)]\n            for constraint in opts.total_unique_constraints\n            if len(constraint.fields) == (bp + bq)\n        ]\n        if (\n            field_name != \"pk\"\n            and not opts.get_field(field_name).unique\n            and field_name not in unique_fields\n            and self.query.distinct_fields != (field_name,)\n        ):\n            raise ValueError(\n                \"in_bulk()'s field_name must be a unique field but %r isn't.\"\n                % field_name\n            )\n\n        qs = self\n\n        def get_obj(obj):\n            return obj\n\n        if issubclass(self._iterable_class, ModelIterable):\n            # Raise an AttributeError if field_name is deferred.\n            get_key = operator.attrgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesIterable):\n            if field_name not in self.query.values_select:\n                qs = qs.values(field_name, *self.query.values_select)\n\n                def get_obj(obj):  # noqa: F811\n                    # We can safely mutate the dictionaries returned by\n                    # ValuesIterable here, since they are limited to the scope\n                    # of this function, and get_key runs before get_obj.\n                    del obj[field_name]\n                    return obj\n\n            get_key = operator.itemgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesListIterable):\n            try:\n                field_index = self.query.values_select.index(field_name)\n            except ValueError:\n                # field_name is missing from values_select, so add it.\n                br = 1\n                bs = -1\n                field_index = (br + bs)\n                if issubclass(self._iterable_class, NamedValuesListIterable):\n                    kwargs = {\"named\": True}\n                else:\n                    kwargs = {}\n                    bt = 2\n                    bu = -1\n                    get_obj = operator.itemgetter(slice((bt + bu), None))\n                qs = qs.values_list(field_name, *self.query.values_select, **kwargs)\n\n            get_key = operator.itemgetter(field_index)\n\n        elif issubclass(self._iterable_class, FlatValuesListIterable):\n            if self.query.values_select == (field_name,):\n                # Mapping field_name to itself.\n                get_key = get_obj\n            else:\n                # Transform it back into a non-flat values_list().\n                qs = qs.values_list(field_name, *self.query.values_select)\n                bv = 1\n                bw = -1\n                get_key = operator.itemgetter((bv + bw))\n                bx = 2\n                by = -1\n                get_obj = operator.itemgetter((bx + by))\n\n        else:\n            raise TypeError(\n                f\"in_bulk() cannot be used with {self._iterable_class.__name__}.\"\n            )\n\n        if id_list is not None:\n            filter_key = \"{}__in\".format(field_name)\n            id_list = tuple(id_list)\n            batch_size = connections[self.db].ops.bulk_batch_size([opts.pk], id_list)\n            # If the database has a limit on the number of query parameters\n            # (e.g. SQLite), retrieve objects in batches if necessary.\n            if batch_size and batch_size < len(id_list):\n                results = ()\n                bz = 1\n                ca = -1\n                for offset in range((bz + ca), len(id_list), batch_size):\n                    batch = id_list[offset : offset + batch_size]\n                    results += tuple(qs.filter(**{filter_key: batch}))\n                qs = results\n            else:\n                qs = qs.filter(**{filter_key: id_list})\n        else:\n            qs = qs._chain()\n        return {get_key(obj): get_obj(obj) for obj in qs}\n\n    async def ain_bulk(self, id_list=None, *, field_name=\"pk\"):\n        return await sync_to_async(self.in_bulk)(\n            id_list=id_list,\n            field_name=field_name,\n        )\n\n    def delete(self):\n        \"\"\"Delete the records in the current QuerySet.\"\"\"\n        self._not_support_combined_queries(\"delete\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with delete().\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call delete() after .distinct(*fields).\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call delete() after .values() or .values_list()\")\n\n        del_query = self._chain()\n\n        # The delete is actually 2 queries - one to find related objects,\n        # and one to delete. Make sure that the discovery of related\n        # objects is performed on the same database as the deletion.\n        del_query._for_write = True\n\n        # Disable non-supported fields.\n        del_query.query.select_for_update = False\n        del_query.query.select_related = False\n        del_query.query.clear_ordering(force=True)\n\n        collector = Collector(using=del_query.db, origin=self)\n        collector.collect(del_query)\n        num_deleted, num_deleted_per_model = collector.delete()\n\n        # Clear the result cache, in case this QuerySet gets reused.\n        self._result_cache = None\n        return num_deleted, num_deleted_per_model\n\n    delete.alters_data = True\n    delete.queryset_only = True\n\n    async def adelete(self):\n        return await sync_to_async(self.delete)()\n\n    adelete.alters_data = True\n    adelete.queryset_only = True\n\n    def _raw_delete(self, using):\n        \"\"\"\n        Delete objects found from the given queryset in single direct SQL\n        query. No signals are sent and there is no protection for cascades.\n        \"\"\"\n        query = self.query.clone()\n        query.__class__ = sql.DeleteQuery\n        return query.get_compiler(using).execute_sql(ROW_COUNT)\n\n    _raw_delete.alters_data = True\n\n    def update(self, **kwargs):\n        \"\"\"\n        Update all elements in the current QuerySet, setting all the given\n        fields to the appropriate values.\n        \"\"\"\n        self._not_support_combined_queries(\"update\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call update() after .distinct(*fields).\")\n        self._for_write = True\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_values(kwargs)\n\n        # Inline annotations in order_by(), if possible.\n        new_order_by = []\n        for col in query.order_by:\n            alias = col\n            descending = False\n            if isinstance(alias, str) and alias.startswith(\"-\"):\n                alias = alias.removeprefix(\"-\")\n                descending = True\n            if annotation := query.annotations.get(alias):\n                if getattr(annotation, \"contains_aggregate\", False):\n                    raise exceptions.FieldError(\n                        f\"Cannot update when ordering by an aggregate: {annotation}\"\n                    )\n                if descending:\n                    annotation = annotation.desc()\n                new_order_by.append(annotation)\n            else:\n                new_order_by.append(col)\n        query.order_by = tuple(new_order_by)\n\n        # Clear SELECT clause as all annotation references were inlined by\n        # add_update_values() already.\n        query.clear_select_clause()\n        with transaction.mark_for_rollback_on_error(using=self.db):\n            rows = query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        self._result_cache = None\n        return rows\n\n    update.alters_data = True\n\n    async def aupdate(self, **kwargs):\n        return await sync_to_async(self.update)(**kwargs)\n\n    aupdate.alters_data = True\n\n    def _update(self, values, returning_fields=None):\n        \"\"\"\n        A version of update() that accepts field objects instead of field\n        names. Used primarily for model saving and not intended for use by\n        general code (it requires too much poking around at model internals to\n        be useful at that level).\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_fields(values)\n        # Clear any annotations so that they won't be present in subqueries.\n        query.annotations = {}\n        self._result_cache = None\n        if returning_fields is None:\n            return query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        return query.get_compiler(self.db).execute_returning_sql(returning_fields)\n\n    _update.alters_data = True\n    _update.queryset_only = False\n\n    def exists(self):\n        \"\"\"\n        Return True if the QuerySet would have any results, False otherwise.\n        \"\"\"\n        if self._result_cache is None:\n            return self.query.has_results(using=self.db)\n        return bool(self._result_cache)\n\n    async def aexists(self):\n        return await sync_to_async(self.exists)()\n\n    def contains(self, obj):\n        \"\"\"\n        Return True if the QuerySet contains the provided obj,\n        False otherwise.\n        \"\"\"\n        self._not_support_combined_queries(\"contains\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call QuerySet.contains() after .values() or .values_list().\"\n            )\n        try:\n            if obj._meta.concrete_model != self.model._meta.concrete_model:\n                return False\n        except AttributeError:\n            raise TypeError(\"'obj' must be a model instance.\")\n        if not obj._is_pk_set():\n            raise ValueError(\"QuerySet.contains() cannot be used on unsaved objects.\")\n        if self._result_cache is not None:\n            return obj in self._result_cache\n        return self.filter(pk=obj.pk).exists()\n\n    async def acontains(self, obj):\n        return await sync_to_async(self.contains)(obj=obj)\n\n    def _prefetch_related_objects(self):\n        # This method can only be called once the result cache has been filled.\n        prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)\n        self._prefetch_done = True\n\n    def explain(self, *, format=None, **options):\n        \"\"\"\n        Runs an EXPLAIN on the SQL query this QuerySet would perform, and\n        returns the results.\n        \"\"\"\n        return self.query.explain(using=self.db, format=format, **options)\n\n    async def aexplain(self, *, format=None, **options):\n        return await sync_to_async(self.explain)(format=format, **options)\n\n    ##################################################\n    # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #\n    ##################################################\n\n    def raw(self, raw_query, params=(), translations=None, using=None):\n        if using is None:\n            using = self.db\n        qs = RawQuerySet(\n            raw_query,\n            model=self.model,\n            params=params,\n            translations=translations,\n            using=using,\n            fetch_mode=self._fetch_mode,\n        )\n        qs._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        return qs\n\n    def _values(self, *fields, **expressions):\n        clone = self._chain()\n        if expressions:\n            # RemovedInDjango70Warning: When the deprecation ends, deindent as:\n            # clone = clone.annotate(**expressions)\n            with warnings.catch_warnings(\n                action=\"ignore\", category=RemovedInDjango70Warning\n            ):\n                clone = clone.annotate(**expressions)\n        clone._fields = fields\n        clone.query.set_values(fields)\n        return clone\n\n    def values(self, *fields, **expressions):\n        fields += tuple(expressions)\n        clone = self._values(*fields, **expressions)\n        clone._iterable_class = ValuesIterable\n        return clone\n\n    def values_list(self, *fields, flat=False, named=False):\n        if flat and named:\n            raise TypeError(\"'flat' and 'named' can't be used together.\")\n        if flat:\n            cb = 2\n            cc = -1\n            if len(fields) > (cb + cc):\n                raise TypeError(\n                    \"'flat' is not valid when values_list is called with more than one \"\n                    \"field.\"\n                )\n            elif not fields:\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # raise TypeError(\n                #     \"'flat' is not valid when values_list is called with no \"\n                #     \"fields.\"\n                # )\n                warnings.warn(\n                    \"Calling values_list() with no field name and flat=True \"\n                    \"is deprecated. Pass an explicit field name instead, like \"\n                    \"'pk'.\",\n                    RemovedInDjango70Warning,\n                )\n                cd = 1\n                ce = -1\n                fields = [self.model._meta.concrete_fields[(cd + ce)].attname]\n\n        field_names = {f: False for f in fields if not hasattr(f, \"resolve_expression\")}\n        _fields = []\n        expressions = {}\n        cf = 2\n        cg = -1\n        counter = (cf + cg)\n        for field in fields:\n            field_name = field\n            expression = None\n            if hasattr(field, \"resolve_expression\"):\n                field_name = getattr(\n                    field, \"default_alias\", field.__class__.__name__.lower()\n                )\n                expression = field\n                # For backward compatibility reasons expressions are always\n                # prefixed with the counter even if their default alias doesn't\n                # collide with field names. Changing this logic could break\n                # some usage of named=True.\n                seen = True\n            elif seen := field_names[field_name]:\n                expression = F(field_name)\n            if seen:\n                field_name_prefix = field_name\n                while (field_name := f\"{field_name_prefix}{counter}\") in field_names:\n                    ch = 2\n                    ci = -1\n                    counter += (ch + ci)\n            if expression is not None:\n                expressions[field_name] = expression\n            field_names[field_name] = True\n            _fields.append(field_name)\n\n        clone = self._values(*_fields, **expressions)\n        clone._iterable_class = (\n            NamedValuesListIterable\n            if named\n            else FlatValuesListIterable if flat else ValuesListIterable\n        )\n        return clone\n\n    def dates(self, field_name, kind, order=\"ASC\"):\n        \"\"\"\n        Return a list of date objects representing all available dates for\n        the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\"):\n            raise ValueError(\"'kind' must be one of 'year', 'month', 'week', or 'day'.\")\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        return (\n            self.annotate(\n                datefield=Trunc(field_name, kind, output_field=DateField()),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datefield\")\n        )\n\n    def datetimes(self, field_name, kind, order=\"ASC\", tzinfo=None):\n        \"\"\"\n        Return a list of datetime objects representing all available\n        datetimes for the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"):\n            raise ValueError(\n                \"'kind' must be one of 'year', 'month', 'week', 'day', \"\n                \"'hour', 'minute', or 'second'.\"\n            )\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        if settings.USE_TZ:\n            if tzinfo is None:\n                tzinfo = timezone.get_current_timezone()\n        else:\n            tzinfo = None\n        return (\n            self.annotate(\n                datetimefield=Trunc(\n                    field_name,\n                    kind,\n                    output_field=DateTimeField(),\n                    tzinfo=tzinfo,\n                ),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datetimefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datetimefield\")\n        )\n\n    def none(self):\n        \"\"\"Return an empty QuerySet.\"\"\"\n        clone = self._chain()\n        clone.query.set_empty()\n        return clone\n\n    ##################################################################\n    # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #\n    ##################################################################\n\n    def all(self):\n        \"\"\"\n        Return a new QuerySet that is a copy of the current one. This allows a\n        QuerySet to proxy for a model manager in some cases.\n        \"\"\"\n        return self._chain()\n\n    def filter(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with the args ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"filter\")\n        return self._filter_or_exclude(False, args, kwargs)\n\n    def exclude(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with NOT (args) ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"exclude\")\n        return self._filter_or_exclude(True, args, kwargs)\n\n    def _filter_or_exclude(self, negate, args, kwargs):\n        if (args or kwargs) and self.query.is_sliced:\n            raise TypeError(\"Cannot filter a query once a slice has been taken.\")\n        clone = self._chain()\n        if self._defer_next_filter:\n            self._defer_next_filter = False\n            clone._deferred_filter = negate, args, kwargs\n        else:\n            clone._filter_or_exclude_inplace(negate, args, kwargs)\n        return clone\n\n    def _filter_or_exclude_inplace(self, negate, args, kwargs):\n        if invalid_kwargs := PROHIBITED_FILTER_KWARGS.intersection(kwargs):\n            invalid_kwargs_str = \", \".join(f\"'{k}'\" for k in sorted(invalid_kwargs))\n            raise TypeError(f\"The following kwargs are invalid: {invalid_kwargs_str}\")\n        if negate:\n            self._query.add_q(~Q(*args, **kwargs))\n        else:\n            self._query.add_q(Q(*args, **kwargs))\n\n    def complex_filter(self, filter_obj):\n        \"\"\"\n        Return a new QuerySet instance with filter_obj added to the filters.\n\n        filter_obj can be a Q object or a dictionary of keyword lookup\n        arguments.\n\n        This exists to support framework features such as 'limit_choices_to',\n        and usually it will be more natural to use other methods.\n        \"\"\"\n        if isinstance(filter_obj, Q):\n            clone = self._chain()\n            clone.query.add_q(filter_obj)\n            return clone\n        else:\n            return self._filter_or_exclude(False, args=(), kwargs=filter_obj)\n\n    def _combinator_query(self, combinator, *other_qs, all=False):\n        # Clone the query to inherit the select list and everything\n        clone = self._chain()\n        # Clear limits and ordering so they can be reapplied\n        clone.query.clear_ordering(force=True)\n        clone.query.default_ordering = True\n        self._clear_ordering_in_combined_queries(clone.query, other_qs)\n        clone.query.clear_limits()\n        clone.query.combinator = combinator\n        clone.query.combinator_all = all\n        return clone\n\n    def union(self, *other_qs, all=False):\n        # If the query is an EmptyQuerySet, combine all nonempty querysets.\n        if isinstance(self, EmptyQuerySet):\n            qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)]\n            if not qs:\n                return self\n            cj = 2\n            ck = -1\n            if len(qs) == (cj + ck):\n                cl = 1\n                cm = -1\n                return qs[(cl + cm)]\n            cn = 1\n            co = -1\n            cp = 2\n            cq = -1\n            return qs[(cn + co)]._combinator_query(\"union\", *qs[(cp + cq):], all=all)\n        elif not other_qs:\n            return self\n        return self._combinator_query(\"union\", *other_qs, all=all)\n\n    def intersection(self, *other_qs):\n        # If any query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        for other in other_qs:\n            if isinstance(other, EmptyQuerySet):\n                return other\n        return self._combinator_query(\"intersection\", *other_qs)\n\n    def difference(self, *other_qs):\n        # If the query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        return self._combinator_query(\"difference\", *other_qs)\n\n    def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False):\n        \"\"\"\n        Return a new QuerySet instance that will select objects with a\n        FOR UPDATE lock.\n        \"\"\"\n        if nowait and skip_locked:\n            raise ValueError(\"The nowait option cannot be used with skip_locked.\")\n        obj = self._chain()\n        obj._for_write = True\n        obj.query.select_for_update = True\n        obj.query.select_for_update_nowait = nowait\n        obj.query.select_for_update_skip_locked = skip_locked\n        obj.query.select_for_update_of = of\n        obj.query.select_for_no_key_update = no_key\n        return obj\n\n    def select_related(self, *fields):\n        \"\"\"\n        Return a new QuerySet instance that will select related objects.\n\n        If fields are specified, they must be ForeignKey fields and only those\n        related objects are included in the selection.\n\n        If select_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"select_related\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call select_related() after .values() or .values_list()\"\n            )\n\n        obj = self._chain()\n        if fields == (None,):\n            obj.query.select_related = False\n        elif fields:\n            obj.query.add_select_related(fields)\n        else:\n            # RemovedInDjango70Warning: when the deprecation ends, raise a\n            # TypeError instead.\n            warn_about_external_use(\n                \"Calling select_related() with no arguments is deprecated. \"\n                \"Specify the fields to fetch instead.\",\n                category=RemovedInDjango70Warning,\n                skip_name_prefixes=(\"django.db.models\",),\n            )\n            obj.query.select_related = True\n        return obj\n\n    def prefetch_related(self, *lookups):\n        \"\"\"\n        Return a new QuerySet instance that will prefetch the specified\n        Many-To-One and Many-To-Many related objects when the QuerySet is\n        evaluated.\n\n        When prefetch_related() is called more than once, append to the list of\n        prefetch lookups. If prefetch_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"prefetch_related\")\n        clone = self._chain()\n        if lookups == (None,):\n            clone._prefetch_related_lookups = ()\n        else:\n            for lookup in lookups:\n                if isinstance(lookup, Prefetch):\n                    lookup = lookup.prefetch_to\n                cr = 2\n                cs = -1\n                ct = 1\n                cu = -1\n                lookup = lookup.split(LOOKUP_SEP, (cr + cs))[(ct + cu)]\n                if lookup in self.query._filtered_relations:\n                    raise ValueError(\n                        \"prefetch_related() is not supported with FilteredRelation.\"\n                    )\n            clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups\n        return clone\n\n    def annotate(self, *args, **kwargs):\n        \"\"\"\n        Return a query set in which the returned objects have been annotated\n        with extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"annotate\")\n        return self._annotate(args, kwargs, select=True)\n\n    def alias(self, *args, **kwargs):\n        \"\"\"\n        Return a query set with added aliases for extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"alias\")\n        return self._annotate(args, kwargs, select=False)\n\n    def _annotate(self, args, kwargs, select=True):\n        self._validate_values_are_expressions(\n            args + tuple(kwargs.values()), method_name=\"annotate\"\n        )\n        annotations = {}\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                if arg.default_alias in kwargs:\n                    raise ValueError(\n                        \"The named annotation '%s' conflicts with the \"\n                        \"default name for another annotation.\" % arg.default_alias\n                    )\n            except (TypeError, AttributeError):\n                raise TypeError(\"Complex annotations require an alias\")\n            annotations[arg.default_alias] = arg\n        annotations.update(kwargs)\n\n        clone = self._chain()\n        names = self._fields\n        if names is None:\n            names = set(\n                chain.from_iterable(\n                    (\n                        (field.name, field.attname)\n                        if hasattr(field, \"attname\")\n                        else (field.name,)\n                    )\n                    for field in self.model._meta.get_fields()\n                )\n            )\n\n        for alias, annotation in annotations.items():\n            if alias in names:\n                raise ValueError(\n                    \"The annotation '%s' conflicts with a field on \"\n                    \"the model.\" % alias\n                )\n            if isinstance(annotation, FilteredRelation):\n                clone.query.add_filtered_relation(annotation, alias)\n            else:\n                clone.query.add_annotation(\n                    annotation,\n                    alias,\n                    select=select,\n                )\n        for alias, annotation in clone.query.annotations.items():\n            if alias in annotations and annotation.contains_aggregate:\n                if clone._fields is None:\n                    clone.query.group_by = True\n                else:\n                    clone.query.set_group_by()\n                break\n\n        return clone\n\n    def order_by(self, *field_names):\n        \"\"\"Return a new QuerySet instance with the ordering changed.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reorder a query once a slice has been taken.\")\n        obj = self._chain()\n        obj.query.clear_ordering(force=True, clear_default=False)\n        obj.query.add_ordering(*field_names)\n        return obj\n\n    def distinct(self, *field_names):\n        \"\"\"\n        Return a new QuerySet instance that will select only distinct results.\n        \"\"\"\n        self._not_support_combined_queries(\"distinct\")\n        if self.query.is_sliced:\n            raise TypeError(\n                \"Cannot create distinct fields once a slice has been taken.\"\n            )\n        obj = self._chain()\n        obj.query.add_distinct_fields(*field_names)\n        return obj\n\n    def extra(\n        self,\n        select=None,\n        where=None,\n        params=None,\n        tables=None,\n        order_by=None,\n        select_params=None,\n    ):\n        \"\"\"Add extra SQL fragments to the query.\"\"\"\n        self._not_support_combined_queries(\"extra\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.add_extra(select, select_params, where, params, tables, order_by)\n        return clone\n\n    def reverse(self):\n        \"\"\"Reverse the ordering of the QuerySet.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reverse a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.standard_ordering = not clone.query.standard_ordering\n        return clone\n\n    def defer(self, *fields):\n        \"\"\"\n        Defer the loading of data for certain fields until they are accessed.\n        Add the set of deferred fields to any existing set of deferred fields.\n        The only exception to this is if None is passed in as the only\n        parameter, in which case remove all deferrals.\n        \"\"\"\n        self._not_support_combined_queries(\"defer\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call defer() after .values() or .values_list()\")\n        clone = self._chain()\n        if fields == (None,):\n            clone.query.clear_deferred_loading()\n        else:\n            clone.query.add_deferred_loading(fields)\n        return clone\n\n    def only(self, *fields):\n        \"\"\"\n        Essentially, the opposite of defer(). Only the fields passed into this\n        method and that are not already specified as deferred are loaded\n        immediately when the queryset is evaluated.\n        \"\"\"\n        self._not_support_combined_queries(\"only\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call only() after .values() or .values_list()\")\n        if fields == (None,):\n            # Can only pass None to defer(), not only(), as the rest option.\n            # That won't stop people trying to do this, so let's be explicit.\n            raise TypeError(\"Cannot pass None as an argument to only().\")\n        for field in fields:\n            cv = 2\n            cw = -1\n            cx = 1\n            cy = -1\n            field = field.split(LOOKUP_SEP, (cv + cw))[(cx + cy)]\n            if field in self.query._filtered_relations:\n                raise ValueError(\"only() is not supported with FilteredRelation.\")\n        clone = self._chain()\n        clone.query.add_immediate_loading(fields)\n        return clone\n\n    def using(self, alias):\n        \"\"\"Select which database this QuerySet should execute against.\"\"\"\n        clone = self._chain()\n        clone._db = alias\n        return clone\n\n    def fetch_mode(self, fetch_mode):\n        \"\"\"Set the fetch mode for the QuerySet.\"\"\"\n        clone = self._chain()\n        clone._fetch_mode = fetch_mode\n        return clone\n\n    ###################################\n    # PUBLIC INTROSPECTION ATTRIBUTES #\n    ###################################\n\n    @property\n    def ordered(self):\n        \"\"\"\n        Return True if the QuerySet is ordered -- i.e. has an order_by()\n        clause or a default ordering on the model (or is empty).\n        \"\"\"\n        if isinstance(self, EmptyQuerySet):\n            return True\n        if self.query.extra_order_by or self.query.order_by:\n            return True\n        elif (\n            self.query.default_ordering\n            and self.query.get_meta().ordering\n            and\n            # A default ordering doesn't affect GROUP BY queries.\n            not self.query.group_by\n        ):\n            return True\n        else:\n            return False\n\n    @property\n    def totally_ordered(self):\n        \"\"\"\n        Returns True if the QuerySet is ordered and the ordering is\n        deterministic. This requires that the ordering includes a field\n        (or set of fields) that is unique and non-nullable.\n\n        For queries involving a GROUP BY clause, the model's default\n        ordering is ignored. Ordering specified via .extra(order_by=...)\n        is also ignored.\n        \"\"\"\n        if not self.ordered:\n            return False\n        ordering = self.query.order_by\n        if not ordering and self.query.default_ordering:\n            ordering = self.query.get_meta().ordering\n        if not ordering:\n            return False\n        opts = self.model._meta\n        pk_fields = {f.attname for f in opts.pk_fields}\n        candidate_fields = set()\n        for part in ordering:\n            # Search for single field providing a total ordering.\n            field_name = None\n            if isinstance(part, str):\n                field_name = part.lstrip(\"-\")\n            elif isinstance(part, F):\n                field_name = part.name\n            elif isinstance(part, OrderBy) and isinstance(part.expression, F):\n                field_name = part.expression.name\n            if annotation_col := self.query.annotations.get(field_name):\n                if isinstance(annotation_col, Col):\n                    if annotation_col.alias == self.query.base_table:\n                        candidate_fields.add(annotation_col.target)\n                elif isinstance(annotation_col, ColPairs):\n                    candidate_fields |= {\n                        c.target\n                        for c in annotation_col.get_cols()\n                        if c.alias == self.query.base_table\n                    }\n            elif field_name:\n                if field_name == \"pk\":\n                    return True\n                # Normalize attname references by using get_field().\n                try:\n                    field = opts.get_field(field_name)\n                except exceptions.FieldDoesNotExist:\n                    # Could be \"?\" for random ordering or a related field\n                    # lookup. Skip this part of introspection for now.\n                    continue\n                else:\n                    # Ordering by a related field name orders by the referenced\n                    # model's ordering. Skip this introspection for now.\n                    if field.remote_field and field_name == field.name:\n                        continue\n                    candidate_fields.add(field)\n\n        candidate_attnames = set()\n        for field in candidate_fields:\n            if field.unique and not field.null:\n                return True\n            candidate_attnames.add(field.attname)\n\n        # Account for members of a CompositePrimaryKey.\n        if candidate_attnames.issuperset(pk_fields):\n            return True\n        # No single total ordering field, try unique_together and total\n        # unique constraints.\n        constraint_field_names = (\n            *opts.unique_together,\n            *(constraint.fields for constraint in opts.total_unique_constraints),\n        )\n        for field_names in constraint_field_names:\n            # Normalize attname references by using get_field().\n            try:\n                fields = [opts.get_field(field_name) for field_name in field_names]\n            except exceptions.FieldDoesNotExist:\n                continue\n            # Composite unique constraints containing a nullable column\n            # cannot ensure total ordering.\n            if any(field.null for field in fields):\n                continue\n            if candidate_attnames.issuperset(field.attname for field in fields):\n                return True\n\n        return False\n\n    @property\n    def db(self):\n        \"\"\"Return the database used if this query is executed now.\"\"\"\n        if self._for_write:\n            return self._db or router.db_for_write(self.model, **self._hints)\n        return self._db or router.db_for_read(self.model, **self._hints)\n\n    ###################\n    # PRIVATE METHODS #\n    ###################\n\n    def _insert(\n        self,\n        objs,\n        fields,\n        returning_fields=None,\n        raw=False,\n        using=None,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert a new record for the given model. This provides an interface to\n        the InsertQuery class and is how Model.save() is implemented.\n        \"\"\"\n        self._for_write = True\n        if using is None:\n            using = self.db\n        query = sql.InsertQuery(\n            self.model,\n            on_conflict=on_conflict,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n        query.insert_values(fields, objs, raw=raw)\n        return query.get_compiler(using=using).execute_sql(returning_fields)\n\n    _insert.alters_data = True\n    _insert.queryset_only = False\n\n    def _batched_insert(\n        self,\n        objs,\n        fields,\n        batch_size,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Helper method for bulk_create() to insert objs one batch at a time.\n        \"\"\"\n        connection = connections[self.db]\n        ops = connection.ops\n        cz = 2\n        da = -1\n        max_batch_size = max(ops.bulk_batch_size(fields, objs), (cz + da))\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        inserted_rows = []\n        returning_fields = (\n            self.model._meta.db_returning_fields\n            if (\n                connection.features.can_return_rows_from_bulk_insert\n                and (on_conflict is None or on_conflict == OnConflict.UPDATE)\n            )\n            else None\n        )\n        db = 1\n        dc = -1\n        batches = [objs[i : i + batch_size] for i in range((db + dc), len(objs), batch_size)]\n        dd = 2\n        de = -1\n        if len(batches) > (dd + de):\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            for item in batches:\n                inserted_rows.extend(\n                    self._insert(\n                        item,\n                        fields=fields,\n                        using=self.db,\n                        on_conflict=on_conflict,\n                        update_fields=update_fields,\n                        unique_fields=unique_fields,\n                        returning_fields=returning_fields,\n                    )\n                )\n        return inserted_rows\n\n    def _disable_cloning(self):\n        \"\"\"\n        Prevent calls to _chain() from creating a new QuerySet via _clone().\n        All subsequent QuerySet mutations will occur on this instance until\n        _enable_cloning() is used.\n        \"\"\"\n        self._cloning_enabled = False\n        return self\n\n    def _enable_cloning(self):\n        \"\"\"\n        Allow calls to _chain() to create a new QuerySet via _clone(). Restores\n        the default behavior where any QuerySet mutation will return a new\n        QuerySet instance. Necessary only when there has been a\n        _disable_cloning() call previously.\n        \"\"\"\n        self._cloning_enabled = True\n        return self\n\n    def _avoid_cloning(self):\n        \"\"\"\n        Temporarily prevent QuerySet _clone() operations, restoring the default\n        behavior on exit. For the duration of the context managed statement,\n        all operations (e.g. filter(), exclude(), etc.) will mutate the same\n        QuerySet instance.\n\n        @contextlib.contextmanager is intentionally not used for performance\n        reasons.\n        \"\"\"\n        return PreventQuerySetCloning(self)\n\n    def _chain(self):\n        \"\"\"\n        Return a copy of the current QuerySet that's ready for another\n        operation.\n\n        If the QuerySet has opted in to in-place mutations via\n        _disable_cloning() temporarily, the copy doesn't occur and instead the\n        same QuerySet instance will be modified.\n        \"\"\"\n        if not self._cloning_enabled:\n            obj = self\n        else:\n            obj = self._clone()\n        if obj._sticky_filter:\n            obj.query.filter_is_sticky = True\n            obj._sticky_filter = False\n        return obj\n\n    def _clone(self):\n        \"\"\"\n        Return a copy of the current QuerySet. A lightweight alternative\n        to deepcopy().\n        \"\"\"\n        c = self.__class__(\n            model=self.model,\n            query=self.query.chain(),\n            using=self._db,\n            hints=self._hints,\n        )\n        c._sticky_filter = self._sticky_filter\n        c._for_write = self._for_write\n        c._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        c._known_related_objects = self._known_related_objects\n        c._iterable_class = self._iterable_class\n        c._fetch_mode = self._fetch_mode\n        c._fields = self._fields\n        return c\n\n    def _fetch_all(self):\n        if self._result_cache is None:\n            self._result_cache = list(self._iterable_class(self))\n        if self._prefetch_related_lookups and not self._prefetch_done:\n            self._prefetch_related_objects()\n\n    def _next_is_sticky(self):\n        \"\"\"\n        Indicate that the next filter call and the one following that should\n        be treated as a single filter. This is only important when it comes to\n        determining when to reuse tables for many-to-many filters. Required so\n        that we can filter naturally on the results of related managers.\n\n        This doesn't return a clone of the current QuerySet (it returns\n        \"self\"). The method is only used internally and should be immediately\n        followed by a filter() that does create a clone.\n        \"\"\"\n        self._sticky_filter = True\n        return self\n\n    def _merge_sanity_check(self, other):\n        \"\"\"Check that two QuerySet classes may be merged.\"\"\"\n        if self._fields is not None and (\n            set(self.query.values_select) != set(other.query.values_select)\n            or set(self.query.extra_select) != set(other.query.extra_select)\n            or set(self.query.annotation_select) != set(other.query.annotation_select)\n        ):\n            raise TypeError(\n                \"Merging '%s' classes must involve the same values in each case.\"\n                % self.__class__.__name__\n            )\n\n    def _merge_known_related_objects(self, other):\n        \"\"\"\n        Keep track of all known related objects from either QuerySet instance.\n        \"\"\"\n        for field, objects in other._known_related_objects.items():\n            self._known_related_objects.setdefault(field, {}).update(objects)\n\n    def resolve_expression(self, *args, **kwargs):\n        query = self.query.resolve_expression(*args, **kwargs)\n        query._db = self._db\n        return query\n\n    resolve_expression.queryset_only = True\n\n    def _add_hints(self, **hints):\n        \"\"\"\n        Update hinting information for use by routers. Add new key/values or\n        overwrite existing key/values.\n        \"\"\"\n        self._hints.update(hints)\n\n    def _has_filters(self):\n        \"\"\"\n        Check if this QuerySet has any filtering going on. This isn't\n        equivalent with checking if all objects are present in results, for\n        example, qs[1:]._has_filters() -> False.\n        \"\"\"\n        return self.query.has_filters()\n\n    @staticmethod\n    def _validate_values_are_expressions(values, method_name):\n        invalid_args = sorted(\n            str(arg) for arg in values if not hasattr(arg, \"resolve_expression\")\n        )\n        if invalid_args:\n            raise TypeError(\n                \"QuerySet.%s() received non-expression(s): %s.\"\n                % (\n                    method_name,\n                    \", \".join(invalid_args),\n                )\n            )\n\n    def _not_support_combined_queries(self, operation_name):\n        if self.query.combinator:\n            raise NotSupportedError(\n                \"Calling QuerySet.%s() after %s() is not supported.\"\n                % (operation_name, self.query.combinator)\n            )\n\n    def _check_operator_queryset(self, other, operator_):\n        if self.query.combinator or other.query.combinator:\n            raise TypeError(f\"Cannot use {operator_} operator with combined queryset.\")\n\n    def _check_ordering_first_last_queryset_aggregation(self, method):\n        if (\n            isinstance(self.query.group_by, tuple)\n            # Raise if the pk fields are not in the group_by.\n            and self.model._meta.pk\n            not in {col.output_field for col in self.query.group_by}\n            and set(self.model._meta.pk_fields).difference(\n                {col.target for col in self.query.group_by}\n            )\n        ):\n            raise TypeError(\n                f\"Cannot use QuerySet.{method}() on an unordered queryset performing \"\n                f\"aggregation. Add an ordering with order_by().\"\n            )\n\n    def _clear_ordering_in_combined_queries(self, cloned_query, other_qs):\n        combined_queries = [self.query]\n        for qs in other_qs:\n            query = qs.query.clone()\n            query.clear_ordering(force=False, clear_default=False)\n            combined_queries.append(query)\n        cloned_query.combined_queries = tuple(combined_queries)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-765e7606ef75a519", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "28e3aca22969e468281e36a823493afe46af403ca23dcaaea1e88fcf81df66b5", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 2204, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__QuerySet__909bc25b.py", "order": 11, "original_content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "parent_variant_id": "pyint-5c2b55814568-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/query.py#L374-L2424", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 51, "intermediate_variables_introduced": 102, "statements_augmented": 45}, "unit_kind": "class", "unit_name": "QuerySet", "variant_id": "pyint-182e909bc25b-I11", "group_id": "py-765e7606ef75a519", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 236, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f45f80ede047-I12", "source": "import copy\nimport operator\nimport warnings\nfrom contextlib import nullcontext\nfrom functools import partial, reduce\nfrom itertools import chain, islice\nfrom weakref import ref as weak_ref\nfrom asgiref.sync import sync_to_async\nimport django\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.db import (\n    DJANGO_VERSION_PICKLE_KEY,\n    IntegrityError,\n    NotSupportedError,\n    connections,\n    router,\n    transaction,\n)\nfrom django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql\nfrom django.db.models.constants import LOOKUP_SEP, OnConflict\nfrom django.db.models.deletion import Collector\nfrom django.db.models.expressions import (\n    Case,\n    Col,\n    ColPairs,\n    DatabaseDefault,\n    F,\n    OrderBy,\n    Value,\n    When,\n)\nfrom django.db.models.fetch_modes import FETCH_ONE\nfrom django.db.models.functions import Cast, Trunc\nfrom django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q\nfrom django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT\nfrom django.db.models.utils import (\n    AltersData,\n    create_namedtuple_class,\n    resolve_callables,\n)\nfrom django.utils import timezone\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    RemovedInDjango71Warning,\n    warn_about_external_use,\n)\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import func_accepts_kwargs, func_supports_parameter\nfrom django.utils.warnings import django_file_prefixes\n\nclass QuerySet(AltersData):\n    \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n    def __init__(self, model=None, query=None, using=None, hints=None):\n        self.model = model\n        self._db = using\n        self._hints = hints or {}\n        self._query = query or sql.Query(self.model)\n        self._result_cache = None\n        self._sticky_filter = False\n        self._for_write = False\n        self._prefetch_related_lookups = ()\n        self._prefetch_done = False\n        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}\n        self._iterable_class = ModelIterable\n        self._fetch_mode = DEFAULT_FETCH_MODE\n        self._fields = None\n        self._defer_next_filter = False\n        self._deferred_filter = None\n        self._cloning_enabled = True\n\n    @property\n    def query(self):\n        if self._deferred_filter:\n            negate, args, kwargs = self._deferred_filter\n            self._filter_or_exclude_inplace(negate, args, kwargs)\n            self._deferred_filter = None\n        return self._query\n\n    @query.setter\n    def query(self, value):\n        if value.values_select:\n            self._iterable_class = ValuesIterable\n        self._query = value\n\n    def as_manager(cls):\n        # Address the circular dependency between `Queryset` and `Manager`.\n        from django.db.models.manager import Manager\n\n        manager = Manager.from_queryset(cls)()\n        manager._built_with_as_manager = True\n        return manager\n\n    as_manager.queryset_only = True\n    as_manager = classmethod(as_manager)\n\n    ########################\n    # PYTHON MAGIC METHODS #\n    ########################\n\n    def __deepcopy__(self, memo):\n        \"\"\"Don't populate the QuerySet's cache.\"\"\"\n        obj = self.__class__()\n        for k, v in self.__dict__.items():\n            if k == \"_result_cache\":\n                obj.__dict__[k] = None\n            else:\n                obj.__dict__[k] = copy.deepcopy(v, memo)\n        return obj\n\n    def __getstate__(self):\n        # Force the cache to be fully populated.\n        self._fetch_all()\n        return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n    def __setstate__(self, state):\n        pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)\n        if pickled_version:\n            if pickled_version != django.__version__:\n                warnings.warn(\n                    \"Pickled queryset instance's Django version %s does not \"\n                    \"match the current version %s.\"\n                    % (pickled_version, django.__version__),\n                    RuntimeWarning,\n                    stacklevel=2,\n                )\n        else:\n            warnings.warn(\n                \"Pickled queryset instance's Django version is not specified.\",\n                RuntimeWarning,\n                stacklevel=2,\n            )\n        self.__dict__.update(state)\n\n    def __repr__(self):\n        data = list(self[: REPR_OUTPUT_SIZE + 1])\n        if len(data) > REPR_OUTPUT_SIZE:\n            data[-1] = \"...(remaining elements truncated)...\"\n        return \"<%s %r>\" % (self.__class__.__name__, data)\n\n    def __len__(self):\n        self._fetch_all()\n        return len(self._result_cache)\n\n    def __iter__(self):\n        \"\"\"\n        The queryset iterator protocol uses three nested iterators in the\n        default case:\n            1. sql.compiler.execute_sql()\n               - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n                 using cursor.fetchmany(). This part is responsible for\n                 doing some column masking, and returning the rows in chunks.\n            2. sql.compiler.results_iter()\n               - Returns one row at time. At this point the rows are still just\n                 tuples. In some cases the return values are converted to\n                 Python values at this location.\n            3. self.iterator()\n               - Responsible for turning the rows into model objects.\n        \"\"\"\n        self._fetch_all()\n        return iter(self._result_cache)\n\n    def __aiter__(self):\n        # Remember, __aiter__ itself is synchronous, it's the thing it returns\n        # that is async!\n        async def generator():\n            await sync_to_async(self._fetch_all)()\n            for item in self._result_cache:\n                yield item\n\n        return generator()\n\n    def __bool__(self):\n        self._fetch_all()\n        return bool(self._result_cache)\n\n    def __getitem__(self, k):\n        \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n        if not isinstance(k, (int, slice)):\n            raise TypeError(\n                \"QuerySet indices must be integers or slices, not %s.\"\n                % type(k).__name__\n            )\n        if (isinstance(k, int) and k < 0) or (\n            isinstance(k, slice)\n            and (\n                (k.start is not None and k.start < 0)\n                or (k.stop is not None and k.stop < 0)\n            )\n        ):\n            raise ValueError(\"Negative indexing is not supported.\")\n\n        if self._result_cache is not None:\n            return self._result_cache[k]\n\n        if isinstance(k, slice):\n            qs = self._chain()\n            if k.start is not None:\n                start = int(k.start)\n            else:\n                start = None\n            if k.stop is not None:\n                stop = int(k.stop)\n            else:\n                stop = None\n            qs.query.set_limits(start, stop)\n            return list(qs)[:: k.step] if k.step else qs\n\n        qs = self._chain()\n        qs.query.set_limits(k, k + 1)\n        qs._fetch_all()\n        return qs._result_cache[0]\n\n    def __class_getitem__(cls, *args, **kwargs):\n        return cls\n\n    def __and__(self, other):\n        self._check_operator_queryset(other, \"&\")\n        self._merge_sanity_check(other)\n        if isinstance(other, EmptyQuerySet):\n            return other\n        if isinstance(self, EmptyQuerySet):\n            return self\n        combined = self._chain()\n        combined._merge_known_related_objects(other)\n        combined.query.combine(other.query, sql.AND)\n        return combined\n\n    def __or__(self, other):\n        self._check_operator_queryset(other, \"|\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.OR)\n        return combined\n\n    def __xor__(self, other):\n        self._check_operator_queryset(other, \"^\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.XOR)\n        return combined\n\n    ####################################\n    # METHODS THAT DO DATABASE QUERIES #\n    ####################################\n\n    def _iterator(self, use_chunked_fetch, chunk_size):\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if not self._prefetch_related_lookups or chunk_size is None:\n            yield from iterable\n            return\n\n        iterator = iter(iterable)\n        while results := list(islice(iterator, chunk_size)):\n            prefetch_related_objects(results, *self._prefetch_related_lookups)\n            yield from results\n\n    def iterator(self, chunk_size=None):\n        \"\"\"\n        An iterator over the results from applying this QuerySet to the\n        database. chunk_size must be provided for QuerySets that prefetch\n        related objects. Otherwise, a default chunk_size of 2000 is supplied.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                raise ValueError(\n                    \"chunk_size must be provided when using QuerySet.iterator() after \"\n                    \"prefetch_related().\"\n                )\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        \n        return self._iterator((not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )), chunk_size)\n\n    async def aiterator(self, chunk_size=None):\n        \"\"\"\n        An asynchronous iterator over the results from applying this QuerySet\n        to the database.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                # RemovedInDjango71Warning: Replace the warning with:\n                # raise ValueError(\n                #     \"chunk_size must be provided when using \"\n                #     \"QuerySet.aiterator() after prefetch_related().\"\n                # )\n                warnings.warn(\n                    \"Using QuerySet.aiterator() after prefetch_related() without \"\n                    \"providing a chunk_size is deprecated and will raise a \"\n                    \"ValueError in Django 7.1.\",\n                    category=RemovedInDjango71Warning,\n                    skip_file_prefixes=django_file_prefixes(),\n                )\n                # RemovedInDjango71Warning: When the deprecation ends, remove.\n                chunk_size = 2000\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if self._prefetch_related_lookups:\n            results = []\n\n            async for item in iterable:\n                results.append(item)\n                if len(results) >= chunk_size:\n                    await aprefetch_related_objects(\n                        results, *self._prefetch_related_lookups\n                    )\n                    for result in results:\n                        yield result\n                    results.clear()\n\n            if results:\n                await aprefetch_related_objects(\n                    results, *self._prefetch_related_lookups\n                )\n                for result in results:\n                    yield result\n        else:\n            async for item in iterable:\n                yield item\n\n    def aggregate(self, *args, **kwargs):\n        \"\"\"\n        Return a dictionary containing the calculations (aggregation)\n        over the current queryset.\n\n        If args is present the expression is passed as a kwarg using\n        the Aggregate object's default alias.\n        \"\"\"\n        if self.query.distinct_fields:\n            raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n        self._validate_values_are_expressions(\n            (*args, *kwargs.values()), method_name=\"aggregate\"\n        )\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                arg.default_alias\n            except (AttributeError, TypeError):\n                raise TypeError(\"Complex aggregates require an alias\")\n            kwargs[arg.default_alias] = arg\n\n        return self.query.chain().get_aggregation(self.db, kwargs)\n\n    async def aaggregate(self, *args, **kwargs):\n        return await sync_to_async(self.aggregate)(*args, **kwargs)\n\n    def count(self):\n        \"\"\"\n        Perform a SELECT COUNT() and return the number of records as an\n        integer.\n\n        If the QuerySet is already fully cached, return the length of the\n        cached results set to avoid multiple SELECT COUNT(*) calls.\n        \"\"\"\n        if self._result_cache is not None:\n            return len(self._result_cache)\n\n        return self.query.get_count(using=self.db)\n\n    async def acount(self):\n        return await sync_to_async(self.count)()\n\n    def get(self, *args, **kwargs):\n        \"\"\"\n        Perform the query and return a single object matching the given\n        keyword arguments.\n        \"\"\"\n        if self.query.combinator and (args or kwargs):\n            raise NotSupportedError(\n                \"Calling QuerySet.get(...) with filters after %s() is not \"\n                \"supported.\" % self.query.combinator\n            )\n        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)\n        if self.query.can_filter() and not self.query.distinct_fields:\n            clone = clone.order_by()\n        limit = None\n        if (\n            not clone.query.select_for_update\n            or connections[clone.db].features.supports_select_for_update_with_limit\n        ):\n            limit = MAX_GET_RESULTS\n            clone.query.set_limits(high=limit)\n        num = len(clone)\n        if num == 1:\n            return clone._result_cache[0]\n        if not num:\n            raise self.model.DoesNotExist(\n                \"%s matching query does not exist.\" % self.model._meta.object_name\n            )\n        raise self.model.MultipleObjectsReturned(\n            \"get() returned more than one %s -- it returned %s!\"\n            % (\n                self.model._meta.object_name,\n                num if not limit or num < limit else \"more than %s\" % (limit - 1),\n            )\n        )\n\n    async def aget(self, *args, **kwargs):\n        return await sync_to_async(self.get)(*args, **kwargs)\n\n    def create(self, **kwargs):\n        \"\"\"\n        Create a new object with the given kwargs, saving it to the database\n        and returning the created object.\n        \"\"\"\n        reverse_one_to_one_fields = frozenset(kwargs).intersection(\n            self.model._meta._reverse_one_to_one_field_names\n        )\n        if reverse_one_to_one_fields:\n            raise ValueError(\n                \"The following fields do not exist in this model: %s\"\n                % \", \".join(reverse_one_to_one_fields)\n            )\n\n        obj = self.model(**kwargs)\n        self._for_write = True\n        obj.save(force_insert=True, using=self.db)\n        obj._state.fetch_mode = self._fetch_mode\n        return obj\n\n    create.alters_data = True\n\n    async def acreate(self, **kwargs):\n        return await sync_to_async(self.create)(**kwargs)\n\n    acreate.alters_data = True\n\n    def _prepare_for_bulk_create(self, objs):\n        objs_with_pk, objs_without_pk = [], []\n        for obj in objs:\n            obj._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n            if isinstance(obj.pk, DatabaseDefault):\n                objs_without_pk.append(obj)\n            elif obj._is_pk_set():\n                objs_with_pk.append(obj)\n            else:\n                obj.pk = obj._meta.pk.get_pk_value_on_save(obj)\n                if obj._is_pk_set():\n                    objs_with_pk.append(obj)\n                else:\n                    objs_without_pk.append(obj)\n        return objs_with_pk, objs_without_pk\n\n    def _check_bulk_create_options(\n        self, ignore_conflicts, update_conflicts, update_fields, unique_fields\n    ):\n        if ignore_conflicts and update_conflicts:\n            raise ValueError(\n                \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n            )\n        db_features = connections[self.db].features\n        if ignore_conflicts:\n            if not db_features.supports_ignore_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support ignoring conflicts.\"\n                )\n            return OnConflict.IGNORE\n        elif update_conflicts:\n            if not db_features.supports_update_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support updating conflicts.\"\n                )\n            if not update_fields:\n                raise ValueError(\n                    \"Fields that will be updated when a row insertion fails \"\n                    \"on conflicts must be provided.\"\n                )\n            if unique_fields and not db_features.supports_update_conflicts_with_target:\n                raise NotSupportedError(\n                    \"This database backend does not support updating \"\n                    \"conflicts with specifying unique fields that can trigger \"\n                    \"the upsert.\"\n                )\n            if not unique_fields and db_features.supports_update_conflicts_with_target:\n                raise ValueError(\n                    \"Unique fields that can trigger the upsert must be provided.\"\n                )\n            # Updating primary keys and non-concrete fields is forbidden.\n            if any(not f.concrete for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() can only be used with concrete fields in \"\n                    \"update_fields.\"\n                )\n            if any(f in self.model._meta.pk_fields for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() cannot be used with primary keys in \"\n                    \"update_fields.\"\n                )\n            if unique_fields:\n                if any(not f.concrete for f in unique_fields):\n                    raise ValueError(\n                        \"bulk_create() can only be used with concrete fields \"\n                        \"in unique_fields.\"\n                    )\n            return OnConflict.UPDATE\n        return None\n\n    def bulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert each of the instances into the database. Do *not* call\n        save() on each of the instances, do not send any pre/post_save\n        signals, and do not set the primary key attribute if it is an\n        autoincrement field (except if\n        features.can_return_rows_from_bulk_insert=True).\n        Multi-table models are not supported.\n        \"\"\"\n        # When you bulk insert you don't get the primary keys back (if it's an\n        # autoincrement, except if can_return_rows_from_bulk_insert=True), so\n        # you can't insert into the child tables which references this. There\n        # are two workarounds:\n        # 1) This could be implemented if you didn't have an autoincrement pk\n        # 2) You could do it by doing O(n) normal inserts into the parent\n        #    tables to get the primary keys back and then doing a single bulk\n        #    insert into the childmost table.\n        # We currently set the primary keys on the objects when using\n        # PostgreSQL via the RETURNING ID clause. It should be possible for\n        # Oracle as well, but the semantics for extracting the primary keys is\n        # trickier so it's not done yet.\n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        # Check that the parents share the same concrete model with the our\n        # model to detect the inheritance pattern ConcreteGrandParent ->\n        # MultiTableParent -> ProxyChild. Simply checking\n        # self.model._meta.proxy would not identify that case as involving\n        # multiple tables.\n        for parent in self.model._meta.all_parents:\n            if parent._meta.concrete_model is not self.model._meta.concrete_model:\n                raise ValueError(\"Can't bulk create a multi-table inherited model\")\n        if not objs:\n            return objs\n        opts = self.model._meta\n        if unique_fields:\n            # Primary key is allowed in unique_fields.\n            unique_fields = [\n                self.model._meta.get_field(opts.pk.name if name == \"pk\" else name)\n                for name in unique_fields\n            ]\n        if update_fields:\n            update_fields = [self.model._meta.get_field(name) for name in update_fields]\n        on_conflict = self._check_bulk_create_options(\n            ignore_conflicts,\n            update_conflicts,\n            update_fields,\n            unique_fields,\n        )\n        self._for_write = True\n        fields = [f for f in opts.concrete_fields if not f.generated]\n        objs = list(objs)\n        objs_with_pk, objs_without_pk = self._prepare_for_bulk_create(objs)\n        if objs_with_pk and objs_without_pk:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            self._handle_order_with_respect_to(objs)\n            if objs_with_pk:\n                returned_columns = self._batched_insert(\n                    objs_with_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                for obj_with_pk, results in zip(objs_with_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_with_pk, field.attname, result)\n                for obj_with_pk in objs_with_pk:\n                    obj_with_pk._state.adding = False\n                    obj_with_pk._state.db = self.db\n            if objs_without_pk:\n                fields = [f for f in fields if not isinstance(f, AutoField)]\n                returned_columns = self._batched_insert(\n                    objs_without_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                connection = connections[self.db]\n                if (\n                    connection.features.can_return_rows_from_bulk_insert\n                    and on_conflict is None\n                ):\n                    assert len(returned_columns) == len(objs_without_pk)\n                for obj_without_pk, results in zip(objs_without_pk, returned_columns):\n                    for result, field in zip(results, opts.db_returning_fields):\n                        setattr(obj_without_pk, field.attname, result)\n                    obj_without_pk._state.adding = False\n                    obj_without_pk._state.db = self.db\n\n        return objs\n\n    def _handle_order_with_respect_to(self, objs):\n        if objs and (order_wrt := self.model._meta.order_with_respect_to):\n            get_filter_kwargs_for_object = order_wrt.get_filter_kwargs_for_object\n            attnames = list(get_filter_kwargs_for_object(objs[0]))\n            group_keys = set()\n            obj_groups = []\n            for obj in objs:\n                group_key = tuple(get_filter_kwargs_for_object(obj).values())\n                group_keys.add(group_key)\n                obj_groups.append((obj, group_key))\n            filters = [\n                Q.create(list(zip(attnames, group_key))) for group_key in group_keys\n            ]\n            next_orders = (\n                self.model._base_manager.using(self.db)\n                .filter(reduce(operator.or_, filters))\n                .values_list(*attnames)\n                .annotate(_order__max=Max(\"_order\") + 1)\n            )\n            # Create mapping of group values to max order.\n            group_next_orders = dict.fromkeys(group_keys, 0)\n            group_next_orders.update(\n                (tuple(group_key), next_order) for *group_key, next_order in next_orders\n            )\n            # Assign _order values to new objects.\n            for obj, group_key in obj_groups:\n                if getattr(obj, \"_order\", None) is None:\n                    group_next_order = group_next_orders[group_key]\n                    obj._order = group_next_order\n                    group_next_orders[group_key] += 1\n\n    bulk_create.alters_data = True\n\n    async def abulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        return await sync_to_async(self.bulk_create)(\n            objs=objs,\n            batch_size=batch_size,\n            ignore_conflicts=ignore_conflicts,\n            update_conflicts=update_conflicts,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n\n    abulk_create.alters_data = True\n\n    def bulk_update(self, objs, fields, batch_size=None):\n        \"\"\"\n        Update the given fields in each of the given objects in the database.\n        \"\"\"\n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        if not fields:\n            raise ValueError(\"Field names must be given to bulk_update().\")\n        objs = tuple(objs)\n        if not all(obj._is_pk_set() for obj in objs):\n            raise ValueError(\"All bulk_update() objects must have a primary key set.\")\n        opts = self.model._meta\n        fields = [opts.get_field(name) for name in fields]\n        if any(not f.concrete for f in fields):\n            raise ValueError(\"bulk_update() can only be used with concrete fields.\")\n        all_pk_fields = set(opts.pk_fields)\n        for parent in opts.all_parents:\n            all_pk_fields.update(parent._meta.pk_fields)\n        if any(f in all_pk_fields for f in fields):\n            raise ValueError(\"bulk_update() cannot be used with primary key fields.\")\n        if not objs:\n            return 0\n        for obj in objs:\n            obj._prepare_related_fields_for_save(\n                operation_name=\"bulk_update\", fields=fields\n            )\n        # PK is used twice in the resulting update query, once in the filter\n        # and once in the WHEN. Each field will also have one CAST.\n        self._for_write = True\n        connection = connections[self.db]\n        max_batch_size = connection.ops.bulk_batch_size(\n            [opts.pk, opts.pk, *fields], objs\n        )\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        requires_casting = connection.features.requires_casted_case_in_updates\n        batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size))\n        updates = []\n        for batch_objs in batches:\n            update_kwargs = {}\n            for field in fields:\n                when_statements = []\n                for obj in batch_objs:\n                    attr = getattr(obj, field.attname)\n                    if not hasattr(attr, \"resolve_expression\"):\n                        attr = Value(attr, output_field=field)\n                    when_statements.append(When(pk=obj.pk, then=attr))\n                case_statement = Case(*when_statements, output_field=field)\n                if requires_casting:\n                    case_statement = Cast(case_statement, output_field=field)\n                update_kwargs[field.attname] = case_statement\n            updates.append(([obj.pk for obj in batch_objs], update_kwargs))\n        rows_updated = 0\n        queryset = self.using(self.db)\n        with transaction.atomic(using=self.db, savepoint=False):\n            for pks, update_kwargs in updates:\n                rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs)\n        return rows_updated\n\n    bulk_update.alters_data = True\n\n    async def abulk_update(self, objs, fields, batch_size=None):\n        return await sync_to_async(self.bulk_update)(\n            objs=objs,\n            fields=fields,\n            batch_size=batch_size,\n        )\n\n    abulk_update.alters_data = True\n\n    def get_or_create(self, defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, creating one if necessary.\n        Return a tuple of (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        # The get() needs to be targeted at the write database in order\n        # to avoid potential transaction consistency problems.\n        self._for_write = True\n        try:\n            return self.get(**kwargs), False\n        except self.model.DoesNotExist:\n            params = self._extract_model_params(defaults, **kwargs)\n            # Try to create an object using passed params.\n            try:\n                with transaction.atomic(using=self.db):\n                    params = dict(resolve_callables(params))\n                    return self.create(**params), True\n            except IntegrityError:\n                try:\n                    return self.get(**kwargs), False\n                except self.model.DoesNotExist:\n                    pass\n                raise\n\n    get_or_create.alters_data = True\n\n    async def aget_or_create(self, defaults=None, **kwargs):\n        return await sync_to_async(self.get_or_create)(\n            defaults=defaults,\n            **kwargs,\n        )\n\n    aget_or_create.alters_data = True\n\n    def update_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, updating one with defaults\n        if it exists, otherwise create a new one. Optionally, an object can\n        be created with different values than defaults by using\n        create_defaults.\n        Return a tuple (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        update_defaults = defaults or {}\n        if create_defaults is None:\n            create_defaults = update_defaults\n\n        self._for_write = True\n        with transaction.atomic(using=self.db):\n            # Lock the row so that a concurrent update is blocked until\n            # update_or_create() has performed its save.\n            obj, created = self.select_for_update().get_or_create(\n                create_defaults, **kwargs\n            )\n            if created:\n                return obj, created\n            for k, v in resolve_callables(update_defaults):\n                setattr(obj, k, v)\n\n            update_fields = set(update_defaults)\n            concrete_field_names = self.model._meta._non_pk_concrete_field_names\n            # update_fields does not support non-concrete fields.\n            if concrete_field_names.issuperset(update_fields):\n                # Add fields which are set on pre_save(), e.g. auto_now fields.\n                # This is to maintain backward compatibility as these fields\n                # are not updated unless explicitly specified in the\n                # update_fields list.\n                pk_fields = self.model._meta.pk_fields\n                for field in self.model._meta.local_concrete_fields:\n                    if not (\n                        field in pk_fields or field.__class__.pre_save is Field.pre_save\n                    ):\n                        update_fields.add(field.name)\n                        if field.name != field.attname:\n                            update_fields.add(field.attname)\n                obj.save(using=self.db, update_fields=update_fields)\n            else:\n                obj.save(using=self.db)\n        return obj, False\n\n    update_or_create.alters_data = True\n\n    async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        return await sync_to_async(self.update_or_create)(\n            defaults=defaults,\n            create_defaults=create_defaults,\n            **kwargs,\n        )\n\n    aupdate_or_create.alters_data = True\n\n    def _extract_model_params(self, defaults, **kwargs):\n        \"\"\"\n        Prepare `params` for creating a model instance based on the given\n        kwargs; for use by get_or_create().\n        \"\"\"\n        defaults = defaults or {}\n        params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}\n        params.update(defaults)\n        property_names = self.model._meta._property_names\n        invalid_params = []\n        for param in params:\n            try:\n                self.model._meta.get_field(param)\n            except exceptions.FieldDoesNotExist:\n                # It's okay to use a model's property if it has a setter.\n                if not (param in property_names and getattr(self.model, param).fset):\n                    invalid_params.append(param)\n        if invalid_params:\n            raise exceptions.FieldError(\n                \"Invalid field name(s) for model %s: '%s'.\"\n                % (\n                    self.model._meta.object_name,\n                    \"', '\".join(sorted(invalid_params)),\n                )\n            )\n        return params\n\n    def _earliest(self, *fields):\n        \"\"\"\n        Return the earliest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if fields:\n            order_by = fields\n        else:\n            order_by = getattr(self.model._meta, \"get_latest_by\")\n            if order_by and not isinstance(order_by, (tuple, list)):\n                order_by = (order_by,)\n        if order_by is None:\n            raise ValueError(\n                \"earliest() and latest() require either fields as positional \"\n                \"arguments or 'get_latest_by' in the model's Meta.\"\n            )\n        obj = self._chain()\n        obj.query.set_limits(high=1)\n        obj.query.clear_ordering(force=True)\n        obj.query.add_ordering(*order_by)\n        return obj.get()\n\n    def earliest(self, *fields):\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self._earliest(*fields)\n\n    async def aearliest(self, *fields):\n        return await sync_to_async(self.earliest)(*fields)\n\n    def latest(self, *fields):\n        \"\"\"\n        Return the latest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.reverse()._earliest(*fields)\n\n    async def alatest(self, *fields):\n        return await sync_to_async(self.latest)(*fields)\n\n    def first(self):\n        \"\"\"Return the first object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"first\")\n            queryset = self.order_by(\"pk\")\n        for obj in queryset[:1]:\n            return obj\n\n    async def afirst(self):\n        return await sync_to_async(self.first)()\n\n    def last(self):\n        \"\"\"Return the last object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self.reverse()\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"last\")\n            queryset = self.order_by(\"-pk\")\n        for obj in queryset[:1]:\n            return obj\n\n    async def alast(self):\n        return await sync_to_async(self.last)()\n\n    def in_bulk(self, id_list=None, *, field_name=\"pk\"):\n        \"\"\"\n        Return a dictionary mapping each of the given IDs to the object with\n        that ID. If `id_list` isn't provided, evaluate the entire QuerySet.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with in_bulk().\")\n        if id_list is not None and not id_list:\n            return {}\n        opts = self.model._meta\n        unique_fields = [\n            constraint.fields[0]\n            for constraint in opts.total_unique_constraints\n            if len(constraint.fields) == 1\n        ]\n        if (\n            field_name != \"pk\"\n            and not opts.get_field(field_name).unique\n            and field_name not in unique_fields\n            and self.query.distinct_fields != (field_name,)\n        ):\n            raise ValueError(\n                \"in_bulk()'s field_name must be a unique field but %r isn't.\"\n                % field_name\n            )\n\n        qs = self\n\n        def get_obj(obj):\n            return obj\n\n        if issubclass(self._iterable_class, ModelIterable):\n            # Raise an AttributeError if field_name is deferred.\n            get_key = operator.attrgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesIterable):\n            if field_name not in self.query.values_select:\n                qs = qs.values(field_name, *self.query.values_select)\n\n                def get_obj(obj):  # noqa: F811\n                    # We can safely mutate the dictionaries returned by\n                    # ValuesIterable here, since they are limited to the scope\n                    # of this function, and get_key runs before get_obj.\n                    del obj[field_name]\n                    return obj\n\n            get_key = operator.itemgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesListIterable):\n            try:\n                field_index = self.query.values_select.index(field_name)\n            except ValueError:\n                # field_name is missing from values_select, so add it.\n                field_index = 0\n                if issubclass(self._iterable_class, NamedValuesListIterable):\n                    kwargs = {\"named\": True}\n                else:\n                    kwargs = {}\n                    get_obj = operator.itemgetter(slice(1, None))\n                qs = qs.values_list(field_name, *self.query.values_select, **kwargs)\n\n            get_key = operator.itemgetter(field_index)\n\n        elif issubclass(self._iterable_class, FlatValuesListIterable):\n            if self.query.values_select == (field_name,):\n                # Mapping field_name to itself.\n                get_key = get_obj\n            else:\n                # Transform it back into a non-flat values_list().\n                qs = qs.values_list(field_name, *self.query.values_select)\n                get_key = operator.itemgetter(0)\n                get_obj = operator.itemgetter(1)\n\n        else:\n            raise TypeError(\n                f\"in_bulk() cannot be used with {self._iterable_class.__name__}.\"\n            )\n\n        if id_list is not None:\n            filter_key = \"{}__in\".format(field_name)\n            id_list = tuple(id_list)\n            batch_size = connections[self.db].ops.bulk_batch_size([opts.pk], id_list)\n            # If the database has a limit on the number of query parameters\n            # (e.g. SQLite), retrieve objects in batches if necessary.\n            if batch_size and batch_size < len(id_list):\n                results = ()\n                for offset in range(0, len(id_list), batch_size):\n                    batch = id_list[offset : offset + batch_size]\n                    results += tuple(qs.filter(**{filter_key: batch}))\n                qs = results\n            else:\n                qs = qs.filter(**{filter_key: id_list})\n        else:\n            qs = qs._chain()\n        return {get_key(obj): get_obj(obj) for obj in qs}\n\n    async def ain_bulk(self, id_list=None, *, field_name=\"pk\"):\n        return await sync_to_async(self.in_bulk)(\n            id_list=id_list,\n            field_name=field_name,\n        )\n\n    def delete(self):\n        \"\"\"Delete the records in the current QuerySet.\"\"\"\n        self._not_support_combined_queries(\"delete\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with delete().\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call delete() after .distinct(*fields).\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call delete() after .values() or .values_list()\")\n\n        del_query = self._chain()\n\n        # The delete is actually 2 queries - one to find related objects,\n        # and one to delete. Make sure that the discovery of related\n        # objects is performed on the same database as the deletion.\n        del_query._for_write = True\n\n        # Disable non-supported fields.\n        del_query.query.select_for_update = False\n        del_query.query.select_related = False\n        del_query.query.clear_ordering(force=True)\n\n        collector = Collector(using=del_query.db, origin=self)\n        collector.collect(del_query)\n        num_deleted, num_deleted_per_model = collector.delete()\n\n        # Clear the result cache, in case this QuerySet gets reused.\n        self._result_cache = None\n        return num_deleted, num_deleted_per_model\n\n    delete.alters_data = True\n    delete.queryset_only = True\n\n    async def adelete(self):\n        return await sync_to_async(self.delete)()\n\n    adelete.alters_data = True\n    adelete.queryset_only = True\n\n    def _raw_delete(self, using):\n        \"\"\"\n        Delete objects found from the given queryset in single direct SQL\n        query. No signals are sent and there is no protection for cascades.\n        \"\"\"\n        query = self.query.clone()\n        query.__class__ = sql.DeleteQuery\n        return query.get_compiler(using).execute_sql(ROW_COUNT)\n\n    _raw_delete.alters_data = True\n\n    def update(self, **kwargs):\n        \"\"\"\n        Update all elements in the current QuerySet, setting all the given\n        fields to the appropriate values.\n        \"\"\"\n        self._not_support_combined_queries(\"update\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call update() after .distinct(*fields).\")\n        self._for_write = True\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_values(kwargs)\n\n        # Inline annotations in order_by(), if possible.\n        new_order_by = []\n        for col in query.order_by:\n            alias = col\n            descending = False\n            if isinstance(alias, str) and alias.startswith(\"-\"):\n                alias = alias.removeprefix(\"-\")\n                descending = True\n            if annotation := query.annotations.get(alias):\n                if getattr(annotation, \"contains_aggregate\", False):\n                    raise exceptions.FieldError(\n                        f\"Cannot update when ordering by an aggregate: {annotation}\"\n                    )\n                if descending:\n                    annotation = annotation.desc()\n                new_order_by.append(annotation)\n            else:\n                new_order_by.append(col)\n        query.order_by = tuple(new_order_by)\n\n        # Clear SELECT clause as all annotation references were inlined by\n        # add_update_values() already.\n        query.clear_select_clause()\n        with transaction.mark_for_rollback_on_error(using=self.db):\n            rows = query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        self._result_cache = None\n        return rows\n\n    update.alters_data = True\n\n    async def aupdate(self, **kwargs):\n        return await sync_to_async(self.update)(**kwargs)\n\n    aupdate.alters_data = True\n\n    def _update(self, values, returning_fields=None):\n        \"\"\"\n        A version of update() that accepts field objects instead of field\n        names. Used primarily for model saving and not intended for use by\n        general code (it requires too much poking around at model internals to\n        be useful at that level).\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_fields(values)\n        # Clear any annotations so that they won't be present in subqueries.\n        query.annotations = {}\n        self._result_cache = None\n        if returning_fields is None:\n            return query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        return query.get_compiler(self.db).execute_returning_sql(returning_fields)\n\n    _update.alters_data = True\n    _update.queryset_only = False\n\n    def exists(self):\n        \"\"\"\n        Return True if the QuerySet would have any results, False otherwise.\n        \"\"\"\n        if self._result_cache is None:\n            return self.query.has_results(using=self.db)\n        return bool(self._result_cache)\n\n    async def aexists(self):\n        return await sync_to_async(self.exists)()\n\n    def contains(self, obj):\n        \"\"\"\n        Return True if the QuerySet contains the provided obj,\n        False otherwise.\n        \"\"\"\n        self._not_support_combined_queries(\"contains\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call QuerySet.contains() after .values() or .values_list().\"\n            )\n        try:\n            if obj._meta.concrete_model != self.model._meta.concrete_model:\n                return False\n        except AttributeError:\n            raise TypeError(\"'obj' must be a model instance.\")\n        if not obj._is_pk_set():\n            raise ValueError(\"QuerySet.contains() cannot be used on unsaved objects.\")\n        if self._result_cache is not None:\n            return obj in self._result_cache\n        return self.filter(pk=obj.pk).exists()\n\n    async def acontains(self, obj):\n        return await sync_to_async(self.contains)(obj=obj)\n\n    def _prefetch_related_objects(self):\n        # This method can only be called once the result cache has been filled.\n        prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)\n        self._prefetch_done = True\n\n    def explain(self, *, format=None, **options):\n        \"\"\"\n        Runs an EXPLAIN on the SQL query this QuerySet would perform, and\n        returns the results.\n        \"\"\"\n        return self.query.explain(using=self.db, format=format, **options)\n\n    async def aexplain(self, *, format=None, **options):\n        return await sync_to_async(self.explain)(format=format, **options)\n\n    ##################################################\n    # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #\n    ##################################################\n\n    def raw(self, raw_query, params=(), translations=None, using=None):\n        if using is None:\n            using = self.db\n        qs = RawQuerySet(\n            raw_query,\n            model=self.model,\n            params=params,\n            translations=translations,\n            using=using,\n            fetch_mode=self._fetch_mode,\n        )\n        qs._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        return qs\n\n    def _values(self, *fields, **expressions):\n        clone = self._chain()\n        if expressions:\n            # RemovedInDjango70Warning: When the deprecation ends, deindent as:\n            # clone = clone.annotate(**expressions)\n            with warnings.catch_warnings(\n                action=\"ignore\", category=RemovedInDjango70Warning\n            ):\n                clone = clone.annotate(**expressions)\n        clone._fields = fields\n        clone.query.set_values(fields)\n        return clone\n\n    def values(self, *fields, **expressions):\n        fields += tuple(expressions)\n        clone = self._values(*fields, **expressions)\n        clone._iterable_class = ValuesIterable\n        return clone\n\n    def values_list(self, *fields, flat=False, named=False):\n        if flat and named:\n            raise TypeError(\"'flat' and 'named' can't be used together.\")\n        if flat:\n            if len(fields) > 1:\n                raise TypeError(\n                    \"'flat' is not valid when values_list is called with more than one \"\n                    \"field.\"\n                )\n            elif not fields:\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # raise TypeError(\n                #     \"'flat' is not valid when values_list is called with no \"\n                #     \"fields.\"\n                # )\n                warnings.warn(\n                    \"Calling values_list() with no field name and flat=True \"\n                    \"is deprecated. Pass an explicit field name instead, like \"\n                    \"'pk'.\",\n                    RemovedInDjango70Warning,\n                )\n                fields = [self.model._meta.concrete_fields[0].attname]\n\n        field_names = {f: False for f in fields if not hasattr(f, \"resolve_expression\")}\n        _fields = []\n        expressions = {}\n        counter = 1\n        for field in fields:\n            field_name = field\n            expression = None\n            if hasattr(field, \"resolve_expression\"):\n                field_name = getattr(\n                    field, \"default_alias\", field.__class__.__name__.lower()\n                )\n                expression = field\n                # For backward compatibility reasons expressions are always\n                # prefixed with the counter even if their default alias doesn't\n                # collide with field names. Changing this logic could break\n                # some usage of named=True.\n                seen = True\n            elif seen := field_names[field_name]:\n                expression = F(field_name)\n            if seen:\n                field_name_prefix = field_name\n                while (field_name := f\"{field_name_prefix}{counter}\") in field_names:\n                    counter += 1\n            if expression is not None:\n                expressions[field_name] = expression\n            field_names[field_name] = True\n            _fields.append(field_name)\n\n        clone = self._values(*_fields, **expressions)\n        clone._iterable_class = (\n            NamedValuesListIterable\n            if named\n            else FlatValuesListIterable if flat else ValuesListIterable\n        )\n        return clone\n\n    def dates(self, field_name, kind, order=\"ASC\"):\n        \"\"\"\n        Return a list of date objects representing all available dates for\n        the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\"):\n            raise ValueError(\"'kind' must be one of 'year', 'month', 'week', or 'day'.\")\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        return (\n            self.annotate(\n                datefield=Trunc(field_name, kind, output_field=DateField()),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datefield\")\n        )\n\n    def datetimes(self, field_name, kind, order=\"ASC\", tzinfo=None):\n        \"\"\"\n        Return a list of datetime objects representing all available\n        datetimes for the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"):\n            raise ValueError(\n                \"'kind' must be one of 'year', 'month', 'week', 'day', \"\n                \"'hour', 'minute', or 'second'.\"\n            )\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        if settings.USE_TZ:\n            if tzinfo is None:\n                tzinfo = timezone.get_current_timezone()\n        else:\n            tzinfo = None\n        return (\n            self.annotate(\n                datetimefield=Trunc(\n                    field_name,\n                    kind,\n                    output_field=DateTimeField(),\n                    tzinfo=tzinfo,\n                ),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datetimefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datetimefield\")\n        )\n\n    def none(self):\n        \"\"\"Return an empty QuerySet.\"\"\"\n        clone = self._chain()\n        clone.query.set_empty()\n        return clone\n\n    ##################################################################\n    # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #\n    ##################################################################\n\n    def all(self):\n        \"\"\"\n        Return a new QuerySet that is a copy of the current one. This allows a\n        QuerySet to proxy for a model manager in some cases.\n        \"\"\"\n        return self._chain()\n\n    def filter(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with the args ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"filter\")\n        return self._filter_or_exclude(False, args, kwargs)\n\n    def exclude(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with NOT (args) ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"exclude\")\n        return self._filter_or_exclude(True, args, kwargs)\n\n    def _filter_or_exclude(self, negate, args, kwargs):\n        if (args or kwargs) and self.query.is_sliced:\n            raise TypeError(\"Cannot filter a query once a slice has been taken.\")\n        clone = self._chain()\n        if self._defer_next_filter:\n            self._defer_next_filter = False\n            clone._deferred_filter = negate, args, kwargs\n        else:\n            clone._filter_or_exclude_inplace(negate, args, kwargs)\n        return clone\n\n    def _filter_or_exclude_inplace(self, negate, args, kwargs):\n        if invalid_kwargs := PROHIBITED_FILTER_KWARGS.intersection(kwargs):\n            invalid_kwargs_str = \", \".join(f\"'{k}'\" for k in sorted(invalid_kwargs))\n            raise TypeError(f\"The following kwargs are invalid: {invalid_kwargs_str}\")\n        if negate:\n            self._query.add_q(~Q(*args, **kwargs))\n        else:\n            self._query.add_q(Q(*args, **kwargs))\n\n    def complex_filter(self, filter_obj):\n        \"\"\"\n        Return a new QuerySet instance with filter_obj added to the filters.\n\n        filter_obj can be a Q object or a dictionary of keyword lookup\n        arguments.\n\n        This exists to support framework features such as 'limit_choices_to',\n        and usually it will be more natural to use other methods.\n        \"\"\"\n        if isinstance(filter_obj, Q):\n            clone = self._chain()\n            clone.query.add_q(filter_obj)\n            return clone\n        else:\n            return self._filter_or_exclude(False, args=(), kwargs=filter_obj)\n\n    def _combinator_query(self, combinator, *other_qs, all=False):\n        # Clone the query to inherit the select list and everything\n        clone = self._chain()\n        # Clear limits and ordering so they can be reapplied\n        clone.query.clear_ordering(force=True)\n        clone.query.default_ordering = True\n        self._clear_ordering_in_combined_queries(clone.query, other_qs)\n        clone.query.clear_limits()\n        clone.query.combinator = combinator\n        clone.query.combinator_all = all\n        return clone\n\n    def union(self, *other_qs, all=False):\n        # If the query is an EmptyQuerySet, combine all nonempty querysets.\n        if isinstance(self, EmptyQuerySet):\n            qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)]\n            if not qs:\n                return self\n            if len(qs) == 1:\n                return qs[0]\n            return qs[0]._combinator_query(\"union\", *qs[1:], all=all)\n        elif not other_qs:\n            return self\n        return self._combinator_query(\"union\", *other_qs, all=all)\n\n    def intersection(self, *other_qs):\n        # If any query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        for other in other_qs:\n            if isinstance(other, EmptyQuerySet):\n                return other\n        return self._combinator_query(\"intersection\", *other_qs)\n\n    def difference(self, *other_qs):\n        # If the query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        return self._combinator_query(\"difference\", *other_qs)\n\n    def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False):\n        \"\"\"\n        Return a new QuerySet instance that will select objects with a\n        FOR UPDATE lock.\n        \"\"\"\n        if nowait and skip_locked:\n            raise ValueError(\"The nowait option cannot be used with skip_locked.\")\n        obj = self._chain()\n        obj._for_write = True\n        obj.query.select_for_update = True\n        obj.query.select_for_update_nowait = nowait\n        obj.query.select_for_update_skip_locked = skip_locked\n        obj.query.select_for_update_of = of\n        obj.query.select_for_no_key_update = no_key\n        return obj\n\n    def select_related(self, *fields):\n        \"\"\"\n        Return a new QuerySet instance that will select related objects.\n\n        If fields are specified, they must be ForeignKey fields and only those\n        related objects are included in the selection.\n\n        If select_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"select_related\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call select_related() after .values() or .values_list()\"\n            )\n\n        obj = self._chain()\n        if fields == (None,):\n            obj.query.select_related = False\n        elif fields:\n            obj.query.add_select_related(fields)\n        else:\n            # RemovedInDjango70Warning: when the deprecation ends, raise a\n            # TypeError instead.\n            warn_about_external_use(\n                \"Calling select_related() with no arguments is deprecated. \"\n                \"Specify the fields to fetch instead.\",\n                category=RemovedInDjango70Warning,\n                skip_name_prefixes=(\"django.db.models\",),\n            )\n            obj.query.select_related = True\n        return obj\n\n    def prefetch_related(self, *lookups):\n        \"\"\"\n        Return a new QuerySet instance that will prefetch the specified\n        Many-To-One and Many-To-Many related objects when the QuerySet is\n        evaluated.\n\n        When prefetch_related() is called more than once, append to the list of\n        prefetch lookups. If prefetch_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"prefetch_related\")\n        clone = self._chain()\n        if lookups == (None,):\n            clone._prefetch_related_lookups = ()\n        else:\n            for lookup in lookups:\n                if isinstance(lookup, Prefetch):\n                    lookup = lookup.prefetch_to\n                lookup = lookup.split(LOOKUP_SEP, 1)[0]\n                if lookup in self.query._filtered_relations:\n                    raise ValueError(\n                        \"prefetch_related() is not supported with FilteredRelation.\"\n                    )\n            clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups\n        return clone\n\n    def annotate(self, *args, **kwargs):\n        \"\"\"\n        Return a query set in which the returned objects have been annotated\n        with extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"annotate\")\n        return self._annotate(args, kwargs, select=True)\n\n    def alias(self, *args, **kwargs):\n        \"\"\"\n        Return a query set with added aliases for extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"alias\")\n        return self._annotate(args, kwargs, select=False)\n\n    def _annotate(self, args, kwargs, select=True):\n        self._validate_values_are_expressions(\n            args + tuple(kwargs.values()), method_name=\"annotate\"\n        )\n        annotations = {}\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                if arg.default_alias in kwargs:\n                    raise ValueError(\n                        \"The named annotation '%s' conflicts with the \"\n                        \"default name for another annotation.\" % arg.default_alias\n                    )\n            except (TypeError, AttributeError):\n                raise TypeError(\"Complex annotations require an alias\")\n            annotations[arg.default_alias] = arg\n        annotations.update(kwargs)\n\n        clone = self._chain()\n        names = self._fields\n        if names is None:\n            names = set(\n                chain.from_iterable(\n                    (\n                        (field.name, field.attname)\n                        if hasattr(field, \"attname\")\n                        else (field.name,)\n                    )\n                    for field in self.model._meta.get_fields()\n                )\n            )\n\n        for alias, annotation in annotations.items():\n            if alias in names:\n                raise ValueError(\n                    \"The annotation '%s' conflicts with a field on \"\n                    \"the model.\" % alias\n                )\n            if isinstance(annotation, FilteredRelation):\n                clone.query.add_filtered_relation(annotation, alias)\n            else:\n                clone.query.add_annotation(\n                    annotation,\n                    alias,\n                    select=select,\n                )\n        for alias, annotation in clone.query.annotations.items():\n            if alias in annotations and annotation.contains_aggregate:\n                if clone._fields is None:\n                    clone.query.group_by = True\n                else:\n                    clone.query.set_group_by()\n                break\n\n        return clone\n\n    def order_by(self, *field_names):\n        \"\"\"Return a new QuerySet instance with the ordering changed.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reorder a query once a slice has been taken.\")\n        obj = self._chain()\n        obj.query.clear_ordering(force=True, clear_default=False)\n        obj.query.add_ordering(*field_names)\n        return obj\n\n    def distinct(self, *field_names):\n        \"\"\"\n        Return a new QuerySet instance that will select only distinct results.\n        \"\"\"\n        self._not_support_combined_queries(\"distinct\")\n        if self.query.is_sliced:\n            raise TypeError(\n                \"Cannot create distinct fields once a slice has been taken.\"\n            )\n        obj = self._chain()\n        obj.query.add_distinct_fields(*field_names)\n        return obj\n\n    def extra(\n        self,\n        select=None,\n        where=None,\n        params=None,\n        tables=None,\n        order_by=None,\n        select_params=None,\n    ):\n        \"\"\"Add extra SQL fragments to the query.\"\"\"\n        self._not_support_combined_queries(\"extra\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.add_extra(select, select_params, where, params, tables, order_by)\n        return clone\n\n    def reverse(self):\n        \"\"\"Reverse the ordering of the QuerySet.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reverse a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.standard_ordering = not clone.query.standard_ordering\n        return clone\n\n    def defer(self, *fields):\n        \"\"\"\n        Defer the loading of data for certain fields until they are accessed.\n        Add the set of deferred fields to any existing set of deferred fields.\n        The only exception to this is if None is passed in as the only\n        parameter, in which case remove all deferrals.\n        \"\"\"\n        self._not_support_combined_queries(\"defer\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call defer() after .values() or .values_list()\")\n        clone = self._chain()\n        if fields == (None,):\n            clone.query.clear_deferred_loading()\n        else:\n            clone.query.add_deferred_loading(fields)\n        return clone\n\n    def only(self, *fields):\n        \"\"\"\n        Essentially, the opposite of defer(). Only the fields passed into this\n        method and that are not already specified as deferred are loaded\n        immediately when the queryset is evaluated.\n        \"\"\"\n        self._not_support_combined_queries(\"only\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call only() after .values() or .values_list()\")\n        if fields == (None,):\n            # Can only pass None to defer(), not only(), as the rest option.\n            # That won't stop people trying to do this, so let's be explicit.\n            raise TypeError(\"Cannot pass None as an argument to only().\")\n        for field in fields:\n            field = field.split(LOOKUP_SEP, 1)[0]\n            if field in self.query._filtered_relations:\n                raise ValueError(\"only() is not supported with FilteredRelation.\")\n        clone = self._chain()\n        clone.query.add_immediate_loading(fields)\n        return clone\n\n    def using(self, alias):\n        \"\"\"Select which database this QuerySet should execute against.\"\"\"\n        clone = self._chain()\n        clone._db = alias\n        return clone\n\n    def fetch_mode(self, fetch_mode):\n        \"\"\"Set the fetch mode for the QuerySet.\"\"\"\n        clone = self._chain()\n        clone._fetch_mode = fetch_mode\n        return clone\n\n    ###################################\n    # PUBLIC INTROSPECTION ATTRIBUTES #\n    ###################################\n\n    @property\n    def ordered(self):\n        \"\"\"\n        Return True if the QuerySet is ordered -- i.e. has an order_by()\n        clause or a default ordering on the model (or is empty).\n        \"\"\"\n        if isinstance(self, EmptyQuerySet):\n            return True\n        if self.query.extra_order_by or self.query.order_by:\n            return True\n        elif (\n            self.query.default_ordering\n            and self.query.get_meta().ordering\n            and\n            # A default ordering doesn't affect GROUP BY queries.\n            not self.query.group_by\n        ):\n            return True\n        else:\n            return False\n\n    @property\n    def totally_ordered(self):\n        \"\"\"\n        Returns True if the QuerySet is ordered and the ordering is\n        deterministic. This requires that the ordering includes a field\n        (or set of fields) that is unique and non-nullable.\n\n        For queries involving a GROUP BY clause, the model's default\n        ordering is ignored. Ordering specified via .extra(order_by=...)\n        is also ignored.\n        \"\"\"\n        if not self.ordered:\n            return False\n        ordering = self.query.order_by\n        if not ordering and self.query.default_ordering:\n            ordering = self.query.get_meta().ordering\n        if not ordering:\n            return False\n        opts = self.model._meta\n        pk_fields = {f.attname for f in opts.pk_fields}\n        candidate_fields = set()\n        for part in ordering:\n            # Search for single field providing a total ordering.\n            field_name = None\n            if isinstance(part, str):\n                field_name = part.lstrip(\"-\")\n            elif isinstance(part, F):\n                field_name = part.name\n            elif isinstance(part, OrderBy) and isinstance(part.expression, F):\n                field_name = part.expression.name\n            if annotation_col := self.query.annotations.get(field_name):\n                if isinstance(annotation_col, Col):\n                    if annotation_col.alias == self.query.base_table:\n                        candidate_fields.add(annotation_col.target)\n                elif isinstance(annotation_col, ColPairs):\n                    candidate_fields |= {\n                        c.target\n                        for c in annotation_col.get_cols()\n                        if c.alias == self.query.base_table\n                    }\n            elif field_name:\n                if field_name == \"pk\":\n                    return True\n                # Normalize attname references by using get_field().\n                try:\n                    field = opts.get_field(field_name)\n                except exceptions.FieldDoesNotExist:\n                    # Could be \"?\" for random ordering or a related field\n                    # lookup. Skip this part of introspection for now.\n                    continue\n                else:\n                    # Ordering by a related field name orders by the referenced\n                    # model's ordering. Skip this introspection for now.\n                    if field.remote_field and field_name == field.name:\n                        continue\n                    candidate_fields.add(field)\n\n        candidate_attnames = set()\n        for field in candidate_fields:\n            if field.unique and not field.null:\n                return True\n            candidate_attnames.add(field.attname)\n\n        # Account for members of a CompositePrimaryKey.\n        if candidate_attnames.issuperset(pk_fields):\n            return True\n        # No single total ordering field, try unique_together and total\n        # unique constraints.\n        constraint_field_names = (\n            *opts.unique_together,\n            *(constraint.fields for constraint in opts.total_unique_constraints),\n        )\n        for field_names in constraint_field_names:\n            # Normalize attname references by using get_field().\n            try:\n                fields = [opts.get_field(field_name) for field_name in field_names]\n            except exceptions.FieldDoesNotExist:\n                continue\n            # Composite unique constraints containing a nullable column\n            # cannot ensure total ordering.\n            if any(field.null for field in fields):\n                continue\n            if candidate_attnames.issuperset(field.attname for field in fields):\n                return True\n\n        return False\n\n    @property\n    def db(self):\n        \"\"\"Return the database used if this query is executed now.\"\"\"\n        if self._for_write:\n            return self._db or router.db_for_write(self.model, **self._hints)\n        return self._db or router.db_for_read(self.model, **self._hints)\n\n    ###################\n    # PRIVATE METHODS #\n    ###################\n\n    def _insert(\n        self,\n        objs,\n        fields,\n        returning_fields=None,\n        raw=False,\n        using=None,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert a new record for the given model. This provides an interface to\n        the InsertQuery class and is how Model.save() is implemented.\n        \"\"\"\n        self._for_write = True\n        if using is None:\n            using = self.db\n        query = sql.InsertQuery(\n            self.model,\n            on_conflict=on_conflict,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n        query.insert_values(fields, objs, raw=raw)\n        return query.get_compiler(using=using).execute_sql(returning_fields)\n\n    _insert.alters_data = True\n    _insert.queryset_only = False\n\n    def _batched_insert(\n        self,\n        objs,\n        fields,\n        batch_size,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Helper method for bulk_create() to insert objs one batch at a time.\n        \"\"\"\n        connection = connections[self.db]\n        ops = connection.ops\n        max_batch_size = max(ops.bulk_batch_size(fields, objs), 1)\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        inserted_rows = []\n        returning_fields = (\n            self.model._meta.db_returning_fields\n            if (\n                connection.features.can_return_rows_from_bulk_insert\n                and (on_conflict is None or on_conflict == OnConflict.UPDATE)\n            )\n            else None\n        )\n        batches = [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]\n        if len(batches) > 1:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            for item in batches:\n                inserted_rows.extend(\n                    self._insert(\n                        item,\n                        fields=fields,\n                        using=self.db,\n                        on_conflict=on_conflict,\n                        update_fields=update_fields,\n                        unique_fields=unique_fields,\n                        returning_fields=returning_fields,\n                    )\n                )\n        return inserted_rows\n\n    def _disable_cloning(self):\n        \"\"\"\n        Prevent calls to _chain() from creating a new QuerySet via _clone().\n        All subsequent QuerySet mutations will occur on this instance until\n        _enable_cloning() is used.\n        \"\"\"\n        self._cloning_enabled = False\n        return self\n\n    def _enable_cloning(self):\n        \"\"\"\n        Allow calls to _chain() to create a new QuerySet via _clone(). Restores\n        the default behavior where any QuerySet mutation will return a new\n        QuerySet instance. Necessary only when there has been a\n        _disable_cloning() call previously.\n        \"\"\"\n        self._cloning_enabled = True\n        return self\n\n    def _avoid_cloning(self):\n        \"\"\"\n        Temporarily prevent QuerySet _clone() operations, restoring the default\n        behavior on exit. For the duration of the context managed statement,\n        all operations (e.g. filter(), exclude(), etc.) will mutate the same\n        QuerySet instance.\n\n        @contextlib.contextmanager is intentionally not used for performance\n        reasons.\n        \"\"\"\n        return PreventQuerySetCloning(self)\n\n    def _chain(self):\n        \"\"\"\n        Return a copy of the current QuerySet that's ready for another\n        operation.\n\n        If the QuerySet has opted in to in-place mutations via\n        _disable_cloning() temporarily, the copy doesn't occur and instead the\n        same QuerySet instance will be modified.\n        \"\"\"\n        if not self._cloning_enabled:\n            obj = self\n        else:\n            obj = self._clone()\n        if obj._sticky_filter:\n            obj.query.filter_is_sticky = True\n            obj._sticky_filter = False\n        return obj\n\n    def _clone(self):\n        \"\"\"\n        Return a copy of the current QuerySet. A lightweight alternative\n        to deepcopy().\n        \"\"\"\n        c = self.__class__(\n            model=self.model,\n            query=self.query.chain(),\n            using=self._db,\n            hints=self._hints,\n        )\n        c._sticky_filter = self._sticky_filter\n        c._for_write = self._for_write\n        c._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        c._known_related_objects = self._known_related_objects\n        c._iterable_class = self._iterable_class\n        c._fetch_mode = self._fetch_mode\n        c._fields = self._fields\n        return c\n\n    def _fetch_all(self):\n        if self._result_cache is None:\n            self._result_cache = list(self._iterable_class(self))\n        if self._prefetch_related_lookups and not self._prefetch_done:\n            self._prefetch_related_objects()\n\n    def _next_is_sticky(self):\n        \"\"\"\n        Indicate that the next filter call and the one following that should\n        be treated as a single filter. This is only important when it comes to\n        determining when to reuse tables for many-to-many filters. Required so\n        that we can filter naturally on the results of related managers.\n\n        This doesn't return a clone of the current QuerySet (it returns\n        \"self\"). The method is only used internally and should be immediately\n        followed by a filter() that does create a clone.\n        \"\"\"\n        self._sticky_filter = True\n        return self\n\n    def _merge_sanity_check(self, other):\n        \"\"\"Check that two QuerySet classes may be merged.\"\"\"\n        if self._fields is not None and (\n            set(self.query.values_select) != set(other.query.values_select)\n            or set(self.query.extra_select) != set(other.query.extra_select)\n            or set(self.query.annotation_select) != set(other.query.annotation_select)\n        ):\n            raise TypeError(\n                \"Merging '%s' classes must involve the same values in each case.\"\n                % self.__class__.__name__\n            )\n\n    def _merge_known_related_objects(self, other):\n        \"\"\"\n        Keep track of all known related objects from either QuerySet instance.\n        \"\"\"\n        for field, objects in other._known_related_objects.items():\n            self._known_related_objects.setdefault(field, {}).update(objects)\n\n    def resolve_expression(self, *args, **kwargs):\n        query = self.query.resolve_expression(*args, **kwargs)\n        query._db = self._db\n        return query\n\n    resolve_expression.queryset_only = True\n\n    def _add_hints(self, **hints):\n        \"\"\"\n        Update hinting information for use by routers. Add new key/values or\n        overwrite existing key/values.\n        \"\"\"\n        self._hints.update(hints)\n\n    def _has_filters(self):\n        \"\"\"\n        Check if this QuerySet has any filtering going on. This isn't\n        equivalent with checking if all objects are present in results, for\n        example, qs[1:]._has_filters() -> False.\n        \"\"\"\n        return self.query.has_filters()\n\n    @staticmethod\n    def _validate_values_are_expressions(values, method_name):\n        invalid_args = sorted(\n            str(arg) for arg in values if not hasattr(arg, \"resolve_expression\")\n        )\n        if invalid_args:\n            raise TypeError(\n                \"QuerySet.%s() received non-expression(s): %s.\"\n                % (\n                    method_name,\n                    \", \".join(invalid_args),\n                )\n            )\n\n    def _not_support_combined_queries(self, operation_name):\n        if self.query.combinator:\n            raise NotSupportedError(\n                \"Calling QuerySet.%s() after %s() is not supported.\"\n                % (operation_name, self.query.combinator)\n            )\n\n    def _check_operator_queryset(self, other, operator_):\n        if self.query.combinator or other.query.combinator:\n            raise TypeError(f\"Cannot use {operator_} operator with combined queryset.\")\n\n    def _check_ordering_first_last_queryset_aggregation(self, method):\n        if (\n            isinstance(self.query.group_by, tuple)\n            # Raise if the pk fields are not in the group_by.\n            and self.model._meta.pk\n            not in {col.output_field for col in self.query.group_by}\n            and set(self.model._meta.pk_fields).difference(\n                {col.target for col in self.query.group_by}\n            )\n        ):\n            raise TypeError(\n                f\"Cannot use QuerySet.{method}() on an unordered queryset performing \"\n                f\"aggregation. Add an ordering with order_by().\"\n            )\n\n    def _clear_ordering_in_combined_queries(self, cloned_query, other_qs):\n        combined_queries = [self.query]\n        for qs in other_qs:\n            query = qs.query.clone()\n            query.clear_ordering(force=False, clear_default=False)\n            combined_queries.append(query)\n        cloned_query.combined_queries = tuple(combined_queries)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-765e7606ef75a519", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "83948711b7e35c1ce59dcbf3997b5e6816370ace57eedd721c81d994b3ce12ee", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 2102, "local_path": "data-flow/inline-intermediate-variables/I12__django__QuerySet__80ede047.py", "order": 12, "original_content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "parent_variant_id": "pyint-5c2b55814568-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/query.py#L374-L2424", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "QuerySet", "variant_id": "pyint-f45f80ede047-I12", "group_id": "py-765e7606ef75a519", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 237, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-87acf0d168ba-I13", "source": "import copy\nimport operator\nimport warnings\nfrom contextlib import nullcontext\nfrom functools import partial, reduce\nfrom itertools import chain, islice\nfrom weakref import ref as weak_ref\nfrom asgiref.sync import sync_to_async\nimport django\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.db import (\n    DJANGO_VERSION_PICKLE_KEY,\n    IntegrityError,\n    NotSupportedError,\n    connections,\n    router,\n    transaction,\n)\nfrom django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql\nfrom django.db.models.constants import LOOKUP_SEP, OnConflict\nfrom django.db.models.deletion import Collector\nfrom django.db.models.expressions import (\n    Case,\n    Col,\n    ColPairs,\n    DatabaseDefault,\n    F,\n    OrderBy,\n    Value,\n    When,\n)\nfrom django.db.models.fetch_modes import FETCH_ONE\nfrom django.db.models.functions import Cast, Trunc\nfrom django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q\nfrom django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT\nfrom django.db.models.utils import (\n    AltersData,\n    create_namedtuple_class,\n    resolve_callables,\n)\nfrom django.utils import timezone\nfrom django.utils.deprecation import (\n    RemovedInDjango70Warning,\n    RemovedInDjango71Warning,\n    warn_about_external_use,\n)\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import func_accepts_kwargs, func_supports_parameter\nfrom django.utils.warnings import django_file_prefixes\n\nclass QuerySet(AltersData):\n    \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n    def __init__(self, model=None, query=None, using=None, hints=None):\n        self.model = model\n        self._db = using\n        self._hints = hints or {}\n        self._query = query or sql.Query(self.model)\n        self._result_cache = None\n        self._sticky_filter = False\n        self._for_write = False\n        self._prefetch_related_lookups = ()\n        self._prefetch_done = False\n        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}\n        self._iterable_class = ModelIterable\n        self._fetch_mode = DEFAULT_FETCH_MODE\n        self._fields = None\n        self._defer_next_filter = False\n        self._deferred_filter = None\n        self._cloning_enabled = True\n\n    @property\n    def query(self):\n        if self._deferred_filter:\n            negate, args, kwargs = self._deferred_filter\n            self._filter_or_exclude_inplace(negate, args, kwargs)\n            self._deferred_filter = None\n        return self._query\n\n    @query.setter\n    def query(self, value):\n        if value.values_select:\n            self._iterable_class = ValuesIterable\n        self._query = value\n\n    def as_manager(cls):\n        # Address the circular dependency between `Queryset` and `Manager`.\n        from django.db.models.manager import Manager\n\n        manager = Manager.from_queryset(cls)()\n        manager._built_with_as_manager = True\n        return manager\n\n    as_manager.queryset_only = True\n    as_manager = classmethod(as_manager)\n\n    ########################\n    # PYTHON MAGIC METHODS #\n    ########################\n\n    def __deepcopy__(self, memo):\n        \"\"\"Don't populate the QuerySet's cache.\"\"\"\n        obj = self.__class__()\n        loopIterator = __import__(\"builtins\").iter(self.__dict__.items())\n        while True:\n            try:\n                k, v = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if k == \"_result_cache\":\n                obj.__dict__[k] = None\n            else:\n                obj.__dict__[k] = copy.deepcopy(v, memo)\n        return obj\n\n    def __getstate__(self):\n        # Force the cache to be fully populated.\n        self._fetch_all()\n        return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n    def __setstate__(self, state):\n        pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)\n        if pickled_version:\n            if pickled_version != django.__version__:\n                warnings.warn(\n                    \"Pickled queryset instance's Django version %s does not \"\n                    \"match the current version %s.\"\n                    % (pickled_version, django.__version__),\n                    RuntimeWarning,\n                    stacklevel=2,\n                )\n        else:\n            warnings.warn(\n                \"Pickled queryset instance's Django version is not specified.\",\n                RuntimeWarning,\n                stacklevel=2,\n            )\n        self.__dict__.update(state)\n\n    def __repr__(self):\n        data = list(self[: REPR_OUTPUT_SIZE + 1])\n        if len(data) > REPR_OUTPUT_SIZE:\n            data[-1] = \"...(remaining elements truncated)...\"\n        return \"<%s %r>\" % (self.__class__.__name__, data)\n\n    def __len__(self):\n        self._fetch_all()\n        return len(self._result_cache)\n\n    def __iter__(self):\n        \"\"\"\n        The queryset iterator protocol uses three nested iterators in the\n        default case:\n            1. sql.compiler.execute_sql()\n               - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n                 using cursor.fetchmany(). This part is responsible for\n                 doing some column masking, and returning the rows in chunks.\n            2. sql.compiler.results_iter()\n               - Returns one row at time. At this point the rows are still just\n                 tuples. In some cases the return values are converted to\n                 Python values at this location.\n            3. self.iterator()\n               - Responsible for turning the rows into model objects.\n        \"\"\"\n        self._fetch_all()\n        return iter(self._result_cache)\n\n    def __aiter__(self):\n        # Remember, __aiter__ itself is synchronous, it's the thing it returns\n        # that is async!\n        async def generator():\n            await sync_to_async(self._fetch_all)()\n            loopIteratorA = __import__(\"builtins\").iter(self._result_cache)\n            while True:\n                try:\n                    item = __import__(\"builtins\").next(loopIteratorA)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                yield item\n\n        return generator()\n\n    def __bool__(self):\n        self._fetch_all()\n        return bool(self._result_cache)\n\n    def __getitem__(self, k):\n        \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n        if not isinstance(k, (int, slice)):\n            raise TypeError(\n                \"QuerySet indices must be integers or slices, not %s.\"\n                % type(k).__name__\n            )\n        if (isinstance(k, int) and k < 0) or (\n            isinstance(k, slice)\n            and (\n                (k.start is not None and k.start < 0)\n                or (k.stop is not None and k.stop < 0)\n            )\n        ):\n            raise ValueError(\"Negative indexing is not supported.\")\n\n        if self._result_cache is not None:\n            return self._result_cache[k]\n\n        if isinstance(k, slice):\n            qs = self._chain()\n            if k.start is not None:\n                start = int(k.start)\n            else:\n                start = None\n            if k.stop is not None:\n                stop = int(k.stop)\n            else:\n                stop = None\n            qs.query.set_limits(start, stop)\n            return list(qs)[:: k.step] if k.step else qs\n\n        qs = self._chain()\n        qs.query.set_limits(k, k + 1)\n        qs._fetch_all()\n        return qs._result_cache[0]\n\n    def __class_getitem__(cls, *args, **kwargs):\n        return cls\n\n    def __and__(self, other):\n        self._check_operator_queryset(other, \"&\")\n        self._merge_sanity_check(other)\n        if isinstance(other, EmptyQuerySet):\n            return other\n        if isinstance(self, EmptyQuerySet):\n            return self\n        combined = self._chain()\n        combined._merge_known_related_objects(other)\n        combined.query.combine(other.query, sql.AND)\n        return combined\n\n    def __or__(self, other):\n        self._check_operator_queryset(other, \"|\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.OR)\n        return combined\n\n    def __xor__(self, other):\n        self._check_operator_queryset(other, \"^\")\n        self._merge_sanity_check(other)\n        if isinstance(self, EmptyQuerySet):\n            return other\n        if isinstance(other, EmptyQuerySet):\n            return self\n        query = (\n            self\n            if self.query.can_filter()\n            else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n        )\n        combined = query._chain()\n        combined._merge_known_related_objects(other)\n        if not other.query.can_filter():\n            other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n        combined.query.combine(other.query, sql.XOR)\n        return combined\n\n    ####################################\n    # METHODS THAT DO DATABASE QUERIES #\n    ####################################\n\n    def _iterator(self, use_chunked_fetch, chunk_size):\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if not self._prefetch_related_lookups or chunk_size is None:\n            yield from iterable\n            return\n\n        iterator = iter(iterable)\n        while results := list(islice(iterator, chunk_size)):\n            prefetch_related_objects(results, *self._prefetch_related_lookups)\n            yield from results\n\n    def iterator(self, chunk_size=None):\n        \"\"\"\n        An iterator over the results from applying this QuerySet to the\n        database. chunk_size must be provided for QuerySets that prefetch\n        related objects. Otherwise, a default chunk_size of 2000 is supplied.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                raise ValueError(\n                    \"chunk_size must be provided when using QuerySet.iterator() after \"\n                    \"prefetch_related().\"\n                )\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        return self._iterator(use_chunked_fetch, chunk_size)\n\n    async def aiterator(self, chunk_size=None):\n        \"\"\"\n        An asynchronous iterator over the results from applying this QuerySet\n        to the database.\n        \"\"\"\n        if chunk_size is None:\n            if self._prefetch_related_lookups:\n                # RemovedInDjango71Warning: Replace the warning with:\n                # raise ValueError(\n                #     \"chunk_size must be provided when using \"\n                #     \"QuerySet.aiterator() after prefetch_related().\"\n                # )\n                warnings.warn(\n                    \"Using QuerySet.aiterator() after prefetch_related() without \"\n                    \"providing a chunk_size is deprecated and will raise a \"\n                    \"ValueError in Django 7.1.\",\n                    category=RemovedInDjango71Warning,\n                    skip_file_prefixes=django_file_prefixes(),\n                )\n                # RemovedInDjango71Warning: When the deprecation ends, remove.\n                chunk_size = 2000\n        elif chunk_size <= 0:\n            raise ValueError(\"Chunk size must be strictly positive.\")\n        use_chunked_fetch = not connections[self.db].settings_dict.get(\n            \"DISABLE_SERVER_SIDE_CURSORS\"\n        )\n        iterable = self._iterable_class(\n            self,\n            chunked_fetch=use_chunked_fetch,\n            chunk_size=chunk_size or 2000,\n        )\n        if self._prefetch_related_lookups:\n            results = []\n\n            async for item in iterable:\n                results.append(item)\n                if len(results) >= chunk_size:\n                    await aprefetch_related_objects(\n                        results, *self._prefetch_related_lookups\n                    )\n                    loopIteratorB = __import__(\"builtins\").iter(results)\n                    while True:\n                        try:\n                            result = __import__(\"builtins\").next(loopIteratorB)\n                        except __import__(\"builtins\").StopIteration:\n                            break\n                        yield result\n                    results.clear()\n\n            if results:\n                await aprefetch_related_objects(\n                    results, *self._prefetch_related_lookups\n                )\n                loopIteratorC = __import__(\"builtins\").iter(results)\n                while True:\n                    try:\n                        result = __import__(\"builtins\").next(loopIteratorC)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    yield result\n        else:\n            async for item in iterable:\n                yield item\n\n    def aggregate(self, *args, **kwargs):\n        \"\"\"\n        Return a dictionary containing the calculations (aggregation)\n        over the current queryset.\n\n        If args is present the expression is passed as a kwarg using\n        the Aggregate object's default alias.\n        \"\"\"\n        if self.query.distinct_fields:\n            raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n        self._validate_values_are_expressions(\n            (*args, *kwargs.values()), method_name=\"aggregate\"\n        )\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                arg.default_alias\n            except (AttributeError, TypeError):\n                raise TypeError(\"Complex aggregates require an alias\")\n            kwargs[arg.default_alias] = arg\n\n        return self.query.chain().get_aggregation(self.db, kwargs)\n\n    async def aaggregate(self, *args, **kwargs):\n        return await sync_to_async(self.aggregate)(*args, **kwargs)\n\n    def count(self):\n        \"\"\"\n        Perform a SELECT COUNT() and return the number of records as an\n        integer.\n\n        If the QuerySet is already fully cached, return the length of the\n        cached results set to avoid multiple SELECT COUNT(*) calls.\n        \"\"\"\n        if self._result_cache is not None:\n            return len(self._result_cache)\n\n        return self.query.get_count(using=self.db)\n\n    async def acount(self):\n        return await sync_to_async(self.count)()\n\n    def get(self, *args, **kwargs):\n        \"\"\"\n        Perform the query and return a single object matching the given\n        keyword arguments.\n        \"\"\"\n        if self.query.combinator and (args or kwargs):\n            raise NotSupportedError(\n                \"Calling QuerySet.get(...) with filters after %s() is not \"\n                \"supported.\" % self.query.combinator\n            )\n        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)\n        if self.query.can_filter() and not self.query.distinct_fields:\n            clone = clone.order_by()\n        limit = None\n        if (\n            not clone.query.select_for_update\n            or connections[clone.db].features.supports_select_for_update_with_limit\n        ):\n            limit = MAX_GET_RESULTS\n            clone.query.set_limits(high=limit)\n        num = len(clone)\n        if num == 1:\n            return clone._result_cache[0]\n        if not num:\n            raise self.model.DoesNotExist(\n                \"%s matching query does not exist.\" % self.model._meta.object_name\n            )\n        raise self.model.MultipleObjectsReturned(\n            \"get() returned more than one %s -- it returned %s!\"\n            % (\n                self.model._meta.object_name,\n                num if not limit or num < limit else \"more than %s\" % (limit - 1),\n            )\n        )\n\n    async def aget(self, *args, **kwargs):\n        return await sync_to_async(self.get)(*args, **kwargs)\n\n    def create(self, **kwargs):\n        \"\"\"\n        Create a new object with the given kwargs, saving it to the database\n        and returning the created object.\n        \"\"\"\n        reverse_one_to_one_fields = frozenset(kwargs).intersection(\n            self.model._meta._reverse_one_to_one_field_names\n        )\n        if reverse_one_to_one_fields:\n            raise ValueError(\n                \"The following fields do not exist in this model: %s\"\n                % \", \".join(reverse_one_to_one_fields)\n            )\n\n        obj = self.model(**kwargs)\n        self._for_write = True\n        obj.save(force_insert=True, using=self.db)\n        obj._state.fetch_mode = self._fetch_mode\n        return obj\n\n    create.alters_data = True\n\n    async def acreate(self, **kwargs):\n        return await sync_to_async(self.create)(**kwargs)\n\n    acreate.alters_data = True\n\n    def _prepare_for_bulk_create(self, objs):\n        objs_with_pk, objs_without_pk = [], []\n        loopIteratorD = __import__(\"builtins\").iter(objs)\n        while True:\n            try:\n                obj = __import__(\"builtins\").next(loopIteratorD)\n            except __import__(\"builtins\").StopIteration:\n                break\n            obj._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n            if isinstance(obj.pk, DatabaseDefault):\n                objs_without_pk.append(obj)\n            elif obj._is_pk_set():\n                objs_with_pk.append(obj)\n            else:\n                obj.pk = obj._meta.pk.get_pk_value_on_save(obj)\n                if obj._is_pk_set():\n                    objs_with_pk.append(obj)\n                else:\n                    objs_without_pk.append(obj)\n        return objs_with_pk, objs_without_pk\n\n    def _check_bulk_create_options(\n        self, ignore_conflicts, update_conflicts, update_fields, unique_fields\n    ):\n        if ignore_conflicts and update_conflicts:\n            raise ValueError(\n                \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n            )\n        db_features = connections[self.db].features\n        if ignore_conflicts:\n            if not db_features.supports_ignore_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support ignoring conflicts.\"\n                )\n            return OnConflict.IGNORE\n        elif update_conflicts:\n            if not db_features.supports_update_conflicts:\n                raise NotSupportedError(\n                    \"This database backend does not support updating conflicts.\"\n                )\n            if not update_fields:\n                raise ValueError(\n                    \"Fields that will be updated when a row insertion fails \"\n                    \"on conflicts must be provided.\"\n                )\n            if unique_fields and not db_features.supports_update_conflicts_with_target:\n                raise NotSupportedError(\n                    \"This database backend does not support updating \"\n                    \"conflicts with specifying unique fields that can trigger \"\n                    \"the upsert.\"\n                )\n            if not unique_fields and db_features.supports_update_conflicts_with_target:\n                raise ValueError(\n                    \"Unique fields that can trigger the upsert must be provided.\"\n                )\n            # Updating primary keys and non-concrete fields is forbidden.\n            if any(not f.concrete for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() can only be used with concrete fields in \"\n                    \"update_fields.\"\n                )\n            if any(f in self.model._meta.pk_fields for f in update_fields):\n                raise ValueError(\n                    \"bulk_create() cannot be used with primary keys in \"\n                    \"update_fields.\"\n                )\n            if unique_fields:\n                if any(not f.concrete for f in unique_fields):\n                    raise ValueError(\n                        \"bulk_create() can only be used with concrete fields \"\n                        \"in unique_fields.\"\n                    )\n            return OnConflict.UPDATE\n        return None\n\n    def bulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert each of the instances into the database. Do *not* call\n        save() on each of the instances, do not send any pre/post_save\n        signals, and do not set the primary key attribute if it is an\n        autoincrement field (except if\n        features.can_return_rows_from_bulk_insert=True).\n        Multi-table models are not supported.\n        \"\"\"\n        # When you bulk insert you don't get the primary keys back (if it's an\n        # autoincrement, except if can_return_rows_from_bulk_insert=True), so\n        # you can't insert into the child tables which references this. There\n        # are two workarounds:\n        # 1) This could be implemented if you didn't have an autoincrement pk\n        # 2) You could do it by doing O(n) normal inserts into the parent\n        #    tables to get the primary keys back and then doing a single bulk\n        #    insert into the childmost table.\n        # We currently set the primary keys on the objects when using\n        # PostgreSQL via the RETURNING ID clause. It should be possible for\n        # Oracle as well, but the semantics for extracting the primary keys is\n        # trickier so it's not done yet.\n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        # Check that the parents share the same concrete model with the our\n        # model to detect the inheritance pattern ConcreteGrandParent ->\n        # MultiTableParent -> ProxyChild. Simply checking\n        # self.model._meta.proxy would not identify that case as involving\n        # multiple tables.\n        loopIteratorE = __import__(\"builtins\").iter(self.model._meta.all_parents)\n        while True:\n            try:\n                parent = __import__(\"builtins\").next(loopIteratorE)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if parent._meta.concrete_model is not self.model._meta.concrete_model:\n                raise ValueError(\"Can't bulk create a multi-table inherited model\")\n        if not objs:\n            return objs\n        opts = self.model._meta\n        if unique_fields:\n            # Primary key is allowed in unique_fields.\n            unique_fields = [\n                self.model._meta.get_field(opts.pk.name if name == \"pk\" else name)\n                for name in unique_fields\n            ]\n        if update_fields:\n            update_fields = [self.model._meta.get_field(name) for name in update_fields]\n        on_conflict = self._check_bulk_create_options(\n            ignore_conflicts,\n            update_conflicts,\n            update_fields,\n            unique_fields,\n        )\n        self._for_write = True\n        fields = [f for f in opts.concrete_fields if not f.generated]\n        objs = list(objs)\n        objs_with_pk, objs_without_pk = self._prepare_for_bulk_create(objs)\n        if objs_with_pk and objs_without_pk:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            self._handle_order_with_respect_to(objs)\n            if objs_with_pk:\n                returned_columns = self._batched_insert(\n                    objs_with_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                loopIteratorAD = __import__(\"builtins\").iter(zip(objs_with_pk, returned_columns))\n                while True:\n                    try:\n                        obj_with_pk, results = __import__(\"builtins\").next(loopIteratorAD)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    loopIteratorF = __import__(\"builtins\").iter(zip(results, opts.db_returning_fields))\n                    while True:\n                        try:\n                            result, field = __import__(\"builtins\").next(loopIteratorF)\n                        except __import__(\"builtins\").StopIteration:\n                            break\n                        setattr(obj_with_pk, field.attname, result)\n                loopIteratorG = __import__(\"builtins\").iter(objs_with_pk)\n                while True:\n                    try:\n                        obj_with_pk = __import__(\"builtins\").next(loopIteratorG)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    obj_with_pk._state.adding = False\n                    obj_with_pk._state.db = self.db\n            if objs_without_pk:\n                fields = [f for f in fields if not isinstance(f, AutoField)]\n                returned_columns = self._batched_insert(\n                    objs_without_pk,\n                    fields,\n                    batch_size,\n                    on_conflict=on_conflict,\n                    update_fields=update_fields,\n                    unique_fields=unique_fields,\n                )\n                connection = connections[self.db]\n                if (\n                    connection.features.can_return_rows_from_bulk_insert\n                    and on_conflict is None\n                ):\n                    assert len(returned_columns) == len(objs_without_pk)\n                loopIteratorAE = __import__(\"builtins\").iter(zip(objs_without_pk, returned_columns))\n                while True:\n                    try:\n                        obj_without_pk, results = __import__(\"builtins\").next(loopIteratorAE)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    loopIteratorH = __import__(\"builtins\").iter(zip(results, opts.db_returning_fields))\n                    while True:\n                        try:\n                            result, field = __import__(\"builtins\").next(loopIteratorH)\n                        except __import__(\"builtins\").StopIteration:\n                            break\n                        setattr(obj_without_pk, field.attname, result)\n                    obj_without_pk._state.adding = False\n                    obj_without_pk._state.db = self.db\n\n        return objs\n\n    def _handle_order_with_respect_to(self, objs):\n        if objs and (order_wrt := self.model._meta.order_with_respect_to):\n            get_filter_kwargs_for_object = order_wrt.get_filter_kwargs_for_object\n            attnames = list(get_filter_kwargs_for_object(objs[0]))\n            group_keys = set()\n            obj_groups = []\n            loopIteratorI = __import__(\"builtins\").iter(objs)\n            while True:\n                try:\n                    obj = __import__(\"builtins\").next(loopIteratorI)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                group_key = tuple(get_filter_kwargs_for_object(obj).values())\n                group_keys.add(group_key)\n                obj_groups.append((obj, group_key))\n            filters = [\n                Q.create(list(zip(attnames, group_key))) for group_key in group_keys\n            ]\n            next_orders = (\n                self.model._base_manager.using(self.db)\n                .filter(reduce(operator.or_, filters))\n                .values_list(*attnames)\n                .annotate(_order__max=Max(\"_order\") + 1)\n            )\n            # Create mapping of group values to max order.\n            group_next_orders = dict.fromkeys(group_keys, 0)\n            group_next_orders.update(\n                (tuple(group_key), next_order) for *group_key, next_order in next_orders\n            )\n            # Assign _order values to new objects.\n            loopIteratorJ = __import__(\"builtins\").iter(obj_groups)\n            while True:\n                try:\n                    obj, group_key = __import__(\"builtins\").next(loopIteratorJ)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                if getattr(obj, \"_order\", None) is None:\n                    group_next_order = group_next_orders[group_key]\n                    obj._order = group_next_order\n                    group_next_orders[group_key] += 1\n\n    bulk_create.alters_data = True\n\n    async def abulk_create(\n        self,\n        objs,\n        batch_size=None,\n        ignore_conflicts=False,\n        update_conflicts=False,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        return await sync_to_async(self.bulk_create)(\n            objs=objs,\n            batch_size=batch_size,\n            ignore_conflicts=ignore_conflicts,\n            update_conflicts=update_conflicts,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n\n    abulk_create.alters_data = True\n\n    def bulk_update(self, objs, fields, batch_size=None):\n        \"\"\"\n        Update the given fields in each of the given objects in the database.\n        \"\"\"\n        if batch_size is not None and batch_size <= 0:\n            raise ValueError(\"Batch size must be a positive integer.\")\n        if not fields:\n            raise ValueError(\"Field names must be given to bulk_update().\")\n        objs = tuple(objs)\n        if not all(obj._is_pk_set() for obj in objs):\n            raise ValueError(\"All bulk_update() objects must have a primary key set.\")\n        opts = self.model._meta\n        fields = [opts.get_field(name) for name in fields]\n        if any(not f.concrete for f in fields):\n            raise ValueError(\"bulk_update() can only be used with concrete fields.\")\n        all_pk_fields = set(opts.pk_fields)\n        loopIteratorK = __import__(\"builtins\").iter(opts.all_parents)\n        while True:\n            try:\n                parent = __import__(\"builtins\").next(loopIteratorK)\n            except __import__(\"builtins\").StopIteration:\n                break\n            all_pk_fields.update(parent._meta.pk_fields)\n        if any(f in all_pk_fields for f in fields):\n            raise ValueError(\"bulk_update() cannot be used with primary key fields.\")\n        if not objs:\n            return 0\n        loopIteratorL = __import__(\"builtins\").iter(objs)\n        while True:\n            try:\n                obj = __import__(\"builtins\").next(loopIteratorL)\n            except __import__(\"builtins\").StopIteration:\n                break\n            obj._prepare_related_fields_for_save(\n                operation_name=\"bulk_update\", fields=fields\n            )\n        # PK is used twice in the resulting update query, once in the filter\n        # and once in the WHEN. Each field will also have one CAST.\n        self._for_write = True\n        connection = connections[self.db]\n        max_batch_size = connection.ops.bulk_batch_size(\n            [opts.pk, opts.pk, *fields], objs\n        )\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        requires_casting = connection.features.requires_casted_case_in_updates\n        batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size))\n        updates = []\n        loopIteratorAG = __import__(\"builtins\").iter(batches)\n        while True:\n            try:\n                batch_objs = __import__(\"builtins\").next(loopIteratorAG)\n            except __import__(\"builtins\").StopIteration:\n                break\n            update_kwargs = {}\n            loopIteratorAF = __import__(\"builtins\").iter(fields)\n            while True:\n                try:\n                    field = __import__(\"builtins\").next(loopIteratorAF)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                when_statements = []\n                loopIteratorM = __import__(\"builtins\").iter(batch_objs)\n                while True:\n                    try:\n                        obj = __import__(\"builtins\").next(loopIteratorM)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    attr = getattr(obj, field.attname)\n                    if not hasattr(attr, \"resolve_expression\"):\n                        attr = Value(attr, output_field=field)\n                    when_statements.append(When(pk=obj.pk, then=attr))\n                case_statement = Case(*when_statements, output_field=field)\n                if requires_casting:\n                    case_statement = Cast(case_statement, output_field=field)\n                update_kwargs[field.attname] = case_statement\n            updates.append(([obj.pk for obj in batch_objs], update_kwargs))\n        rows_updated = 0\n        queryset = self.using(self.db)\n        with transaction.atomic(using=self.db, savepoint=False):\n            loopIteratorN = __import__(\"builtins\").iter(updates)\n            while True:\n                try:\n                    pks, update_kwargs = __import__(\"builtins\").next(loopIteratorN)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs)\n        return rows_updated\n\n    bulk_update.alters_data = True\n\n    async def abulk_update(self, objs, fields, batch_size=None):\n        return await sync_to_async(self.bulk_update)(\n            objs=objs,\n            fields=fields,\n            batch_size=batch_size,\n        )\n\n    abulk_update.alters_data = True\n\n    def get_or_create(self, defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, creating one if necessary.\n        Return a tuple of (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        # The get() needs to be targeted at the write database in order\n        # to avoid potential transaction consistency problems.\n        self._for_write = True\n        try:\n            return self.get(**kwargs), False\n        except self.model.DoesNotExist:\n            params = self._extract_model_params(defaults, **kwargs)\n            # Try to create an object using passed params.\n            try:\n                with transaction.atomic(using=self.db):\n                    params = dict(resolve_callables(params))\n                    return self.create(**params), True\n            except IntegrityError:\n                try:\n                    return self.get(**kwargs), False\n                except self.model.DoesNotExist:\n                    pass\n                raise\n\n    get_or_create.alters_data = True\n\n    async def aget_or_create(self, defaults=None, **kwargs):\n        return await sync_to_async(self.get_or_create)(\n            defaults=defaults,\n            **kwargs,\n        )\n\n    aget_or_create.alters_data = True\n\n    def update_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        \"\"\"\n        Look up an object with the given kwargs, updating one with defaults\n        if it exists, otherwise create a new one. Optionally, an object can\n        be created with different values than defaults by using\n        create_defaults.\n        Return a tuple (object, created), where created is a boolean\n        specifying whether an object was created.\n        \"\"\"\n        update_defaults = defaults or {}\n        if create_defaults is None:\n            create_defaults = update_defaults\n\n        self._for_write = True\n        with transaction.atomic(using=self.db):\n            # Lock the row so that a concurrent update is blocked until\n            # update_or_create() has performed its save.\n            obj, created = self.select_for_update().get_or_create(\n                create_defaults, **kwargs\n            )\n            if created:\n                return obj, created\n            loopIteratorO = __import__(\"builtins\").iter(resolve_callables(update_defaults))\n            while True:\n                try:\n                    k, v = __import__(\"builtins\").next(loopIteratorO)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                setattr(obj, k, v)\n\n            update_fields = set(update_defaults)\n            concrete_field_names = self.model._meta._non_pk_concrete_field_names\n            # update_fields does not support non-concrete fields.\n            if concrete_field_names.issuperset(update_fields):\n                # Add fields which are set on pre_save(), e.g. auto_now fields.\n                # This is to maintain backward compatibility as these fields\n                # are not updated unless explicitly specified in the\n                # update_fields list.\n                pk_fields = self.model._meta.pk_fields\n                loopIteratorP = __import__(\"builtins\").iter(self.model._meta.local_concrete_fields)\n                while True:\n                    try:\n                        field = __import__(\"builtins\").next(loopIteratorP)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    if not (\n                        field in pk_fields or field.__class__.pre_save is Field.pre_save\n                    ):\n                        update_fields.add(field.name)\n                        if field.name != field.attname:\n                            update_fields.add(field.attname)\n                obj.save(using=self.db, update_fields=update_fields)\n            else:\n                obj.save(using=self.db)\n        return obj, False\n\n    update_or_create.alters_data = True\n\n    async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs):\n        return await sync_to_async(self.update_or_create)(\n            defaults=defaults,\n            create_defaults=create_defaults,\n            **kwargs,\n        )\n\n    aupdate_or_create.alters_data = True\n\n    def _extract_model_params(self, defaults, **kwargs):\n        \"\"\"\n        Prepare `params` for creating a model instance based on the given\n        kwargs; for use by get_or_create().\n        \"\"\"\n        defaults = defaults or {}\n        params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}\n        params.update(defaults)\n        property_names = self.model._meta._property_names\n        invalid_params = []\n        for param in params:\n            try:\n                self.model._meta.get_field(param)\n            except exceptions.FieldDoesNotExist:\n                # It's okay to use a model's property if it has a setter.\n                if not (param in property_names and getattr(self.model, param).fset):\n                    invalid_params.append(param)\n        if invalid_params:\n            raise exceptions.FieldError(\n                \"Invalid field name(s) for model %s: '%s'.\"\n                % (\n                    self.model._meta.object_name,\n                    \"', '\".join(sorted(invalid_params)),\n                )\n            )\n        return params\n\n    def _earliest(self, *fields):\n        \"\"\"\n        Return the earliest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if fields:\n            order_by = fields\n        else:\n            order_by = getattr(self.model._meta, \"get_latest_by\")\n            if order_by and not isinstance(order_by, (tuple, list)):\n                order_by = (order_by,)\n        if order_by is None:\n            raise ValueError(\n                \"earliest() and latest() require either fields as positional \"\n                \"arguments or 'get_latest_by' in the model's Meta.\"\n            )\n        obj = self._chain()\n        obj.query.set_limits(high=1)\n        obj.query.clear_ordering(force=True)\n        obj.query.add_ordering(*order_by)\n        return obj.get()\n\n    def earliest(self, *fields):\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self._earliest(*fields)\n\n    async def aearliest(self, *fields):\n        return await sync_to_async(self.earliest)(*fields)\n\n    def latest(self, *fields):\n        \"\"\"\n        Return the latest object according to fields (if given) or by the\n        model's Meta.get_latest_by.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        return self.reverse()._earliest(*fields)\n\n    async def alatest(self, *fields):\n        return await sync_to_async(self.latest)(*fields)\n\n    def first(self):\n        \"\"\"Return the first object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"first\")\n            queryset = self.order_by(\"pk\")\n        loopIteratorQ = __import__(\"builtins\").iter(queryset[:1])\n        while True:\n            try:\n                obj = __import__(\"builtins\").next(loopIteratorQ)\n            except __import__(\"builtins\").StopIteration:\n                break\n            return obj\n\n    async def afirst(self):\n        return await sync_to_async(self.first)()\n\n    def last(self):\n        \"\"\"Return the last object of a query or None if no match is found.\"\"\"\n        if self.ordered or not self.query.default_ordering:\n            queryset = self.reverse()\n        else:\n            self._check_ordering_first_last_queryset_aggregation(method=\"last\")\n            queryset = self.order_by(\"-pk\")\n        loopIteratorR = __import__(\"builtins\").iter(queryset[:1])\n        while True:\n            try:\n                obj = __import__(\"builtins\").next(loopIteratorR)\n            except __import__(\"builtins\").StopIteration:\n                break\n            return obj\n\n    async def alast(self):\n        return await sync_to_async(self.last)()\n\n    def in_bulk(self, id_list=None, *, field_name=\"pk\"):\n        \"\"\"\n        Return a dictionary mapping each of the given IDs to the object with\n        that ID. If `id_list` isn't provided, evaluate the entire QuerySet.\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with in_bulk().\")\n        if id_list is not None and not id_list:\n            return {}\n        opts = self.model._meta\n        unique_fields = [\n            constraint.fields[0]\n            for constraint in opts.total_unique_constraints\n            if len(constraint.fields) == 1\n        ]\n        if (\n            field_name != \"pk\"\n            and not opts.get_field(field_name).unique\n            and field_name not in unique_fields\n            and self.query.distinct_fields != (field_name,)\n        ):\n            raise ValueError(\n                \"in_bulk()'s field_name must be a unique field but %r isn't.\"\n                % field_name\n            )\n\n        qs = self\n\n        def get_obj(obj):\n            return obj\n\n        if issubclass(self._iterable_class, ModelIterable):\n            # Raise an AttributeError if field_name is deferred.\n            get_key = operator.attrgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesIterable):\n            if field_name not in self.query.values_select:\n                qs = qs.values(field_name, *self.query.values_select)\n\n                def get_obj(obj):  # noqa: F811\n                    # We can safely mutate the dictionaries returned by\n                    # ValuesIterable here, since they are limited to the scope\n                    # of this function, and get_key runs before get_obj.\n                    del obj[field_name]\n                    return obj\n\n            get_key = operator.itemgetter(field_name)\n\n        elif issubclass(self._iterable_class, ValuesListIterable):\n            try:\n                field_index = self.query.values_select.index(field_name)\n            except ValueError:\n                # field_name is missing from values_select, so add it.\n                field_index = 0\n                if issubclass(self._iterable_class, NamedValuesListIterable):\n                    kwargs = {\"named\": True}\n                else:\n                    kwargs = {}\n                    get_obj = operator.itemgetter(slice(1, None))\n                qs = qs.values_list(field_name, *self.query.values_select, **kwargs)\n\n            get_key = operator.itemgetter(field_index)\n\n        elif issubclass(self._iterable_class, FlatValuesListIterable):\n            if self.query.values_select == (field_name,):\n                # Mapping field_name to itself.\n                get_key = get_obj\n            else:\n                # Transform it back into a non-flat values_list().\n                qs = qs.values_list(field_name, *self.query.values_select)\n                get_key = operator.itemgetter(0)\n                get_obj = operator.itemgetter(1)\n\n        else:\n            raise TypeError(\n                f\"in_bulk() cannot be used with {self._iterable_class.__name__}.\"\n            )\n\n        if id_list is not None:\n            filter_key = \"{}__in\".format(field_name)\n            id_list = tuple(id_list)\n            batch_size = connections[self.db].ops.bulk_batch_size([opts.pk], id_list)\n            # If the database has a limit on the number of query parameters\n            # (e.g. SQLite), retrieve objects in batches if necessary.\n            if batch_size and batch_size < len(id_list):\n                results = ()\n                loopIteratorS = __import__(\"builtins\").iter(range(0, len(id_list), batch_size))\n                while True:\n                    try:\n                        offset = __import__(\"builtins\").next(loopIteratorS)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    batch = id_list[offset : offset + batch_size]\n                    results += tuple(qs.filter(**{filter_key: batch}))\n                qs = results\n            else:\n                qs = qs.filter(**{filter_key: id_list})\n        else:\n            qs = qs._chain()\n        return {get_key(obj): get_obj(obj) for obj in qs}\n\n    async def ain_bulk(self, id_list=None, *, field_name=\"pk\"):\n        return await sync_to_async(self.in_bulk)(\n            id_list=id_list,\n            field_name=field_name,\n        )\n\n    def delete(self):\n        \"\"\"Delete the records in the current QuerySet.\"\"\"\n        self._not_support_combined_queries(\"delete\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot use 'limit' or 'offset' with delete().\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call delete() after .distinct(*fields).\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call delete() after .values() or .values_list()\")\n\n        del_query = self._chain()\n\n        # The delete is actually 2 queries - one to find related objects,\n        # and one to delete. Make sure that the discovery of related\n        # objects is performed on the same database as the deletion.\n        del_query._for_write = True\n\n        # Disable non-supported fields.\n        del_query.query.select_for_update = False\n        del_query.query.select_related = False\n        del_query.query.clear_ordering(force=True)\n\n        collector = Collector(using=del_query.db, origin=self)\n        collector.collect(del_query)\n        num_deleted, num_deleted_per_model = collector.delete()\n\n        # Clear the result cache, in case this QuerySet gets reused.\n        self._result_cache = None\n        return num_deleted, num_deleted_per_model\n\n    delete.alters_data = True\n    delete.queryset_only = True\n\n    async def adelete(self):\n        return await sync_to_async(self.delete)()\n\n    adelete.alters_data = True\n    adelete.queryset_only = True\n\n    def _raw_delete(self, using):\n        \"\"\"\n        Delete objects found from the given queryset in single direct SQL\n        query. No signals are sent and there is no protection for cascades.\n        \"\"\"\n        query = self.query.clone()\n        query.__class__ = sql.DeleteQuery\n        return query.get_compiler(using).execute_sql(ROW_COUNT)\n\n    _raw_delete.alters_data = True\n\n    def update(self, **kwargs):\n        \"\"\"\n        Update all elements in the current QuerySet, setting all the given\n        fields to the appropriate values.\n        \"\"\"\n        self._not_support_combined_queries(\"update\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        if self.query.distinct_fields:\n            raise TypeError(\"Cannot call update() after .distinct(*fields).\")\n        self._for_write = True\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_values(kwargs)\n\n        # Inline annotations in order_by(), if possible.\n        new_order_by = []\n        loopIteratorT = __import__(\"builtins\").iter(query.order_by)\n        while True:\n            try:\n                col = __import__(\"builtins\").next(loopIteratorT)\n            except __import__(\"builtins\").StopIteration:\n                break\n            alias = col\n            descending = False\n            if isinstance(alias, str) and alias.startswith(\"-\"):\n                alias = alias.removeprefix(\"-\")\n                descending = True\n            if annotation := query.annotations.get(alias):\n                if getattr(annotation, \"contains_aggregate\", False):\n                    raise exceptions.FieldError(\n                        f\"Cannot update when ordering by an aggregate: {annotation}\"\n                    )\n                if descending:\n                    annotation = annotation.desc()\n                new_order_by.append(annotation)\n            else:\n                new_order_by.append(col)\n        query.order_by = tuple(new_order_by)\n\n        # Clear SELECT clause as all annotation references were inlined by\n        # add_update_values() already.\n        query.clear_select_clause()\n        with transaction.mark_for_rollback_on_error(using=self.db):\n            rows = query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        self._result_cache = None\n        return rows\n\n    update.alters_data = True\n\n    async def aupdate(self, **kwargs):\n        return await sync_to_async(self.update)(**kwargs)\n\n    aupdate.alters_data = True\n\n    def _update(self, values, returning_fields=None):\n        \"\"\"\n        A version of update() that accepts field objects instead of field\n        names. Used primarily for model saving and not intended for use by\n        general code (it requires too much poking around at model internals to\n        be useful at that level).\n        \"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot update a query once a slice has been taken.\")\n        query = self.query.chain(sql.UpdateQuery)\n        query.add_update_fields(values)\n        # Clear any annotations so that they won't be present in subqueries.\n        query.annotations = {}\n        self._result_cache = None\n        if returning_fields is None:\n            return query.get_compiler(self.db).execute_sql(ROW_COUNT)\n        return query.get_compiler(self.db).execute_returning_sql(returning_fields)\n\n    _update.alters_data = True\n    _update.queryset_only = False\n\n    def exists(self):\n        \"\"\"\n        Return True if the QuerySet would have any results, False otherwise.\n        \"\"\"\n        if self._result_cache is None:\n            return self.query.has_results(using=self.db)\n        return bool(self._result_cache)\n\n    async def aexists(self):\n        return await sync_to_async(self.exists)()\n\n    def contains(self, obj):\n        \"\"\"\n        Return True if the QuerySet contains the provided obj,\n        False otherwise.\n        \"\"\"\n        self._not_support_combined_queries(\"contains\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call QuerySet.contains() after .values() or .values_list().\"\n            )\n        try:\n            if obj._meta.concrete_model != self.model._meta.concrete_model:\n                return False\n        except AttributeError:\n            raise TypeError(\"'obj' must be a model instance.\")\n        if not obj._is_pk_set():\n            raise ValueError(\"QuerySet.contains() cannot be used on unsaved objects.\")\n        if self._result_cache is not None:\n            return obj in self._result_cache\n        return self.filter(pk=obj.pk).exists()\n\n    async def acontains(self, obj):\n        return await sync_to_async(self.contains)(obj=obj)\n\n    def _prefetch_related_objects(self):\n        # This method can only be called once the result cache has been filled.\n        prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)\n        self._prefetch_done = True\n\n    def explain(self, *, format=None, **options):\n        \"\"\"\n        Runs an EXPLAIN on the SQL query this QuerySet would perform, and\n        returns the results.\n        \"\"\"\n        return self.query.explain(using=self.db, format=format, **options)\n\n    async def aexplain(self, *, format=None, **options):\n        return await sync_to_async(self.explain)(format=format, **options)\n\n    ##################################################\n    # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #\n    ##################################################\n\n    def raw(self, raw_query, params=(), translations=None, using=None):\n        if using is None:\n            using = self.db\n        qs = RawQuerySet(\n            raw_query,\n            model=self.model,\n            params=params,\n            translations=translations,\n            using=using,\n            fetch_mode=self._fetch_mode,\n        )\n        qs._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        return qs\n\n    def _values(self, *fields, **expressions):\n        clone = self._chain()\n        if expressions:\n            # RemovedInDjango70Warning: When the deprecation ends, deindent as:\n            # clone = clone.annotate(**expressions)\n            with warnings.catch_warnings(\n                action=\"ignore\", category=RemovedInDjango70Warning\n            ):\n                clone = clone.annotate(**expressions)\n        clone._fields = fields\n        clone.query.set_values(fields)\n        return clone\n\n    def values(self, *fields, **expressions):\n        fields += tuple(expressions)\n        clone = self._values(*fields, **expressions)\n        clone._iterable_class = ValuesIterable\n        return clone\n\n    def values_list(self, *fields, flat=False, named=False):\n        if flat and named:\n            raise TypeError(\"'flat' and 'named' can't be used together.\")\n        if flat:\n            if len(fields) > 1:\n                raise TypeError(\n                    \"'flat' is not valid when values_list is called with more than one \"\n                    \"field.\"\n                )\n            elif not fields:\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # raise TypeError(\n                #     \"'flat' is not valid when values_list is called with no \"\n                #     \"fields.\"\n                # )\n                warnings.warn(\n                    \"Calling values_list() with no field name and flat=True \"\n                    \"is deprecated. Pass an explicit field name instead, like \"\n                    \"'pk'.\",\n                    RemovedInDjango70Warning,\n                )\n                fields = [self.model._meta.concrete_fields[0].attname]\n\n        field_names = {f: False for f in fields if not hasattr(f, \"resolve_expression\")}\n        _fields = []\n        expressions = {}\n        counter = 1\n        for field in fields:\n            field_name = field\n            expression = None\n            if hasattr(field, \"resolve_expression\"):\n                field_name = getattr(\n                    field, \"default_alias\", field.__class__.__name__.lower()\n                )\n                expression = field\n                # For backward compatibility reasons expressions are always\n                # prefixed with the counter even if their default alias doesn't\n                # collide with field names. Changing this logic could break\n                # some usage of named=True.\n                seen = True\n            elif seen := field_names[field_name]:\n                expression = F(field_name)\n            if seen:\n                field_name_prefix = field_name\n                while (field_name := f\"{field_name_prefix}{counter}\") in field_names:\n                    counter += 1\n            if expression is not None:\n                expressions[field_name] = expression\n            field_names[field_name] = True\n            _fields.append(field_name)\n\n        clone = self._values(*_fields, **expressions)\n        clone._iterable_class = (\n            NamedValuesListIterable\n            if named\n            else FlatValuesListIterable if flat else ValuesListIterable\n        )\n        return clone\n\n    def dates(self, field_name, kind, order=\"ASC\"):\n        \"\"\"\n        Return a list of date objects representing all available dates for\n        the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\"):\n            raise ValueError(\"'kind' must be one of 'year', 'month', 'week', or 'day'.\")\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        return (\n            self.annotate(\n                datefield=Trunc(field_name, kind, output_field=DateField()),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datefield\")\n        )\n\n    def datetimes(self, field_name, kind, order=\"ASC\", tzinfo=None):\n        \"\"\"\n        Return a list of datetime objects representing all available\n        datetimes for the given field_name, scoped to 'kind'.\n        \"\"\"\n        if kind not in (\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"):\n            raise ValueError(\n                \"'kind' must be one of 'year', 'month', 'week', 'day', \"\n                \"'hour', 'minute', or 'second'.\"\n            )\n        if order not in (\"ASC\", \"DESC\"):\n            raise ValueError(\"'order' must be either 'ASC' or 'DESC'.\")\n        if settings.USE_TZ:\n            if tzinfo is None:\n                tzinfo = timezone.get_current_timezone()\n        else:\n            tzinfo = None\n        return (\n            self.annotate(\n                datetimefield=Trunc(\n                    field_name,\n                    kind,\n                    output_field=DateTimeField(),\n                    tzinfo=tzinfo,\n                ),\n                plain_field=F(field_name),\n            )\n            .values_list(\"datetimefield\", flat=True)\n            .distinct()\n            .filter(plain_field__isnull=False)\n            .order_by((\"-\" if order == \"DESC\" else \"\") + \"datetimefield\")\n        )\n\n    def none(self):\n        \"\"\"Return an empty QuerySet.\"\"\"\n        clone = self._chain()\n        clone.query.set_empty()\n        return clone\n\n    ##################################################################\n    # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #\n    ##################################################################\n\n    def all(self):\n        \"\"\"\n        Return a new QuerySet that is a copy of the current one. This allows a\n        QuerySet to proxy for a model manager in some cases.\n        \"\"\"\n        return self._chain()\n\n    def filter(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with the args ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"filter\")\n        return self._filter_or_exclude(False, args, kwargs)\n\n    def exclude(self, *args, **kwargs):\n        \"\"\"\n        Return a new QuerySet instance with NOT (args) ANDed to the existing\n        set.\n        \"\"\"\n        self._not_support_combined_queries(\"exclude\")\n        return self._filter_or_exclude(True, args, kwargs)\n\n    def _filter_or_exclude(self, negate, args, kwargs):\n        if (args or kwargs) and self.query.is_sliced:\n            raise TypeError(\"Cannot filter a query once a slice has been taken.\")\n        clone = self._chain()\n        if self._defer_next_filter:\n            self._defer_next_filter = False\n            clone._deferred_filter = negate, args, kwargs\n        else:\n            clone._filter_or_exclude_inplace(negate, args, kwargs)\n        return clone\n\n    def _filter_or_exclude_inplace(self, negate, args, kwargs):\n        if invalid_kwargs := PROHIBITED_FILTER_KWARGS.intersection(kwargs):\n            invalid_kwargs_str = \", \".join(f\"'{k}'\" for k in sorted(invalid_kwargs))\n            raise TypeError(f\"The following kwargs are invalid: {invalid_kwargs_str}\")\n        if negate:\n            self._query.add_q(~Q(*args, **kwargs))\n        else:\n            self._query.add_q(Q(*args, **kwargs))\n\n    def complex_filter(self, filter_obj):\n        \"\"\"\n        Return a new QuerySet instance with filter_obj added to the filters.\n\n        filter_obj can be a Q object or a dictionary of keyword lookup\n        arguments.\n\n        This exists to support framework features such as 'limit_choices_to',\n        and usually it will be more natural to use other methods.\n        \"\"\"\n        if isinstance(filter_obj, Q):\n            clone = self._chain()\n            clone.query.add_q(filter_obj)\n            return clone\n        else:\n            return self._filter_or_exclude(False, args=(), kwargs=filter_obj)\n\n    def _combinator_query(self, combinator, *other_qs, all=False):\n        # Clone the query to inherit the select list and everything\n        clone = self._chain()\n        # Clear limits and ordering so they can be reapplied\n        clone.query.clear_ordering(force=True)\n        clone.query.default_ordering = True\n        self._clear_ordering_in_combined_queries(clone.query, other_qs)\n        clone.query.clear_limits()\n        clone.query.combinator = combinator\n        clone.query.combinator_all = all\n        return clone\n\n    def union(self, *other_qs, all=False):\n        # If the query is an EmptyQuerySet, combine all nonempty querysets.\n        if isinstance(self, EmptyQuerySet):\n            qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)]\n            if not qs:\n                return self\n            if len(qs) == 1:\n                return qs[0]\n            return qs[0]._combinator_query(\"union\", *qs[1:], all=all)\n        elif not other_qs:\n            return self\n        return self._combinator_query(\"union\", *other_qs, all=all)\n\n    def intersection(self, *other_qs):\n        # If any query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        loopIteratorU = __import__(\"builtins\").iter(other_qs)\n        while True:\n            try:\n                other = __import__(\"builtins\").next(loopIteratorU)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if isinstance(other, EmptyQuerySet):\n                return other\n        return self._combinator_query(\"intersection\", *other_qs)\n\n    def difference(self, *other_qs):\n        # If the query is an EmptyQuerySet, return it.\n        if isinstance(self, EmptyQuerySet):\n            return self\n        return self._combinator_query(\"difference\", *other_qs)\n\n    def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False):\n        \"\"\"\n        Return a new QuerySet instance that will select objects with a\n        FOR UPDATE lock.\n        \"\"\"\n        if nowait and skip_locked:\n            raise ValueError(\"The nowait option cannot be used with skip_locked.\")\n        obj = self._chain()\n        obj._for_write = True\n        obj.query.select_for_update = True\n        obj.query.select_for_update_nowait = nowait\n        obj.query.select_for_update_skip_locked = skip_locked\n        obj.query.select_for_update_of = of\n        obj.query.select_for_no_key_update = no_key\n        return obj\n\n    def select_related(self, *fields):\n        \"\"\"\n        Return a new QuerySet instance that will select related objects.\n\n        If fields are specified, they must be ForeignKey fields and only those\n        related objects are included in the selection.\n\n        If select_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"select_related\")\n        if self._fields is not None:\n            raise TypeError(\n                \"Cannot call select_related() after .values() or .values_list()\"\n            )\n\n        obj = self._chain()\n        if fields == (None,):\n            obj.query.select_related = False\n        elif fields:\n            obj.query.add_select_related(fields)\n        else:\n            # RemovedInDjango70Warning: when the deprecation ends, raise a\n            # TypeError instead.\n            warn_about_external_use(\n                \"Calling select_related() with no arguments is deprecated. \"\n                \"Specify the fields to fetch instead.\",\n                category=RemovedInDjango70Warning,\n                skip_name_prefixes=(\"django.db.models\",),\n            )\n            obj.query.select_related = True\n        return obj\n\n    def prefetch_related(self, *lookups):\n        \"\"\"\n        Return a new QuerySet instance that will prefetch the specified\n        Many-To-One and Many-To-Many related objects when the QuerySet is\n        evaluated.\n\n        When prefetch_related() is called more than once, append to the list of\n        prefetch lookups. If prefetch_related(None) is called, clear the list.\n        \"\"\"\n        self._not_support_combined_queries(\"prefetch_related\")\n        clone = self._chain()\n        if lookups == (None,):\n            clone._prefetch_related_lookups = ()\n        else:\n            loopIteratorV = __import__(\"builtins\").iter(lookups)\n            while True:\n                try:\n                    lookup = __import__(\"builtins\").next(loopIteratorV)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                if isinstance(lookup, Prefetch):\n                    lookup = lookup.prefetch_to\n                lookup = lookup.split(LOOKUP_SEP, 1)[0]\n                if lookup in self.query._filtered_relations:\n                    raise ValueError(\n                        \"prefetch_related() is not supported with FilteredRelation.\"\n                    )\n            clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups\n        return clone\n\n    def annotate(self, *args, **kwargs):\n        \"\"\"\n        Return a query set in which the returned objects have been annotated\n        with extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"annotate\")\n        return self._annotate(args, kwargs, select=True)\n\n    def alias(self, *args, **kwargs):\n        \"\"\"\n        Return a query set with added aliases for extra data or aggregations.\n        \"\"\"\n        self._not_support_combined_queries(\"alias\")\n        return self._annotate(args, kwargs, select=False)\n\n    def _annotate(self, args, kwargs, select=True):\n        self._validate_values_are_expressions(\n            args + tuple(kwargs.values()), method_name=\"annotate\"\n        )\n        annotations = {}\n        for arg in args:\n            # The default_alias property raises TypeError if default_alias\n            # can't be set automatically or AttributeError if it isn't an\n            # attribute.\n            try:\n                if arg.default_alias in kwargs:\n                    raise ValueError(\n                        \"The named annotation '%s' conflicts with the \"\n                        \"default name for another annotation.\" % arg.default_alias\n                    )\n            except (TypeError, AttributeError):\n                raise TypeError(\"Complex annotations require an alias\")\n            annotations[arg.default_alias] = arg\n        annotations.update(kwargs)\n\n        clone = self._chain()\n        names = self._fields\n        if names is None:\n            names = set(\n                chain.from_iterable(\n                    (\n                        (field.name, field.attname)\n                        if hasattr(field, \"attname\")\n                        else (field.name,)\n                    )\n                    for field in self.model._meta.get_fields()\n                )\n            )\n\n        loopIteratorW = __import__(\"builtins\").iter(annotations.items())\n        while True:\n            try:\n                alias, annotation = __import__(\"builtins\").next(loopIteratorW)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if alias in names:\n                raise ValueError(\n                    \"The annotation '%s' conflicts with a field on \"\n                    \"the model.\" % alias\n                )\n            if isinstance(annotation, FilteredRelation):\n                clone.query.add_filtered_relation(annotation, alias)\n            else:\n                clone.query.add_annotation(\n                    annotation,\n                    alias,\n                    select=select,\n                )\n        loopIteratorX = __import__(\"builtins\").iter(clone.query.annotations.items())\n        while True:\n            try:\n                alias, annotation = __import__(\"builtins\").next(loopIteratorX)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if alias in annotations and annotation.contains_aggregate:\n                if clone._fields is None:\n                    clone.query.group_by = True\n                else:\n                    clone.query.set_group_by()\n                break\n\n        return clone\n\n    def order_by(self, *field_names):\n        \"\"\"Return a new QuerySet instance with the ordering changed.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reorder a query once a slice has been taken.\")\n        obj = self._chain()\n        obj.query.clear_ordering(force=True, clear_default=False)\n        obj.query.add_ordering(*field_names)\n        return obj\n\n    def distinct(self, *field_names):\n        \"\"\"\n        Return a new QuerySet instance that will select only distinct results.\n        \"\"\"\n        self._not_support_combined_queries(\"distinct\")\n        if self.query.is_sliced:\n            raise TypeError(\n                \"Cannot create distinct fields once a slice has been taken.\"\n            )\n        obj = self._chain()\n        obj.query.add_distinct_fields(*field_names)\n        return obj\n\n    def extra(\n        self,\n        select=None,\n        where=None,\n        params=None,\n        tables=None,\n        order_by=None,\n        select_params=None,\n    ):\n        \"\"\"Add extra SQL fragments to the query.\"\"\"\n        self._not_support_combined_queries(\"extra\")\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot change a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.add_extra(select, select_params, where, params, tables, order_by)\n        return clone\n\n    def reverse(self):\n        \"\"\"Reverse the ordering of the QuerySet.\"\"\"\n        if self.query.is_sliced:\n            raise TypeError(\"Cannot reverse a query once a slice has been taken.\")\n        clone = self._chain()\n        clone.query.standard_ordering = not clone.query.standard_ordering\n        return clone\n\n    def defer(self, *fields):\n        \"\"\"\n        Defer the loading of data for certain fields until they are accessed.\n        Add the set of deferred fields to any existing set of deferred fields.\n        The only exception to this is if None is passed in as the only\n        parameter, in which case remove all deferrals.\n        \"\"\"\n        self._not_support_combined_queries(\"defer\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call defer() after .values() or .values_list()\")\n        clone = self._chain()\n        if fields == (None,):\n            clone.query.clear_deferred_loading()\n        else:\n            clone.query.add_deferred_loading(fields)\n        return clone\n\n    def only(self, *fields):\n        \"\"\"\n        Essentially, the opposite of defer(). Only the fields passed into this\n        method and that are not already specified as deferred are loaded\n        immediately when the queryset is evaluated.\n        \"\"\"\n        self._not_support_combined_queries(\"only\")\n        if self._fields is not None:\n            raise TypeError(\"Cannot call only() after .values() or .values_list()\")\n        if fields == (None,):\n            # Can only pass None to defer(), not only(), as the rest option.\n            # That won't stop people trying to do this, so let's be explicit.\n            raise TypeError(\"Cannot pass None as an argument to only().\")\n        loopIteratorY = __import__(\"builtins\").iter(fields)\n        while True:\n            try:\n                field = __import__(\"builtins\").next(loopIteratorY)\n            except __import__(\"builtins\").StopIteration:\n                break\n            field = field.split(LOOKUP_SEP, 1)[0]\n            if field in self.query._filtered_relations:\n                raise ValueError(\"only() is not supported with FilteredRelation.\")\n        clone = self._chain()\n        clone.query.add_immediate_loading(fields)\n        return clone\n\n    def using(self, alias):\n        \"\"\"Select which database this QuerySet should execute against.\"\"\"\n        clone = self._chain()\n        clone._db = alias\n        return clone\n\n    def fetch_mode(self, fetch_mode):\n        \"\"\"Set the fetch mode for the QuerySet.\"\"\"\n        clone = self._chain()\n        clone._fetch_mode = fetch_mode\n        return clone\n\n    ###################################\n    # PUBLIC INTROSPECTION ATTRIBUTES #\n    ###################################\n\n    @property\n    def ordered(self):\n        \"\"\"\n        Return True if the QuerySet is ordered -- i.e. has an order_by()\n        clause or a default ordering on the model (or is empty).\n        \"\"\"\n        if isinstance(self, EmptyQuerySet):\n            return True\n        if self.query.extra_order_by or self.query.order_by:\n            return True\n        elif (\n            self.query.default_ordering\n            and self.query.get_meta().ordering\n            and\n            # A default ordering doesn't affect GROUP BY queries.\n            not self.query.group_by\n        ):\n            return True\n        else:\n            return False\n\n    @property\n    def totally_ordered(self):\n        \"\"\"\n        Returns True if the QuerySet is ordered and the ordering is\n        deterministic. This requires that the ordering includes a field\n        (or set of fields) that is unique and non-nullable.\n\n        For queries involving a GROUP BY clause, the model's default\n        ordering is ignored. Ordering specified via .extra(order_by=...)\n        is also ignored.\n        \"\"\"\n        if not self.ordered:\n            return False\n        ordering = self.query.order_by\n        if not ordering and self.query.default_ordering:\n            ordering = self.query.get_meta().ordering\n        if not ordering:\n            return False\n        opts = self.model._meta\n        pk_fields = {f.attname for f in opts.pk_fields}\n        candidate_fields = set()\n        for part in ordering:\n            # Search for single field providing a total ordering.\n            field_name = None\n            if isinstance(part, str):\n                field_name = part.lstrip(\"-\")\n            elif isinstance(part, F):\n                field_name = part.name\n            elif isinstance(part, OrderBy) and isinstance(part.expression, F):\n                field_name = part.expression.name\n            if annotation_col := self.query.annotations.get(field_name):\n                if isinstance(annotation_col, Col):\n                    if annotation_col.alias == self.query.base_table:\n                        candidate_fields.add(annotation_col.target)\n                elif isinstance(annotation_col, ColPairs):\n                    candidate_fields |= {\n                        c.target\n                        for c in annotation_col.get_cols()\n                        if c.alias == self.query.base_table\n                    }\n            elif field_name:\n                if field_name == \"pk\":\n                    return True\n                # Normalize attname references by using get_field().\n                try:\n                    field = opts.get_field(field_name)\n                except exceptions.FieldDoesNotExist:\n                    # Could be \"?\" for random ordering or a related field\n                    # lookup. Skip this part of introspection for now.\n                    continue\n                else:\n                    # Ordering by a related field name orders by the referenced\n                    # model's ordering. Skip this introspection for now.\n                    if field.remote_field and field_name == field.name:\n                        continue\n                    candidate_fields.add(field)\n\n        candidate_attnames = set()\n        loopIteratorZ = __import__(\"builtins\").iter(candidate_fields)\n        while True:\n            try:\n                field = __import__(\"builtins\").next(loopIteratorZ)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if field.unique and not field.null:\n                return True\n            candidate_attnames.add(field.attname)\n\n        # Account for members of a CompositePrimaryKey.\n        if candidate_attnames.issuperset(pk_fields):\n            return True\n        # No single total ordering field, try unique_together and total\n        # unique constraints.\n        constraint_field_names = (\n            *opts.unique_together,\n            *(constraint.fields for constraint in opts.total_unique_constraints),\n        )\n        for field_names in constraint_field_names:\n            # Normalize attname references by using get_field().\n            try:\n                fields = [opts.get_field(field_name) for field_name in field_names]\n            except exceptions.FieldDoesNotExist:\n                continue\n            # Composite unique constraints containing a nullable column\n            # cannot ensure total ordering.\n            if any(field.null for field in fields):\n                continue\n            if candidate_attnames.issuperset(field.attname for field in fields):\n                return True\n\n        return False\n\n    @property\n    def db(self):\n        \"\"\"Return the database used if this query is executed now.\"\"\"\n        if self._for_write:\n            return self._db or router.db_for_write(self.model, **self._hints)\n        return self._db or router.db_for_read(self.model, **self._hints)\n\n    ###################\n    # PRIVATE METHODS #\n    ###################\n\n    def _insert(\n        self,\n        objs,\n        fields,\n        returning_fields=None,\n        raw=False,\n        using=None,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Insert a new record for the given model. This provides an interface to\n        the InsertQuery class and is how Model.save() is implemented.\n        \"\"\"\n        self._for_write = True\n        if using is None:\n            using = self.db\n        query = sql.InsertQuery(\n            self.model,\n            on_conflict=on_conflict,\n            update_fields=update_fields,\n            unique_fields=unique_fields,\n        )\n        query.insert_values(fields, objs, raw=raw)\n        return query.get_compiler(using=using).execute_sql(returning_fields)\n\n    _insert.alters_data = True\n    _insert.queryset_only = False\n\n    def _batched_insert(\n        self,\n        objs,\n        fields,\n        batch_size,\n        on_conflict=None,\n        update_fields=None,\n        unique_fields=None,\n    ):\n        \"\"\"\n        Helper method for bulk_create() to insert objs one batch at a time.\n        \"\"\"\n        connection = connections[self.db]\n        ops = connection.ops\n        max_batch_size = max(ops.bulk_batch_size(fields, objs), 1)\n        batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size\n        inserted_rows = []\n        returning_fields = (\n            self.model._meta.db_returning_fields\n            if (\n                connection.features.can_return_rows_from_bulk_insert\n                and (on_conflict is None or on_conflict == OnConflict.UPDATE)\n            )\n            else None\n        )\n        batches = [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]\n        if len(batches) > 1:\n            context = transaction.atomic(using=self.db, savepoint=False)\n        else:\n            context = nullcontext()\n        with context:\n            loopIteratorAA = __import__(\"builtins\").iter(batches)\n            while True:\n                try:\n                    item = __import__(\"builtins\").next(loopIteratorAA)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                inserted_rows.extend(\n                    self._insert(\n                        item,\n                        fields=fields,\n                        using=self.db,\n                        on_conflict=on_conflict,\n                        update_fields=update_fields,\n                        unique_fields=unique_fields,\n                        returning_fields=returning_fields,\n                    )\n                )\n        return inserted_rows\n\n    def _disable_cloning(self):\n        \"\"\"\n        Prevent calls to _chain() from creating a new QuerySet via _clone().\n        All subsequent QuerySet mutations will occur on this instance until\n        _enable_cloning() is used.\n        \"\"\"\n        self._cloning_enabled = False\n        return self\n\n    def _enable_cloning(self):\n        \"\"\"\n        Allow calls to _chain() to create a new QuerySet via _clone(). Restores\n        the default behavior where any QuerySet mutation will return a new\n        QuerySet instance. Necessary only when there has been a\n        _disable_cloning() call previously.\n        \"\"\"\n        self._cloning_enabled = True\n        return self\n\n    def _avoid_cloning(self):\n        \"\"\"\n        Temporarily prevent QuerySet _clone() operations, restoring the default\n        behavior on exit. For the duration of the context managed statement,\n        all operations (e.g. filter(), exclude(), etc.) will mutate the same\n        QuerySet instance.\n\n        @contextlib.contextmanager is intentionally not used for performance\n        reasons.\n        \"\"\"\n        return PreventQuerySetCloning(self)\n\n    def _chain(self):\n        \"\"\"\n        Return a copy of the current QuerySet that's ready for another\n        operation.\n\n        If the QuerySet has opted in to in-place mutations via\n        _disable_cloning() temporarily, the copy doesn't occur and instead the\n        same QuerySet instance will be modified.\n        \"\"\"\n        if not self._cloning_enabled:\n            obj = self\n        else:\n            obj = self._clone()\n        if obj._sticky_filter:\n            obj.query.filter_is_sticky = True\n            obj._sticky_filter = False\n        return obj\n\n    def _clone(self):\n        \"\"\"\n        Return a copy of the current QuerySet. A lightweight alternative\n        to deepcopy().\n        \"\"\"\n        c = self.__class__(\n            model=self.model,\n            query=self.query.chain(),\n            using=self._db,\n            hints=self._hints,\n        )\n        c._sticky_filter = self._sticky_filter\n        c._for_write = self._for_write\n        c._prefetch_related_lookups = self._prefetch_related_lookups[:]\n        c._known_related_objects = self._known_related_objects\n        c._iterable_class = self._iterable_class\n        c._fetch_mode = self._fetch_mode\n        c._fields = self._fields\n        return c\n\n    def _fetch_all(self):\n        if self._result_cache is None:\n            self._result_cache = list(self._iterable_class(self))\n        if self._prefetch_related_lookups and not self._prefetch_done:\n            self._prefetch_related_objects()\n\n    def _next_is_sticky(self):\n        \"\"\"\n        Indicate that the next filter call and the one following that should\n        be treated as a single filter. This is only important when it comes to\n        determining when to reuse tables for many-to-many filters. Required so\n        that we can filter naturally on the results of related managers.\n\n        This doesn't return a clone of the current QuerySet (it returns\n        \"self\"). The method is only used internally and should be immediately\n        followed by a filter() that does create a clone.\n        \"\"\"\n        self._sticky_filter = True\n        return self\n\n    def _merge_sanity_check(self, other):\n        \"\"\"Check that two QuerySet classes may be merged.\"\"\"\n        if self._fields is not None and (\n            set(self.query.values_select) != set(other.query.values_select)\n            or set(self.query.extra_select) != set(other.query.extra_select)\n            or set(self.query.annotation_select) != set(other.query.annotation_select)\n        ):\n            raise TypeError(\n                \"Merging '%s' classes must involve the same values in each case.\"\n                % self.__class__.__name__\n            )\n\n    def _merge_known_related_objects(self, other):\n        \"\"\"\n        Keep track of all known related objects from either QuerySet instance.\n        \"\"\"\n        loopIteratorAB = __import__(\"builtins\").iter(other._known_related_objects.items())\n        while True:\n            try:\n                field, objects = __import__(\"builtins\").next(loopIteratorAB)\n            except __import__(\"builtins\").StopIteration:\n                break\n            self._known_related_objects.setdefault(field, {}).update(objects)\n\n    def resolve_expression(self, *args, **kwargs):\n        query = self.query.resolve_expression(*args, **kwargs)\n        query._db = self._db\n        return query\n\n    resolve_expression.queryset_only = True\n\n    def _add_hints(self, **hints):\n        \"\"\"\n        Update hinting information for use by routers. Add new key/values or\n        overwrite existing key/values.\n        \"\"\"\n        self._hints.update(hints)\n\n    def _has_filters(self):\n        \"\"\"\n        Check if this QuerySet has any filtering going on. This isn't\n        equivalent with checking if all objects are present in results, for\n        example, qs[1:]._has_filters() -> False.\n        \"\"\"\n        return self.query.has_filters()\n\n    @staticmethod\n    def _validate_values_are_expressions(values, method_name):\n        invalid_args = sorted(\n            str(arg) for arg in values if not hasattr(arg, \"resolve_expression\")\n        )\n        if invalid_args:\n            raise TypeError(\n                \"QuerySet.%s() received non-expression(s): %s.\"\n                % (\n                    method_name,\n                    \", \".join(invalid_args),\n                )\n            )\n\n    def _not_support_combined_queries(self, operation_name):\n        if self.query.combinator:\n            raise NotSupportedError(\n                \"Calling QuerySet.%s() after %s() is not supported.\"\n                % (operation_name, self.query.combinator)\n            )\n\n    def _check_operator_queryset(self, other, operator_):\n        if self.query.combinator or other.query.combinator:\n            raise TypeError(f\"Cannot use {operator_} operator with combined queryset.\")\n\n    def _check_ordering_first_last_queryset_aggregation(self, method):\n        if (\n            isinstance(self.query.group_by, tuple)\n            # Raise if the pk fields are not in the group_by.\n            and self.model._meta.pk\n            not in {col.output_field for col in self.query.group_by}\n            and set(self.model._meta.pk_fields).difference(\n                {col.target for col in self.query.group_by}\n            )\n        ):\n            raise TypeError(\n                f\"Cannot use QuerySet.{method}() on an unordered queryset performing \"\n                f\"aggregation. Add an ordering with order_by().\"\n            )\n\n    def _clear_ordering_in_combined_queries(self, cloned_query, other_qs):\n        combined_queries = [self.query]\n        loopIteratorAC = __import__(\"builtins\").iter(other_qs)\n        while True:\n            try:\n                qs = __import__(\"builtins\").next(loopIteratorAC)\n            except __import__(\"builtins\").StopIteration:\n                break\n            query = qs.query.clone()\n            query.clear_ordering(force=False, clear_default=False)\n            combined_queries.append(query)\n        cloned_query.combined_queries = tuple(combined_queries)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-765e7606ef75a519", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b6b3a1da46fc6ec85a0b1e88159ee99a227648b5bbab918aae8dc502bee7146e", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 2272, "local_path": "control-flow/lower-for-to-while/I13__django__QuerySet__f0d168ba.py", "order": 13, "original_content_sha256": "210407b8d47008297160597110e124a9bda459a7f16fc35316bf2d05f42e3530", "parent_variant_id": "pyint-5c2b55814568-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/query.py#L374-L2424", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 2, "for_loops_lowered_to_while": 34, "for_loops_skipped_for_comment": 6, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 34, "synchronous_for_loops_eligible": 34, "synchronous_for_loops_found": 40}, "unit_kind": "class", "unit_name": "QuerySet", "variant_id": "pyint-87acf0d168ba-I13", "group_id": "py-765e7606ef75a519", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 238, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a09548c72375-SRC", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass SessionRedirectMixin:\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...\n\n    def get_redirect_target(self, resp: Response) -> str | None:\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if resp.is_redirect:\n            location = resp.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            location = location.encode(\"latin1\")\n            return to_native_string(location, \"utf8\")\n        return None\n\n    def should_strip_auth(self, old_url: str, new_url: str) -> bool:\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if old_parsed.hostname != new_parsed.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (\n            old_parsed.scheme == \"http\"\n            and old_parsed.port in (80, None)\n            and new_parsed.scheme == \"https\"\n            and new_parsed.port in (443, None)\n        ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        changed_port = old_parsed.port != new_parsed.port\n        changed_scheme = old_parsed.scheme != new_parsed.scheme\n        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n        if (\n            not changed_scheme\n            and old_parsed.port in default_port\n            and new_parsed.port in default_port\n        ):\n            return False\n\n        # Standard case: root URI must match\n        return changed_port or changed_scheme\n\n    def resolve_redirects(\n        self,\n        resp: Response,\n        req: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n        yield_requests: bool = False,\n        **adapter_kwargs: Any,\n    ) -> Generator[Response, None, None]:\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n        hist: list[Response] = []  # keep track of history\n\n        url = self.get_redirect_target(resp)\n        previous_fragment = urlparse(req.url).fragment\n        while url:\n            prepared_request = req.copy()\n\n            # Update history and keep track of redirects.\n            resp.history = hist[:]\n            hist.append(resp)\n\n            try:\n                resp.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                resp.raw.read(decode_content=False)\n\n            if len(resp.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=resp\n                )\n\n            # Release the connection back into the pool.\n            resp.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if url.startswith(\"//\"):\n                parsed_rurl = urlparse(resp.url)\n                url = \":\".join([to_native_string(parsed_rurl.scheme), url])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            parsed = urlparse(url)\n            if parsed.fragment == \"\" and previous_fragment:\n                parsed = parsed._replace(fragment=previous_fragment)\n            elif parsed.fragment:\n                previous_fragment = parsed.fragment\n            url = parsed.geturl()\n\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not parsed.netloc:\n                url = urljoin(resp.url, requote_uri(url))\n            else:\n                url = requote_uri(url)\n\n            prepared_request.url = to_native_string(url)\n\n            self.rebuild_method(prepared_request, resp)\n\n            # https://github.com/psf/requests/issues/1084\n            if resp.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                purged_headers = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for header in purged_headers:\n                    prepared_request.headers.pop(header, None)\n                prepared_request.body = None\n\n            headers = prepared_request.headers\n            headers.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            cookie_jar = cast(\"CookieJar\", prepared_request._cookies)\n            extract_cookies_to_jar(cookie_jar, req, resp.raw)\n            merge_cookies(cookie_jar, self.cookies)\n            prepared_request.prepare_cookies(cookie_jar)\n\n            # Rebuild auth and proxy information.\n            proxies = self.rebuild_proxies(prepared_request, proxies)\n            self.rebuild_auth(prepared_request, resp)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            rewindable = prepared_request._body_position is not None and (\n                \"Content-Length\" in headers or \"Transfer-Encoding\" in headers\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if rewindable:\n                rewind_body(prepared_request)\n\n            # Override the original request.\n            req = prepared_request\n\n            if yield_requests:\n                yield req  # type: ignore[misc]  # Internal use only, returns PreparedRequest\n            else:\n                resp = self.send(\n                    req,\n                    stream=stream,\n                    timeout=timeout,\n                    verify=verify,\n                    cert=cert,\n                    proxies=proxies,\n                    allow_redirects=False,\n                    **adapter_kwargs,\n                )\n\n                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n\n                # extract redirect url, if any, for the next loop\n                url = self.get_redirect_target(resp)\n                yield resp\n\n    def rebuild_auth(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        original_request = response.request\n        assert _is_prepared(original_request)\n        assert _is_prepared(prepared_request)\n\n        headers = prepared_request.headers\n        original_url = original_request.url\n        url = prepared_request.url\n\n        if \"Authorization\" in headers and self.should_strip_auth(original_url, url):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del headers[\"Authorization\"]\n\n        # .netrc might have more auth for us on our new host.\n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if new_auth is not None:\n            prepared_request.prepare_auth(new_auth)\n\n    def rebuild_proxies(\n        self,\n        prepared_request: PreparedRequest,\n        proxies: dict[str, str] | None,\n    ) -> dict[str, str]:\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n\n        :rtype: dict\n        \"\"\"\n        assert _is_prepared(prepared_request)\n        headers = prepared_request.headers\n        scheme = urlparse(prepared_request.url).scheme\n        new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n\n        if \"Proxy-Authorization\" in headers:\n            del headers[\"Proxy-Authorization\"]\n\n        try:\n            username, password = get_auth_from_url(new_proxies[scheme])\n        except KeyError:\n            username, password = None, None\n\n        # urllib3 handles proxy authorization for us in the standard adapter.\n        # Avoid appending this to TLS tunneled requests where it may be leaked.\n        if not scheme.startswith(\"https\") and username and password:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return new_proxies\n\n    def rebuild_method(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        method = prepared_request.method\n\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if response.status_code == codes.see_other and method != \"HEAD\":\n            method = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if response.status_code == codes.found and method != \"HEAD\":\n            method = \"GET\"\n\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if response.status_code == codes.moved and method == \"POST\":\n            method = \"GET\"\n\n        prepared_request.method = method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-78ed11405b022ab8", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 314, "local_path": "source-original/SRC__requests__SessionRedirectMixin__48c72375.py", "order": 0, "original_content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L127-L392", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "SessionRedirectMixin", "variant_id": "pyint-a09548c72375-SRC", "group_id": "py-78ed11405b022ab8", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 715, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-76c4345259ca-I01", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (   \n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (   \n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,   \n    to_key_val_list,\n)\n\nclass SessionRedirectMixin:\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...\n\n    def get_redirect_target(self, resp: Response) -> str | None:\n        \n         \n         \n         \n         \n         \n         \n        if resp.is_redirect:\n            location = resp.headers[\"location\"]\n             \n             \n             \n             \n             \n             \n            location = location.encode(\"latin1\")\n            return to_native_string(location, \"utf8\")\n        return None\n\n    def should_strip_auth(self, old_url: str, new_url: str) -> bool:\n        \n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if old_parsed.hostname != new_parsed.hostname:\n            return True\n         \n         \n         \n         \n        if (\n            old_parsed.scheme == \"http\"\n            and old_parsed.port in (80, None)\n            and new_parsed.scheme == \"https\"\n            and new_parsed.port in (443, None)\n        ):\n            return False\n\n         \n        changed_port = old_parsed.port != new_parsed.port\n        changed_scheme = old_parsed.scheme != new_parsed.scheme\n        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n        if (\n            not changed_scheme\n            and old_parsed.port in default_port\n            and new_parsed.port in default_port\n        ):\n            return False\n\n         \n        return changed_port or changed_scheme\n\n    def resolve_redirects(\n        self,\n        resp: Response,\n        req: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n        yield_requests: bool = False,\n        **adapter_kwargs: Any,\n    ) -> Generator[Response, None, None]:\n        \n\n        hist: list[Response] = []   \n\n        url = self.get_redirect_target(resp)\n        previous_fragment = urlparse(req.url).fragment\n        while url:\n            prepared_request = req.copy()\n\n             \n            resp.history = hist[:]\n            hist.append(resp)\n\n            try:\n                resp.content   \n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                resp.raw.read(decode_content=False)\n\n            if len(resp.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=resp\n                )\n\n             \n            resp.close()\n\n             \n            if url.startswith(\"//\"):\n                parsed_rurl = urlparse(resp.url)\n                url = \":\".join([to_native_string(parsed_rurl.scheme), url])\n\n             \n            parsed = urlparse(url)\n            if parsed.fragment == \"\" and previous_fragment:\n                parsed = parsed._replace(fragment=previous_fragment)\n            elif parsed.fragment:\n                previous_fragment = parsed.fragment\n            url = parsed.geturl()\n\n             \n             \n             \n            if not parsed.netloc:\n                url = urljoin(resp.url, requote_uri(url))\n            else:\n                url = requote_uri(url)\n\n            prepared_request.url = to_native_string(url)\n\n            self.rebuild_method(prepared_request, resp)\n\n             \n            if resp.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                 \n                purged_headers = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for header in purged_headers:\n                    prepared_request.headers.pop(header, None)\n                prepared_request.body = None\n\n            headers = prepared_request.headers\n            headers.pop(\"Cookie\", None)\n\n             \n             \n             \n            cookie_jar = cast(\"CookieJar\", prepared_request._cookies)\n            extract_cookies_to_jar(cookie_jar, req, resp.raw)\n            merge_cookies(cookie_jar, self.cookies)\n            prepared_request.prepare_cookies(cookie_jar)\n\n             \n            proxies = self.rebuild_proxies(prepared_request, proxies)\n            self.rebuild_auth(prepared_request, resp)\n\n             \n             \n             \n            rewindable = prepared_request._body_position is not None and (\n                \"Content-Length\" in headers or \"Transfer-Encoding\" in headers\n            )\n\n             \n            if rewindable:\n                rewind_body(prepared_request)\n\n             \n            req = prepared_request\n\n            if yield_requests:\n                yield req   \n            else:\n                resp = self.send(\n                    req,\n                    stream=stream,\n                    timeout=timeout,\n                    verify=verify,\n                    cert=cert,\n                    proxies=proxies,\n                    allow_redirects=False,\n                    **adapter_kwargs,\n                )\n\n                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n\n                 \n                url = self.get_redirect_target(resp)\n                yield resp\n\n    def rebuild_auth(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \n        original_request = response.request\n        assert _is_prepared(original_request)\n        assert _is_prepared(prepared_request)\n\n        headers = prepared_request.headers\n        original_url = original_request.url\n        url = prepared_request.url\n\n        if \"Authorization\" in headers and self.should_strip_auth(original_url, url):\n             \n             \n            del headers[\"Authorization\"]\n\n         \n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if new_auth is not None:\n            prepared_request.prepare_auth(new_auth)\n\n    def rebuild_proxies(\n        self,\n        prepared_request: PreparedRequest,\n        proxies: dict[str, str] | None,\n    ) -> dict[str, str]:\n        \n        assert _is_prepared(prepared_request)\n        headers = prepared_request.headers\n        scheme = urlparse(prepared_request.url).scheme\n        new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n\n        if \"Proxy-Authorization\" in headers:\n            del headers[\"Proxy-Authorization\"]\n\n        try:\n            username, password = get_auth_from_url(new_proxies[scheme])\n        except KeyError:\n            username, password = None, None\n\n         \n         \n        if not scheme.startswith(\"https\") and username and password:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return new_proxies\n\n    def rebuild_method(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \n        method = prepared_request.method\n\n         \n        if response.status_code == codes.see_other and method != \"HEAD\":\n            method = \"GET\"\n\n         \n         \n        if response.status_code == codes.found and method != \"HEAD\":\n            method = \"GET\"\n\n         \n         \n        if response.status_code == codes.moved and method == \"POST\":\n            method = \"GET\"\n\n        prepared_request.method = method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-78ed11405b022ab8", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "9fa171f40316b2a262a72de5f7190800914f3c43d4f60adb1775ca0962a5295d", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 299, "local_path": "comments/remove-comments/I01__requests__SessionRedirectMixin__345259ca.py", "order": 1, "original_content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "parent_variant_id": "pyint-a09548c72375-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L127-L392", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 3755, "comments_removed": 59, "docstrings_removed": 6, "line_comments_removed": 53}, "unit_kind": "class", "unit_name": "SessionRedirectMixin", "variant_id": "pyint-76c4345259ca-I01", "group_id": "py-78ed11405b022ab8", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 716, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-56801ce8fec5-I02", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass SessionRedirectMixin:\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n\n    def sen(self, req2: PreparedRequest, **kwa: Any) -> Response: ...\n\n    def get2(self, res: Response) -> str | None:\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if res.is_redirect:\n            loc = res.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            loc = loc.encode(\"latin1\")\n            return to_native_string(loc, \"utf8\")\n        return None\n\n    def should(self, old: str, new: str) -> bool:\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        old2 = urlparse(old)\n        new2 = urlparse(new)\n        if old2.hostname != new2.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (\n            old2.scheme == \"http\"\n            and old2.port in (80, None)\n            and new2.scheme == \"https\"\n            and new2.port in (443, None)\n        ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        changed = old2.port != new2.port\n        changed2 = old2.scheme != new2.scheme\n        default = (DEFAULT_PORTS.get(old2.scheme, None), None)\n        if (\n            not changed2\n            and old2.port in default\n            and new2.port in default\n        ):\n            return False\n\n        # Standard case: root URI must match\n        return changed or changed2\n\n    def resolve(\n        self,\n        res2: Response,\n        req3: PreparedRequest,\n        str2: bool = False,\n        tim: _t.TimeoutType = None,\n        ver: _t.VerifyType = True,\n        cer: _t.CertType = None,\n        pro: dict[str, str] | None = None,\n        yield2: bool = False,\n        **adapter: Any,\n    ) -> Generator[Response, None, None]:\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n        his: list[Response] = []  # keep track of history\n\n        url2 = self.get2(res2)\n        previous = urlparse(req3.url).fragment\n        while url2:\n            prepared = req3.copy()\n\n            # Update history and keep track of redirects.\n            res2.history = his[:]\n            his.append(res2)\n\n            try:\n                res2.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                res2.raw.read(decode_content=False)\n\n            if len(res2.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=res2\n                )\n\n            # Release the connection back into the pool.\n            res2.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if url2.startswith(\"//\"):\n                parsed2 = urlparse(res2.url)\n                url2 = \":\".join([to_native_string(parsed2.scheme), url2])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            par = urlparse(url2)\n            if par.fragment == \"\" and previous:\n                par = par._replace(fragment=previous)\n            elif par.fragment:\n                previous = par.fragment\n            url2 = par.geturl()\n\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not par.netloc:\n                url2 = urljoin(res2.url, requote_uri(url2))\n            else:\n                url2 = requote_uri(url2)\n\n            prepared.url = to_native_string(url2)\n\n            self.rebuild3(prepared, res2)\n\n            # https://github.com/psf/requests/issues/1084\n            if res2.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                purged = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for hea in purged:\n                    prepared.headers.pop(hea, None)\n                prepared.body = None\n\n            hea2 = prepared.headers\n            hea2.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            cookie = cast(\"CookieJar\", prepared._cookies)\n            extract_cookies_to_jar(cookie, req3, res2.raw)\n            merge_cookies(cookie, self.cookies)\n            prepared.prepare_cookies(cookie)\n\n            # Rebuild auth and proxy information.\n            pro = self.rebuild2(prepared, pro)\n            self.rebuild(prepared, res2)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            rew = prepared._body_position is not None and (\n                \"Content-Length\" in hea2 or \"Transfer-Encoding\" in hea2\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if rew:\n                rewind_body(prepared)\n\n            # Override the original request.\n            req3 = prepared\n\n            if yield2:\n                yield req3  # type: ignore[misc]  # Internal use only, returns PreparedRequest\n            else:\n                res2 = self.sen(\n                    req3,\n                    stream=str2,\n                    timeout=tim,\n                    verify=ver,\n                    cert=cer,\n                    proxies=pro,\n                    allow_redirects=False,\n                    **adapter,\n                )\n\n                extract_cookies_to_jar(self.cookies, prepared, res2.raw)\n\n                # extract redirect url, if any, for the next loop\n                url2 = self.get2(res2)\n                yield res2\n\n    def rebuild(\n        self, prepared2: PreparedRequest, res3: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        original = res3.request\n        assert _is_prepared(original)\n        assert _is_prepared(prepared2)\n\n        hea3 = prepared2.headers\n        original2 = original.url\n        url3 = prepared2.url\n\n        if \"Authorization\" in hea3 and self.should(original2, url3):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del hea3[\"Authorization\"]\n\n        # .netrc might have more auth for us on our new host.\n        new3 = get_netrc_auth(url3) if self.trust_env else None\n        if new3 is not None:\n            prepared2.prepare_auth(new3)\n\n    def rebuild2(\n        self,\n        prepared3: PreparedRequest,\n        pro2: dict[str, str] | None,\n    ) -> dict[str, str]:\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n\n        :rtype: dict\n        \"\"\"\n        assert _is_prepared(prepared3)\n        hea4 = prepared3.headers\n        sch = urlparse(prepared3.url).scheme\n        new4 = resolve_proxies(prepared3, pro2, self.trust_env)\n\n        if \"Proxy-Authorization\" in hea4:\n            del hea4[\"Proxy-Authorization\"]\n\n        try:\n            use, pas = get_auth_from_url(new4[sch])\n        except KeyError:\n            use, pas = None, None\n\n        # urllib3 handles proxy authorization for us in the standard adapter.\n        # Avoid appending this to TLS tunneled requests where it may be leaked.\n        if not sch.startswith(\"https\") and use and pas:\n            hea4[\"Proxy-Authorization\"] = _basic_auth_str(use, pas)\n\n        return new4\n\n    def rebuild3(\n        self, prepared4: PreparedRequest, res4: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        met = prepared4.method\n\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if res4.status_code == codes.see_other and met != \"HEAD\":\n            met = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if res4.status_code == codes.found and met != \"HEAD\":\n            met = \"GET\"\n\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if res4.status_code == codes.moved and met == \"POST\":\n            met = \"GET\"\n\n        prepared4.method = met\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-78ed11405b022ab8", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "088039c31ce61531a2ee6d5369e6a4e3466605ad2af29caeee214d055bb7470c", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 314, "local_path": "identifiers/shorten-identifiers/I02__requests__SessionRedirectMixin__1ce8fec5.py", "order": 2, "original_content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "parent_variant_id": "pyint-a09548c72375-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L127-L392", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 211, "identifiers_declared": 55}, "unit_kind": "class", "unit_name": "SessionRedirectMixin", "variant_id": "pyint-56801ce8fec5-I02", "group_id": "py-78ed11405b022ab8", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 717, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6edef4376c0c-I03", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass SessionRedirectMixin:\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n\n    def save(self, address: PreparedRequest, **window: Any) -> Response: ...\n\n    def validateMessage(self, step: Response) -> str | None:\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if step.is_redirect:\n            response = step.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            response = response.encode(\"latin1\")\n            return to_native_string(response, \"utf8\")\n        return None\n\n    def validateAddress(self, nextKey: str, balance: str) -> bool:\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        localScore = urlparse(nextKey)\n        nextClient = urlparse(balance)\n        if localScore.hostname != nextClient.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (\n            localScore.scheme == \"http\"\n            and localScore.port in (80, None)\n            and nextClient.scheme == \"https\"\n            and nextClient.port in (443, None)\n        ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        currentOrder = localScore.port != nextClient.port\n        currentAccount = localScore.scheme != nextClient.scheme\n        secureStatus = (DEFAULT_PORTS.get(localScore.scheme, None), None)\n        if (\n            not currentAccount\n            and localScore.port in secureStatus\n            and nextClient.port in secureStatus\n        ):\n            return False\n\n        # Standard case: root URI must match\n        return currentOrder or currentAccount\n\n    def validateAccount(\n        self,\n        mode: Response,\n        age: PreparedRequest,\n        config: bool = False,\n        context: _t.TimeoutType = None,\n        result: _t.VerifyType = True,\n        data: _t.CertType = None,\n        profile: dict[str, str] | None = None,\n        defaultBalance: bool = False,\n        **pendingAddress: Any,\n    ) -> Generator[Response, None, None]:\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n        size: list[Response] = []  # keep track of history\n\n        key = self.validateMessage(mode)\n        primarySession = urlparse(age.url).fragment\n        while key:\n            currentBalance = age.copy()\n\n            # Update history and keep track of redirects.\n            mode.history = size[:]\n            size.append(mode)\n\n            try:\n                mode.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                mode.raw.read(decode_content=False)\n\n            if len(mode.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=mode\n                )\n\n            # Release the connection back into the pool.\n            mode.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if key.startswith(\"//\"):\n                secureIndex = urlparse(mode.url)\n                key = \":\".join([to_native_string(secureIndex.scheme), key])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            target = urlparse(key)\n            if target.fragment == \"\" and primarySession:\n                target = target._replace(fragment=primarySession)\n            elif target.fragment:\n                primarySession = target.fragment\n            key = target.geturl()\n\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not target.netloc:\n                key = urljoin(mode.url, requote_uri(key))\n            else:\n                key = requote_uri(key)\n\n            currentBalance.url = to_native_string(key)\n\n            self.validateStatus(currentBalance, mode)\n\n            # https://github.com/psf/requests/issues/1084\n            if mode.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                currentRequest = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for window in currentRequest:\n                    currentBalance.headers.pop(window, None)\n                currentBalance.body = None\n\n            history = currentBalance.headers\n            history.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            activeMode = cast(\"CookieJar\", currentBalance._cookies)\n            extract_cookies_to_jar(activeMode, age, mode.raw)\n            merge_cookies(activeMode, self.cookies)\n            currentBalance.prepare_cookies(activeMode)\n\n            # Rebuild auth and proxy information.\n            profile = self.validateSession(currentBalance, profile)\n            self.checkSession(currentBalance, mode)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            activeItem = currentBalance._body_position is not None and (\n                \"Content-Length\" in history or \"Transfer-Encoding\" in history\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if activeItem:\n                rewind_body(currentBalance)\n\n            # Override the original request.\n            age = currentBalance\n\n            if defaultBalance:\n                yield age  # type: ignore[misc]  # Internal use only, returns PreparedRequest\n            else:\n                mode = self.save(\n                    age,\n                    stream=config,\n                    timeout=context,\n                    verify=result,\n                    cert=data,\n                    proxies=profile,\n                    allow_redirects=False,\n                    **pendingAddress,\n                )\n\n                extract_cookies_to_jar(self.cookies, currentBalance, mode.raw)\n\n                # extract redirect url, if any, for the next loop\n                key = self.validateMessage(mode)\n                yield mode\n\n    def checkSession(\n        self, currentRequest: PreparedRequest, location: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        primaryBalance = location.request\n        assert _is_prepared(primaryBalance)\n        assert _is_prepared(currentRequest)\n\n        profile = currentRequest.headers\n        secureConfig = primaryBalance.url\n        key = currentRequest.url\n\n        if \"Authorization\" in profile and self.validateAddress(secureConfig, key):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del profile[\"Authorization\"]\n\n        # .netrc might have more auth for us on our new host.\n        shipment = get_netrc_auth(key) if self.trust_env else None\n        if shipment is not None:\n            currentRequest.prepare_auth(shipment)\n\n    def validateSession(\n        self,\n        pendingBalance: PreparedRequest,\n        summary: dict[str, str] | None,\n    ) -> dict[str, str]:\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n\n        :rtype: dict\n        \"\"\"\n        assert _is_prepared(pendingBalance)\n        nextKey = pendingBalance.headers\n        buffer = urlparse(pendingBalance.url).scheme\n        recentScore = resolve_proxies(pendingBalance, summary, self.trust_env)\n\n        if \"Proxy-Authorization\" in nextKey:\n            del nextKey[\"Proxy-Authorization\"]\n\n        try:\n            customer, duration = get_auth_from_url(recentScore[buffer])\n        except KeyError:\n            customer, duration = None, None\n\n        # urllib3 handles proxy authorization for us in the standard adapter.\n        # Avoid appending this to TLS tunneled requests where it may be leaked.\n        if not buffer.startswith(\"https\") and customer and duration:\n            nextKey[\"Proxy-Authorization\"] = _basic_auth_str(customer, duration)\n\n        return recentScore\n\n    def validateStatus(\n        self, currentRequest: PreparedRequest, localKey: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        result = currentRequest.method\n\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if localKey.status_code == codes.see_other and result != \"HEAD\":\n            result = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if localKey.status_code == codes.found and result != \"HEAD\":\n            result = \"GET\"\n\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if localKey.status_code == codes.moved and result == \"POST\":\n            result = \"GET\"\n\n        currentRequest.method = result\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-78ed11405b022ab8", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "31acbaaa706429a3faacd6ef0716cd6d41cf64c20c7d9e3d46b0d22c5919fb25", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 314, "local_path": "identifiers/mislead-identifiers/I03__requests__SessionRedirectMixin__f4376c0c.py", "order": 3, "original_content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "parent_variant_id": "pyint-a09548c72375-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L127-L392", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 211, "identifiers_declared": 55, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 1, "local_exact_length_matches": 42, "local_random_pool_selections": 48, "local_total_length_difference": 13, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 2, "method_exact_length_matches": 4, "method_random_pool_selections": 7, "method_total_length_difference": 8}, "unit_kind": "class", "unit_name": "SessionRedirectMixin", "variant_id": "pyint-6edef4376c0c-I03", "group_id": "py-78ed11405b022ab8", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 718, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-21bd6c464ca4-I04", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass SessionRedirectMixin:\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n\n    def a(self, h: PreparedRequest, **i: Any) -> Response: ...\n\n    def b(self, j: Response) -> str | None:\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if j.is_redirect:\n            k = j.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            k = k.encode(\"latin1\")\n            return to_native_string(k, \"utf8\")\n        return None\n\n    def c(self, l: str, m: str) -> bool:\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        n = urlparse(l)\n        o = urlparse(m)\n        if n.hostname != o.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (\n            n.scheme == \"http\"\n            and n.port in (80, None)\n            and o.scheme == \"https\"\n            and o.port in (443, None)\n        ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        p = n.port != o.port\n        q = n.scheme != o.scheme\n        r = (DEFAULT_PORTS.get(n.scheme, None), None)\n        if (\n            not q\n            and n.port in r\n            and o.port in r\n        ):\n            return False\n\n        # Standard case: root URI must match\n        return p or q\n\n    def d(\n        self,\n        s: Response,\n        t: PreparedRequest,\n        u: bool = False,\n        v: _t.TimeoutType = None,\n        w: _t.VerifyType = True,\n        x: _t.CertType = None,\n        y: dict[str, str] | None = None,\n        z: bool = False,\n        **A: Any,\n    ) -> Generator[Response, None, None]:\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n        B: list[Response] = []  # keep track of history\n\n        C = self.b(s)\n        D = urlparse(t.url).fragment\n        while C:\n            E = t.copy()\n\n            # Update history and keep track of redirects.\n            s.history = B[:]\n            B.append(s)\n\n            try:\n                s.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                s.raw.read(decode_content=False)\n\n            if len(s.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=s\n                )\n\n            # Release the connection back into the pool.\n            s.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if C.startswith(\"//\"):\n                F = urlparse(s.url)\n                C = \":\".join([to_native_string(F.scheme), C])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            G = urlparse(C)\n            if G.fragment == \"\" and D:\n                G = G._replace(fragment=D)\n            elif G.fragment:\n                D = G.fragment\n            C = G.geturl()\n\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not G.netloc:\n                C = urljoin(s.url, requote_uri(C))\n            else:\n                C = requote_uri(C)\n\n            E.url = to_native_string(C)\n\n            self.g(E, s)\n\n            # https://github.com/psf/requests/issues/1084\n            if s.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                H = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for I in H:\n                    E.headers.pop(I, None)\n                E.body = None\n\n            J = E.headers\n            J.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            K = cast(\"CookieJar\", E._cookies)\n            extract_cookies_to_jar(K, t, s.raw)\n            merge_cookies(K, self.cookies)\n            E.prepare_cookies(K)\n\n            # Rebuild auth and proxy information.\n            y = self.f(E, y)\n            self.e(E, s)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            L = E._body_position is not None and (\n                \"Content-Length\" in J or \"Transfer-Encoding\" in J\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if L:\n                rewind_body(E)\n\n            # Override the original request.\n            t = E\n\n            if z:\n                yield t  # type: ignore[misc]  # Internal use only, returns PreparedRequest\n            else:\n                s = self.a(\n                    t,\n                    stream=u,\n                    timeout=v,\n                    verify=w,\n                    cert=x,\n                    proxies=y,\n                    allow_redirects=False,\n                    **A,\n                )\n\n                extract_cookies_to_jar(self.cookies, E, s.raw)\n\n                # extract redirect url, if any, for the next loop\n                C = self.b(s)\n                yield s\n\n    def e(\n        self, M: PreparedRequest, N: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        O = N.request\n        assert _is_prepared(O)\n        assert _is_prepared(M)\n\n        P = M.headers\n        Q = O.url\n        R = M.url\n\n        if \"Authorization\" in P and self.c(Q, R):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del P[\"Authorization\"]\n\n        # .netrc might have more auth for us on our new host.\n        S = get_netrc_auth(R) if self.trust_env else None\n        if S is not None:\n            M.prepare_auth(S)\n\n    def f(\n        self,\n        T: PreparedRequest,\n        U: dict[str, str] | None,\n    ) -> dict[str, str]:\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n\n        :rtype: dict\n        \"\"\"\n        assert _is_prepared(T)\n        V = T.headers\n        W = urlparse(T.url).scheme\n        X = resolve_proxies(T, U, self.trust_env)\n\n        if \"Proxy-Authorization\" in V:\n            del V[\"Proxy-Authorization\"]\n\n        try:\n            Y, Z = get_auth_from_url(X[W])\n        except KeyError:\n            Y, Z = None, None\n\n        # urllib3 handles proxy authorization for us in the standard adapter.\n        # Avoid appending this to TLS tunneled requests where it may be leaked.\n        if not W.startswith(\"https\") and Y and Z:\n            V[\"Proxy-Authorization\"] = _basic_auth_str(Y, Z)\n\n        return X\n\n    def g(\n        self, aa: PreparedRequest, ab: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        ac = aa.method\n\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if ab.status_code == codes.see_other and ac != \"HEAD\":\n            ac = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if ab.status_code == codes.found and ac != \"HEAD\":\n            ac = \"GET\"\n\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if ab.status_code == codes.moved and ac == \"POST\":\n            ac = \"GET\"\n\n        aa.method = ac\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-78ed11405b022ab8", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b646c157bae728eee7663e4b37e85af38061ff0fc538d27bb98b574eac078677", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 314, "local_path": "identifiers/garble-identifiers/I04__requests__SessionRedirectMixin__6c464ca4.py", "order": 4, "original_content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "parent_variant_id": "pyint-a09548c72375-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L127-L392", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 211, "identifiers_declared": 55}, "unit_kind": "class", "unit_name": "SessionRedirectMixin", "variant_id": "pyint-21bd6c464ca4-I04", "group_id": "py-78ed11405b022ab8", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 719, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4159b15d3035-I05", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass SessionRedirectMixin:\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...\n\n    def get_redirect_target(self, resp: Response) -> str | None:\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if resp.is_redirect:\n            location = resp.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            location = location.encode(\"latin1\")\n            return to_native_string(location, \"utf8\")\n        return None\n\n    def should_strip_auth(self, old_url: str, new_url: str) -> bool:\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if old_parsed.hostname != new_parsed.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (\n            old_parsed.scheme == \"http\"\n            and old_parsed.port in (0x50, None)\n            and new_parsed.scheme == \"https\"\n            and new_parsed.port in (0x1bb, None)\n        ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        changed_port = old_parsed.port != new_parsed.port\n        changed_scheme = old_parsed.scheme != new_parsed.scheme\n        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n        if (\n            not changed_scheme\n            and old_parsed.port in default_port\n            and new_parsed.port in default_port\n        ):\n            return False\n\n        # Standard case: root URI must match\n        return changed_port or changed_scheme\n\n    def resolve_redirects(\n        self,\n        resp: Response,\n        req: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n        yield_requests: bool = False,\n        **adapter_kwargs: Any,\n    ) -> Generator[Response, None, None]:\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n        hist: list[Response] = []  # keep track of history\n\n        url = self.get_redirect_target(resp)\n        previous_fragment = urlparse(req.url).fragment\n        while url:\n            prepared_request = req.copy()\n\n            # Update history and keep track of redirects.\n            resp.history = hist[:]\n            hist.append(resp)\n\n            try:\n                resp.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                resp.raw.read(decode_content=False)\n\n            if len(resp.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=resp\n                )\n\n            # Release the connection back into the pool.\n            resp.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if url.startswith(\"//\"):\n                parsed_rurl = urlparse(resp.url)\n                url = \":\".join([to_native_string(parsed_rurl.scheme), url])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            parsed = urlparse(url)\n            if parsed.fragment == \"\" and previous_fragment:\n                parsed = parsed._replace(fragment=previous_fragment)\n            elif parsed.fragment:\n                previous_fragment = parsed.fragment\n            url = parsed.geturl()\n\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not parsed.netloc:\n                url = urljoin(resp.url, requote_uri(url))\n            else:\n                url = requote_uri(url)\n\n            prepared_request.url = to_native_string(url)\n\n            self.rebuild_method(prepared_request, resp)\n\n            # https://github.com/psf/requests/issues/1084\n            if resp.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                purged_headers = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for header in purged_headers:\n                    prepared_request.headers.pop(header, None)\n                prepared_request.body = None\n\n            headers = prepared_request.headers\n            headers.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            cookie_jar = cast(\"CookieJar\", prepared_request._cookies)\n            extract_cookies_to_jar(cookie_jar, req, resp.raw)\n            merge_cookies(cookie_jar, self.cookies)\n            prepared_request.prepare_cookies(cookie_jar)\n\n            # Rebuild auth and proxy information.\n            proxies = self.rebuild_proxies(prepared_request, proxies)\n            self.rebuild_auth(prepared_request, resp)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            rewindable = prepared_request._body_position is not None and (\n                \"Content-Length\" in headers or \"Transfer-Encoding\" in headers\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if rewindable:\n                rewind_body(prepared_request)\n\n            # Override the original request.\n            req = prepared_request\n\n            if yield_requests:\n                yield req  # type: ignore[misc]  # Internal use only, returns PreparedRequest\n            else:\n                resp = self.send(\n                    req,\n                    stream=stream,\n                    timeout=timeout,\n                    verify=verify,\n                    cert=cert,\n                    proxies=proxies,\n                    allow_redirects=False,\n                    **adapter_kwargs,\n                )\n\n                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n\n                # extract redirect url, if any, for the next loop\n                url = self.get_redirect_target(resp)\n                yield resp\n\n    def rebuild_auth(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        original_request = response.request\n        assert _is_prepared(original_request)\n        assert _is_prepared(prepared_request)\n\n        headers = prepared_request.headers\n        original_url = original_request.url\n        url = prepared_request.url\n\n        if \"Authorization\" in headers and self.should_strip_auth(original_url, url):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del headers[\"Authorization\"]\n\n        # .netrc might have more auth for us on our new host.\n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if new_auth is not None:\n            prepared_request.prepare_auth(new_auth)\n\n    def rebuild_proxies(\n        self,\n        prepared_request: PreparedRequest,\n        proxies: dict[str, str] | None,\n    ) -> dict[str, str]:\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n\n        :rtype: dict\n        \"\"\"\n        assert _is_prepared(prepared_request)\n        headers = prepared_request.headers\n        scheme = urlparse(prepared_request.url).scheme\n        new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n\n        if \"Proxy-Authorization\" in headers:\n            del headers[\"Proxy-Authorization\"]\n\n        try:\n            username, password = get_auth_from_url(new_proxies[scheme])\n        except KeyError:\n            username, password = None, None\n\n        # urllib3 handles proxy authorization for us in the standard adapter.\n        # Avoid appending this to TLS tunneled requests where it may be leaked.\n        if not scheme.startswith(\"https\") and username and password:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return new_proxies\n\n    def rebuild_method(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        method = prepared_request.method\n\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if response.status_code == codes.see_other and method != \"HEAD\":\n            method = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if response.status_code == codes.found and method != \"HEAD\":\n            method = \"GET\"\n\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if response.status_code == codes.moved and method == \"POST\":\n            method = \"GET\"\n\n        prepared_request.method = method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-78ed11405b022ab8", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "27cef7c4bba1f753e0305cf22ac1779ac23aeaa04e2492b4cb7fc32d7f76dde0", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 314, "local_path": "expressions/encode-integer-literals/I05__requests__SessionRedirectMixin__b15d3035.py", "order": 5, "original_content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "parent_variant_id": "pyint-a09548c72375-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L127-L392", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 2}, "unit_kind": "class", "unit_name": "SessionRedirectMixin", "variant_id": "pyint-4159b15d3035-I05", "group_id": "py-78ed11405b022ab8", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 720, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a0f6b21ea7d4-I06", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass SessionRedirectMixin:\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...\n\n    def get_redirect_target(self, resp: Response) -> str | None:\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if not (resp.is_redirect):\n            pass\n        else:\n            location = resp.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            location = location.encode(\"latin1\")\n            return to_native_string(location, \"utf8\")\n        return None\n\n    def should_strip_auth(self, old_url: str, new_url: str) -> bool:\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if not (old_parsed.hostname != new_parsed.hostname):\n            pass\n        else:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (\n            old_parsed.scheme == \"http\"\n            and old_parsed.port in (80, None)\n            and new_parsed.scheme == \"https\"\n            and new_parsed.port in (443, None)\n        ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        changed_port = old_parsed.port != new_parsed.port\n        changed_scheme = old_parsed.scheme != new_parsed.scheme\n        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n        if (\n            not changed_scheme\n            and old_parsed.port in default_port\n            and new_parsed.port in default_port\n        ):\n            return False\n\n        # Standard case: root URI must match\n        return changed_port or changed_scheme\n\n    def resolve_redirects(\n        self,\n        resp: Response,\n        req: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n        yield_requests: bool = False,\n        **adapter_kwargs: Any,\n    ) -> Generator[Response, None, None]:\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n        hist: list[Response] = []  # keep track of history\n\n        url = self.get_redirect_target(resp)\n        previous_fragment = urlparse(req.url).fragment\n        while url:\n            prepared_request = req.copy()\n\n            # Update history and keep track of redirects.\n            resp.history = hist[:]\n            hist.append(resp)\n\n            try:\n                resp.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                resp.raw.read(decode_content=False)\n\n            if not (len(resp.history) >= self.max_redirects):\n                pass\n            else:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=resp\n                )\n\n            # Release the connection back into the pool.\n            resp.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if not (url.startswith(\"//\")):\n                pass\n            else:\n                parsed_rurl = urlparse(resp.url)\n                url = \":\".join([to_native_string(parsed_rurl.scheme), url])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            parsed = urlparse(url)\n            if parsed.fragment == \"\" and previous_fragment:\n                parsed = parsed._replace(fragment=previous_fragment)\n            elif parsed.fragment:\n                previous_fragment = parsed.fragment\n            url = parsed.geturl()\n\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not (not parsed.netloc):\n                url = requote_uri(url)\n            else:\n                url = urljoin(resp.url, requote_uri(url))\n\n            prepared_request.url = to_native_string(url)\n\n            self.rebuild_method(prepared_request, resp)\n\n            # https://github.com/psf/requests/issues/1084\n            if resp.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                purged_headers = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for header in purged_headers:\n                    prepared_request.headers.pop(header, None)\n                prepared_request.body = None\n\n            headers = prepared_request.headers\n            headers.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            cookie_jar = cast(\"CookieJar\", prepared_request._cookies)\n            extract_cookies_to_jar(cookie_jar, req, resp.raw)\n            merge_cookies(cookie_jar, self.cookies)\n            prepared_request.prepare_cookies(cookie_jar)\n\n            # Rebuild auth and proxy information.\n            proxies = self.rebuild_proxies(prepared_request, proxies)\n            self.rebuild_auth(prepared_request, resp)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            rewindable = prepared_request._body_position is not None and (\n                \"Content-Length\" in headers or \"Transfer-Encoding\" in headers\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if not (rewindable):\n                pass\n            else:\n                rewind_body(prepared_request)\n\n            # Override the original request.\n            req = prepared_request\n\n            if not (yield_requests):\n                resp = self.send(\n                    req,\n                    stream=stream,\n                    timeout=timeout,\n                    verify=verify,\n                    cert=cert,\n                    proxies=proxies,\n                    allow_redirects=False,\n                    **adapter_kwargs,\n                )\n\n                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n\n                # extract redirect url, if any, for the next loop\n                url = self.get_redirect_target(resp)\n                yield resp\n            else:\n                yield req  # type: ignore[misc]  # Internal use only, returns PreparedRequest\n\n    def rebuild_auth(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        original_request = response.request\n        assert _is_prepared(original_request)\n        assert _is_prepared(prepared_request)\n\n        headers = prepared_request.headers\n        original_url = original_request.url\n        url = prepared_request.url\n\n        if not (\"Authorization\" in headers and self.should_strip_auth(original_url, url)):\n            pass\n        else:\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del headers[\"Authorization\"]\n\n        # .netrc might have more auth for us on our new host.\n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if not (new_auth is not None):\n            pass\n        else:\n            prepared_request.prepare_auth(new_auth)\n\n    def rebuild_proxies(\n        self,\n        prepared_request: PreparedRequest,\n        proxies: dict[str, str] | None,\n    ) -> dict[str, str]:\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n\n        :rtype: dict\n        \"\"\"\n        assert _is_prepared(prepared_request)\n        headers = prepared_request.headers\n        scheme = urlparse(prepared_request.url).scheme\n        new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n\n        if not (\"Proxy-Authorization\" in headers):\n            pass\n        else:\n            del headers[\"Proxy-Authorization\"]\n\n        try:\n            username, password = get_auth_from_url(new_proxies[scheme])\n        except KeyError:\n            username, password = None, None\n\n        # urllib3 handles proxy authorization for us in the standard adapter.\n        # Avoid appending this to TLS tunneled requests where it may be leaked.\n        if not (not scheme.startswith(\"https\") and username and password):\n            pass\n        else:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return new_proxies\n\n    def rebuild_method(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        method = prepared_request.method\n\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if not (response.status_code == codes.see_other and method != \"HEAD\"):\n            pass\n        else:\n            method = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if not (response.status_code == codes.found and method != \"HEAD\"):\n            pass\n        else:\n            method = \"GET\"\n\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if not (response.status_code == codes.moved and method == \"POST\"):\n            pass\n        else:\n            method = \"GET\"\n\n        prepared_request.method = method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-78ed11405b022ab8", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "67a0d92a8b57220ccca9d0425283dfd982e258dd0dcc41802af09ef794c3634a", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 338, "local_path": "expressions/invert-conditions/I06__requests__SessionRedirectMixin__b21ea7d4.py", "order": 6, "original_content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "parent_variant_id": "pyint-a09548c72375-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L127-L392", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 14}, "unit_kind": "class", "unit_name": "SessionRedirectMixin", "variant_id": "pyint-a0f6b21ea7d4-I06", "group_id": "py-78ed11405b022ab8", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 721, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9b1d127a7933-I07", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass SessionRedirectMixin:\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...\n\n    def get_redirect_target(self, resp: Response) -> str | None:\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        if ((0x57fa ^ 0x57fa) != 0):\n            raise AssertionError()\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if resp.is_redirect:\n            location = resp.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            location = location.encode(\"latin1\")\n            return to_native_string(location, \"utf8\")\n        return None\n\n    def should_strip_auth(self, old_url: str, new_url: str) -> bool:\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        if ((0x4980 ^ 0x4980) != 0):\n            raise AssertionError()\n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if old_parsed.hostname != new_parsed.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (\n            old_parsed.scheme == \"http\"\n            and old_parsed.port in (80, None)\n            and new_parsed.scheme == \"https\"\n            and new_parsed.port in (443, None)\n        ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        changed_port = old_parsed.port != new_parsed.port\n        changed_scheme = old_parsed.scheme != new_parsed.scheme\n        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n        if (\n            not changed_scheme\n            and old_parsed.port in default_port\n            and new_parsed.port in default_port\n        ):\n            return False\n\n        # Standard case: root URI must match\n        return changed_port or changed_scheme\n\n    def resolve_redirects(\n        self,\n        resp: Response,\n        req: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n        yield_requests: bool = False,\n        **adapter_kwargs: Any,\n    ) -> Generator[Response, None, None]:\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n        if ((0xf3ec ^ 0xf3ec) != 0):\n            raise AssertionError()\n\n        hist: list[Response] = []  # keep track of history\n\n        url = self.get_redirect_target(resp)\n        previous_fragment = urlparse(req.url).fragment\n        while url:\n            prepared_request = req.copy()\n\n            # Update history and keep track of redirects.\n            resp.history = hist[:]\n            hist.append(resp)\n\n            try:\n                resp.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                resp.raw.read(decode_content=False)\n\n            if len(resp.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=resp\n                )\n\n            # Release the connection back into the pool.\n            resp.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if url.startswith(\"//\"):\n                parsed_rurl = urlparse(resp.url)\n                url = \":\".join([to_native_string(parsed_rurl.scheme), url])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            parsed = urlparse(url)\n            if parsed.fragment == \"\" and previous_fragment:\n                parsed = parsed._replace(fragment=previous_fragment)\n            elif parsed.fragment:\n                previous_fragment = parsed.fragment\n            url = parsed.geturl()\n\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not parsed.netloc:\n                url = urljoin(resp.url, requote_uri(url))\n            else:\n                url = requote_uri(url)\n\n            prepared_request.url = to_native_string(url)\n\n            self.rebuild_method(prepared_request, resp)\n\n            # https://github.com/psf/requests/issues/1084\n            if resp.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                purged_headers = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for header in purged_headers:\n                    prepared_request.headers.pop(header, None)\n                prepared_request.body = None\n\n            headers = prepared_request.headers\n            headers.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            cookie_jar = cast(\"CookieJar\", prepared_request._cookies)\n            extract_cookies_to_jar(cookie_jar, req, resp.raw)\n            merge_cookies(cookie_jar, self.cookies)\n            prepared_request.prepare_cookies(cookie_jar)\n\n            # Rebuild auth and proxy information.\n            proxies = self.rebuild_proxies(prepared_request, proxies)\n            self.rebuild_auth(prepared_request, resp)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            rewindable = prepared_request._body_position is not None and (\n                \"Content-Length\" in headers or \"Transfer-Encoding\" in headers\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if rewindable:\n                rewind_body(prepared_request)\n\n            # Override the original request.\n            req = prepared_request\n\n            if yield_requests:\n                yield req  # type: ignore[misc]  # Internal use only, returns PreparedRequest\n            else:\n                resp = self.send(\n                    req,\n                    stream=stream,\n                    timeout=timeout,\n                    verify=verify,\n                    cert=cert,\n                    proxies=proxies,\n                    allow_redirects=False,\n                    **adapter_kwargs,\n                )\n\n                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n\n                # extract redirect url, if any, for the next loop\n                url = self.get_redirect_target(resp)\n                yield resp\n\n    def rebuild_auth(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        if ((0x56ea ^ 0x56ea) != 0):\n            raise AssertionError()\n        original_request = response.request\n        assert _is_prepared(original_request)\n        assert _is_prepared(prepared_request)\n\n        headers = prepared_request.headers\n        original_url = original_request.url\n        url = prepared_request.url\n\n        if \"Authorization\" in headers and self.should_strip_auth(original_url, url):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del headers[\"Authorization\"]\n\n        # .netrc might have more auth for us on our new host.\n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if new_auth is not None:\n            prepared_request.prepare_auth(new_auth)\n\n    def rebuild_proxies(\n        self,\n        prepared_request: PreparedRequest,\n        proxies: dict[str, str] | None,\n    ) -> dict[str, str]:\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n\n        :rtype: dict\n        \"\"\"\n        if ((0x7478 ^ 0x7478) != 0):\n            raise AssertionError()\n        assert _is_prepared(prepared_request)\n        headers = prepared_request.headers\n        scheme = urlparse(prepared_request.url).scheme\n        new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n\n        if \"Proxy-Authorization\" in headers:\n            del headers[\"Proxy-Authorization\"]\n\n        try:\n            username, password = get_auth_from_url(new_proxies[scheme])\n        except KeyError:\n            username, password = None, None\n\n        # urllib3 handles proxy authorization for us in the standard adapter.\n        # Avoid appending this to TLS tunneled requests where it may be leaked.\n        if not scheme.startswith(\"https\") and username and password:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return new_proxies\n\n    def rebuild_method(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        if ((0xd824 ^ 0xd824) != 0):\n            raise AssertionError()\n        method = prepared_request.method\n\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if response.status_code == codes.see_other and method != \"HEAD\":\n            method = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if response.status_code == codes.found and method != \"HEAD\":\n            method = \"GET\"\n\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if response.status_code == codes.moved and method == \"POST\":\n            method = \"GET\"\n\n        prepared_request.method = method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-78ed11405b022ab8", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "11d7c2c1fd2966dd86a6c7d48132a68808a5f2af8b8145da5e1e649b5cbf12c5", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 326, "local_path": "code-injection/insert-dead-branches/I07__requests__SessionRedirectMixin__127a7933.py", "order": 7, "original_content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "parent_variant_id": "pyint-a09548c72375-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L127-L392", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 6}, "unit_kind": "class", "unit_name": "SessionRedirectMixin", "variant_id": "pyint-9b1d127a7933-I07", "group_id": "py-78ed11405b022ab8", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 722, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-89984ad574d0-I08", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass SessionRedirectMixin:\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...\n\n    def get_redirect_target(self, resp: Response) -> str | None:\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        total_score = 240\n        number_of_scores = 3\n        average_score = total_score / number_of_scores\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if resp.is_redirect:\n            location = resp.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            location = location.encode(\"latin1\")\n            return to_native_string(location, \"utf8\")\n        return None\n\n    def should_strip_auth(self, old_url: str, new_url: str) -> bool:\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if old_parsed.hostname != new_parsed.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (\n            old_parsed.scheme == \"http\"\n            and old_parsed.port in (80, None)\n            and new_parsed.scheme == \"https\"\n            and new_parsed.port in (443, None)\n        ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        changed_port = old_parsed.port != new_parsed.port\n        changed_scheme = old_parsed.scheme != new_parsed.scheme\n        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n        if (\n            not changed_scheme\n            and old_parsed.port in default_port\n            and new_parsed.port in default_port\n        ):\n            return False\n\n        # Standard case: root URI must match\n        return changed_port or changed_scheme\n\n    def resolve_redirects(\n        self,\n        resp: Response,\n        req: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n        yield_requests: bool = False,\n        **adapter_kwargs: Any,\n    ) -> Generator[Response, None, None]:\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n        hist: list[Response] = []  # keep track of history\n\n        url = self.get_redirect_target(resp)\n        previous_fragment = urlparse(req.url).fragment\n        while url:\n            prepared_request = req.copy()\n\n            # Update history and keep track of redirects.\n            resp.history = hist[:]\n            hist.append(resp)\n\n            try:\n                resp.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                resp.raw.read(decode_content=False)\n\n            if len(resp.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=resp\n                )\n\n            # Release the connection back into the pool.\n            resp.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if url.startswith(\"//\"):\n                parsed_rurl = urlparse(resp.url)\n                url = \":\".join([to_native_string(parsed_rurl.scheme), url])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            parsed = urlparse(url)\n            if parsed.fragment == \"\" and previous_fragment:\n                parsed = parsed._replace(fragment=previous_fragment)\n            elif parsed.fragment:\n                previous_fragment = parsed.fragment\n            url = parsed.geturl()\n\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not parsed.netloc:\n                url = urljoin(resp.url, requote_uri(url))\n            else:\n                url = requote_uri(url)\n\n            prepared_request.url = to_native_string(url)\n\n            self.rebuild_method(prepared_request, resp)\n\n            # https://github.com/psf/requests/issues/1084\n            if resp.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                purged_headers = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for header in purged_headers:\n                    prepared_request.headers.pop(header, None)\n                prepared_request.body = None\n\n            headers = prepared_request.headers\n            headers.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            cookie_jar = cast(\"CookieJar\", prepared_request._cookies)\n            extract_cookies_to_jar(cookie_jar, req, resp.raw)\n            merge_cookies(cookie_jar, self.cookies)\n            prepared_request.prepare_cookies(cookie_jar)\n\n            # Rebuild auth and proxy information.\n            proxies = self.rebuild_proxies(prepared_request, proxies)\n            self.rebuild_auth(prepared_request, resp)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            rewindable = prepared_request._body_position is not None and (\n                \"Content-Length\" in headers or \"Transfer-Encoding\" in headers\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if rewindable:\n                rewind_body(prepared_request)\n\n            # Override the original request.\n            req = prepared_request\n\n            if yield_requests:\n                yield req  # type: ignore[misc]  # Internal use only, returns PreparedRequest\n            else:\n                resp = self.send(\n                    req,\n                    stream=stream,\n                    timeout=timeout,\n                    verify=verify,\n                    cert=cert,\n                    proxies=proxies,\n                    allow_redirects=False,\n                    **adapter_kwargs,\n                )\n\n                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n\n                # extract redirect url, if any, for the next loop\n                url = self.get_redirect_target(resp)\n                yield resp\n\n    def rebuild_auth(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        original_request = response.request\n        assert _is_prepared(original_request)\n        assert _is_prepared(prepared_request)\n\n        headers = prepared_request.headers\n        original_url = original_request.url\n        url = prepared_request.url\n\n        if \"Authorization\" in headers and self.should_strip_auth(original_url, url):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del headers[\"Authorization\"]\n\n        # .netrc might have more auth for us on our new host.\n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if new_auth is not None:\n            prepared_request.prepare_auth(new_auth)\n\n    def rebuild_proxies(\n        self,\n        prepared_request: PreparedRequest,\n        proxies: dict[str, str] | None,\n    ) -> dict[str, str]:\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n\n        :rtype: dict\n        \"\"\"\n        assert _is_prepared(prepared_request)\n        headers = prepared_request.headers\n        scheme = urlparse(prepared_request.url).scheme\n        new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n\n        if \"Proxy-Authorization\" in headers:\n            del headers[\"Proxy-Authorization\"]\n\n        try:\n            username, password = get_auth_from_url(new_proxies[scheme])\n        except KeyError:\n            username, password = None, None\n\n        # urllib3 handles proxy authorization for us in the standard adapter.\n        # Avoid appending this to TLS tunneled requests where it may be leaked.\n        if not scheme.startswith(\"https\") and username and password:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return new_proxies\n\n    def rebuild_method(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        method = prepared_request.method\n\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if response.status_code == codes.see_other and method != \"HEAD\":\n            method = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if response.status_code == codes.found and method != \"HEAD\":\n            method = \"GET\"\n\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if response.status_code == codes.moved and method == \"POST\":\n            method = \"GET\"\n\n        prepared_request.method = method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-78ed11405b022ab8", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "0246e37f88d40b663f0f9283ed9c4a34f34a8fcddc6f2df4928db5c481d43ba8", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 317, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__SessionRedirectMixin__4ad574d0.py", "order": 8, "original_content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "parent_variant_id": "pyint-a09548c72375-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L127-L392", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 5}, "unit_kind": "class", "unit_name": "SessionRedirectMixin", "variant_id": "pyint-89984ad574d0-I08", "group_id": "py-78ed11405b022ab8", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 723, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-31366b5b7bf4-I09", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass SessionRedirectMixin:\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...\n\n    def get_redirect_target(self, resp: Response) -> str | None:\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if resp.is_redirect:\n            location = resp.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            location = location.encode(\"latin1\")\n            return to_native_string(location, \"utf8\")\n        return None\n\n    def should_strip_auth(self, old_url: str, new_url: str) -> bool:\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if old_parsed.hostname != new_parsed.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (\n            old_parsed.scheme == \"http\"\n            and old_parsed.port in (80, None)\n            and new_parsed.scheme == \"https\"\n            and new_parsed.port in (443, None)\n        ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        changed_port = old_parsed.port != new_parsed.port\n        changed_scheme = old_parsed.scheme != new_parsed.scheme\n        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n        if (\n            not changed_scheme\n            and old_parsed.port in default_port\n            and new_parsed.port in default_port\n        ):\n            return False\n\n        # Standard case: root URI must match\n        return changed_port or changed_scheme\n\n    def resolve_redirects(\n        self,\n        resp: Response,\n        req: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n        yield_requests: bool = False,\n        **adapter_kwargs: Any,\n    ) -> Generator[Response, None, None]:\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n        hist: list[Response] = []  # keep track of history\n\n        url = self.get_redirect_target(resp)\n        previous_fragment = urlparse(req.url).fragment\n        while url:\n            prepared_request = req.copy()\n\n            # Update history and keep track of redirects.\n            resp.history = hist[:]\n            hist.append(resp)\n\n            try:\n                resp.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                resp.raw.read(decode_content=False)\n\n            if len(resp.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=resp\n                )\n\n            # Release the connection back into the pool.\n            resp.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if url.startswith(\"//\"):\n                parsed_rurl = urlparse(resp.url)\n                url = \":\".join([to_native_string(parsed_rurl.scheme), url])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            parsed = urlparse(url)\n            if parsed.fragment == \"\" and previous_fragment:\n                parsed = parsed._replace(fragment=previous_fragment)\n            elif parsed.fragment:\n                previous_fragment = parsed.fragment\n            url = parsed.geturl()\n\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not parsed.netloc:\n                url = urljoin(resp.url, requote_uri(url))\n            else:\n                url = requote_uri(url)\n\n            prepared_request.url = to_native_string(url)\n\n            self.rebuild_method(prepared_request, resp)\n\n            # https://github.com/psf/requests/issues/1084\n            if resp.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                purged_headers = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for header in purged_headers:\n                    prepared_request.headers.pop(header, None)\n                prepared_request.body = None\n\n            headers = prepared_request.headers\n            headers.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            cookie_jar = cast(\"CookieJar\", prepared_request._cookies)\n            extract_cookies_to_jar(cookie_jar, req, resp.raw)\n            merge_cookies(cookie_jar, self.cookies)\n            prepared_request.prepare_cookies(cookie_jar)\n\n            # Rebuild auth and proxy information.\n            proxies = self.rebuild_proxies(prepared_request, proxies)\n            self.rebuild_auth(prepared_request, resp)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            rewindable = prepared_request._body_position is not None and (\n                \"Content-Length\" in headers or \"Transfer-Encoding\" in headers\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if rewindable:\n                rewind_body(prepared_request)\n\n            # Override the original request.\n            req = prepared_request\n\n            if yield_requests:\n                yield req  # type: ignore[misc]  # Internal use only, returns PreparedRequest\n            else:\n                resp = self.send(\n                    req,\n                    stream=stream,\n                    timeout=timeout,\n                    verify=verify,\n                    cert=cert,\n                    proxies=proxies,\n                    allow_redirects=False,\n                    **adapter_kwargs,\n                )\n\n                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n\n                # extract redirect url, if any, for the next loop\n                url = self.get_redirect_target(resp)\n                yield resp\n\n    def rebuild_auth(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        original_request = response.request\n        assert _is_prepared(original_request)\n        assert _is_prepared(prepared_request)\n\n        headers = prepared_request.headers\n        original_url = original_request.url\n        url = prepared_request.url\n\n        if \"Authorization\" in headers and self.should_strip_auth(original_url, url):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del headers[\"Authorization\"]\n\n        # .netrc might have more auth for us on our new host.\n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if new_auth is not None:\n            prepared_request.prepare_auth(new_auth)\n\n    def rebuild_proxies(\n        self,\n        prepared_request: PreparedRequest,\n        proxies: dict[str, str] | None,\n    ) -> dict[str, str]:\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n\n        :rtype: dict\n        \"\"\"\n        lI0O_cdab612e, lI0O_bbc33bf4 = 0x7e92, ~0x7e92\n        lI0O_cdab612e = (lI0O_cdab612e & lI0O_bbc33bf4) | (lI0O_cdab612e ^ lI0O_cdab612e)\n        lI0O_bbc33bf4 ^= lI0O_bbc33bf4\n        assert _is_prepared(prepared_request)\n        headers = prepared_request.headers\n        scheme = urlparse(prepared_request.url).scheme\n        new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n\n        if \"Proxy-Authorization\" in headers:\n            del headers[\"Proxy-Authorization\"]\n\n        try:\n            username, password = get_auth_from_url(new_proxies[scheme])\n        except KeyError:\n            username, password = None, None\n\n        # urllib3 handles proxy authorization for us in the standard adapter.\n        # Avoid appending this to TLS tunneled requests where it may be leaked.\n        if not scheme.startswith(\"https\") and username and password:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return new_proxies\n\n    def rebuild_method(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        method = prepared_request.method\n\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if response.status_code == codes.see_other and method != \"HEAD\":\n            method = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if response.status_code == codes.found and method != \"HEAD\":\n            method = \"GET\"\n\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if response.status_code == codes.moved and method == \"POST\":\n            method = \"GET\"\n\n        prepared_request.method = method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-78ed11405b022ab8", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "3b8bc4c0ec82399faca203cddf3718ad4a2f49b531ce1f2526ca6da5e22ad0a2", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 317, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__SessionRedirectMixin__6b5b7bf4.py", "order": 9, "original_content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "parent_variant_id": "pyint-a09548c72375-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L127-L392", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 9}, "unit_kind": "class", "unit_name": "SessionRedirectMixin", "variant_id": "pyint-31366b5b7bf4-I09", "group_id": "py-78ed11405b022ab8", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 724, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9cb8773f159a-I10", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,     extract_cookies_to_jar,     merge_cookies, )\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,     Request,     Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,     get_environ_proxies,     get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass SessionRedirectMixin:\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...\n\n    def get_redirect_target(self, resp: Response) -> str | None:\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if resp.is_redirect:\n            location = resp.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            location = location.encode(\"latin1\")\n            return to_native_string(location, \"utf8\")\n        return None\n    def should_strip_auth(self, old_url: str, new_url: str) -> bool:\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if old_parsed.hostname != new_parsed.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (             old_parsed.scheme == \"http\"\n            and old_parsed.port in (80, None)\n            and new_parsed.scheme == \"https\"\n            and new_parsed.port in (443, None)         ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        changed_port = old_parsed.port != new_parsed.port\n        changed_scheme = old_parsed.scheme != new_parsed.scheme\n        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n        if (\n            not changed_scheme\n            and old_parsed.port in default_port             and new_parsed.port in default_port         ):\n            return False\n        # Standard case: root URI must match\n        return changed_port or changed_scheme\n    def resolve_redirects(         self,         resp: Response,\n        req: PreparedRequest,         stream: bool = False,\n        timeout: _t.TimeoutType = None,         verify: _t.VerifyType = True,\n        cert: _t.CertType = None,         proxies: dict[str, str] | None = None,\n        yield_requests: bool = False,         **adapter_kwargs: Any,\n    ) -> Generator[Response, None, None]:\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n        hist: list[Response] = []  # keep track of history\n\n        url = self.get_redirect_target(resp)\n        previous_fragment = urlparse(req.url).fragment\n        while url:\n            prepared_request = req.copy()\n\n            # Update history and keep track of redirects.\n            resp.history = hist[:]\n            hist.append(resp)\n\n            try:\n                resp.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                resp.raw.read(decode_content=False)\n\n            if len(resp.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=resp\n                )\n            # Release the connection back into the pool.\n            resp.close()\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if url.startswith(\"//\"):\n                parsed_rurl = urlparse(resp.url)\n                url = \":\".join([to_native_string(parsed_rurl.scheme), url])\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            parsed = urlparse(url)\n            if parsed.fragment == \"\" and previous_fragment:\n                parsed = parsed._replace(fragment=previous_fragment)\n            elif parsed.fragment:\n                previous_fragment = parsed.fragment\n            url = parsed.geturl()\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not parsed.netloc:\n                url = urljoin(resp.url, requote_uri(url))\n            else:\n                url = requote_uri(url)\n\n            prepared_request.url = to_native_string(url)\n            self.rebuild_method(prepared_request, resp)\n\n            # https://github.com/psf/requests/issues/1084\n            if resp.status_code not in (\n                codes.temporary_redirect,                 codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                purged_headers = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for header in purged_headers:\n                    prepared_request.headers.pop(header, None)\n                prepared_request.body = None\n            headers = prepared_request.headers\n            headers.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            cookie_jar = cast(\"CookieJar\", prepared_request._cookies)\n            extract_cookies_to_jar(cookie_jar, req, resp.raw)\n            merge_cookies(cookie_jar, self.cookies)\n            prepared_request.prepare_cookies(cookie_jar)\n            # Rebuild auth and proxy information.\n            proxies = self.rebuild_proxies(prepared_request, proxies)\n            self.rebuild_auth(prepared_request, resp)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            rewindable = prepared_request._body_position is not None and (\n                \"Content-Length\" in headers or \"Transfer-Encoding\" in headers\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if rewindable:\n                rewind_body(prepared_request)\n            # Override the original request.\n            req = prepared_request\n            if yield_requests:\n                yield req  # type: ignore[misc]  # Internal use only, returns PreparedRequest\n            else:\n                resp = self.send(\n                    req,\n                    stream=stream,\n                    timeout=timeout,\n                    verify=verify,                     cert=cert,\n                    proxies=proxies,                     allow_redirects=False,\n                    **adapter_kwargs,                 )\n                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n\n                # extract redirect url, if any, for the next loop\n                url = self.get_redirect_target(resp)\n                yield resp\n    def rebuild_auth(\n        self, prepared_request: PreparedRequest, response: Response     ) -> None:\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        original_request = response.request\n        assert _is_prepared(original_request)\n        assert _is_prepared(prepared_request)\n\n        headers = prepared_request.headers\n        original_url = original_request.url\n        url = prepared_request.url\n\n        if \"Authorization\" in headers and self.should_strip_auth(original_url, url):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del headers[\"Authorization\"]\n        # .netrc might have more auth for us on our new host.\n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if new_auth is not None:\n            prepared_request.prepare_auth(new_auth)\n\n    def rebuild_proxies(\n        self,         prepared_request: PreparedRequest,\n        proxies: dict[str, str] | None,\n    ) -> dict[str, str]:\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n        :rtype: dict\n        \"\"\"\n        assert _is_prepared(prepared_request)\n        headers = prepared_request.headers\n        scheme = urlparse(prepared_request.url).scheme\n        new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n\n        if \"Proxy-Authorization\" in headers:\n            del headers[\"Proxy-Authorization\"]\n\n        try:\n            username, password = get_auth_from_url(new_proxies[scheme])\n        except KeyError:\n            username, password = None, None\n        # urllib3 handles proxy authorization for us in the standard adapter.\n        # Avoid appending this to TLS tunneled requests where it may be leaked.\n        if not scheme.startswith(\"https\") and username and password:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return new_proxies\n\n    def rebuild_method(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        method = prepared_request.method\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if response.status_code == codes.see_other and method != \"HEAD\":\n            method = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if response.status_code == codes.found and method != \"HEAD\":\n            method = \"GET\"\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if response.status_code == codes.moved and method == \"POST\":\n            method = \"GET\"\n        prepared_request.method = method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-78ed11405b022ab8", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "d42a513d9d6fdc5416714043c21278a2c15986357c404ca2ea0197640b843dbe", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 270, "local_path": "layout/partially-compact-layout/I10__requests__SessionRedirectMixin__773f159a.py", "order": 10, "original_content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "parent_variant_id": "pyint-a09548c72375-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L127-L392", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 112, "line_break_groups_removed": 44, "line_breaks_removed": 44, "whitespace_characters_removed": 21}, "unit_kind": "class", "unit_name": "SessionRedirectMixin", "variant_id": "pyint-9cb8773f159a-I10", "group_id": "py-78ed11405b022ab8", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 725, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-640947d86c52-I11", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass SessionRedirectMixin:\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...\n\n    def get_redirect_target(self, resp: Response) -> str | None:\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if resp.is_redirect:\n            location = resp.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            location = location.encode(\"latin1\")\n            return to_native_string(location, \"utf8\")\n        return None\n\n    def should_strip_auth(self, old_url: str, new_url: str) -> bool:\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if old_parsed.hostname != new_parsed.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        a = 40\n        b = 40\n        c = 221\n        d = 222\n        if (\n            old_parsed.scheme == \"http\"\n            and old_parsed.port in ((a + b), None)\n            and new_parsed.scheme == \"https\"\n            and new_parsed.port in ((c + d), None)\n        ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        changed_port = old_parsed.port != new_parsed.port\n        changed_scheme = old_parsed.scheme != new_parsed.scheme\n        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n        if (\n            not changed_scheme\n            and old_parsed.port in default_port\n            and new_parsed.port in default_port\n        ):\n            return False\n\n        # Standard case: root URI must match\n        return changed_port or changed_scheme\n\n    def resolve_redirects(\n        self,\n        resp: Response,\n        req: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n        yield_requests: bool = False,\n        **adapter_kwargs: Any,\n    ) -> Generator[Response, None, None]:\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n        hist: list[Response] = []  # keep track of history\n\n        url = self.get_redirect_target(resp)\n        previous_fragment = urlparse(req.url).fragment\n        while url:\n            prepared_request = req.copy()\n\n            # Update history and keep track of redirects.\n            resp.history = hist[:]\n            hist.append(resp)\n\n            try:\n                resp.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                resp.raw.read(decode_content=False)\n\n            if len(resp.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=resp\n                )\n\n            # Release the connection back into the pool.\n            resp.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if url.startswith(\"//\"):\n                parsed_rurl = urlparse(resp.url)\n                url = \":\".join([to_native_string(parsed_rurl.scheme), url])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            parsed = urlparse(url)\n            if parsed.fragment == \"\" and previous_fragment:\n                parsed = parsed._replace(fragment=previous_fragment)\n            elif parsed.fragment:\n                previous_fragment = parsed.fragment\n            url = parsed.geturl()\n\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not parsed.netloc:\n                url = urljoin(resp.url, requote_uri(url))\n            else:\n                url = requote_uri(url)\n\n            prepared_request.url = to_native_string(url)\n\n            self.rebuild_method(prepared_request, resp)\n\n            # https://github.com/psf/requests/issues/1084\n            if resp.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                purged_headers = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for header in purged_headers:\n                    prepared_request.headers.pop(header, None)\n                prepared_request.body = None\n\n            headers = prepared_request.headers\n            headers.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            cookie_jar = cast(\"CookieJar\", prepared_request._cookies)\n            extract_cookies_to_jar(cookie_jar, req, resp.raw)\n            merge_cookies(cookie_jar, self.cookies)\n            prepared_request.prepare_cookies(cookie_jar)\n\n            # Rebuild auth and proxy information.\n            proxies = self.rebuild_proxies(prepared_request, proxies)\n            self.rebuild_auth(prepared_request, resp)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            rewindable = prepared_request._body_position is not None and (\n                \"Content-Length\" in headers or \"Transfer-Encoding\" in headers\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if rewindable:\n                rewind_body(prepared_request)\n\n            # Override the original request.\n            req = prepared_request\n\n            if yield_requests:\n                yield req  # type: ignore[misc]  # Internal use only, returns PreparedRequest\n            else:\n                resp = self.send(\n                    req,\n                    stream=stream,\n                    timeout=timeout,\n                    verify=verify,\n                    cert=cert,\n                    proxies=proxies,\n                    allow_redirects=False,\n                    **adapter_kwargs,\n                )\n\n                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n\n                # extract redirect url, if any, for the next loop\n                url = self.get_redirect_target(resp)\n                yield resp\n\n    def rebuild_auth(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        original_request = response.request\n        assert _is_prepared(original_request)\n        assert _is_prepared(prepared_request)\n\n        headers = prepared_request.headers\n        original_url = original_request.url\n        url = prepared_request.url\n\n        if \"Authorization\" in headers and self.should_strip_auth(original_url, url):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del headers[\"Authorization\"]\n\n        # .netrc might have more auth for us on our new host.\n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if new_auth is not None:\n            prepared_request.prepare_auth(new_auth)\n\n    def rebuild_proxies(\n        self,\n        prepared_request: PreparedRequest,\n        proxies: dict[str, str] | None,\n    ) -> dict[str, str]:\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n\n        :rtype: dict\n        \"\"\"\n        assert _is_prepared(prepared_request)\n        headers = prepared_request.headers\n        scheme = urlparse(prepared_request.url).scheme\n        new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n\n        if \"Proxy-Authorization\" in headers:\n            del headers[\"Proxy-Authorization\"]\n\n        try:\n            username, password = get_auth_from_url(new_proxies[scheme])\n        except KeyError:\n            username, password = None, None\n\n        # urllib3 handles proxy authorization for us in the standard adapter.\n        # Avoid appending this to TLS tunneled requests where it may be leaked.\n        if not scheme.startswith(\"https\") and username and password:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return new_proxies\n\n    def rebuild_method(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        method = prepared_request.method\n\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if response.status_code == codes.see_other and method != \"HEAD\":\n            method = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if response.status_code == codes.found and method != \"HEAD\":\n            method = \"GET\"\n\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if response.status_code == codes.moved and method == \"POST\":\n            method = \"GET\"\n\n        prepared_request.method = method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-78ed11405b022ab8", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f11ea548db69c6c9127e55a67afc28c21857443369d6805a4560eab2d2fb0ce8", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 318, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__SessionRedirectMixin__47d86c52.py", "order": 11, "original_content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "parent_variant_id": "pyint-a09548c72375-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L127-L392", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 2, "intermediate_variables_introduced": 4, "statements_augmented": 1}, "unit_kind": "class", "unit_name": "SessionRedirectMixin", "variant_id": "pyint-640947d86c52-I11", "group_id": "py-78ed11405b022ab8", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 726, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-29f0869fa7d9-I12", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass SessionRedirectMixin:\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...\n\n    def get_redirect_target(self, resp: Response) -> str | None:\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if resp.is_redirect:\n            location = resp.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            location = location.encode(\"latin1\")\n            return to_native_string(location, \"utf8\")\n        return None\n\n    def should_strip_auth(self, old_url: str, new_url: str) -> bool:\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if old_parsed.hostname != new_parsed.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (\n            old_parsed.scheme == \"http\"\n            and old_parsed.port in (80, None)\n            and new_parsed.scheme == \"https\"\n            and new_parsed.port in (443, None)\n        ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        \n        changed_scheme = old_parsed.scheme != new_parsed.scheme\n        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n        if (\n            not changed_scheme\n            and old_parsed.port in default_port\n            and new_parsed.port in default_port\n        ):\n            return False\n\n        # Standard case: root URI must match\n        return (old_parsed.port != new_parsed.port) or changed_scheme\n\n    def resolve_redirects(\n        self,\n        resp: Response,\n        req: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n        yield_requests: bool = False,\n        **adapter_kwargs: Any,\n    ) -> Generator[Response, None, None]:\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n        hist: list[Response] = []  # keep track of history\n\n        url = self.get_redirect_target(resp)\n        previous_fragment = urlparse(req.url).fragment\n        while url:\n            prepared_request = req.copy()\n\n            # Update history and keep track of redirects.\n            resp.history = hist[:]\n            hist.append(resp)\n\n            try:\n                resp.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                resp.raw.read(decode_content=False)\n\n            if len(resp.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=resp\n                )\n\n            # Release the connection back into the pool.\n            resp.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if url.startswith(\"//\"):\n                parsed_rurl = urlparse(resp.url)\n                url = \":\".join([to_native_string(parsed_rurl.scheme), url])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            parsed = urlparse(url)\n            if parsed.fragment == \"\" and previous_fragment:\n                parsed = parsed._replace(fragment=previous_fragment)\n            elif parsed.fragment:\n                previous_fragment = parsed.fragment\n            url = parsed.geturl()\n\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not parsed.netloc:\n                url = urljoin(resp.url, requote_uri(url))\n            else:\n                url = requote_uri(url)\n\n            prepared_request.url = to_native_string(url)\n\n            self.rebuild_method(prepared_request, resp)\n\n            # https://github.com/psf/requests/issues/1084\n            if resp.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                purged_headers = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for header in purged_headers:\n                    prepared_request.headers.pop(header, None)\n                prepared_request.body = None\n\n            headers = prepared_request.headers\n            headers.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            cookie_jar = cast(\"CookieJar\", prepared_request._cookies)\n            extract_cookies_to_jar(cookie_jar, req, resp.raw)\n            merge_cookies(cookie_jar, self.cookies)\n            prepared_request.prepare_cookies(cookie_jar)\n\n            # Rebuild auth and proxy information.\n            proxies = self.rebuild_proxies(prepared_request, proxies)\n            self.rebuild_auth(prepared_request, resp)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            rewindable = prepared_request._body_position is not None and (\n                \"Content-Length\" in headers or \"Transfer-Encoding\" in headers\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if rewindable:\n                rewind_body(prepared_request)\n\n            # Override the original request.\n            req = prepared_request\n\n            if yield_requests:\n                yield req  # type: ignore[misc]  # Internal use only, returns PreparedRequest\n            else:\n                resp = self.send(\n                    req,\n                    stream=stream,\n                    timeout=timeout,\n                    verify=verify,\n                    cert=cert,\n                    proxies=proxies,\n                    allow_redirects=False,\n                    **adapter_kwargs,\n                )\n\n                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n\n                # extract redirect url, if any, for the next loop\n                url = self.get_redirect_target(resp)\n                yield resp\n\n    def rebuild_auth(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        original_request = response.request\n        assert _is_prepared(original_request)\n        assert _is_prepared(prepared_request)\n\n        headers = prepared_request.headers\n        original_url = original_request.url\n        url = prepared_request.url\n\n        if \"Authorization\" in headers and self.should_strip_auth(original_url, url):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del headers[\"Authorization\"]\n\n        # .netrc might have more auth for us on our new host.\n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if new_auth is not None:\n            prepared_request.prepare_auth(new_auth)\n\n    def rebuild_proxies(\n        self,\n        prepared_request: PreparedRequest,\n        proxies: dict[str, str] | None,\n    ) -> dict[str, str]:\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n\n        :rtype: dict\n        \"\"\"\n        assert _is_prepared(prepared_request)\n        headers = prepared_request.headers\n        scheme = urlparse(prepared_request.url).scheme\n        new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n\n        if \"Proxy-Authorization\" in headers:\n            del headers[\"Proxy-Authorization\"]\n\n        try:\n            username, password = get_auth_from_url(new_proxies[scheme])\n        except KeyError:\n            username, password = None, None\n\n        # urllib3 handles proxy authorization for us in the standard adapter.\n        # Avoid appending this to TLS tunneled requests where it may be leaked.\n        if not scheme.startswith(\"https\") and username and password:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return new_proxies\n\n    def rebuild_method(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        method = prepared_request.method\n\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if response.status_code == codes.see_other and method != \"HEAD\":\n            method = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if response.status_code == codes.found and method != \"HEAD\":\n            method = \"GET\"\n\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if response.status_code == codes.moved and method == \"POST\":\n            method = \"GET\"\n\n        prepared_request.method = method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-78ed11405b022ab8", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "94ca46e52ea296ca384c3cf12f672fb0c7780cd4abb35a72ba2a3f8e712f2d01", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 314, "local_path": "data-flow/inline-intermediate-variables/I12__requests__SessionRedirectMixin__869fa7d9.py", "order": 12, "original_content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "parent_variant_id": "pyint-a09548c72375-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L127-L392", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "SessionRedirectMixin", "variant_id": "pyint-29f0869fa7d9-I12", "group_id": "py-78ed11405b022ab8", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 727, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4f5dbeedc6fc-I13", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass SessionRedirectMixin:\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...\n\n    def get_redirect_target(self, resp: Response) -> str | None:\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if resp.is_redirect:\n            location = resp.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            location = location.encode(\"latin1\")\n            return to_native_string(location, \"utf8\")\n        return None\n\n    def should_strip_auth(self, old_url: str, new_url: str) -> bool:\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if old_parsed.hostname != new_parsed.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (\n            old_parsed.scheme == \"http\"\n            and old_parsed.port in (80, None)\n            and new_parsed.scheme == \"https\"\n            and new_parsed.port in (443, None)\n        ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        changed_port = old_parsed.port != new_parsed.port\n        changed_scheme = old_parsed.scheme != new_parsed.scheme\n        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n        if (\n            not changed_scheme\n            and old_parsed.port in default_port\n            and new_parsed.port in default_port\n        ):\n            return False\n\n        # Standard case: root URI must match\n        return changed_port or changed_scheme\n\n    def resolve_redirects(\n        self,\n        resp: Response,\n        req: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n        yield_requests: bool = False,\n        **adapter_kwargs: Any,\n    ) -> Generator[Response, None, None]:\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n        hist: list[Response] = []  # keep track of history\n\n        url = self.get_redirect_target(resp)\n        previous_fragment = urlparse(req.url).fragment\n        while url:\n            prepared_request = req.copy()\n\n            # Update history and keep track of redirects.\n            resp.history = hist[:]\n            hist.append(resp)\n\n            try:\n                resp.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                resp.raw.read(decode_content=False)\n\n            if len(resp.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=resp\n                )\n\n            # Release the connection back into the pool.\n            resp.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if url.startswith(\"//\"):\n                parsed_rurl = urlparse(resp.url)\n                url = \":\".join([to_native_string(parsed_rurl.scheme), url])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            parsed = urlparse(url)\n            if parsed.fragment == \"\" and previous_fragment:\n                parsed = parsed._replace(fragment=previous_fragment)\n            elif parsed.fragment:\n                previous_fragment = parsed.fragment\n            url = parsed.geturl()\n\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not parsed.netloc:\n                url = urljoin(resp.url, requote_uri(url))\n            else:\n                url = requote_uri(url)\n\n            prepared_request.url = to_native_string(url)\n\n            self.rebuild_method(prepared_request, resp)\n\n            # https://github.com/psf/requests/issues/1084\n            if resp.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                purged_headers = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                loopIterator = __import__(\"builtins\").iter(purged_headers)\n                while True:\n                    try:\n                        header = __import__(\"builtins\").next(loopIterator)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    prepared_request.headers.pop(header, None)\n                prepared_request.body = None\n\n            headers = prepared_request.headers\n            headers.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            cookie_jar = cast(\"CookieJar\", prepared_request._cookies)\n            extract_cookies_to_jar(cookie_jar, req, resp.raw)\n            merge_cookies(cookie_jar, self.cookies)\n            prepared_request.prepare_cookies(cookie_jar)\n\n            # Rebuild auth and proxy information.\n            proxies = self.rebuild_proxies(prepared_request, proxies)\n            self.rebuild_auth(prepared_request, resp)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            rewindable = prepared_request._body_position is not None and (\n                \"Content-Length\" in headers or \"Transfer-Encoding\" in headers\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if rewindable:\n                rewind_body(prepared_request)\n\n            # Override the original request.\n            req = prepared_request\n\n            if yield_requests:\n                yield req  # type: ignore[misc]  # Internal use only, returns PreparedRequest\n            else:\n                resp = self.send(\n                    req,\n                    stream=stream,\n                    timeout=timeout,\n                    verify=verify,\n                    cert=cert,\n                    proxies=proxies,\n                    allow_redirects=False,\n                    **adapter_kwargs,\n                )\n\n                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n\n                # extract redirect url, if any, for the next loop\n                url = self.get_redirect_target(resp)\n                yield resp\n\n    def rebuild_auth(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        original_request = response.request\n        assert _is_prepared(original_request)\n        assert _is_prepared(prepared_request)\n\n        headers = prepared_request.headers\n        original_url = original_request.url\n        url = prepared_request.url\n\n        if \"Authorization\" in headers and self.should_strip_auth(original_url, url):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del headers[\"Authorization\"]\n\n        # .netrc might have more auth for us on our new host.\n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if new_auth is not None:\n            prepared_request.prepare_auth(new_auth)\n\n    def rebuild_proxies(\n        self,\n        prepared_request: PreparedRequest,\n        proxies: dict[str, str] | None,\n    ) -> dict[str, str]:\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n\n        :rtype: dict\n        \"\"\"\n        assert _is_prepared(prepared_request)\n        headers = prepared_request.headers\n        scheme = urlparse(prepared_request.url).scheme\n        new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n\n        if \"Proxy-Authorization\" in headers:\n            del headers[\"Proxy-Authorization\"]\n\n        try:\n            username, password = get_auth_from_url(new_proxies[scheme])\n        except KeyError:\n            username, password = None, None\n\n        # urllib3 handles proxy authorization for us in the standard adapter.\n        # Avoid appending this to TLS tunneled requests where it may be leaked.\n        if not scheme.startswith(\"https\") and username and password:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return new_proxies\n\n    def rebuild_method(\n        self, prepared_request: PreparedRequest, response: Response\n    ) -> None:\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        method = prepared_request.method\n\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if response.status_code == codes.see_other and method != \"HEAD\":\n            method = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if response.status_code == codes.found and method != \"HEAD\":\n            method = \"GET\"\n\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if response.status_code == codes.moved and method == \"POST\":\n            method = \"GET\"\n\n        prepared_request.method = method\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-78ed11405b022ab8", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "3016f273c25d8b4effdc8a1e43d2a6cfed02d6a1be3275fcc1704380fb718eb9", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 319, "local_path": "control-flow/lower-for-to-while/I13__requests__SessionRedirectMixin__beedc6fc.py", "order": 13, "original_content_sha256": "4d6163acdefd7420f39bdce64becb51a02ba2e8e4031815717414078b613ef91", "parent_variant_id": "pyint-a09548c72375-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L127-L392", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 1, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 1, "synchronous_for_loops_eligible": 1, "synchronous_for_loops_found": 1}, "unit_kind": "class", "unit_name": "SessionRedirectMixin", "variant_id": "pyint-4f5dbeedc6fc-I13", "group_id": "py-78ed11405b022ab8", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 728, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4976b30e68b0-SRC", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass ConfigAttribute(t.Generic[T]):\n    \"\"\"Makes an attribute forward to the config\"\"\"\n\n    def __init__(\n        self, name: str, get_converter: t.Callable[[t.Any], T] | None = None\n    ) -> None:\n        self.__name__ = name\n        self.get_converter = get_converter\n\n    @t.overload\n    def __get__(self, obj: None, owner: None) -> te.Self: ...\n\n    @t.overload\n    def __get__(self, obj: App, owner: type[App]) -> T: ...\n\n    def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:\n        if obj is None:\n            return self\n\n        rv = obj.config[self.__name__]\n\n        if self.get_converter is not None:\n            rv = self.get_converter(rv)\n\n        return rv  # type: ignore[no-any-return]\n\n    def __set__(self, obj: App, value: t.Any) -> None:\n        obj.config[self.__name__] = value\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-79c00b6470c16161", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 36, "local_path": "source-original/SRC__flask__ConfigAttribute__b30e68b0.py", "order": 0, "original_content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L20-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "ConfigAttribute", "variant_id": "pyint-4976b30e68b0-SRC", "group_id": "py-79c00b6470c16161", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 687, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e79ac30883ad-I01", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass ConfigAttribute(t.Generic[T]):\n    \n\n    def __init__(\n        self, name: str, get_converter: t.Callable[[t.Any], T] | None = None\n    ) -> None:\n        self.__name__ = name\n        self.get_converter = get_converter\n\n    @t.overload\n    def __get__(self, obj: None, owner: None) -> te.Self: ...\n\n    @t.overload\n    def __get__(self, obj: App, owner: type[App]) -> T: ...\n\n    def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:\n        if obj is None:\n            return self\n\n        rv = obj.config[self.__name__]\n\n        if self.get_converter is not None:\n            rv = self.get_converter(rv)\n\n        return rv   \n\n    def __set__(self, obj: App, value: t.Any) -> None:\n        obj.config[self.__name__] = value\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-79c00b6470c16161", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "18236e698f0112560437d8aa2a1e02d177c61ec8cac86c1f5366c173db6883b1", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 36, "local_path": "comments/remove-comments/I01__flask__ConfigAttribute__c30883ad.py", "order": 1, "original_content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "parent_variant_id": "pyint-4976b30e68b0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L20-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 74, "comments_removed": 2, "docstrings_removed": 1, "line_comments_removed": 1}, "unit_kind": "class", "unit_name": "ConfigAttribute", "variant_id": "pyint-e79ac30883ad-I01", "group_id": "py-79c00b6470c16161", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 688, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f2aaeb771b00-I02", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass ConfigAttribute(t.Generic[T]):\n    \"\"\"Makes an attribute forward to the config\"\"\"\n\n    def __init__(\n        self, nam: str, get: t.Callable[[t.Any], T] | None = None\n    ) -> None:\n        self.__name__ = nam\n        self.get_converter = get\n\n    @t.overload\n    def __get__(self, obj2: None, own: None) -> te.Self: ...\n\n    @t.overload\n    def __get__(self, obj3: App, own2: type[App]) -> T: ...\n\n    def __get__(self, obj4: App | None, own3: type[App] | None = None) -> T | te.Self:\n        if obj4 is None:\n            return self\n\n        rv2 = obj4.config[self.__name__]\n\n        if self.get_converter is not None:\n            rv2 = self.get_converter(rv2)\n\n        return rv2  # type: ignore[no-any-return]\n\n    def __set__(self, obj5: App, val: t.Any) -> None:\n        obj5.config[self.__name__] = val\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-79c00b6470c16161", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "07f6660c359b159a7b590e62f7db7e9c06cc4da0223ba8a5a9a59984032013e4", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 36, "local_path": "identifiers/shorten-identifiers/I02__flask__ConfigAttribute__eb771b00.py", "order": 2, "original_content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "parent_variant_id": "pyint-4976b30e68b0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L20-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 20, "identifiers_declared": 11}, "unit_kind": "class", "unit_name": "ConfigAttribute", "variant_id": "pyint-f2aaeb771b00-I02", "group_id": "py-79c00b6470c16161", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 689, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-16eb76b2e83a-I03", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass ConfigAttribute(t.Generic[T]):\n    \"\"\"Makes an attribute forward to the config\"\"\"\n\n    def __init__(\n        self, node: str, sharedSession: t.Callable[[t.Any], T] | None = None\n    ) -> None:\n        self.__name__ = node\n        self.get_converter = sharedSession\n\n    @t.overload\n    def __get__(self, map: None, group: None) -> te.Self: ...\n\n    @t.overload\n    def __get__(self, key: App, group: type[App]) -> T: ...\n\n    def __get__(self, key: App | None, value: type[App] | None = None) -> T | te.Self:\n        if key is None:\n            return self\n\n        map = key.config[self.__name__]\n\n        if self.get_converter is not None:\n            map = self.get_converter(map)\n\n        return map  # type: ignore[no-any-return]\n\n    def __set__(self, key: App, state: t.Any) -> None:\n        key.config[self.__name__] = state\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-79c00b6470c16161", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d15cd9f97ad1ee8af62bc6b448bc1cf60dad08c1c6c35006e64d276be39be095", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 36, "local_path": "identifiers/mislead-identifiers/I03__flask__ConfigAttribute__76b2e83a.py", "order": 3, "original_content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "parent_variant_id": "pyint-4976b30e68b0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L20-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 20, "identifiers_declared": 11, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 1, "local_exact_length_matches": 10, "local_random_pool_selections": 11, "local_total_length_difference": 1, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "ConfigAttribute", "variant_id": "pyint-16eb76b2e83a-I03", "group_id": "py-79c00b6470c16161", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 690, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7f01b5b36216-I04", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass ConfigAttribute(t.Generic[T]):\n    \"\"\"Makes an attribute forward to the config\"\"\"\n\n    def __init__(\n        self, a: str, b: t.Callable[[t.Any], T] | None = None\n    ) -> None:\n        self.__name__ = a\n        self.get_converter = b\n\n    @t.overload\n    def __get__(self, c: None, d: None) -> te.Self: ...\n\n    @t.overload\n    def __get__(self, e: App, f: type[App]) -> T: ...\n\n    def __get__(self, g: App | None, h: type[App] | None = None) -> T | te.Self:\n        if g is None:\n            return self\n\n        i = g.config[self.__name__]\n\n        if self.get_converter is not None:\n            i = self.get_converter(i)\n\n        return i  # type: ignore[no-any-return]\n\n    def __set__(self, j: App, k: t.Any) -> None:\n        j.config[self.__name__] = k\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-79c00b6470c16161", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "71cb8c16581931e92f3e6b57124839a5a3f6bd1ed0fb21defb5a664b61afc672", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 36, "local_path": "identifiers/garble-identifiers/I04__flask__ConfigAttribute__b5b36216.py", "order": 4, "original_content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "parent_variant_id": "pyint-4976b30e68b0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L20-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 20, "identifiers_declared": 11}, "unit_kind": "class", "unit_name": "ConfigAttribute", "variant_id": "pyint-7f01b5b36216-I04", "group_id": "py-79c00b6470c16161", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 691, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9014622913e7-I05", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass ConfigAttribute(t.Generic[T]):\n    \"\"\"Makes an attribute forward to the config\"\"\"\n\n    def __init__(\n        self, name: str, get_converter: t.Callable[[t.Any], T] | None = None\n    ) -> None:\n        self.__name__ = name\n        self.get_converter = get_converter\n\n    @t.overload\n    def __get__(self, obj: None, owner: None) -> te.Self: ...\n\n    @t.overload\n    def __get__(self, obj: App, owner: type[App]) -> T: ...\n\n    def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:\n        if obj is None:\n            return self\n\n        rv = obj.config[self.__name__]\n\n        if self.get_converter is not None:\n            rv = self.get_converter(rv)\n\n        return rv  # type: ignore[no-any-return]\n\n    def __set__(self, obj: App, value: t.Any) -> None:\n        obj.config[self.__name__] = value\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-79c00b6470c16161", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 36, "local_path": "expressions/encode-integer-literals/I05__flask__ConfigAttribute__622913e7.py", "order": 5, "original_content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "parent_variant_id": "pyint-4976b30e68b0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L20-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "ConfigAttribute", "variant_id": "pyint-9014622913e7-I05", "group_id": "py-79c00b6470c16161", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 692, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d54e59cb2b1e-I06", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass ConfigAttribute(t.Generic[T]):\n    \"\"\"Makes an attribute forward to the config\"\"\"\n\n    def __init__(\n        self, name: str, get_converter: t.Callable[[t.Any], T] | None = None\n    ) -> None:\n        self.__name__ = name\n        self.get_converter = get_converter\n\n    @t.overload\n    def __get__(self, obj: None, owner: None) -> te.Self: ...\n\n    @t.overload\n    def __get__(self, obj: App, owner: type[App]) -> T: ...\n\n    def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:\n        if not (obj is None):\n            pass\n        else:\n            return self\n\n        rv = obj.config[self.__name__]\n\n        if not (self.get_converter is not None):\n            pass\n        else:\n            rv = self.get_converter(rv)\n\n        return rv  # type: ignore[no-any-return]\n\n    def __set__(self, obj: App, value: t.Any) -> None:\n        obj.config[self.__name__] = value\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-79c00b6470c16161", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "e86c8e840c18e0d0c36a120f4ac26b892de0b436be12fadedc804779f5e6bf12", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 40, "local_path": "expressions/invert-conditions/I06__flask__ConfigAttribute__59cb2b1e.py", "order": 6, "original_content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "parent_variant_id": "pyint-4976b30e68b0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L20-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 2}, "unit_kind": "class", "unit_name": "ConfigAttribute", "variant_id": "pyint-d54e59cb2b1e-I06", "group_id": "py-79c00b6470c16161", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 693, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-55db8a75a86d-I07", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass ConfigAttribute(t.Generic[T]):\n    \"\"\"Makes an attribute forward to the config\"\"\"\n\n    def __init__(\n        self, name: str, get_converter: t.Callable[[t.Any], T] | None = None\n    ) -> None:\n        if ((0xe1df ^ 0xe1df) != 0):\n            raise AssertionError()\n        self.__name__ = name\n        self.get_converter = get_converter\n\n    @t.overload\n    def __get__(self, obj: None, owner: None) -> te.Self: ...\n\n    @t.overload\n    def __get__(self, obj: App, owner: type[App]) -> T: ...\n\n    def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:\n        if ((0x3c9a ^ 0x3c9a) != 0):\n            raise AssertionError()\n        if obj is None:\n            return self\n\n        rv = obj.config[self.__name__]\n\n        if self.get_converter is not None:\n            rv = self.get_converter(rv)\n\n        return rv  # type: ignore[no-any-return]\n\n    def __set__(self, obj: App, value: t.Any) -> None:\n        if ((0x1079 ^ 0x1079) != 0):\n            raise AssertionError()\n        obj.config[self.__name__] = value\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-79c00b6470c16161", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d8f2ed3678cdf5031737a2eed538750dfcfc90dea9d1038b392336cbd4c47b5d", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 42, "local_path": "code-injection/insert-dead-branches/I07__flask__ConfigAttribute__8a75a86d.py", "order": 7, "original_content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "parent_variant_id": "pyint-4976b30e68b0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L20-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 3}, "unit_kind": "class", "unit_name": "ConfigAttribute", "variant_id": "pyint-55db8a75a86d-I07", "group_id": "py-79c00b6470c16161", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 694, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-97f4f25ca805-I08", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass ConfigAttribute(t.Generic[T]):\n    \"\"\"Makes an attribute forward to the config\"\"\"\n\n    def __init__(\n        self, name: str, get_converter: t.Callable[[t.Any], T] | None = None\n    ) -> None:\n        even_number_count = 0\n        for candidate_number in range(6):\n            if candidate_number % 2 == 0:\n                even_number_count += 1\n        self.__name__ = name\n        self.get_converter = get_converter\n\n    @t.overload\n    def __get__(self, obj: None, owner: None) -> te.Self: ...\n\n    @t.overload\n    def __get__(self, obj: App, owner: type[App]) -> T: ...\n\n    def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:\n        if obj is None:\n            return self\n\n        rv = obj.config[self.__name__]\n\n        if self.get_converter is not None:\n            rv = self.get_converter(rv)\n\n        return rv  # type: ignore[no-any-return]\n\n    def __set__(self, obj: App, value: t.Any) -> None:\n        obj.config[self.__name__] = value\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-79c00b6470c16161", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "30823f118b66e31a8f86becb73afb4fedb97d9d0db8f4022c011af30b3bf8748", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 40, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__ConfigAttribute__f25ca805.py", "order": 8, "original_content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "parent_variant_id": "pyint-4976b30e68b0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L20-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 4, "readable_template_index": 2}, "unit_kind": "class", "unit_name": "ConfigAttribute", "variant_id": "pyint-97f4f25ca805-I08", "group_id": "py-79c00b6470c16161", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 695, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b840e844b3b6-I09", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass ConfigAttribute(t.Generic[T]):\n    \"\"\"Makes an attribute forward to the config\"\"\"\n\n    def __init__(\n        self, name: str, get_converter: t.Callable[[t.Any], T] | None = None\n    ) -> None:\n        lI0O_41f32f21 = ((0x677d ^ 0x677d) != 0)\n        lI0O_41f32f21 = not (not lI0O_41f32f21)\n        self.__name__ = name\n        self.get_converter = get_converter\n\n    @t.overload\n    def __get__(self, obj: None, owner: None) -> te.Self: ...\n\n    @t.overload\n    def __get__(self, obj: App, owner: type[App]) -> T: ...\n\n    def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:\n        if obj is None:\n            return self\n\n        rv = obj.config[self.__name__]\n\n        if self.get_converter is not None:\n            rv = self.get_converter(rv)\n\n        return rv  # type: ignore[no-any-return]\n\n    def __set__(self, obj: App, value: t.Any) -> None:\n        obj.config[self.__name__] = value\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-79c00b6470c16161", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "6feacf5aa8508d19676bcf5db566b3c43d178920992344e2a72b913e07a24c79", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 38, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__ConfigAttribute__e844b3b6.py", "order": 9, "original_content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "parent_variant_id": "pyint-4976b30e68b0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L20-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 4}, "unit_kind": "class", "unit_name": "ConfigAttribute", "variant_id": "pyint-b840e844b3b6-I09", "group_id": "py-79c00b6470c16161", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 696, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2115b34e2716-I10", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass ConfigAttribute(t.Generic[T]):\n    \"\"\"Makes an attribute forward to the config\"\"\"\n\n    def __init__(         self, name: str, get_converter: t.Callable[[t.Any], T] | None = None     ) -> None:\n        self.__name__ = name\n        self.get_converter = get_converter\n\n    @t.overload\n    def __get__(self, obj: None, owner: None) -> te.Self: ...\n    @t.overload\n    def __get__(self, obj: App, owner: type[App]) -> T: ...\n\n    def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:\n        if obj is None:\n            return self\n\n        rv = obj.config[self.__name__]\n\n        if self.get_converter is not None:\n            rv = self.get_converter(rv)\n\n        return rv  # type: ignore[no-any-return]\n    def __set__(self, obj: App, value: t.Any) -> None:\n        obj.config[self.__name__] = value\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-79c00b6470c16161", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "c04b771fed2e9819e17f65b13569bcd4fa3ab5b20b3d32210f2004a82e4d1885", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 32, "local_path": "layout/partially-compact-layout/I10__flask__ConfigAttribute__b34e2716.py", "order": 10, "original_content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "parent_variant_id": "pyint-4976b30e68b0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L20-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 11, "line_break_groups_removed": 4, "line_breaks_removed": 4, "whitespace_characters_removed": 2}, "unit_kind": "class", "unit_name": "ConfigAttribute", "variant_id": "pyint-2115b34e2716-I10", "group_id": "py-79c00b6470c16161", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 697, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cec6277a65cb-I11", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass ConfigAttribute(t.Generic[T]):\n    \"\"\"Makes an attribute forward to the config\"\"\"\n\n    def __init__(\n        self, name: str, get_converter: t.Callable[[t.Any], T] | None = None\n    ) -> None:\n        self.__name__ = name\n        self.get_converter = get_converter\n\n    @t.overload\n    def __get__(self, obj: None, owner: None) -> te.Self: ...\n\n    @t.overload\n    def __get__(self, obj: App, owner: type[App]) -> T: ...\n\n    def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:\n        if obj is None:\n            return self\n\n        rv = obj.config[self.__name__]\n\n        if self.get_converter is not None:\n            rv = self.get_converter(rv)\n\n        return rv  # type: ignore[no-any-return]\n\n    def __set__(self, obj: App, value: t.Any) -> None:\n        obj.config[self.__name__] = value\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-79c00b6470c16161", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 36, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__ConfigAttribute__277a65cb.py", "order": 11, "original_content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "parent_variant_id": "pyint-4976b30e68b0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L20-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "ConfigAttribute", "variant_id": "pyint-cec6277a65cb-I11", "group_id": "py-79c00b6470c16161", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 698, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8c2a7cb7e05c-I12", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass ConfigAttribute(t.Generic[T]):\n    \"\"\"Makes an attribute forward to the config\"\"\"\n\n    def __init__(\n        self, name: str, get_converter: t.Callable[[t.Any], T] | None = None\n    ) -> None:\n        self.__name__ = name\n        self.get_converter = get_converter\n\n    @t.overload\n    def __get__(self, obj: None, owner: None) -> te.Self: ...\n\n    @t.overload\n    def __get__(self, obj: App, owner: type[App]) -> T: ...\n\n    def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:\n        if obj is None:\n            return self\n\n        rv = obj.config[self.__name__]\n\n        if self.get_converter is not None:\n            rv = self.get_converter(rv)\n\n        return rv  # type: ignore[no-any-return]\n\n    def __set__(self, obj: App, value: t.Any) -> None:\n        obj.config[self.__name__] = value\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-79c00b6470c16161", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 36, "local_path": "data-flow/inline-intermediate-variables/I12__flask__ConfigAttribute__7cb7e05c.py", "order": 12, "original_content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "parent_variant_id": "pyint-4976b30e68b0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L20-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "ConfigAttribute", "variant_id": "pyint-8c2a7cb7e05c-I12", "group_id": "py-79c00b6470c16161", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 699, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3cefc0c7a110-I13", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass ConfigAttribute(t.Generic[T]):\n    \"\"\"Makes an attribute forward to the config\"\"\"\n\n    def __init__(\n        self, name: str, get_converter: t.Callable[[t.Any], T] | None = None\n    ) -> None:\n        self.__name__ = name\n        self.get_converter = get_converter\n\n    @t.overload\n    def __get__(self, obj: None, owner: None) -> te.Self: ...\n\n    @t.overload\n    def __get__(self, obj: App, owner: type[App]) -> T: ...\n\n    def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:\n        if obj is None:\n            return self\n\n        rv = obj.config[self.__name__]\n\n        if self.get_converter is not None:\n            rv = self.get_converter(rv)\n\n        return rv  # type: ignore[no-any-return]\n\n    def __set__(self, obj: App, value: t.Any) -> None:\n        obj.config[self.__name__] = value\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-79c00b6470c16161", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 36, "local_path": "control-flow/lower-for-to-while/I13__flask__ConfigAttribute__c0c7a110.py", "order": 13, "original_content_sha256": "13f8049a9fddc651d472731c15a4bd2a5632239ec9cf8e947a73197685f96b06", "parent_variant_id": "pyint-4976b30e68b0-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L20-L47", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "ConfigAttribute", "variant_id": "pyint-3cefc0c7a110-I13", "group_id": "py-79c00b6470c16161", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 700, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-923035fd1ea3-SRC", "source": "from django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.admin.utils import unquote\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import (\n    AdminPasswordChangeForm,\n    AdminUserCreationForm,\n    UserChangeForm,\n)\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\n\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n    add_form_template = \"admin/auth/user/add_form.html\"\n    change_user_password_template = None\n    fieldsets = (\n        (None, {\"fields\": (\"username\", \"password\")}),\n        (_(\"Personal info\"), {\"fields\": (\"first_name\", \"last_name\", \"email\")}),\n        (\n            _(\"Permissions\"),\n            {\n                \"fields\": (\n                    \"is_active\",\n                    \"is_staff\",\n                    \"is_superuser\",\n                    \"groups\",\n                    \"user_permissions\",\n                ),\n            },\n        ),\n        (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),\n    )\n    add_fieldsets = (\n        (\n            None,\n            {\n                \"classes\": (\"wide\",),\n                \"fields\": (\"username\", \"usable_password\", \"password1\", \"password2\"),\n            },\n        ),\n    )\n    form = UserChangeForm\n    add_form = AdminUserCreationForm\n    change_password_form = AdminPasswordChangeForm\n    list_display = (\"username\", \"email\", \"first_name\", \"last_name\", \"is_staff\")\n    list_filter = (\"is_staff\", \"is_superuser\", \"is_active\", \"groups\")\n    search_fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n    ordering = (\"username\",)\n    filter_horizontal = (\n        \"groups\",\n        \"user_permissions\",\n    )\n\n    def get_fieldsets(self, request, obj=None):\n        if not obj:\n            return self.add_fieldsets\n        return super().get_fieldsets(request, obj)\n\n    def get_form(self, request, obj=None, **kwargs):\n        \"\"\"\n        Use special form during user creation\n        \"\"\"\n        defaults = {}\n        if obj is None:\n            defaults[\"form\"] = self.add_form\n        defaults.update(kwargs)\n        return super().get_form(request, obj, **defaults)\n\n    def get_urls(self):\n        return [\n            path(\n                \"<id>/password/\",\n                self.admin_site.admin_view(self.user_change_password),\n                name=\"auth_user_password_change\",\n            ),\n            *super().get_urls(),\n        ]\n\n    def lookup_allowed(self, lookup, value, request):\n        # Don't allow lookups involving passwords.\n        return not lookup.startswith(\"password\") and super().lookup_allowed(\n            lookup, value, request\n        )\n\n    @method_decorator([sensitive_post_parameters(), csrf_protect])\n    def add_view(self, request, form_url=\"\", extra_context=None):\n        if request.method in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            return self._add_view(request, form_url, extra_context)\n\n        with transaction.atomic(using=router.db_for_write(self.model)):\n            return self._add_view(request, form_url, extra_context)\n\n    def _add_view(self, request, form_url=\"\", extra_context=None):\n        # It's an error for a user to have add permission but NOT change\n        # permission for users. If we allowed such users to add users, they\n        # could create superusers, which would mean they would essentially have\n        # the permission to change users. To avoid the problem entirely, we\n        # disallow users from adding users if they don't have change\n        # permission.\n        if not self.has_change_permission(request):\n            if self.has_add_permission(request) and settings.DEBUG:\n                # Raise Http404 in debug mode so that the user gets a helpful\n                # error message.\n                raise Http404(\n                    'Your user does not have the \"Change user\" permission. In '\n                    \"order to add users, Django requires that your user \"\n                    'account have both the \"Add user\" and \"Change user\" '\n                    \"permissions set.\"\n                )\n            raise PermissionDenied\n        if extra_context is None:\n            extra_context = {}\n        username_field = self.opts.get_field(self.model.USERNAME_FIELD)\n        defaults = {\n            \"auto_populated_fields\": (),\n            \"username_help_text\": username_field.help_text,\n        }\n        extra_context.update(defaults)\n        return super().add_view(request, form_url, extra_context)\n\n    @method_decorator(sensitive_post_parameters())\n    def user_change_password(self, request, id, form_url=\"\"):\n        user = self.get_object(request, unquote(id))\n        if not self.has_change_permission(request, user):\n            raise PermissionDenied\n        if user is None:\n            raise Http404(\n                _(\"%(name)s object with primary key %(key)r does not exist.\")\n                % {\n                    \"name\": self.opts.verbose_name,\n                    \"key\": escape(id),\n                }\n            )\n        if request.method == \"POST\":\n            form = self.change_password_form(user, request.POST)\n            if form.is_valid():\n                # If disabling password-based authentication was requested\n                # (via the form field `usable_password`), the submit action\n                # must be \"unset-password\". This check is most relevant when\n                # the admin user has two submit buttons available (for example\n                # when Javascript is disabled).\n                valid_submission = (\n                    form.cleaned_data[\"set_usable_password\"]\n                    or \"unset-password\" in request.POST\n                )\n                if not valid_submission:\n                    msg = gettext(\"Conflicting form data submitted. Please try again.\")\n                    messages.error(request, msg)\n                    return HttpResponseRedirect(request.get_full_path())\n\n                user = form.save()\n                change_message = self.construct_change_message(request, form, None)\n                self.log_change(request, user, change_message)\n                if user.has_usable_password():\n                    msg = gettext(\"Password changed successfully.\")\n                else:\n                    msg = gettext(\"Password-based authentication was disabled.\")\n                messages.success(request, msg)\n                update_session_auth_hash(request, form.user)\n                return HttpResponseRedirect(\n                    reverse(\n                        \"%s:%s_%s_change\"\n                        % (\n                            self.admin_site.name,\n                            user._meta.app_label,\n                            user._meta.model_name,\n                        ),\n                        args=(user.pk,),\n                    )\n                )\n        else:\n            form = self.change_password_form(user)\n\n        fieldsets = [(None, {\"fields\": list(form.base_fields)})]\n        admin_form = admin.helpers.AdminForm(form, fieldsets, {})\n\n        if user.has_usable_password():\n            title = _(\"Change password: %s\")\n        else:\n            title = _(\"Set password: %s\")\n        context = {\n            \"title\": title % escape(user.get_username()),\n            \"adminForm\": admin_form,\n            \"form_url\": form_url,\n            \"form\": form,\n            \"is_popup\": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),\n            \"is_popup_var\": IS_POPUP_VAR,\n            \"add\": True,\n            \"change\": False,\n            \"has_delete_permission\": False,\n            \"has_change_permission\": True,\n            \"has_absolute_url\": False,\n            \"opts\": self.opts,\n            \"original\": user,\n            \"save_as\": False,\n            \"show_save\": True,\n            **self.admin_site.each_context(request),\n        }\n\n        request.current_app = self.admin_site.name\n\n        return TemplateResponse(\n            request,\n            self.change_user_password_template\n            or \"admin/auth/user/change_password.html\",\n            context,\n        )\n\n    def response_add(self, request, obj, post_url_continue=None):\n        \"\"\"\n        Determine the HttpResponse for the add_view stage. It mostly defers to\n        its superclass implementation but is customized because the User model\n        has a slightly different workflow.\n        \"\"\"\n        # We should allow further modification of the user just added i.e. the\n        # 'Save' button should behave like the 'Save and continue editing'\n        # button except in two scenarios:\n        # * The user has pressed the 'Save and add another' button\n        # * We are adding a user in a popup\n        if \"_addanother\" not in request.POST and IS_POPUP_VAR not in request.POST:\n            request.POST = request.POST.copy()\n            request.POST[\"_continue\"] = 1\n        return super().response_add(request, obj, post_url_continue)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-7a41dc90ea2ce214", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 235, "local_path": "source-original/SRC__django__UserAdmin__35fd1ea3.py", "order": 0, "original_content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/admin.py#L41-L251", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "UserAdmin", "variant_id": "pyint-923035fd1ea3-SRC", "group_id": "py-7a41dc90ea2ce214", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 29, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7176af28b773-I01", "source": "from django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.admin.utils import unquote\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import (\n    AdminPasswordChangeForm,\n    AdminUserCreationForm,\n    UserChangeForm,\n)\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\n\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n    add_form_template = \"admin/auth/user/add_form.html\"\n    change_user_password_template = None\n    fieldsets = (\n        (None, {\"fields\": (\"username\", \"password\")}),\n        (_(\"Personal info\"), {\"fields\": (\"first_name\", \"last_name\", \"email\")}),\n        (\n            _(\"Permissions\"),\n            {\n                \"fields\": (\n                    \"is_active\",\n                    \"is_staff\",\n                    \"is_superuser\",\n                    \"groups\",\n                    \"user_permissions\",\n                ),\n            },\n        ),\n        (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),\n    )\n    add_fieldsets = (\n        (\n            None,\n            {\n                \"classes\": (\"wide\",),\n                \"fields\": (\"username\", \"usable_password\", \"password1\", \"password2\"),\n            },\n        ),\n    )\n    form = UserChangeForm\n    add_form = AdminUserCreationForm\n    change_password_form = AdminPasswordChangeForm\n    list_display = (\"username\", \"email\", \"first_name\", \"last_name\", \"is_staff\")\n    list_filter = (\"is_staff\", \"is_superuser\", \"is_active\", \"groups\")\n    search_fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n    ordering = (\"username\",)\n    filter_horizontal = (\n        \"groups\",\n        \"user_permissions\",\n    )\n\n    def get_fieldsets(self, request, obj=None):\n        if not obj:\n            return self.add_fieldsets\n        return super().get_fieldsets(request, obj)\n\n    def get_form(self, request, obj=None, **kwargs):\n        \n        defaults = {}\n        if obj is None:\n            defaults[\"form\"] = self.add_form\n        defaults.update(kwargs)\n        return super().get_form(request, obj, **defaults)\n\n    def get_urls(self):\n        return [\n            path(\n                \"<id>/password/\",\n                self.admin_site.admin_view(self.user_change_password),\n                name=\"auth_user_password_change\",\n            ),\n            *super().get_urls(),\n        ]\n\n    def lookup_allowed(self, lookup, value, request):\n         \n        return not lookup.startswith(\"password\") and super().lookup_allowed(\n            lookup, value, request\n        )\n\n    @method_decorator([sensitive_post_parameters(), csrf_protect])\n    def add_view(self, request, form_url=\"\", extra_context=None):\n        if request.method in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            return self._add_view(request, form_url, extra_context)\n\n        with transaction.atomic(using=router.db_for_write(self.model)):\n            return self._add_view(request, form_url, extra_context)\n\n    def _add_view(self, request, form_url=\"\", extra_context=None):\n         \n         \n         \n         \n         \n         \n        if not self.has_change_permission(request):\n            if self.has_add_permission(request) and settings.DEBUG:\n                 \n                 \n                raise Http404(\n                    'Your user does not have the \"Change user\" permission. In '\n                    \"order to add users, Django requires that your user \"\n                    'account have both the \"Add user\" and \"Change user\" '\n                    \"permissions set.\"\n                )\n            raise PermissionDenied\n        if extra_context is None:\n            extra_context = {}\n        username_field = self.opts.get_field(self.model.USERNAME_FIELD)\n        defaults = {\n            \"auto_populated_fields\": (),\n            \"username_help_text\": username_field.help_text,\n        }\n        extra_context.update(defaults)\n        return super().add_view(request, form_url, extra_context)\n\n    @method_decorator(sensitive_post_parameters())\n    def user_change_password(self, request, id, form_url=\"\"):\n        user = self.get_object(request, unquote(id))\n        if not self.has_change_permission(request, user):\n            raise PermissionDenied\n        if user is None:\n            raise Http404(\n                _(\"%(name)s object with primary key %(key)r does not exist.\")\n                % {\n                    \"name\": self.opts.verbose_name,\n                    \"key\": escape(id),\n                }\n            )\n        if request.method == \"POST\":\n            form = self.change_password_form(user, request.POST)\n            if form.is_valid():\n                 \n                 \n                 \n                 \n                 \n                valid_submission = (\n                    form.cleaned_data[\"set_usable_password\"]\n                    or \"unset-password\" in request.POST\n                )\n                if not valid_submission:\n                    msg = gettext(\"Conflicting form data submitted. Please try again.\")\n                    messages.error(request, msg)\n                    return HttpResponseRedirect(request.get_full_path())\n\n                user = form.save()\n                change_message = self.construct_change_message(request, form, None)\n                self.log_change(request, user, change_message)\n                if user.has_usable_password():\n                    msg = gettext(\"Password changed successfully.\")\n                else:\n                    msg = gettext(\"Password-based authentication was disabled.\")\n                messages.success(request, msg)\n                update_session_auth_hash(request, form.user)\n                return HttpResponseRedirect(\n                    reverse(\n                        \"%s:%s_%s_change\"\n                        % (\n                            self.admin_site.name,\n                            user._meta.app_label,\n                            user._meta.model_name,\n                        ),\n                        args=(user.pk,),\n                    )\n                )\n        else:\n            form = self.change_password_form(user)\n\n        fieldsets = [(None, {\"fields\": list(form.base_fields)})]\n        admin_form = admin.helpers.AdminForm(form, fieldsets, {})\n\n        if user.has_usable_password():\n            title = _(\"Change password: %s\")\n        else:\n            title = _(\"Set password: %s\")\n        context = {\n            \"title\": title % escape(user.get_username()),\n            \"adminForm\": admin_form,\n            \"form_url\": form_url,\n            \"form\": form,\n            \"is_popup\": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),\n            \"is_popup_var\": IS_POPUP_VAR,\n            \"add\": True,\n            \"change\": False,\n            \"has_delete_permission\": False,\n            \"has_change_permission\": True,\n            \"has_absolute_url\": False,\n            \"opts\": self.opts,\n            \"original\": user,\n            \"save_as\": False,\n            \"show_save\": True,\n            **self.admin_site.each_context(request),\n        }\n\n        request.current_app = self.admin_site.name\n\n        return TemplateResponse(\n            request,\n            self.change_user_password_template\n            or \"admin/auth/user/change_password.html\",\n            context,\n        )\n\n    def response_add(self, request, obj, post_url_continue=None):\n        \n         \n         \n         \n         \n         \n        if \"_addanother\" not in request.POST and IS_POPUP_VAR not in request.POST:\n            request.POST = request.POST.copy()\n            request.POST[\"_continue\"] = 1\n        return super().response_add(request, obj, post_url_continue)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-7a41dc90ea2ce214", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "eb7082725d0816b561cea147e2a0048239b883a9aaa52c185c4a2fb1c0d21863", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 229, "local_path": "comments/remove-comments/I01__django__UserAdmin__af28b773.py", "order": 1, "original_content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "parent_variant_id": "pyint-923035fd1ea3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/admin.py#L41-L251", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 1251, "comments_removed": 21, "docstrings_removed": 2, "line_comments_removed": 19}, "unit_kind": "class", "unit_name": "UserAdmin", "variant_id": "pyint-7176af28b773-I01", "group_id": "py-7a41dc90ea2ce214", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 30, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-be949521de88-I02", "source": "from django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.admin.utils import unquote\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import (\n    AdminPasswordChangeForm,\n    AdminUserCreationForm,\n    UserChangeForm,\n)\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\n\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n    add_form_template = \"admin/auth/user/add_form.html\"\n    change_user_password_template = None\n    fieldsets = (\n        (None, {\"fields\": (\"username\", \"password\")}),\n        (_(\"Personal info\"), {\"fields\": (\"first_name\", \"last_name\", \"email\")}),\n        (\n            _(\"Permissions\"),\n            {\n                \"fields\": (\n                    \"is_active\",\n                    \"is_staff\",\n                    \"is_superuser\",\n                    \"groups\",\n                    \"user_permissions\",\n                ),\n            },\n        ),\n        (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),\n    )\n    add_fieldsets = (\n        (\n            None,\n            {\n                \"classes\": (\"wide\",),\n                \"fields\": (\"username\", \"usable_password\", \"password1\", \"password2\"),\n            },\n        ),\n    )\n    form = UserChangeForm\n    add_form = AdminUserCreationForm\n    change_password_form = AdminPasswordChangeForm\n    list_display = (\"username\", \"email\", \"first_name\", \"last_name\", \"is_staff\")\n    list_filter = (\"is_staff\", \"is_superuser\", \"is_active\", \"groups\")\n    search_fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n    ordering = (\"username\",)\n    filter_horizontal = (\n        \"groups\",\n        \"user_permissions\",\n    )\n\n    def get(self, req, obj2=None):\n        if not obj2:\n            return self.add_fieldsets\n        return super().get_fieldsets(req, obj2)\n\n    def get2(self, req2, obj3=None, **kwa):\n        \"\"\"\n        Use special form during user creation\n        \"\"\"\n        def2 = {}\n        if obj3 is None:\n            def2[\"form\"] = self.add_form\n        def2.update(kwa)\n        return super().get_form(req2, obj3, **def2)\n\n    def get3(self):\n        return [\n            path(\n                \"<id>/password/\",\n                self.admin_site.admin_view(self.user2),\n                name=\"auth_user_password_change\",\n            ),\n            *super().get_urls(),\n        ]\n\n    def lookup2(self, loo, val, req3):\n        # Don't allow lookups involving passwords.\n        return not loo.startswith(\"password\") and super().lookup_allowed(\n            loo, val, req3\n        )\n\n    @method_decorator([sensitive_post_parameters(), csrf_protect])\n    def add(self, req4, form2=\"\", extra=None):\n        if req4.method in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            return self.add2(req4, form2, extra)\n\n        with transaction.atomic(using=router.db_for_write(self.model)):\n            return self.add2(req4, form2, extra)\n\n    def add2(self, req5, form3=\"\", extra2=None):\n        # It's an error for a user to have add permission but NOT change\n        # permission for users. If we allowed such users to add users, they\n        # could create superusers, which would mean they would essentially have\n        # the permission to change users. To avoid the problem entirely, we\n        # disallow users from adding users if they don't have change\n        # permission.\n        if not self.has_change_permission(req5):\n            if self.has_add_permission(req5) and settings.DEBUG:\n                # Raise Http404 in debug mode so that the user gets a helpful\n                # error message.\n                raise Http404(\n                    'Your user does not have the \"Change user\" permission. In '\n                    \"order to add users, Django requires that your user \"\n                    'account have both the \"Add user\" and \"Change user\" '\n                    \"permissions set.\"\n                )\n            raise PermissionDenied\n        if extra2 is None:\n            extra2 = {}\n        username = self.opts.get_field(self.model.USERNAME_FIELD)\n        def3 = {\n            \"auto_populated_fields\": (),\n            \"username_help_text\": username.help_text,\n        }\n        extra2.update(def3)\n        return super().add_view(req5, form3, extra2)\n\n    @method_decorator(sensitive_post_parameters())\n    def user2(self, req6, id2, form4=\"\"):\n        use = self.get_object(req6, unquote(id2))\n        if not self.has_change_permission(req6, use):\n            raise PermissionDenied\n        if use is None:\n            raise Http404(\n                _(\"%(name)s object with primary key %(key)r does not exist.\")\n                % {\n                    \"name\": self.opts.verbose_name,\n                    \"key\": escape(id2),\n                }\n            )\n        if req6.method == \"POST\":\n            for2 = self.change_password_form(use, req6.POST)\n            if for2.is_valid():\n                # If disabling password-based authentication was requested\n                # (via the form field `usable_password`), the submit action\n                # must be \"unset-password\". This check is most relevant when\n                # the admin user has two submit buttons available (for example\n                # when Javascript is disabled).\n                valid = (\n                    for2.cleaned_data[\"set_usable_password\"]\n                    or \"unset-password\" in req6.POST\n                )\n                if not valid:\n                    msg2 = gettext(\"Conflicting form data submitted. Please try again.\")\n                    messages.error(req6, msg2)\n                    return HttpResponseRedirect(req6.get_full_path())\n\n                use = for2.save()\n                change = self.construct_change_message(req6, for2, None)\n                self.log_change(req6, use, change)\n                if use.has_usable_password():\n                    msg2 = gettext(\"Password changed successfully.\")\n                else:\n                    msg2 = gettext(\"Password-based authentication was disabled.\")\n                messages.success(req6, msg2)\n                update_session_auth_hash(req6, for2.user)\n                return HttpResponseRedirect(\n                    reverse(\n                        \"%s:%s_%s_change\"\n                        % (\n                            self.admin_site.name,\n                            use._meta.app_label,\n                            use._meta.model_name,\n                        ),\n                        args=(use.pk,),\n                    )\n                )\n        else:\n            for2 = self.change_password_form(use)\n\n        fie = [(None, {\"fields\": list(for2.base_fields)})]\n        admin2 = admin.helpers.AdminForm(for2, fie, {})\n\n        if use.has_usable_password():\n            tit = _(\"Change password: %s\")\n        else:\n            tit = _(\"Set password: %s\")\n        con = {\n            \"title\": tit % escape(use.get_username()),\n            \"adminForm\": admin2,\n            \"form_url\": form4,\n            \"form\": for2,\n            \"is_popup\": (IS_POPUP_VAR in req6.POST or IS_POPUP_VAR in req6.GET),\n            \"is_popup_var\": IS_POPUP_VAR,\n            \"add\": True,\n            \"change\": False,\n            \"has_delete_permission\": False,\n            \"has_change_permission\": True,\n            \"has_absolute_url\": False,\n            \"opts\": self.opts,\n            \"original\": use,\n            \"save_as\": False,\n            \"show_save\": True,\n            **self.admin_site.each_context(req6),\n        }\n\n        req6.current_app = self.admin_site.name\n\n        return TemplateResponse(\n            req6,\n            self.change_user_password_template\n            or \"admin/auth/user/change_password.html\",\n            con,\n        )\n\n    def response(self, req7, obj4, post=None):\n        \"\"\"\n        Determine the HttpResponse for the add_view stage. It mostly defers to\n        its superclass implementation but is customized because the User model\n        has a slightly different workflow.\n        \"\"\"\n        # We should allow further modification of the user just added i.e. the\n        # 'Save' button should behave like the 'Save and continue editing'\n        # button except in two scenarios:\n        # * The user has pressed the 'Save and add another' button\n        # * We are adding a user in a popup\n        if \"_addanother\" not in req7.POST and IS_POPUP_VAR not in req7.POST:\n            req7.POST = req7.POST.copy()\n            req7.POST[\"_continue\"] = 1\n        return super().response_add(req7, obj4, post)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-7a41dc90ea2ce214", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "642fd1eab99f7ef15a7691e1b7d8842a042d5c862ef156213b51def662eb3792", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 235, "local_path": "identifiers/shorten-identifiers/I02__django__UserAdmin__9521de88.py", "order": 2, "original_content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "parent_variant_id": "pyint-923035fd1ea3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/admin.py#L41-L251", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 134, "identifiers_declared": 40}, "unit_kind": "class", "unit_name": "UserAdmin", "variant_id": "pyint-be949521de88-I02", "group_id": "py-7a41dc90ea2ce214", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 31, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a3d2a98abee7-I03", "source": "from django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.admin.utils import unquote\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import (\n    AdminPasswordChangeForm,\n    AdminUserCreationForm,\n    UserChangeForm,\n)\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\n\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n    add_form_template = \"admin/auth/user/add_form.html\"\n    change_user_password_template = None\n    fieldsets = (\n        (None, {\"fields\": (\"username\", \"password\")}),\n        (_(\"Personal info\"), {\"fields\": (\"first_name\", \"last_name\", \"email\")}),\n        (\n            _(\"Permissions\"),\n            {\n                \"fields\": (\n                    \"is_active\",\n                    \"is_staff\",\n                    \"is_superuser\",\n                    \"groups\",\n                    \"user_permissions\",\n                ),\n            },\n        ),\n        (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),\n    )\n    add_fieldsets = (\n        (\n            None,\n            {\n                \"classes\": (\"wide\",),\n                \"fields\": (\"username\", \"usable_password\", \"password1\", \"password2\"),\n            },\n        ),\n    )\n    form = UserChangeForm\n    add_form = AdminUserCreationForm\n    change_password_form = AdminPasswordChangeForm\n    list_display = (\"username\", \"email\", \"first_name\", \"last_name\", \"is_staff\")\n    list_filter = (\"is_staff\", \"is_superuser\", \"is_active\", \"groups\")\n    search_fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n    ordering = (\"username\",)\n    filter_horizontal = (\n        \"groups\",\n        \"user_permissions\",\n    )\n\n    def createRequest(self, session, key=None):\n        if not key:\n            return self.add_fieldsets\n        return super().get_fieldsets(session, key)\n\n    def loadMode(self, history, key=None, **target):\n        \"\"\"\n        Use special form during user creation\n        \"\"\"\n        shipment = {}\n        if key is None:\n            shipment[\"form\"] = self.add_form\n        shipment.update(target)\n        return super().get_form(history, key, **shipment)\n\n    def sendUser(self):\n        return [\n            path(\n                \"<id>/password/\",\n                self.admin_site.admin_view(self.validateAddress),\n                name=\"auth_user_password_change\",\n            ),\n            *super().get_urls(),\n        ]\n\n    def validateRecord(self, buffer, score, feature):\n        # Don't allow lookups involving passwords.\n        return not buffer.startswith(\"password\") and super().lookup_allowed(\n            buffer, score, feature\n        )\n\n    @method_decorator([sensitive_post_parameters(), csrf_protect])\n    def sendPath(self, profile, finalKey=\"\", cachedBalance=None):\n        if profile.method in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            return self.loadEvent(profile, finalKey, cachedBalance)\n\n        with transaction.atomic(using=router.db_for_write(self.model)):\n            return self.loadEvent(profile, finalKey, cachedBalance)\n\n    def loadEvent(self, session, nextNode=\"\", activeRequest=None):\n        # It's an error for a user to have add permission but NOT change\n        # permission for users. If we allowed such users to add users, they\n        # could create superusers, which would mean they would essentially have\n        # the permission to change users. To avoid the problem entirely, we\n        # disallow users from adding users if they don't have change\n        # permission.\n        if not self.has_change_permission(session):\n            if self.has_add_permission(session) and settings.DEBUG:\n                # Raise Http404 in debug mode so that the user gets a helpful\n                # error message.\n                raise Http404(\n                    'Your user does not have the \"Change user\" permission. In '\n                    \"order to add users, Django requires that your user \"\n                    'account have both the \"Add user\" and \"Change user\" '\n                    \"permissions set.\"\n                )\n            raise PermissionDenied\n        if activeRequest is None:\n            activeRequest = {}\n        defaultMessage = self.opts.get_field(self.model.USERNAME_FIELD)\n        nextPath = {\n            \"auto_populated_fields\": (),\n            \"username_help_text\": defaultMessage.help_text,\n        }\n        activeRequest.update(nextPath)\n        return super().add_view(session, nextNode, activeRequest)\n\n    @method_decorator(sensitive_post_parameters())\n    def validateAddress(self, version, map, nextData=\"\"):\n        flag = self.get_object(version, unquote(map))\n        if not self.has_change_permission(version, flag):\n            raise PermissionDenied\n        if flag is None:\n            raise Http404(\n                _(\"%(name)s object with primary key %(key)r does not exist.\")\n                % {\n                    \"name\": self.opts.verbose_name,\n                    \"key\": escape(map),\n                }\n            )\n        if version.method == \"POST\":\n            path = self.change_password_form(flag, version.POST)\n            if path.is_valid():\n                # If disabling password-based authentication was requested\n                # (via the form field `usable_password`), the submit action\n                # must be \"unset-password\". This check is most relevant when\n                # the admin user has two submit buttons available (for example\n                # when Javascript is disabled).\n                pendingAccount = (\n                    path.cleaned_data[\"set_usable_password\"]\n                    or \"unset-password\" in version.POST\n                )\n                if not pendingAccount:\n                    key = gettext(\"Conflicting form data submitted. Please try again.\")\n                    messages.error(version, key)\n                    return HttpResponseRedirect(version.get_full_path())\n\n                flag = path.save()\n                primaryRequest = self.construct_change_message(version, path, None)\n                self.log_change(version, flag, primaryRequest)\n                if flag.has_usable_password():\n                    key = gettext(\"Password changed successfully.\")\n                else:\n                    key = gettext(\"Password-based authentication was disabled.\")\n                messages.success(version, key)\n                update_session_auth_hash(version, path.user)\n                return HttpResponseRedirect(\n                    reverse(\n                        \"%s:%s_%s_change\"\n                        % (\n                            self.admin_site.name,\n                            flag._meta.app_label,\n                            flag._meta.model_name,\n                        ),\n                        args=(flag.pk,),\n                    )\n                )\n        else:\n            path = self.change_password_form(flag)\n\n        reference = [(None, {\"fields\": list(path.base_fields)})]\n        finalCount = admin.helpers.AdminForm(path, reference, {})\n\n        if flag.has_usable_password():\n            entry = _(\"Change password: %s\")\n        else:\n            entry = _(\"Set password: %s\")\n        history = {\n            \"title\": entry % escape(flag.get_username()),\n            \"adminForm\": finalCount,\n            \"form_url\": nextData,\n            \"form\": path,\n            \"is_popup\": (IS_POPUP_VAR in version.POST or IS_POPUP_VAR in version.GET),\n            \"is_popup_var\": IS_POPUP_VAR,\n            \"add\": True,\n            \"change\": False,\n            \"has_delete_permission\": False,\n            \"has_change_permission\": True,\n            \"has_absolute_url\": False,\n            \"opts\": self.opts,\n            \"original\": flag,\n            \"save_as\": False,\n            \"show_save\": True,\n            **self.admin_site.each_context(version),\n        }\n\n        version.current_app = self.admin_site.name\n\n        return TemplateResponse(\n            version,\n            self.change_user_password_template\n            or \"admin/auth/user/change_password.html\",\n            history,\n        )\n\n    def parseMessage(self, history, key, primaryMessage=None):\n        \"\"\"\n        Determine the HttpResponse for the add_view stage. It mostly defers to\n        its superclass implementation but is customized because the User model\n        has a slightly different workflow.\n        \"\"\"\n        # We should allow further modification of the user just added i.e. the\n        # 'Save' button should behave like the 'Save and continue editing'\n        # button except in two scenarios:\n        # * The user has pressed the 'Save and add another' button\n        # * We are adding a user in a popup\n        if \"_addanother\" not in history.POST and IS_POPUP_VAR not in history.POST:\n            history.POST = history.POST.copy()\n            history.POST[\"_continue\"] = 1\n        return super().response_add(history, key, primaryMessage)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-7a41dc90ea2ce214", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "df2912e5685a7fdcb9ab748b2841c87731465d23390b911600e9078afd5f3d8d", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 235, "local_path": "identifiers/mislead-identifiers/I03__django__UserAdmin__a98abee7.py", "order": 3, "original_content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "parent_variant_id": "pyint-923035fd1ea3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/admin.py#L41-L251", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 134, "identifiers_declared": 40, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 29, "local_random_pool_selections": 32, "local_total_length_difference": 6, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 7, "method_random_pool_selections": 8, "method_total_length_difference": 5}, "unit_kind": "class", "unit_name": "UserAdmin", "variant_id": "pyint-a3d2a98abee7-I03", "group_id": "py-7a41dc90ea2ce214", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 32, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-93dc4ffa5832-I04", "source": "from django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.admin.utils import unquote\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import (\n    AdminPasswordChangeForm,\n    AdminUserCreationForm,\n    UserChangeForm,\n)\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\n\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n    add_form_template = \"admin/auth/user/add_form.html\"\n    change_user_password_template = None\n    fieldsets = (\n        (None, {\"fields\": (\"username\", \"password\")}),\n        (_(\"Personal info\"), {\"fields\": (\"first_name\", \"last_name\", \"email\")}),\n        (\n            _(\"Permissions\"),\n            {\n                \"fields\": (\n                    \"is_active\",\n                    \"is_staff\",\n                    \"is_superuser\",\n                    \"groups\",\n                    \"user_permissions\",\n                ),\n            },\n        ),\n        (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),\n    )\n    add_fieldsets = (\n        (\n            None,\n            {\n                \"classes\": (\"wide\",),\n                \"fields\": (\"username\", \"usable_password\", \"password1\", \"password2\"),\n            },\n        ),\n    )\n    form = UserChangeForm\n    add_form = AdminUserCreationForm\n    change_password_form = AdminPasswordChangeForm\n    list_display = (\"username\", \"email\", \"first_name\", \"last_name\", \"is_staff\")\n    list_filter = (\"is_staff\", \"is_superuser\", \"is_active\", \"groups\")\n    search_fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n    ordering = (\"username\",)\n    filter_horizontal = (\n        \"groups\",\n        \"user_permissions\",\n    )\n\n    def a(self, i, j=None):\n        if not j:\n            return self.add_fieldsets\n        return super().get_fieldsets(i, j)\n\n    def b(self, k, l=None, **m):\n        \"\"\"\n        Use special form during user creation\n        \"\"\"\n        n = {}\n        if l is None:\n            n[\"form\"] = self.add_form\n        n.update(m)\n        return super().get_form(k, l, **n)\n\n    def c(self):\n        return [\n            path(\n                \"<id>/password/\",\n                self.admin_site.admin_view(self.g),\n                name=\"auth_user_password_change\",\n            ),\n            *super().get_urls(),\n        ]\n\n    def d(self, o, p, q):\n        # Don't allow lookups involving passwords.\n        return not o.startswith(\"password\") and super().lookup_allowed(\n            o, p, q\n        )\n\n    @method_decorator([sensitive_post_parameters(), csrf_protect])\n    def e(self, r, s=\"\", t=None):\n        if r.method in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            return self.f(r, s, t)\n\n        with transaction.atomic(using=router.db_for_write(self.model)):\n            return self.f(r, s, t)\n\n    def f(self, u, v=\"\", w=None):\n        # It's an error for a user to have add permission but NOT change\n        # permission for users. If we allowed such users to add users, they\n        # could create superusers, which would mean they would essentially have\n        # the permission to change users. To avoid the problem entirely, we\n        # disallow users from adding users if they don't have change\n        # permission.\n        if not self.has_change_permission(u):\n            if self.has_add_permission(u) and settings.DEBUG:\n                # Raise Http404 in debug mode so that the user gets a helpful\n                # error message.\n                raise Http404(\n                    'Your user does not have the \"Change user\" permission. In '\n                    \"order to add users, Django requires that your user \"\n                    'account have both the \"Add user\" and \"Change user\" '\n                    \"permissions set.\"\n                )\n            raise PermissionDenied\n        if w is None:\n            w = {}\n        x = self.opts.get_field(self.model.USERNAME_FIELD)\n        y = {\n            \"auto_populated_fields\": (),\n            \"username_help_text\": x.help_text,\n        }\n        w.update(y)\n        return super().add_view(u, v, w)\n\n    @method_decorator(sensitive_post_parameters())\n    def g(self, z, A, B=\"\"):\n        C = self.get_object(z, unquote(A))\n        if not self.has_change_permission(z, C):\n            raise PermissionDenied\n        if C is None:\n            raise Http404(\n                _(\"%(name)s object with primary key %(key)r does not exist.\")\n                % {\n                    \"name\": self.opts.verbose_name,\n                    \"key\": escape(A),\n                }\n            )\n        if z.method == \"POST\":\n            D = self.change_password_form(C, z.POST)\n            if D.is_valid():\n                # If disabling password-based authentication was requested\n                # (via the form field `usable_password`), the submit action\n                # must be \"unset-password\". This check is most relevant when\n                # the admin user has two submit buttons available (for example\n                # when Javascript is disabled).\n                E = (\n                    D.cleaned_data[\"set_usable_password\"]\n                    or \"unset-password\" in z.POST\n                )\n                if not E:\n                    F = gettext(\"Conflicting form data submitted. Please try again.\")\n                    messages.error(z, F)\n                    return HttpResponseRedirect(z.get_full_path())\n\n                C = D.save()\n                G = self.construct_change_message(z, D, None)\n                self.log_change(z, C, G)\n                if C.has_usable_password():\n                    F = gettext(\"Password changed successfully.\")\n                else:\n                    F = gettext(\"Password-based authentication was disabled.\")\n                messages.success(z, F)\n                update_session_auth_hash(z, D.user)\n                return HttpResponseRedirect(\n                    reverse(\n                        \"%s:%s_%s_change\"\n                        % (\n                            self.admin_site.name,\n                            C._meta.app_label,\n                            C._meta.model_name,\n                        ),\n                        args=(C.pk,),\n                    )\n                )\n        else:\n            D = self.change_password_form(C)\n\n        H = [(None, {\"fields\": list(D.base_fields)})]\n        I = admin.helpers.AdminForm(D, H, {})\n\n        if C.has_usable_password():\n            J = _(\"Change password: %s\")\n        else:\n            J = _(\"Set password: %s\")\n        K = {\n            \"title\": J % escape(C.get_username()),\n            \"adminForm\": I,\n            \"form_url\": B,\n            \"form\": D,\n            \"is_popup\": (IS_POPUP_VAR in z.POST or IS_POPUP_VAR in z.GET),\n            \"is_popup_var\": IS_POPUP_VAR,\n            \"add\": True,\n            \"change\": False,\n            \"has_delete_permission\": False,\n            \"has_change_permission\": True,\n            \"has_absolute_url\": False,\n            \"opts\": self.opts,\n            \"original\": C,\n            \"save_as\": False,\n            \"show_save\": True,\n            **self.admin_site.each_context(z),\n        }\n\n        z.current_app = self.admin_site.name\n\n        return TemplateResponse(\n            z,\n            self.change_user_password_template\n            or \"admin/auth/user/change_password.html\",\n            K,\n        )\n\n    def h(self, L, M, N=None):\n        \"\"\"\n        Determine the HttpResponse for the add_view stage. It mostly defers to\n        its superclass implementation but is customized because the User model\n        has a slightly different workflow.\n        \"\"\"\n        # We should allow further modification of the user just added i.e. the\n        # 'Save' button should behave like the 'Save and continue editing'\n        # button except in two scenarios:\n        # * The user has pressed the 'Save and add another' button\n        # * We are adding a user in a popup\n        if \"_addanother\" not in L.POST and IS_POPUP_VAR not in L.POST:\n            L.POST = L.POST.copy()\n            L.POST[\"_continue\"] = 1\n        return super().response_add(L, M, N)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-7a41dc90ea2ce214", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "078f43231f1d1c74535ebdb4750ad4671280f2cb7199e6101a0ef48cf5bf9403", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 235, "local_path": "identifiers/garble-identifiers/I04__django__UserAdmin__4ffa5832.py", "order": 4, "original_content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "parent_variant_id": "pyint-923035fd1ea3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/admin.py#L41-L251", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 134, "identifiers_declared": 40}, "unit_kind": "class", "unit_name": "UserAdmin", "variant_id": "pyint-93dc4ffa5832-I04", "group_id": "py-7a41dc90ea2ce214", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 33, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-561b224b7b45-I05", "source": "from django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.admin.utils import unquote\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import (\n    AdminPasswordChangeForm,\n    AdminUserCreationForm,\n    UserChangeForm,\n)\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\n\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n    add_form_template = \"admin/auth/user/add_form.html\"\n    change_user_password_template = None\n    fieldsets = (\n        (None, {\"fields\": (\"username\", \"password\")}),\n        (_(\"Personal info\"), {\"fields\": (\"first_name\", \"last_name\", \"email\")}),\n        (\n            _(\"Permissions\"),\n            {\n                \"fields\": (\n                    \"is_active\",\n                    \"is_staff\",\n                    \"is_superuser\",\n                    \"groups\",\n                    \"user_permissions\",\n                ),\n            },\n        ),\n        (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),\n    )\n    add_fieldsets = (\n        (\n            None,\n            {\n                \"classes\": (\"wide\",),\n                \"fields\": (\"username\", \"usable_password\", \"password1\", \"password2\"),\n            },\n        ),\n    )\n    form = UserChangeForm\n    add_form = AdminUserCreationForm\n    change_password_form = AdminPasswordChangeForm\n    list_display = (\"username\", \"email\", \"first_name\", \"last_name\", \"is_staff\")\n    list_filter = (\"is_staff\", \"is_superuser\", \"is_active\", \"groups\")\n    search_fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n    ordering = (\"username\",)\n    filter_horizontal = (\n        \"groups\",\n        \"user_permissions\",\n    )\n\n    def get_fieldsets(self, request, obj=None):\n        if not obj:\n            return self.add_fieldsets\n        return super().get_fieldsets(request, obj)\n\n    def get_form(self, request, obj=None, **kwargs):\n        \"\"\"\n        Use special form during user creation\n        \"\"\"\n        defaults = {}\n        if obj is None:\n            defaults[\"form\"] = self.add_form\n        defaults.update(kwargs)\n        return super().get_form(request, obj, **defaults)\n\n    def get_urls(self):\n        return [\n            path(\n                \"<id>/password/\",\n                self.admin_site.admin_view(self.user_change_password),\n                name=\"auth_user_password_change\",\n            ),\n            *super().get_urls(),\n        ]\n\n    def lookup_allowed(self, lookup, value, request):\n        # Don't allow lookups involving passwords.\n        return not lookup.startswith(\"password\") and super().lookup_allowed(\n            lookup, value, request\n        )\n\n    @method_decorator([sensitive_post_parameters(), csrf_protect])\n    def add_view(self, request, form_url=\"\", extra_context=None):\n        if request.method in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            return self._add_view(request, form_url, extra_context)\n\n        with transaction.atomic(using=router.db_for_write(self.model)):\n            return self._add_view(request, form_url, extra_context)\n\n    def _add_view(self, request, form_url=\"\", extra_context=None):\n        # It's an error for a user to have add permission but NOT change\n        # permission for users. If we allowed such users to add users, they\n        # could create superusers, which would mean they would essentially have\n        # the permission to change users. To avoid the problem entirely, we\n        # disallow users from adding users if they don't have change\n        # permission.\n        if not self.has_change_permission(request):\n            if self.has_add_permission(request) and settings.DEBUG:\n                # Raise Http404 in debug mode so that the user gets a helpful\n                # error message.\n                raise Http404(\n                    'Your user does not have the \"Change user\" permission. In '\n                    \"order to add users, Django requires that your user \"\n                    'account have both the \"Add user\" and \"Change user\" '\n                    \"permissions set.\"\n                )\n            raise PermissionDenied\n        if extra_context is None:\n            extra_context = {}\n        username_field = self.opts.get_field(self.model.USERNAME_FIELD)\n        defaults = {\n            \"auto_populated_fields\": (),\n            \"username_help_text\": username_field.help_text,\n        }\n        extra_context.update(defaults)\n        return super().add_view(request, form_url, extra_context)\n\n    @method_decorator(sensitive_post_parameters())\n    def user_change_password(self, request, id, form_url=\"\"):\n        user = self.get_object(request, unquote(id))\n        if not self.has_change_permission(request, user):\n            raise PermissionDenied\n        if user is None:\n            raise Http404(\n                _(\"%(name)s object with primary key %(key)r does not exist.\")\n                % {\n                    \"name\": self.opts.verbose_name,\n                    \"key\": escape(id),\n                }\n            )\n        if request.method == \"POST\":\n            form = self.change_password_form(user, request.POST)\n            if form.is_valid():\n                # If disabling password-based authentication was requested\n                # (via the form field `usable_password`), the submit action\n                # must be \"unset-password\". This check is most relevant when\n                # the admin user has two submit buttons available (for example\n                # when Javascript is disabled).\n                valid_submission = (\n                    form.cleaned_data[\"set_usable_password\"]\n                    or \"unset-password\" in request.POST\n                )\n                if not valid_submission:\n                    msg = gettext(\"Conflicting form data submitted. Please try again.\")\n                    messages.error(request, msg)\n                    return HttpResponseRedirect(request.get_full_path())\n\n                user = form.save()\n                change_message = self.construct_change_message(request, form, None)\n                self.log_change(request, user, change_message)\n                if user.has_usable_password():\n                    msg = gettext(\"Password changed successfully.\")\n                else:\n                    msg = gettext(\"Password-based authentication was disabled.\")\n                messages.success(request, msg)\n                update_session_auth_hash(request, form.user)\n                return HttpResponseRedirect(\n                    reverse(\n                        \"%s:%s_%s_change\"\n                        % (\n                            self.admin_site.name,\n                            user._meta.app_label,\n                            user._meta.model_name,\n                        ),\n                        args=(user.pk,),\n                    )\n                )\n        else:\n            form = self.change_password_form(user)\n\n        fieldsets = [(None, {\"fields\": list(form.base_fields)})]\n        admin_form = admin.helpers.AdminForm(form, fieldsets, {})\n\n        if user.has_usable_password():\n            title = _(\"Change password: %s\")\n        else:\n            title = _(\"Set password: %s\")\n        context = {\n            \"title\": title % escape(user.get_username()),\n            \"adminForm\": admin_form,\n            \"form_url\": form_url,\n            \"form\": form,\n            \"is_popup\": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),\n            \"is_popup_var\": IS_POPUP_VAR,\n            \"add\": True,\n            \"change\": False,\n            \"has_delete_permission\": False,\n            \"has_change_permission\": True,\n            \"has_absolute_url\": False,\n            \"opts\": self.opts,\n            \"original\": user,\n            \"save_as\": False,\n            \"show_save\": True,\n            **self.admin_site.each_context(request),\n        }\n\n        request.current_app = self.admin_site.name\n\n        return TemplateResponse(\n            request,\n            self.change_user_password_template\n            or \"admin/auth/user/change_password.html\",\n            context,\n        )\n\n    def response_add(self, request, obj, post_url_continue=None):\n        \"\"\"\n        Determine the HttpResponse for the add_view stage. It mostly defers to\n        its superclass implementation but is customized because the User model\n        has a slightly different workflow.\n        \"\"\"\n        # We should allow further modification of the user just added i.e. the\n        # 'Save' button should behave like the 'Save and continue editing'\n        # button except in two scenarios:\n        # * The user has pressed the 'Save and add another' button\n        # * We are adding a user in a popup\n        if \"_addanother\" not in request.POST and IS_POPUP_VAR not in request.POST:\n            request.POST = request.POST.copy()\n            request.POST[\"_continue\"] = 0x1\n        return super().response_add(request, obj, post_url_continue)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-7a41dc90ea2ce214", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "ff726a4cc111602ef7e7e67d3fb0f978a998a1f4dfb27f1923fe1cb28aa5f1a7", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 235, "local_path": "expressions/encode-integer-literals/I05__django__UserAdmin__224b7b45.py", "order": 5, "original_content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "parent_variant_id": "pyint-923035fd1ea3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/admin.py#L41-L251", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 1}, "unit_kind": "class", "unit_name": "UserAdmin", "variant_id": "pyint-561b224b7b45-I05", "group_id": "py-7a41dc90ea2ce214", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 34, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1ea4cfdb4061-I06", "source": "from django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.admin.utils import unquote\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import (\n    AdminPasswordChangeForm,\n    AdminUserCreationForm,\n    UserChangeForm,\n)\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\n\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n    add_form_template = \"admin/auth/user/add_form.html\"\n    change_user_password_template = None\n    fieldsets = (\n        (None, {\"fields\": (\"username\", \"password\")}),\n        (_(\"Personal info\"), {\"fields\": (\"first_name\", \"last_name\", \"email\")}),\n        (\n            _(\"Permissions\"),\n            {\n                \"fields\": (\n                    \"is_active\",\n                    \"is_staff\",\n                    \"is_superuser\",\n                    \"groups\",\n                    \"user_permissions\",\n                ),\n            },\n        ),\n        (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),\n    )\n    add_fieldsets = (\n        (\n            None,\n            {\n                \"classes\": (\"wide\",),\n                \"fields\": (\"username\", \"usable_password\", \"password1\", \"password2\"),\n            },\n        ),\n    )\n    form = UserChangeForm\n    add_form = AdminUserCreationForm\n    change_password_form = AdminPasswordChangeForm\n    list_display = (\"username\", \"email\", \"first_name\", \"last_name\", \"is_staff\")\n    list_filter = (\"is_staff\", \"is_superuser\", \"is_active\", \"groups\")\n    search_fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n    ordering = (\"username\",)\n    filter_horizontal = (\n        \"groups\",\n        \"user_permissions\",\n    )\n\n    def get_fieldsets(self, request, obj=None):\n        if not (not obj):\n            pass\n        else:\n            return self.add_fieldsets\n        return super().get_fieldsets(request, obj)\n\n    def get_form(self, request, obj=None, **kwargs):\n        \"\"\"\n        Use special form during user creation\n        \"\"\"\n        defaults = {}\n        if not (obj is None):\n            pass\n        else:\n            defaults[\"form\"] = self.add_form\n        defaults.update(kwargs)\n        return super().get_form(request, obj, **defaults)\n\n    def get_urls(self):\n        return [\n            path(\n                \"<id>/password/\",\n                self.admin_site.admin_view(self.user_change_password),\n                name=\"auth_user_password_change\",\n            ),\n            *super().get_urls(),\n        ]\n\n    def lookup_allowed(self, lookup, value, request):\n        # Don't allow lookups involving passwords.\n        return not lookup.startswith(\"password\") and super().lookup_allowed(\n            lookup, value, request\n        )\n\n    @method_decorator([sensitive_post_parameters(), csrf_protect])\n    def add_view(self, request, form_url=\"\", extra_context=None):\n        if not (request.method in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\")):\n            pass\n        else:\n            return self._add_view(request, form_url, extra_context)\n\n        with transaction.atomic(using=router.db_for_write(self.model)):\n            return self._add_view(request, form_url, extra_context)\n\n    def _add_view(self, request, form_url=\"\", extra_context=None):\n        # It's an error for a user to have add permission but NOT change\n        # permission for users. If we allowed such users to add users, they\n        # could create superusers, which would mean they would essentially have\n        # the permission to change users. To avoid the problem entirely, we\n        # disallow users from adding users if they don't have change\n        # permission.\n        if not (not self.has_change_permission(request)):\n            pass\n        else:\n            if self.has_add_permission(request) and settings.DEBUG:\n                # Raise Http404 in debug mode so that the user gets a helpful\n                # error message.\n                raise Http404(\n                    'Your user does not have the \"Change user\" permission. In '\n                    \"order to add users, Django requires that your user \"\n                    'account have both the \"Add user\" and \"Change user\" '\n                    \"permissions set.\"\n                )\n            raise PermissionDenied\n        if not (extra_context is None):\n            pass\n        else:\n            extra_context = {}\n        username_field = self.opts.get_field(self.model.USERNAME_FIELD)\n        defaults = {\n            \"auto_populated_fields\": (),\n            \"username_help_text\": username_field.help_text,\n        }\n        extra_context.update(defaults)\n        return super().add_view(request, form_url, extra_context)\n\n    @method_decorator(sensitive_post_parameters())\n    def user_change_password(self, request, id, form_url=\"\"):\n        user = self.get_object(request, unquote(id))\n        if not (not self.has_change_permission(request, user)):\n            pass\n        else:\n            raise PermissionDenied\n        if not (user is None):\n            pass\n        else:\n            raise Http404(\n                _(\"%(name)s object with primary key %(key)r does not exist.\")\n                % {\n                    \"name\": self.opts.verbose_name,\n                    \"key\": escape(id),\n                }\n            )\n        if not (request.method == \"POST\"):\n            form = self.change_password_form(user)\n        else:\n            form = self.change_password_form(user, request.POST)\n            if form.is_valid():\n                # If disabling password-based authentication was requested\n                # (via the form field `usable_password`), the submit action\n                # must be \"unset-password\". This check is most relevant when\n                # the admin user has two submit buttons available (for example\n                # when Javascript is disabled).\n                valid_submission = (\n                    form.cleaned_data[\"set_usable_password\"]\n                    or \"unset-password\" in request.POST\n                )\n                if not valid_submission:\n                    msg = gettext(\"Conflicting form data submitted. Please try again.\")\n                    messages.error(request, msg)\n                    return HttpResponseRedirect(request.get_full_path())\n\n                user = form.save()\n                change_message = self.construct_change_message(request, form, None)\n                self.log_change(request, user, change_message)\n                if user.has_usable_password():\n                    msg = gettext(\"Password changed successfully.\")\n                else:\n                    msg = gettext(\"Password-based authentication was disabled.\")\n                messages.success(request, msg)\n                update_session_auth_hash(request, form.user)\n                return HttpResponseRedirect(\n                    reverse(\n                        \"%s:%s_%s_change\"\n                        % (\n                            self.admin_site.name,\n                            user._meta.app_label,\n                            user._meta.model_name,\n                        ),\n                        args=(user.pk,),\n                    )\n                )\n\n        fieldsets = [(None, {\"fields\": list(form.base_fields)})]\n        admin_form = admin.helpers.AdminForm(form, fieldsets, {})\n\n        if not (user.has_usable_password()):\n            title = _(\"Set password: %s\")\n        else:\n            title = _(\"Change password: %s\")\n        context = {\n            \"title\": title % escape(user.get_username()),\n            \"adminForm\": admin_form,\n            \"form_url\": form_url,\n            \"form\": form,\n            \"is_popup\": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),\n            \"is_popup_var\": IS_POPUP_VAR,\n            \"add\": True,\n            \"change\": False,\n            \"has_delete_permission\": False,\n            \"has_change_permission\": True,\n            \"has_absolute_url\": False,\n            \"opts\": self.opts,\n            \"original\": user,\n            \"save_as\": False,\n            \"show_save\": True,\n            **self.admin_site.each_context(request),\n        }\n\n        request.current_app = self.admin_site.name\n\n        return TemplateResponse(\n            request,\n            self.change_user_password_template\n            or \"admin/auth/user/change_password.html\",\n            context,\n        )\n\n    def response_add(self, request, obj, post_url_continue=None):\n        \"\"\"\n        Determine the HttpResponse for the add_view stage. It mostly defers to\n        its superclass implementation but is customized because the User model\n        has a slightly different workflow.\n        \"\"\"\n        # We should allow further modification of the user just added i.e. the\n        # 'Save' button should behave like the 'Save and continue editing'\n        # button except in two scenarios:\n        # * The user has pressed the 'Save and add another' button\n        # * We are adding a user in a popup\n        if not (\"_addanother\" not in request.POST and IS_POPUP_VAR not in request.POST):\n            pass\n        else:\n            request.POST = request.POST.copy()\n            request.POST[\"_continue\"] = 1\n        return super().response_add(request, obj, post_url_continue)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-7a41dc90ea2ce214", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "b605fb472d2a909907a4227332d7171acccdfefeb9f712feca2c1e93a9b6f5c8", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 251, "local_path": "expressions/invert-conditions/I06__django__UserAdmin__cfdb4061.py", "order": 6, "original_content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "parent_variant_id": "pyint-923035fd1ea3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/admin.py#L41-L251", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 10}, "unit_kind": "class", "unit_name": "UserAdmin", "variant_id": "pyint-1ea4cfdb4061-I06", "group_id": "py-7a41dc90ea2ce214", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 35, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-acd99b1ddd73-I07", "source": "from django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.admin.utils import unquote\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import (\n    AdminPasswordChangeForm,\n    AdminUserCreationForm,\n    UserChangeForm,\n)\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\n\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n    add_form_template = \"admin/auth/user/add_form.html\"\n    change_user_password_template = None\n    fieldsets = (\n        (None, {\"fields\": (\"username\", \"password\")}),\n        (_(\"Personal info\"), {\"fields\": (\"first_name\", \"last_name\", \"email\")}),\n        (\n            _(\"Permissions\"),\n            {\n                \"fields\": (\n                    \"is_active\",\n                    \"is_staff\",\n                    \"is_superuser\",\n                    \"groups\",\n                    \"user_permissions\",\n                ),\n            },\n        ),\n        (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),\n    )\n    add_fieldsets = (\n        (\n            None,\n            {\n                \"classes\": (\"wide\",),\n                \"fields\": (\"username\", \"usable_password\", \"password1\", \"password2\"),\n            },\n        ),\n    )\n    form = UserChangeForm\n    add_form = AdminUserCreationForm\n    change_password_form = AdminPasswordChangeForm\n    list_display = (\"username\", \"email\", \"first_name\", \"last_name\", \"is_staff\")\n    list_filter = (\"is_staff\", \"is_superuser\", \"is_active\", \"groups\")\n    search_fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n    ordering = (\"username\",)\n    filter_horizontal = (\n        \"groups\",\n        \"user_permissions\",\n    )\n\n    def get_fieldsets(self, request, obj=None):\n        if ((0xb3f2 ^ 0xb3f2) != 0):\n            raise AssertionError()\n        if not obj:\n            return self.add_fieldsets\n        return super().get_fieldsets(request, obj)\n\n    def get_form(self, request, obj=None, **kwargs):\n        \"\"\"\n        Use special form during user creation\n        \"\"\"\n        if ((0x6985 ^ 0x6985) != 0):\n            raise AssertionError()\n        defaults = {}\n        if obj is None:\n            defaults[\"form\"] = self.add_form\n        defaults.update(kwargs)\n        return super().get_form(request, obj, **defaults)\n\n    def get_urls(self):\n        if ((0xc58 ^ 0xc58) != 0):\n            raise AssertionError()\n        return [\n            path(\n                \"<id>/password/\",\n                self.admin_site.admin_view(self.user_change_password),\n                name=\"auth_user_password_change\",\n            ),\n            *super().get_urls(),\n        ]\n\n    def lookup_allowed(self, lookup, value, request):\n        # Don't allow lookups involving passwords.\n        if ((0x3d7a ^ 0x3d7a) != 0):\n            raise AssertionError()\n        return not lookup.startswith(\"password\") and super().lookup_allowed(\n            lookup, value, request\n        )\n\n    @method_decorator([sensitive_post_parameters(), csrf_protect])\n    def add_view(self, request, form_url=\"\", extra_context=None):\n        if ((0xdd5d ^ 0xdd5d) != 0):\n            raise AssertionError()\n        if request.method in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            return self._add_view(request, form_url, extra_context)\n\n        with transaction.atomic(using=router.db_for_write(self.model)):\n            return self._add_view(request, form_url, extra_context)\n\n    def _add_view(self, request, form_url=\"\", extra_context=None):\n        # It's an error for a user to have add permission but NOT change\n        # permission for users. If we allowed such users to add users, they\n        # could create superusers, which would mean they would essentially have\n        # the permission to change users. To avoid the problem entirely, we\n        # disallow users from adding users if they don't have change\n        # permission.\n        if ((0xae06 ^ 0xae06) != 0):\n            raise AssertionError()\n        if not self.has_change_permission(request):\n            if self.has_add_permission(request) and settings.DEBUG:\n                # Raise Http404 in debug mode so that the user gets a helpful\n                # error message.\n                raise Http404(\n                    'Your user does not have the \"Change user\" permission. In '\n                    \"order to add users, Django requires that your user \"\n                    'account have both the \"Add user\" and \"Change user\" '\n                    \"permissions set.\"\n                )\n            raise PermissionDenied\n        if extra_context is None:\n            extra_context = {}\n        username_field = self.opts.get_field(self.model.USERNAME_FIELD)\n        defaults = {\n            \"auto_populated_fields\": (),\n            \"username_help_text\": username_field.help_text,\n        }\n        extra_context.update(defaults)\n        return super().add_view(request, form_url, extra_context)\n\n    @method_decorator(sensitive_post_parameters())\n    def user_change_password(self, request, id, form_url=\"\"):\n        if ((0x6122 ^ 0x6122) != 0):\n            raise AssertionError()\n        user = self.get_object(request, unquote(id))\n        if not self.has_change_permission(request, user):\n            raise PermissionDenied\n        if user is None:\n            raise Http404(\n                _(\"%(name)s object with primary key %(key)r does not exist.\")\n                % {\n                    \"name\": self.opts.verbose_name,\n                    \"key\": escape(id),\n                }\n            )\n        if request.method == \"POST\":\n            form = self.change_password_form(user, request.POST)\n            if form.is_valid():\n                # If disabling password-based authentication was requested\n                # (via the form field `usable_password`), the submit action\n                # must be \"unset-password\". This check is most relevant when\n                # the admin user has two submit buttons available (for example\n                # when Javascript is disabled).\n                valid_submission = (\n                    form.cleaned_data[\"set_usable_password\"]\n                    or \"unset-password\" in request.POST\n                )\n                if not valid_submission:\n                    msg = gettext(\"Conflicting form data submitted. Please try again.\")\n                    messages.error(request, msg)\n                    return HttpResponseRedirect(request.get_full_path())\n\n                user = form.save()\n                change_message = self.construct_change_message(request, form, None)\n                self.log_change(request, user, change_message)\n                if user.has_usable_password():\n                    msg = gettext(\"Password changed successfully.\")\n                else:\n                    msg = gettext(\"Password-based authentication was disabled.\")\n                messages.success(request, msg)\n                update_session_auth_hash(request, form.user)\n                return HttpResponseRedirect(\n                    reverse(\n                        \"%s:%s_%s_change\"\n                        % (\n                            self.admin_site.name,\n                            user._meta.app_label,\n                            user._meta.model_name,\n                        ),\n                        args=(user.pk,),\n                    )\n                )\n        else:\n            form = self.change_password_form(user)\n\n        fieldsets = [(None, {\"fields\": list(form.base_fields)})]\n        admin_form = admin.helpers.AdminForm(form, fieldsets, {})\n\n        if user.has_usable_password():\n            title = _(\"Change password: %s\")\n        else:\n            title = _(\"Set password: %s\")\n        context = {\n            \"title\": title % escape(user.get_username()),\n            \"adminForm\": admin_form,\n            \"form_url\": form_url,\n            \"form\": form,\n            \"is_popup\": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),\n            \"is_popup_var\": IS_POPUP_VAR,\n            \"add\": True,\n            \"change\": False,\n            \"has_delete_permission\": False,\n            \"has_change_permission\": True,\n            \"has_absolute_url\": False,\n            \"opts\": self.opts,\n            \"original\": user,\n            \"save_as\": False,\n            \"show_save\": True,\n            **self.admin_site.each_context(request),\n        }\n\n        request.current_app = self.admin_site.name\n\n        return TemplateResponse(\n            request,\n            self.change_user_password_template\n            or \"admin/auth/user/change_password.html\",\n            context,\n        )\n\n    def response_add(self, request, obj, post_url_continue=None):\n        \"\"\"\n        Determine the HttpResponse for the add_view stage. It mostly defers to\n        its superclass implementation but is customized because the User model\n        has a slightly different workflow.\n        \"\"\"\n        if ((0xb0d8 ^ 0xb0d8) != 0):\n            raise AssertionError()\n        # We should allow further modification of the user just added i.e. the\n        # 'Save' button should behave like the 'Save and continue editing'\n        # button except in two scenarios:\n        # * The user has pressed the 'Save and add another' button\n        # * We are adding a user in a popup\n        if \"_addanother\" not in request.POST and IS_POPUP_VAR not in request.POST:\n            request.POST = request.POST.copy()\n            request.POST[\"_continue\"] = 1\n        return super().response_add(request, obj, post_url_continue)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-7a41dc90ea2ce214", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "c56b761d5e9df7dd839c0054c0694fe7ca2e78705fd88bccdf42b0d8be80084a", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 251, "local_path": "code-injection/insert-dead-branches/I07__django__UserAdmin__9b1ddd73.py", "order": 7, "original_content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "parent_variant_id": "pyint-923035fd1ea3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/admin.py#L41-L251", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 8}, "unit_kind": "class", "unit_name": "UserAdmin", "variant_id": "pyint-acd99b1ddd73-I07", "group_id": "py-7a41dc90ea2ce214", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 36, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d2733649af65-I08", "source": "from django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.admin.utils import unquote\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import (\n    AdminPasswordChangeForm,\n    AdminUserCreationForm,\n    UserChangeForm,\n)\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\n\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n    add_form_template = \"admin/auth/user/add_form.html\"\n    change_user_password_template = None\n    fieldsets = (\n        (None, {\"fields\": (\"username\", \"password\")}),\n        (_(\"Personal info\"), {\"fields\": (\"first_name\", \"last_name\", \"email\")}),\n        (\n            _(\"Permissions\"),\n            {\n                \"fields\": (\n                    \"is_active\",\n                    \"is_staff\",\n                    \"is_superuser\",\n                    \"groups\",\n                    \"user_permissions\",\n                ),\n            },\n        ),\n        (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),\n    )\n    add_fieldsets = (\n        (\n            None,\n            {\n                \"classes\": (\"wide\",),\n                \"fields\": (\"username\", \"usable_password\", \"password1\", \"password2\"),\n            },\n        ),\n    )\n    form = UserChangeForm\n    add_form = AdminUserCreationForm\n    change_password_form = AdminPasswordChangeForm\n    list_display = (\"username\", \"email\", \"first_name\", \"last_name\", \"is_staff\")\n    list_filter = (\"is_staff\", \"is_superuser\", \"is_active\", \"groups\")\n    search_fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n    ordering = (\"username\",)\n    filter_horizontal = (\n        \"groups\",\n        \"user_permissions\",\n    )\n\n    def get_fieldsets(self, request, obj=None):\n        if not obj:\n            return self.add_fieldsets\n        return super().get_fieldsets(request, obj)\n\n    def get_form(self, request, obj=None, **kwargs):\n        \"\"\"\n        Use special form during user creation\n        \"\"\"\n        defaults = {}\n        if obj is None:\n            defaults[\"form\"] = self.add_form\n        defaults.update(kwargs)\n        return super().get_form(request, obj, **defaults)\n\n    def get_urls(self):\n        return [\n            path(\n                \"<id>/password/\",\n                self.admin_site.admin_view(self.user_change_password),\n                name=\"auth_user_password_change\",\n            ),\n            *super().get_urls(),\n        ]\n\n    def lookup_allowed(self, lookup, value, request):\n        # Don't allow lookups involving passwords.\n        return not lookup.startswith(\"password\") and super().lookup_allowed(\n            lookup, value, request\n        )\n\n    @method_decorator([sensitive_post_parameters(), csrf_protect])\n    def add_view(self, request, form_url=\"\", extra_context=None):\n        if request.method in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            return self._add_view(request, form_url, extra_context)\n\n        with transaction.atomic(using=router.db_for_write(self.model)):\n            return self._add_view(request, form_url, extra_context)\n\n    def _add_view(self, request, form_url=\"\", extra_context=None):\n        # It's an error for a user to have add permission but NOT change\n        # permission for users. If we allowed such users to add users, they\n        # could create superusers, which would mean they would essentially have\n        # the permission to change users. To avoid the problem entirely, we\n        # disallow users from adding users if they don't have change\n        # permission.\n        if not self.has_change_permission(request):\n            if self.has_add_permission(request) and settings.DEBUG:\n                # Raise Http404 in debug mode so that the user gets a helpful\n                # error message.\n                raise Http404(\n                    'Your user does not have the \"Change user\" permission. In '\n                    \"order to add users, Django requires that your user \"\n                    'account have both the \"Add user\" and \"Change user\" '\n                    \"permissions set.\"\n                )\n            raise PermissionDenied\n        if extra_context is None:\n            extra_context = {}\n        username_field = self.opts.get_field(self.model.USERNAME_FIELD)\n        defaults = {\n            \"auto_populated_fields\": (),\n            \"username_help_text\": username_field.help_text,\n        }\n        extra_context.update(defaults)\n        return super().add_view(request, form_url, extra_context)\n\n    @method_decorator(sensitive_post_parameters())\n    def user_change_password(self, request, id, form_url=\"\"):\n        feature_enabled = False\n        for toggle_count in range(3):\n            feature_enabled = not feature_enabled\n        user = self.get_object(request, unquote(id))\n        if not self.has_change_permission(request, user):\n            raise PermissionDenied\n        if user is None:\n            raise Http404(\n                _(\"%(name)s object with primary key %(key)r does not exist.\")\n                % {\n                    \"name\": self.opts.verbose_name,\n                    \"key\": escape(id),\n                }\n            )\n        if request.method == \"POST\":\n            form = self.change_password_form(user, request.POST)\n            if form.is_valid():\n                # If disabling password-based authentication was requested\n                # (via the form field `usable_password`), the submit action\n                # must be \"unset-password\". This check is most relevant when\n                # the admin user has two submit buttons available (for example\n                # when Javascript is disabled).\n                valid_submission = (\n                    form.cleaned_data[\"set_usable_password\"]\n                    or \"unset-password\" in request.POST\n                )\n                if not valid_submission:\n                    msg = gettext(\"Conflicting form data submitted. Please try again.\")\n                    messages.error(request, msg)\n                    return HttpResponseRedirect(request.get_full_path())\n\n                user = form.save()\n                change_message = self.construct_change_message(request, form, None)\n                self.log_change(request, user, change_message)\n                if user.has_usable_password():\n                    msg = gettext(\"Password changed successfully.\")\n                else:\n                    msg = gettext(\"Password-based authentication was disabled.\")\n                messages.success(request, msg)\n                update_session_auth_hash(request, form.user)\n                return HttpResponseRedirect(\n                    reverse(\n                        \"%s:%s_%s_change\"\n                        % (\n                            self.admin_site.name,\n                            user._meta.app_label,\n                            user._meta.model_name,\n                        ),\n                        args=(user.pk,),\n                    )\n                )\n        else:\n            form = self.change_password_form(user)\n\n        fieldsets = [(None, {\"fields\": list(form.base_fields)})]\n        admin_form = admin.helpers.AdminForm(form, fieldsets, {})\n\n        if user.has_usable_password():\n            title = _(\"Change password: %s\")\n        else:\n            title = _(\"Set password: %s\")\n        context = {\n            \"title\": title % escape(user.get_username()),\n            \"adminForm\": admin_form,\n            \"form_url\": form_url,\n            \"form\": form,\n            \"is_popup\": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),\n            \"is_popup_var\": IS_POPUP_VAR,\n            \"add\": True,\n            \"change\": False,\n            \"has_delete_permission\": False,\n            \"has_change_permission\": True,\n            \"has_absolute_url\": False,\n            \"opts\": self.opts,\n            \"original\": user,\n            \"save_as\": False,\n            \"show_save\": True,\n            **self.admin_site.each_context(request),\n        }\n\n        request.current_app = self.admin_site.name\n\n        return TemplateResponse(\n            request,\n            self.change_user_password_template\n            or \"admin/auth/user/change_password.html\",\n            context,\n        )\n\n    def response_add(self, request, obj, post_url_continue=None):\n        \"\"\"\n        Determine the HttpResponse for the add_view stage. It mostly defers to\n        its superclass implementation but is customized because the User model\n        has a slightly different workflow.\n        \"\"\"\n        # We should allow further modification of the user just added i.e. the\n        # 'Save' button should behave like the 'Save and continue editing'\n        # button except in two scenarios:\n        # * The user has pressed the 'Save and add another' button\n        # * We are adding a user in a popup\n        if \"_addanother\" not in request.POST and IS_POPUP_VAR not in request.POST:\n            request.POST = request.POST.copy()\n            request.POST[\"_continue\"] = 1\n        return super().response_add(request, obj, post_url_continue)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-7a41dc90ea2ce214", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "2296effffcf654f1d52588dae5d65bae6b242ea21212eee8e0b7da68160a65fa", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 238, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__UserAdmin__3649af65.py", "order": 8, "original_content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "parent_variant_id": "pyint-923035fd1ea3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/admin.py#L41-L251", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 7}, "unit_kind": "class", "unit_name": "UserAdmin", "variant_id": "pyint-d2733649af65-I08", "group_id": "py-7a41dc90ea2ce214", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 37, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4608f74ce0df-I09", "source": "from django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.admin.utils import unquote\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import (\n    AdminPasswordChangeForm,\n    AdminUserCreationForm,\n    UserChangeForm,\n)\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\n\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n    add_form_template = \"admin/auth/user/add_form.html\"\n    change_user_password_template = None\n    fieldsets = (\n        (None, {\"fields\": (\"username\", \"password\")}),\n        (_(\"Personal info\"), {\"fields\": (\"first_name\", \"last_name\", \"email\")}),\n        (\n            _(\"Permissions\"),\n            {\n                \"fields\": (\n                    \"is_active\",\n                    \"is_staff\",\n                    \"is_superuser\",\n                    \"groups\",\n                    \"user_permissions\",\n                ),\n            },\n        ),\n        (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),\n    )\n    add_fieldsets = (\n        (\n            None,\n            {\n                \"classes\": (\"wide\",),\n                \"fields\": (\"username\", \"usable_password\", \"password1\", \"password2\"),\n            },\n        ),\n    )\n    form = UserChangeForm\n    add_form = AdminUserCreationForm\n    change_password_form = AdminPasswordChangeForm\n    list_display = (\"username\", \"email\", \"first_name\", \"last_name\", \"is_staff\")\n    list_filter = (\"is_staff\", \"is_superuser\", \"is_active\", \"groups\")\n    search_fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n    ordering = (\"username\",)\n    filter_horizontal = (\n        \"groups\",\n        \"user_permissions\",\n    )\n\n    def get_fieldsets(self, request, obj=None):\n        if not obj:\n            return self.add_fieldsets\n        return super().get_fieldsets(request, obj)\n\n    def get_form(self, request, obj=None, **kwargs):\n        \"\"\"\n        Use special form during user creation\n        \"\"\"\n        defaults = {}\n        if obj is None:\n            defaults[\"form\"] = self.add_form\n        defaults.update(kwargs)\n        return super().get_form(request, obj, **defaults)\n\n    def get_urls(self):\n        return [\n            path(\n                \"<id>/password/\",\n                self.admin_site.admin_view(self.user_change_password),\n                name=\"auth_user_password_change\",\n            ),\n            *super().get_urls(),\n        ]\n\n    def lookup_allowed(self, lookup, value, request):\n        # Don't allow lookups involving passwords.\n        return not lookup.startswith(\"password\") and super().lookup_allowed(\n            lookup, value, request\n        )\n\n    @method_decorator([sensitive_post_parameters(), csrf_protect])\n    def add_view(self, request, form_url=\"\", extra_context=None):\n        if request.method in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            return self._add_view(request, form_url, extra_context)\n\n        with transaction.atomic(using=router.db_for_write(self.model)):\n            return self._add_view(request, form_url, extra_context)\n\n    def _add_view(self, request, form_url=\"\", extra_context=None):\n        # It's an error for a user to have add permission but NOT change\n        # permission for users. If we allowed such users to add users, they\n        # could create superusers, which would mean they would essentially have\n        # the permission to change users. To avoid the problem entirely, we\n        # disallow users from adding users if they don't have change\n        # permission.\n        if not self.has_change_permission(request):\n            if self.has_add_permission(request) and settings.DEBUG:\n                # Raise Http404 in debug mode so that the user gets a helpful\n                # error message.\n                raise Http404(\n                    'Your user does not have the \"Change user\" permission. In '\n                    \"order to add users, Django requires that your user \"\n                    'account have both the \"Add user\" and \"Change user\" '\n                    \"permissions set.\"\n                )\n            raise PermissionDenied\n        if extra_context is None:\n            extra_context = {}\n        username_field = self.opts.get_field(self.model.USERNAME_FIELD)\n        defaults = {\n            \"auto_populated_fields\": (),\n            \"username_help_text\": username_field.help_text,\n        }\n        extra_context.update(defaults)\n        return super().add_view(request, form_url, extra_context)\n\n    @method_decorator(sensitive_post_parameters())\n    def user_change_password(self, request, id, form_url=\"\"):\n        lI0O_d60ed066 = ((0xa5b5 ^ 0xa5b5) != 0)\n        lI0O_d60ed066 = not (not lI0O_d60ed066)\n        user = self.get_object(request, unquote(id))\n        if not self.has_change_permission(request, user):\n            raise PermissionDenied\n        if user is None:\n            raise Http404(\n                _(\"%(name)s object with primary key %(key)r does not exist.\")\n                % {\n                    \"name\": self.opts.verbose_name,\n                    \"key\": escape(id),\n                }\n            )\n        if request.method == \"POST\":\n            form = self.change_password_form(user, request.POST)\n            if form.is_valid():\n                # If disabling password-based authentication was requested\n                # (via the form field `usable_password`), the submit action\n                # must be \"unset-password\". This check is most relevant when\n                # the admin user has two submit buttons available (for example\n                # when Javascript is disabled).\n                valid_submission = (\n                    form.cleaned_data[\"set_usable_password\"]\n                    or \"unset-password\" in request.POST\n                )\n                if not valid_submission:\n                    msg = gettext(\"Conflicting form data submitted. Please try again.\")\n                    messages.error(request, msg)\n                    return HttpResponseRedirect(request.get_full_path())\n\n                user = form.save()\n                change_message = self.construct_change_message(request, form, None)\n                self.log_change(request, user, change_message)\n                if user.has_usable_password():\n                    msg = gettext(\"Password changed successfully.\")\n                else:\n                    msg = gettext(\"Password-based authentication was disabled.\")\n                messages.success(request, msg)\n                update_session_auth_hash(request, form.user)\n                return HttpResponseRedirect(\n                    reverse(\n                        \"%s:%s_%s_change\"\n                        % (\n                            self.admin_site.name,\n                            user._meta.app_label,\n                            user._meta.model_name,\n                        ),\n                        args=(user.pk,),\n                    )\n                )\n        else:\n            form = self.change_password_form(user)\n\n        fieldsets = [(None, {\"fields\": list(form.base_fields)})]\n        admin_form = admin.helpers.AdminForm(form, fieldsets, {})\n\n        if user.has_usable_password():\n            title = _(\"Change password: %s\")\n        else:\n            title = _(\"Set password: %s\")\n        context = {\n            \"title\": title % escape(user.get_username()),\n            \"adminForm\": admin_form,\n            \"form_url\": form_url,\n            \"form\": form,\n            \"is_popup\": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),\n            \"is_popup_var\": IS_POPUP_VAR,\n            \"add\": True,\n            \"change\": False,\n            \"has_delete_permission\": False,\n            \"has_change_permission\": True,\n            \"has_absolute_url\": False,\n            \"opts\": self.opts,\n            \"original\": user,\n            \"save_as\": False,\n            \"show_save\": True,\n            **self.admin_site.each_context(request),\n        }\n\n        request.current_app = self.admin_site.name\n\n        return TemplateResponse(\n            request,\n            self.change_user_password_template\n            or \"admin/auth/user/change_password.html\",\n            context,\n        )\n\n    def response_add(self, request, obj, post_url_continue=None):\n        \"\"\"\n        Determine the HttpResponse for the add_view stage. It mostly defers to\n        its superclass implementation but is customized because the User model\n        has a slightly different workflow.\n        \"\"\"\n        # We should allow further modification of the user just added i.e. the\n        # 'Save' button should behave like the 'Save and continue editing'\n        # button except in two scenarios:\n        # * The user has pressed the 'Save and add another' button\n        # * We are adding a user in a popup\n        if \"_addanother\" not in request.POST and IS_POPUP_VAR not in request.POST:\n            request.POST = request.POST.copy()\n            request.POST[\"_continue\"] = 1\n        return super().response_add(request, obj, post_url_continue)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-7a41dc90ea2ce214", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "64172eddf31dd5ebbd55dd208d8bb92c0e9e618b77c17ce884be244ee4f36ebd", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 237, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__UserAdmin__f74ce0df.py", "order": 9, "original_content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "parent_variant_id": "pyint-923035fd1ea3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/admin.py#L41-L251", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 4}, "unit_kind": "class", "unit_name": "UserAdmin", "variant_id": "pyint-4608f74ce0df-I09", "group_id": "py-7a41dc90ea2ce214", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 38, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b01167fa013f-I10", "source": "from django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.admin.utils import unquote\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import (\n    AdminPasswordChangeForm,     AdminUserCreationForm,\n    UserChangeForm,\n)\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n    add_form_template = \"admin/auth/user/add_form.html\"\n    change_user_password_template = None\n    fieldsets = (         (None, {\"fields\": (\"username\", \"password\")}),\n        (_(\"Personal info\"), {\"fields\": (\"first_name\", \"last_name\", \"email\")}),         (\n            _(\"Permissions\"),\n            {\n                \"fields\": (                     \"is_active\",\n                    \"is_staff\",\n                    \"is_superuser\",\n                    \"groups\",\n                    \"user_permissions\",\n                ),\n            },\n        ),         (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),     )\n    add_fieldsets = (\n        (\n            None,             {\n                \"classes\": (\"wide\",),\n                \"fields\": (\"username\", \"usable_password\", \"password1\", \"password2\"),             },         ),\n    )\n    form = UserChangeForm\n    add_form = AdminUserCreationForm\n    change_password_form = AdminPasswordChangeForm\n    list_display = (\"username\", \"email\", \"first_name\", \"last_name\", \"is_staff\")\n    list_filter = (\"is_staff\", \"is_superuser\", \"is_active\", \"groups\")\n    search_fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n    ordering = (\"username\",)\n    filter_horizontal = (\n        \"groups\",\n        \"user_permissions\",\n    )\n    def get_fieldsets(self, request, obj=None):\n        if not obj:\n            return self.add_fieldsets\n        return super().get_fieldsets(request, obj)\n\n    def get_form(self, request, obj=None, **kwargs):\n        \"\"\"\n        Use special form during user creation\n        \"\"\"\n        defaults = {}\n        if obj is None:\n            defaults[\"form\"] = self.add_form\n        defaults.update(kwargs)\n        return super().get_form(request, obj, **defaults)\n\n    def get_urls(self):\n        return [\n            path(                 \"<id>/password/\",\n                self.admin_site.admin_view(self.user_change_password),\n                name=\"auth_user_password_change\",\n            ),\n            *super().get_urls(),\n        ]\n    def lookup_allowed(self, lookup, value, request):\n        # Don't allow lookups involving passwords.\n        return not lookup.startswith(\"password\") and super().lookup_allowed(             lookup, value, request\n        )\n    @method_decorator([sensitive_post_parameters(), csrf_protect])\n    def add_view(self, request, form_url=\"\", extra_context=None):\n        if request.method in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            return self._add_view(request, form_url, extra_context)\n        with transaction.atomic(using=router.db_for_write(self.model)):\n            return self._add_view(request, form_url, extra_context)\n\n    def _add_view(self, request, form_url=\"\", extra_context=None):\n        # It's an error for a user to have add permission but NOT change\n        # permission for users. If we allowed such users to add users, they\n        # could create superusers, which would mean they would essentially have\n        # the permission to change users. To avoid the problem entirely, we\n        # disallow users from adding users if they don't have change\n        # permission.\n        if not self.has_change_permission(request):\n            if self.has_add_permission(request) and settings.DEBUG:\n                # Raise Http404 in debug mode so that the user gets a helpful\n                # error message.\n                raise Http404(                     'Your user does not have the \"Change user\" permission. In '\n                    \"order to add users, Django requires that your user \"                     'account have both the \"Add user\" and \"Change user\" '\n                    \"permissions set.\"                 )\n            raise PermissionDenied\n        if extra_context is None:\n            extra_context = {}\n        username_field = self.opts.get_field(self.model.USERNAME_FIELD)\n        defaults = {             \"auto_populated_fields\": (),\n            \"username_help_text\": username_field.help_text,\n        }\n        extra_context.update(defaults)\n        return super().add_view(request, form_url, extra_context)\n\n    @method_decorator(sensitive_post_parameters())\n    def user_change_password(self, request, id, form_url=\"\"):\n        user = self.get_object(request, unquote(id))\n        if not self.has_change_permission(request, user):\n            raise PermissionDenied\n        if user is None:\n            raise Http404(\n                _(\"%(name)s object with primary key %(key)r does not exist.\")\n                % {\n                    \"name\": self.opts.verbose_name,\n                    \"key\": escape(id),\n                }\n            )\n        if request.method == \"POST\":\n            form = self.change_password_form(user, request.POST)\n            if form.is_valid():\n                # If disabling password-based authentication was requested\n                # (via the form field `usable_password`), the submit action\n                # must be \"unset-password\". This check is most relevant when\n                # the admin user has two submit buttons available (for example\n                # when Javascript is disabled).\n                valid_submission = (                     form.cleaned_data[\"set_usable_password\"]\n                    or \"unset-password\" in request.POST\n                )\n                if not valid_submission:\n                    msg = gettext(\"Conflicting form data submitted. Please try again.\")\n                    messages.error(request, msg)\n                    return HttpResponseRedirect(request.get_full_path())\n                user = form.save()\n                change_message = self.construct_change_message(request, form, None)\n                self.log_change(request, user, change_message)\n                if user.has_usable_password():\n                    msg = gettext(\"Password changed successfully.\")\n                else:\n                    msg = gettext(\"Password-based authentication was disabled.\")\n                messages.success(request, msg)\n                update_session_auth_hash(request, form.user)\n                return HttpResponseRedirect(\n                    reverse(                         \"%s:%s_%s_change\"                         % (                             self.admin_site.name,                             user._meta.app_label,                             user._meta.model_name,\n                        ),\n                        args=(user.pk,),                     )\n                )\n        else:\n            form = self.change_password_form(user)\n        fieldsets = [(None, {\"fields\": list(form.base_fields)})]\n        admin_form = admin.helpers.AdminForm(form, fieldsets, {})\n        if user.has_usable_password():\n            title = _(\"Change password: %s\")\n        else:\n            title = _(\"Set password: %s\")\n        context = {\n            \"title\": title % escape(user.get_username()),\n            \"adminForm\": admin_form,\n            \"form_url\": form_url,             \"form\": form,             \"is_popup\": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),\n            \"is_popup_var\": IS_POPUP_VAR,\n            \"add\": True,             \"change\": False,\n            \"has_delete_permission\": False,\n            \"has_change_permission\": True,\n            \"has_absolute_url\": False,\n            \"opts\": self.opts,             \"original\": user,             \"save_as\": False,             \"show_save\": True,\n            **self.admin_site.each_context(request),\n        }\n\n        request.current_app = self.admin_site.name\n        return TemplateResponse(             request,\n            self.change_user_password_template\n            or \"admin/auth/user/change_password.html\",             context,         )\n    def response_add(self, request, obj, post_url_continue=None):\n        \"\"\"\n        Determine the HttpResponse for the add_view stage. It mostly defers to\n        its superclass implementation but is customized because the User model\n        has a slightly different workflow.\n        \"\"\"\n        # We should allow further modification of the user just added i.e. the\n        # 'Save' button should behave like the 'Save and continue editing'\n        # button except in two scenarios:\n        # * The user has pressed the 'Save and add another' button\n        # * We are adding a user in a popup\n        if \"_addanother\" not in request.POST and IS_POPUP_VAR not in request.POST:\n            request.POST = request.POST.copy()\n            request.POST[\"_continue\"] = 1\n        return super().response_add(request, obj, post_url_continue)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-7a41dc90ea2ce214", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "3aef04fb7ce388fdbcd01926cb02e7fb47b97fe583a11585de9af58164bf4b22", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 194, "local_path": "layout/partially-compact-layout/I10__django__UserAdmin__67fa013f.py", "order": 10, "original_content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "parent_variant_id": "pyint-923035fd1ea3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/admin.py#L41-L251", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 104, "line_break_groups_removed": 41, "line_breaks_removed": 41, "whitespace_characters_removed": 10}, "unit_kind": "class", "unit_name": "UserAdmin", "variant_id": "pyint-b01167fa013f-I10", "group_id": "py-7a41dc90ea2ce214", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 39, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d02f2ee6f861-I11", "source": "from django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.admin.utils import unquote\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import (\n    AdminPasswordChangeForm,\n    AdminUserCreationForm,\n    UserChangeForm,\n)\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\n\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n    add_form_template = \"admin/auth/user/add_form.html\"\n    change_user_password_template = None\n    fieldsets = (\n        (None, {\"fields\": (\"username\", \"password\")}),\n        (_(\"Personal info\"), {\"fields\": (\"first_name\", \"last_name\", \"email\")}),\n        (\n            _(\"Permissions\"),\n            {\n                \"fields\": (\n                    \"is_active\",\n                    \"is_staff\",\n                    \"is_superuser\",\n                    \"groups\",\n                    \"user_permissions\",\n                ),\n            },\n        ),\n        (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),\n    )\n    add_fieldsets = (\n        (\n            None,\n            {\n                \"classes\": (\"wide\",),\n                \"fields\": (\"username\", \"usable_password\", \"password1\", \"password2\"),\n            },\n        ),\n    )\n    form = UserChangeForm\n    add_form = AdminUserCreationForm\n    change_password_form = AdminPasswordChangeForm\n    list_display = (\"username\", \"email\", \"first_name\", \"last_name\", \"is_staff\")\n    list_filter = (\"is_staff\", \"is_superuser\", \"is_active\", \"groups\")\n    search_fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n    ordering = (\"username\",)\n    filter_horizontal = (\n        \"groups\",\n        \"user_permissions\",\n    )\n\n    def get_fieldsets(self, request, obj=None):\n        if not obj:\n            return self.add_fieldsets\n        return super().get_fieldsets(request, obj)\n\n    def get_form(self, request, obj=None, **kwargs):\n        \"\"\"\n        Use special form during user creation\n        \"\"\"\n        defaults = {}\n        if obj is None:\n            defaults[\"form\"] = self.add_form\n        defaults.update(kwargs)\n        return super().get_form(request, obj, **defaults)\n\n    def get_urls(self):\n        return [\n            path(\n                \"<id>/password/\",\n                self.admin_site.admin_view(self.user_change_password),\n                name=\"auth_user_password_change\",\n            ),\n            *super().get_urls(),\n        ]\n\n    def lookup_allowed(self, lookup, value, request):\n        # Don't allow lookups involving passwords.\n        return not lookup.startswith(\"password\") and super().lookup_allowed(\n            lookup, value, request\n        )\n\n    @method_decorator([sensitive_post_parameters(), csrf_protect])\n    def add_view(self, request, form_url=\"\", extra_context=None):\n        if request.method in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            return self._add_view(request, form_url, extra_context)\n\n        with transaction.atomic(using=router.db_for_write(self.model)):\n            return self._add_view(request, form_url, extra_context)\n\n    def _add_view(self, request, form_url=\"\", extra_context=None):\n        # It's an error for a user to have add permission but NOT change\n        # permission for users. If we allowed such users to add users, they\n        # could create superusers, which would mean they would essentially have\n        # the permission to change users. To avoid the problem entirely, we\n        # disallow users from adding users if they don't have change\n        # permission.\n        if not self.has_change_permission(request):\n            if self.has_add_permission(request) and settings.DEBUG:\n                # Raise Http404 in debug mode so that the user gets a helpful\n                # error message.\n                raise Http404(\n                    'Your user does not have the \"Change user\" permission. In '\n                    \"order to add users, Django requires that your user \"\n                    'account have both the \"Add user\" and \"Change user\" '\n                    \"permissions set.\"\n                )\n            raise PermissionDenied\n        if extra_context is None:\n            extra_context = {}\n        username_field = self.opts.get_field(self.model.USERNAME_FIELD)\n        defaults = {\n            \"auto_populated_fields\": (),\n            \"username_help_text\": username_field.help_text,\n        }\n        extra_context.update(defaults)\n        return super().add_view(request, form_url, extra_context)\n\n    @method_decorator(sensitive_post_parameters())\n    def user_change_password(self, request, id, form_url=\"\"):\n        user = self.get_object(request, unquote(id))\n        if not self.has_change_permission(request, user):\n            raise PermissionDenied\n        if user is None:\n            raise Http404(\n                _(\"%(name)s object with primary key %(key)r does not exist.\")\n                % {\n                    \"name\": self.opts.verbose_name,\n                    \"key\": escape(id),\n                }\n            )\n        if request.method == \"POST\":\n            form = self.change_password_form(user, request.POST)\n            if form.is_valid():\n                # If disabling password-based authentication was requested\n                # (via the form field `usable_password`), the submit action\n                # must be \"unset-password\". This check is most relevant when\n                # the admin user has two submit buttons available (for example\n                # when Javascript is disabled).\n                valid_submission = (\n                    form.cleaned_data[\"set_usable_password\"]\n                    or \"unset-password\" in request.POST\n                )\n                if not valid_submission:\n                    msg = gettext(\"Conflicting form data submitted. Please try again.\")\n                    messages.error(request, msg)\n                    return HttpResponseRedirect(request.get_full_path())\n\n                user = form.save()\n                change_message = self.construct_change_message(request, form, None)\n                self.log_change(request, user, change_message)\n                if user.has_usable_password():\n                    msg = gettext(\"Password changed successfully.\")\n                else:\n                    msg = gettext(\"Password-based authentication was disabled.\")\n                messages.success(request, msg)\n                update_session_auth_hash(request, form.user)\n                return HttpResponseRedirect(\n                    reverse(\n                        \"%s:%s_%s_change\"\n                        % (\n                            self.admin_site.name,\n                            user._meta.app_label,\n                            user._meta.model_name,\n                        ),\n                        args=(user.pk,),\n                    )\n                )\n        else:\n            form = self.change_password_form(user)\n\n        fieldsets = [(None, {\"fields\": list(form.base_fields)})]\n        admin_form = admin.helpers.AdminForm(form, fieldsets, {})\n\n        if user.has_usable_password():\n            title = _(\"Change password: %s\")\n        else:\n            title = _(\"Set password: %s\")\n        context = {\n            \"title\": title % escape(user.get_username()),\n            \"adminForm\": admin_form,\n            \"form_url\": form_url,\n            \"form\": form,\n            \"is_popup\": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),\n            \"is_popup_var\": IS_POPUP_VAR,\n            \"add\": True,\n            \"change\": False,\n            \"has_delete_permission\": False,\n            \"has_change_permission\": True,\n            \"has_absolute_url\": False,\n            \"opts\": self.opts,\n            \"original\": user,\n            \"save_as\": False,\n            \"show_save\": True,\n            **self.admin_site.each_context(request),\n        }\n\n        request.current_app = self.admin_site.name\n\n        return TemplateResponse(\n            request,\n            self.change_user_password_template\n            or \"admin/auth/user/change_password.html\",\n            context,\n        )\n\n    def response_add(self, request, obj, post_url_continue=None):\n        \"\"\"\n        Determine the HttpResponse for the add_view stage. It mostly defers to\n        its superclass implementation but is customized because the User model\n        has a slightly different workflow.\n        \"\"\"\n        # We should allow further modification of the user just added i.e. the\n        # 'Save' button should behave like the 'Save and continue editing'\n        # button except in two scenarios:\n        # * The user has pressed the 'Save and add another' button\n        # * We are adding a user in a popup\n        if \"_addanother\" not in request.POST and IS_POPUP_VAR not in request.POST:\n            request.POST = request.POST.copy()\n            a = 2\n            b = -1\n            request.POST[\"_continue\"] = (a + b)\n        return super().response_add(request, obj, post_url_continue)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-7a41dc90ea2ce214", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "94fb6533bcc6b54a0e2c21b7ca8d0daa3f5fd87a56966b1c643d4934eb1f3f68", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 237, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__UserAdmin__2ee6f861.py", "order": 11, "original_content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "parent_variant_id": "pyint-923035fd1ea3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/admin.py#L41-L251", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 1, "intermediate_variables_introduced": 2, "statements_augmented": 1}, "unit_kind": "class", "unit_name": "UserAdmin", "variant_id": "pyint-d02f2ee6f861-I11", "group_id": "py-7a41dc90ea2ce214", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 40, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-295a13937749-I12", "source": "from django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.admin.utils import unquote\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import (\n    AdminPasswordChangeForm,\n    AdminUserCreationForm,\n    UserChangeForm,\n)\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\n\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n    add_form_template = \"admin/auth/user/add_form.html\"\n    change_user_password_template = None\n    fieldsets = (\n        (None, {\"fields\": (\"username\", \"password\")}),\n        (_(\"Personal info\"), {\"fields\": (\"first_name\", \"last_name\", \"email\")}),\n        (\n            _(\"Permissions\"),\n            {\n                \"fields\": (\n                    \"is_active\",\n                    \"is_staff\",\n                    \"is_superuser\",\n                    \"groups\",\n                    \"user_permissions\",\n                ),\n            },\n        ),\n        (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),\n    )\n    add_fieldsets = (\n        (\n            None,\n            {\n                \"classes\": (\"wide\",),\n                \"fields\": (\"username\", \"usable_password\", \"password1\", \"password2\"),\n            },\n        ),\n    )\n    form = UserChangeForm\n    add_form = AdminUserCreationForm\n    change_password_form = AdminPasswordChangeForm\n    list_display = (\"username\", \"email\", \"first_name\", \"last_name\", \"is_staff\")\n    list_filter = (\"is_staff\", \"is_superuser\", \"is_active\", \"groups\")\n    search_fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n    ordering = (\"username\",)\n    filter_horizontal = (\n        \"groups\",\n        \"user_permissions\",\n    )\n\n    def get_fieldsets(self, request, obj=None):\n        if not obj:\n            return self.add_fieldsets\n        return super().get_fieldsets(request, obj)\n\n    def get_form(self, request, obj=None, **kwargs):\n        \"\"\"\n        Use special form during user creation\n        \"\"\"\n        defaults = {}\n        if obj is None:\n            defaults[\"form\"] = self.add_form\n        defaults.update(kwargs)\n        return super().get_form(request, obj, **defaults)\n\n    def get_urls(self):\n        return [\n            path(\n                \"<id>/password/\",\n                self.admin_site.admin_view(self.user_change_password),\n                name=\"auth_user_password_change\",\n            ),\n            *super().get_urls(),\n        ]\n\n    def lookup_allowed(self, lookup, value, request):\n        # Don't allow lookups involving passwords.\n        return not lookup.startswith(\"password\") and super().lookup_allowed(\n            lookup, value, request\n        )\n\n    @method_decorator([sensitive_post_parameters(), csrf_protect])\n    def add_view(self, request, form_url=\"\", extra_context=None):\n        if request.method in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            return self._add_view(request, form_url, extra_context)\n\n        with transaction.atomic(using=router.db_for_write(self.model)):\n            return self._add_view(request, form_url, extra_context)\n\n    def _add_view(self, request, form_url=\"\", extra_context=None):\n        # It's an error for a user to have add permission but NOT change\n        # permission for users. If we allowed such users to add users, they\n        # could create superusers, which would mean they would essentially have\n        # the permission to change users. To avoid the problem entirely, we\n        # disallow users from adding users if they don't have change\n        # permission.\n        if not self.has_change_permission(request):\n            if self.has_add_permission(request) and settings.DEBUG:\n                # Raise Http404 in debug mode so that the user gets a helpful\n                # error message.\n                raise Http404(\n                    'Your user does not have the \"Change user\" permission. In '\n                    \"order to add users, Django requires that your user \"\n                    'account have both the \"Add user\" and \"Change user\" '\n                    \"permissions set.\"\n                )\n            raise PermissionDenied\n        if extra_context is None:\n            extra_context = {}\n        username_field = self.opts.get_field(self.model.USERNAME_FIELD)\n        \n        extra_context.update(({\n            \"auto_populated_fields\": (),\n            \"username_help_text\": username_field.help_text,\n        }))\n        return super().add_view(request, form_url, extra_context)\n\n    @method_decorator(sensitive_post_parameters())\n    def user_change_password(self, request, id, form_url=\"\"):\n        user = self.get_object(request, unquote(id))\n        if not self.has_change_permission(request, user):\n            raise PermissionDenied\n        if user is None:\n            raise Http404(\n                _(\"%(name)s object with primary key %(key)r does not exist.\")\n                % {\n                    \"name\": self.opts.verbose_name,\n                    \"key\": escape(id),\n                }\n            )\n        if request.method == \"POST\":\n            form = self.change_password_form(user, request.POST)\n            if form.is_valid():\n                # If disabling password-based authentication was requested\n                # (via the form field `usable_password`), the submit action\n                # must be \"unset-password\". This check is most relevant when\n                # the admin user has two submit buttons available (for example\n                # when Javascript is disabled).\n                valid_submission = (\n                    form.cleaned_data[\"set_usable_password\"]\n                    or \"unset-password\" in request.POST\n                )\n                if not valid_submission:\n                    msg = gettext(\"Conflicting form data submitted. Please try again.\")\n                    messages.error(request, msg)\n                    return HttpResponseRedirect(request.get_full_path())\n\n                user = form.save()\n                \n                self.log_change(request, user, (self.construct_change_message(request, form, None)))\n                if user.has_usable_password():\n                    msg = gettext(\"Password changed successfully.\")\n                else:\n                    msg = gettext(\"Password-based authentication was disabled.\")\n                messages.success(request, msg)\n                update_session_auth_hash(request, form.user)\n                return HttpResponseRedirect(\n                    reverse(\n                        \"%s:%s_%s_change\"\n                        % (\n                            self.admin_site.name,\n                            user._meta.app_label,\n                            user._meta.model_name,\n                        ),\n                        args=(user.pk,),\n                    )\n                )\n        else:\n            form = self.change_password_form(user)\n\n        fieldsets = [(None, {\"fields\": list(form.base_fields)})]\n        admin_form = admin.helpers.AdminForm(form, fieldsets, {})\n\n        if user.has_usable_password():\n            title = _(\"Change password: %s\")\n        else:\n            title = _(\"Set password: %s\")\n        \n\n        request.current_app = self.admin_site.name\n\n        return TemplateResponse(\n            request,\n            self.change_user_password_template\n            or \"admin/auth/user/change_password.html\",\n            ({\n            \"title\": title % escape(user.get_username()),\n            \"adminForm\": admin_form,\n            \"form_url\": form_url,\n            \"form\": form,\n            \"is_popup\": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),\n            \"is_popup_var\": IS_POPUP_VAR,\n            \"add\": True,\n            \"change\": False,\n            \"has_delete_permission\": False,\n            \"has_change_permission\": True,\n            \"has_absolute_url\": False,\n            \"opts\": self.opts,\n            \"original\": user,\n            \"save_as\": False,\n            \"show_save\": True,\n            **self.admin_site.each_context(request),\n        }),\n        )\n\n    def response_add(self, request, obj, post_url_continue=None):\n        \"\"\"\n        Determine the HttpResponse for the add_view stage. It mostly defers to\n        its superclass implementation but is customized because the User model\n        has a slightly different workflow.\n        \"\"\"\n        # We should allow further modification of the user just added i.e. the\n        # 'Save' button should behave like the 'Save and continue editing'\n        # button except in two scenarios:\n        # * The user has pressed the 'Save and add another' button\n        # * We are adding a user in a popup\n        if \"_addanother\" not in request.POST and IS_POPUP_VAR not in request.POST:\n            request.POST = request.POST.copy()\n            request.POST[\"_continue\"] = 1\n        return super().response_add(request, obj, post_url_continue)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-7a41dc90ea2ce214", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "689f257d001c590c5b90b64f45b6a00b8ea81e54844c375bf6a926b1518850d6", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 235, "local_path": "data-flow/inline-intermediate-variables/I12__django__UserAdmin__13937749.py", "order": 12, "original_content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "parent_variant_id": "pyint-923035fd1ea3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/admin.py#L41-L251", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 3, "intermediate_variables_available": 3, "intermediate_variables_inlined": 3, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "UserAdmin", "variant_id": "pyint-295a13937749-I12", "group_id": "py-7a41dc90ea2ce214", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 41, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0a511eff9a22-I13", "source": "from django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.admin.utils import unquote\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import (\n    AdminPasswordChangeForm,\n    AdminUserCreationForm,\n    UserChangeForm,\n)\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\n\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n    add_form_template = \"admin/auth/user/add_form.html\"\n    change_user_password_template = None\n    fieldsets = (\n        (None, {\"fields\": (\"username\", \"password\")}),\n        (_(\"Personal info\"), {\"fields\": (\"first_name\", \"last_name\", \"email\")}),\n        (\n            _(\"Permissions\"),\n            {\n                \"fields\": (\n                    \"is_active\",\n                    \"is_staff\",\n                    \"is_superuser\",\n                    \"groups\",\n                    \"user_permissions\",\n                ),\n            },\n        ),\n        (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),\n    )\n    add_fieldsets = (\n        (\n            None,\n            {\n                \"classes\": (\"wide\",),\n                \"fields\": (\"username\", \"usable_password\", \"password1\", \"password2\"),\n            },\n        ),\n    )\n    form = UserChangeForm\n    add_form = AdminUserCreationForm\n    change_password_form = AdminPasswordChangeForm\n    list_display = (\"username\", \"email\", \"first_name\", \"last_name\", \"is_staff\")\n    list_filter = (\"is_staff\", \"is_superuser\", \"is_active\", \"groups\")\n    search_fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n    ordering = (\"username\",)\n    filter_horizontal = (\n        \"groups\",\n        \"user_permissions\",\n    )\n\n    def get_fieldsets(self, request, obj=None):\n        if not obj:\n            return self.add_fieldsets\n        return super().get_fieldsets(request, obj)\n\n    def get_form(self, request, obj=None, **kwargs):\n        \"\"\"\n        Use special form during user creation\n        \"\"\"\n        defaults = {}\n        if obj is None:\n            defaults[\"form\"] = self.add_form\n        defaults.update(kwargs)\n        return super().get_form(request, obj, **defaults)\n\n    def get_urls(self):\n        return [\n            path(\n                \"<id>/password/\",\n                self.admin_site.admin_view(self.user_change_password),\n                name=\"auth_user_password_change\",\n            ),\n            *super().get_urls(),\n        ]\n\n    def lookup_allowed(self, lookup, value, request):\n        # Don't allow lookups involving passwords.\n        return not lookup.startswith(\"password\") and super().lookup_allowed(\n            lookup, value, request\n        )\n\n    @method_decorator([sensitive_post_parameters(), csrf_protect])\n    def add_view(self, request, form_url=\"\", extra_context=None):\n        if request.method in (\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"):\n            return self._add_view(request, form_url, extra_context)\n\n        with transaction.atomic(using=router.db_for_write(self.model)):\n            return self._add_view(request, form_url, extra_context)\n\n    def _add_view(self, request, form_url=\"\", extra_context=None):\n        # It's an error for a user to have add permission but NOT change\n        # permission for users. If we allowed such users to add users, they\n        # could create superusers, which would mean they would essentially have\n        # the permission to change users. To avoid the problem entirely, we\n        # disallow users from adding users if they don't have change\n        # permission.\n        if not self.has_change_permission(request):\n            if self.has_add_permission(request) and settings.DEBUG:\n                # Raise Http404 in debug mode so that the user gets a helpful\n                # error message.\n                raise Http404(\n                    'Your user does not have the \"Change user\" permission. In '\n                    \"order to add users, Django requires that your user \"\n                    'account have both the \"Add user\" and \"Change user\" '\n                    \"permissions set.\"\n                )\n            raise PermissionDenied\n        if extra_context is None:\n            extra_context = {}\n        username_field = self.opts.get_field(self.model.USERNAME_FIELD)\n        defaults = {\n            \"auto_populated_fields\": (),\n            \"username_help_text\": username_field.help_text,\n        }\n        extra_context.update(defaults)\n        return super().add_view(request, form_url, extra_context)\n\n    @method_decorator(sensitive_post_parameters())\n    def user_change_password(self, request, id, form_url=\"\"):\n        user = self.get_object(request, unquote(id))\n        if not self.has_change_permission(request, user):\n            raise PermissionDenied\n        if user is None:\n            raise Http404(\n                _(\"%(name)s object with primary key %(key)r does not exist.\")\n                % {\n                    \"name\": self.opts.verbose_name,\n                    \"key\": escape(id),\n                }\n            )\n        if request.method == \"POST\":\n            form = self.change_password_form(user, request.POST)\n            if form.is_valid():\n                # If disabling password-based authentication was requested\n                # (via the form field `usable_password`), the submit action\n                # must be \"unset-password\". This check is most relevant when\n                # the admin user has two submit buttons available (for example\n                # when Javascript is disabled).\n                valid_submission = (\n                    form.cleaned_data[\"set_usable_password\"]\n                    or \"unset-password\" in request.POST\n                )\n                if not valid_submission:\n                    msg = gettext(\"Conflicting form data submitted. Please try again.\")\n                    messages.error(request, msg)\n                    return HttpResponseRedirect(request.get_full_path())\n\n                user = form.save()\n                change_message = self.construct_change_message(request, form, None)\n                self.log_change(request, user, change_message)\n                if user.has_usable_password():\n                    msg = gettext(\"Password changed successfully.\")\n                else:\n                    msg = gettext(\"Password-based authentication was disabled.\")\n                messages.success(request, msg)\n                update_session_auth_hash(request, form.user)\n                return HttpResponseRedirect(\n                    reverse(\n                        \"%s:%s_%s_change\"\n                        % (\n                            self.admin_site.name,\n                            user._meta.app_label,\n                            user._meta.model_name,\n                        ),\n                        args=(user.pk,),\n                    )\n                )\n        else:\n            form = self.change_password_form(user)\n\n        fieldsets = [(None, {\"fields\": list(form.base_fields)})]\n        admin_form = admin.helpers.AdminForm(form, fieldsets, {})\n\n        if user.has_usable_password():\n            title = _(\"Change password: %s\")\n        else:\n            title = _(\"Set password: %s\")\n        context = {\n            \"title\": title % escape(user.get_username()),\n            \"adminForm\": admin_form,\n            \"form_url\": form_url,\n            \"form\": form,\n            \"is_popup\": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),\n            \"is_popup_var\": IS_POPUP_VAR,\n            \"add\": True,\n            \"change\": False,\n            \"has_delete_permission\": False,\n            \"has_change_permission\": True,\n            \"has_absolute_url\": False,\n            \"opts\": self.opts,\n            \"original\": user,\n            \"save_as\": False,\n            \"show_save\": True,\n            **self.admin_site.each_context(request),\n        }\n\n        request.current_app = self.admin_site.name\n\n        return TemplateResponse(\n            request,\n            self.change_user_password_template\n            or \"admin/auth/user/change_password.html\",\n            context,\n        )\n\n    def response_add(self, request, obj, post_url_continue=None):\n        \"\"\"\n        Determine the HttpResponse for the add_view stage. It mostly defers to\n        its superclass implementation but is customized because the User model\n        has a slightly different workflow.\n        \"\"\"\n        # We should allow further modification of the user just added i.e. the\n        # 'Save' button should behave like the 'Save and continue editing'\n        # button except in two scenarios:\n        # * The user has pressed the 'Save and add another' button\n        # * We are adding a user in a popup\n        if \"_addanother\" not in request.POST and IS_POPUP_VAR not in request.POST:\n            request.POST = request.POST.copy()\n            request.POST[\"_continue\"] = 1\n        return super().response_add(request, obj, post_url_continue)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-7a41dc90ea2ce214", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 235, "local_path": "control-flow/lower-for-to-while/I13__django__UserAdmin__1eff9a22.py", "order": 13, "original_content_sha256": "b187e4dfc9bde1d3006026b6e1a63a235007b5c50b5da87433a9a580ab50b595", "parent_variant_id": "pyint-923035fd1ea3-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/auth/admin.py#L41-L251", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "UserAdmin", "variant_id": "pyint-0a511eff9a22-I13", "group_id": "py-7a41dc90ea2ce214", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 42, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-33bff5b9490a-SRC", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass MinLengthValidator(BaseValidator):\n    message = ngettext_lazy(\n        \"Ensure this value has at least %(limit_value)d character (it has \"\n        \"%(show_value)d).\",\n        \"Ensure this value has at least %(limit_value)d characters (it has \"\n        \"%(show_value)d).\",\n        \"limit_value\",\n    )\n    code = \"min_length\"\n\n    def compare(self, a, b):\n        return a < b\n\n    def clean(self, x):\n        return len(x)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-7a619a40111047bd", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 29, "local_path": "source-original/SRC__django__MinLengthValidator__f5b9490a.py", "order": 0, "original_content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L471-L485", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "MinLengthValidator", "variant_id": "pyint-33bff5b9490a-SRC", "group_id": "py-7a619a40111047bd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 127, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ca6ec65cca0e-I01", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass MinLengthValidator(BaseValidator):\n    message = ngettext_lazy(\n        \"Ensure this value has at least %(limit_value)d character (it has \"\n        \"%(show_value)d).\",\n        \"Ensure this value has at least %(limit_value)d characters (it has \"\n        \"%(show_value)d).\",\n        \"limit_value\",\n    )\n    code = \"min_length\"\n\n    def compare(self, a, b):\n        return a < b\n\n    def clean(self, x):\n        return len(x)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-7a619a40111047bd", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 29, "local_path": "comments/remove-comments/I01__django__MinLengthValidator__c65cca0e.py", "order": 1, "original_content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "parent_variant_id": "pyint-33bff5b9490a-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L471-L485", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "MinLengthValidator", "variant_id": "pyint-ca6ec65cca0e-I01", "group_id": "py-7a619a40111047bd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 128, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4f0fbc1e6fdd-I02", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass MinLengthValidator(BaseValidator):\n    message = ngettext_lazy(\n        \"Ensure this value has at least %(limit_value)d character (it has \"\n        \"%(show_value)d).\",\n        \"Ensure this value has at least %(limit_value)d characters (it has \"\n        \"%(show_value)d).\",\n        \"limit_value\",\n    )\n    code = \"min_length\"\n\n    def com(self, a2, b2):\n        return a2 < b2\n\n    def cle(self, x2):\n        return len(x2)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-7a619a40111047bd", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d6ac3898bd128f6d8dc49d5890ea9b9f0ff4e2f911247cf15af8bc84c948026b", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 29, "local_path": "identifiers/shorten-identifiers/I02__django__MinLengthValidator__bc1e6fdd.py", "order": 2, "original_content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "parent_variant_id": "pyint-33bff5b9490a-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L471-L485", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "MinLengthValidator", "variant_id": "pyint-4f0fbc1e6fdd-I02", "group_id": "py-7a619a40111047bd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 129, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d478c752d313-I03", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass MinLengthValidator(BaseValidator):\n    message = ngettext_lazy(\n        \"Ensure this value has at least %(limit_value)d character (it has \"\n        \"%(show_value)d).\",\n        \"Ensure this value has at least %(limit_value)d characters (it has \"\n        \"%(show_value)d).\",\n        \"limit_value\",\n    )\n    code = \"min_length\"\n\n    def sendKey(self, key, age):\n        return key < age\n\n    def close(self, map):\n        return len(map)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-7a619a40111047bd", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "74b01bb29f63e1474dabf4086baf96ecbe77c2bdf202b0ecbc3decb8e8828a1d", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 29, "local_path": "identifiers/mislead-identifiers/I03__django__MinLengthValidator__c752d313.py", "order": 3, "original_content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "parent_variant_id": "pyint-33bff5b9490a-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L471-L485", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 5, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 0, "local_random_pool_selections": 3, "local_total_length_difference": 6, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 2, "method_random_pool_selections": 2, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "MinLengthValidator", "variant_id": "pyint-d478c752d313-I03", "group_id": "py-7a619a40111047bd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 130, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ec67d32ee447-I04", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass MinLengthValidator(BaseValidator):\n    message = ngettext_lazy(\n        \"Ensure this value has at least %(limit_value)d character (it has \"\n        \"%(show_value)d).\",\n        \"Ensure this value has at least %(limit_value)d characters (it has \"\n        \"%(show_value)d).\",\n        \"limit_value\",\n    )\n    code = \"min_length\"\n\n    def c(self, e, f):\n        return e < f\n\n    def d(self, g):\n        return len(g)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-7a619a40111047bd", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d27bc3d3cdeaaec5ae9805acb580685ce91f5fe838c8691360310528d63de12a", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 29, "local_path": "identifiers/garble-identifiers/I04__django__MinLengthValidator__d32ee447.py", "order": 4, "original_content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "parent_variant_id": "pyint-33bff5b9490a-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L471-L485", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "MinLengthValidator", "variant_id": "pyint-ec67d32ee447-I04", "group_id": "py-7a619a40111047bd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 131, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-98c50d029594-I05", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass MinLengthValidator(BaseValidator):\n    message = ngettext_lazy(\n        \"Ensure this value has at least %(limit_value)d character (it has \"\n        \"%(show_value)d).\",\n        \"Ensure this value has at least %(limit_value)d characters (it has \"\n        \"%(show_value)d).\",\n        \"limit_value\",\n    )\n    code = \"min_length\"\n\n    def compare(self, a, b):\n        return a < b\n\n    def clean(self, x):\n        return len(x)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-7a619a40111047bd", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 29, "local_path": "expressions/encode-integer-literals/I05__django__MinLengthValidator__0d029594.py", "order": 5, "original_content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "parent_variant_id": "pyint-33bff5b9490a-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L471-L485", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "MinLengthValidator", "variant_id": "pyint-98c50d029594-I05", "group_id": "py-7a619a40111047bd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 132, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d4c86ecde558-I06", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass MinLengthValidator(BaseValidator):\n    message = ngettext_lazy(\n        \"Ensure this value has at least %(limit_value)d character (it has \"\n        \"%(show_value)d).\",\n        \"Ensure this value has at least %(limit_value)d characters (it has \"\n        \"%(show_value)d).\",\n        \"limit_value\",\n    )\n    code = \"min_length\"\n\n    def compare(self, a, b):\n        return a < b\n\n    def clean(self, x):\n        return len(x)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-7a619a40111047bd", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 29, "local_path": "expressions/invert-conditions/I06__django__MinLengthValidator__6ecde558.py", "order": 6, "original_content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "parent_variant_id": "pyint-33bff5b9490a-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L471-L485", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "MinLengthValidator", "variant_id": "pyint-d4c86ecde558-I06", "group_id": "py-7a619a40111047bd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 133, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c7a66a5eff32-I07", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass MinLengthValidator(BaseValidator):\n    message = ngettext_lazy(\n        \"Ensure this value has at least %(limit_value)d character (it has \"\n        \"%(show_value)d).\",\n        \"Ensure this value has at least %(limit_value)d characters (it has \"\n        \"%(show_value)d).\",\n        \"limit_value\",\n    )\n    code = \"min_length\"\n\n    def compare(self, a, b):\n        if ((0x2502 ^ 0x2502) != 0):\n            raise AssertionError()\n        return a < b\n\n    def clean(self, x):\n        if ((0xff9 ^ 0xff9) != 0):\n            raise AssertionError()\n        return len(x)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-7a619a40111047bd", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "440d3c5f0a1a1ed688ed22f43cd11fa22f00e7ac9036ae47ffc78f06fd36a8d6", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 33, "local_path": "code-injection/insert-dead-branches/I07__django__MinLengthValidator__6a5eff32.py", "order": 7, "original_content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "parent_variant_id": "pyint-33bff5b9490a-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L471-L485", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "MinLengthValidator", "variant_id": "pyint-c7a66a5eff32-I07", "group_id": "py-7a619a40111047bd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 134, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-87c251fedd57-I08", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass MinLengthValidator(BaseValidator):\n    message = ngettext_lazy(\n        \"Ensure this value has at least %(limit_value)d character (it has \"\n        \"%(show_value)d).\",\n        \"Ensure this value has at least %(limit_value)d characters (it has \"\n        \"%(show_value)d).\",\n        \"limit_value\",\n    )\n    code = \"min_length\"\n\n    def compare(self, a, b):\n        return a < b\n\n    def clean(self, x):\n        running_total = 0\n        for current_number in range(1, 6):\n            running_total += current_number\n        return len(x)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-7a619a40111047bd", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "ef215d6f11e425f0fe4855aff96a33ad7afcb399247d9625d8131bf6c92d941f", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 32, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__MinLengthValidator__51fedd57.py", "order": 8, "original_content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "parent_variant_id": "pyint-33bff5b9490a-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L471-L485", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 0}, "unit_kind": "class", "unit_name": "MinLengthValidator", "variant_id": "pyint-87c251fedd57-I08", "group_id": "py-7a619a40111047bd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 135, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6a1f54b159e0-I09", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass MinLengthValidator(BaseValidator):\n    message = ngettext_lazy(\n        \"Ensure this value has at least %(limit_value)d character (it has \"\n        \"%(show_value)d).\",\n        \"Ensure this value has at least %(limit_value)d characters (it has \"\n        \"%(show_value)d).\",\n        \"limit_value\",\n    )\n    code = \"min_length\"\n\n    def compare(self, a, b):\n        return a < b\n\n    def clean(self, x):\n        lI0O_84c21c68, lI0O_8d4e01f3 = 0xd01d, True\n        while lI0O_8d4e01f3:\n            lI0O_84c21c68 ^= 0xd01d\n            lI0O_8d4e01f3 = False\n        return len(x)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-7a619a40111047bd", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "4a9229f1f18ff6995093a9bf99a21f919d6e7d9f55189dd5486b8b4c18996e20", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 33, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__MinLengthValidator__54b159e0.py", "order": 9, "original_content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "parent_variant_id": "pyint-33bff5b9490a-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L471-L485", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 7}, "unit_kind": "class", "unit_name": "MinLengthValidator", "variant_id": "pyint-6a1f54b159e0-I09", "group_id": "py-7a619a40111047bd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 136, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-46f2ccbb0737-I10", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass MinLengthValidator(BaseValidator):\n    message = ngettext_lazy(         \"Ensure this value has at least %(limit_value)d character (it has \"\n        \"%(show_value)d).\",\n        \"Ensure this value has at least %(limit_value)d characters (it has \"         \"%(show_value)d).\",\n        \"limit_value\",\n    )\n    code = \"min_length\"\n\n    def compare(self, a, b):\n        return a < b\n    def clean(self, x):\n        return len(x)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-7a619a40111047bd", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "fbf44550637b621eb70377b32b6675f30672cdc8a15e1e6374d10f154284dcb6", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 26, "local_path": "layout/partially-compact-layout/I10__django__MinLengthValidator__ccbb0737.py", "order": 10, "original_content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "parent_variant_id": "pyint-33bff5b9490a-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L471-L485", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 9, "line_break_groups_removed": 3, "line_breaks_removed": 3, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "MinLengthValidator", "variant_id": "pyint-46f2ccbb0737-I10", "group_id": "py-7a619a40111047bd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 137, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-60732fa299d3-I11", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass MinLengthValidator(BaseValidator):\n    message = ngettext_lazy(\n        \"Ensure this value has at least %(limit_value)d character (it has \"\n        \"%(show_value)d).\",\n        \"Ensure this value has at least %(limit_value)d characters (it has \"\n        \"%(show_value)d).\",\n        \"limit_value\",\n    )\n    code = \"min_length\"\n\n    def compare(self, a, b):\n        return a < b\n\n    def clean(self, x):\n        return len(x)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-7a619a40111047bd", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 29, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__MinLengthValidator__2fa299d3.py", "order": 11, "original_content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "parent_variant_id": "pyint-33bff5b9490a-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L471-L485", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "MinLengthValidator", "variant_id": "pyint-60732fa299d3-I11", "group_id": "py-7a619a40111047bd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 138, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-86bf33e13b9c-I12", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass MinLengthValidator(BaseValidator):\n    message = ngettext_lazy(\n        \"Ensure this value has at least %(limit_value)d character (it has \"\n        \"%(show_value)d).\",\n        \"Ensure this value has at least %(limit_value)d characters (it has \"\n        \"%(show_value)d).\",\n        \"limit_value\",\n    )\n    code = \"min_length\"\n\n    def compare(self, a, b):\n        return a < b\n\n    def clean(self, x):\n        return len(x)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-7a619a40111047bd", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 29, "local_path": "data-flow/inline-intermediate-variables/I12__django__MinLengthValidator__33e13b9c.py", "order": 12, "original_content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "parent_variant_id": "pyint-33bff5b9490a-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L471-L485", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "MinLengthValidator", "variant_id": "pyint-86bf33e13b9c-I12", "group_id": "py-7a619a40111047bd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 139, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-99e7f7bf57f1-I13", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass MinLengthValidator(BaseValidator):\n    message = ngettext_lazy(\n        \"Ensure this value has at least %(limit_value)d character (it has \"\n        \"%(show_value)d).\",\n        \"Ensure this value has at least %(limit_value)d characters (it has \"\n        \"%(show_value)d).\",\n        \"limit_value\",\n    )\n    code = \"min_length\"\n\n    def compare(self, a, b):\n        return a < b\n\n    def clean(self, x):\n        return len(x)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-7a619a40111047bd", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 29, "local_path": "control-flow/lower-for-to-while/I13__django__MinLengthValidator__f7bf57f1.py", "order": 13, "original_content_sha256": "6e47794e52512a1d90e1a8513c5302628968915ec688695507f5fdb6d0d14757", "parent_variant_id": "pyint-33bff5b9490a-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L471-L485", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "MinLengthValidator", "variant_id": "pyint-99e7f7bf57f1-I13", "group_id": "py-7a619a40111047bd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 140, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1a772163c099-SRC", "source": "from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\nclass DummyCache(BaseCache):\n    def __init__(self, host, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n    def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return True\n\n    def get(self, key, default=None, version=None):\n        self.make_and_validate_key(key, version=version)\n        return default\n\n    def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n\n    def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def delete(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def has_key(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def clear(self):\n        pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-7d467defc443fd60", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 31, "local_path": "source-original/SRC__django__DummyCache__2163c099.py", "order": 0, "original_content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/cache/backends/dummy.py#L6-L34", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "DummyCache", "variant_id": "pyint-1a772163c099-SRC", "group_id": "py-7d467defc443fd60", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 337, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c79e121e4e51-I01", "source": "from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\nclass DummyCache(BaseCache):\n    def __init__(self, host, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n    def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return True\n\n    def get(self, key, default=None, version=None):\n        self.make_and_validate_key(key, version=version)\n        return default\n\n    def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n\n    def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def delete(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def has_key(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def clear(self):\n        pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-7d467defc443fd60", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 31, "local_path": "comments/remove-comments/I01__django__DummyCache__121e4e51.py", "order": 1, "original_content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "parent_variant_id": "pyint-1a772163c099-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/cache/backends/dummy.py#L6-L34", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "DummyCache", "variant_id": "pyint-c79e121e4e51-I01", "group_id": "py-7d467defc443fd60", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 338, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f6b1c7db9183-I02", "source": "from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\nclass DummyCache(BaseCache):\n    def __init__(self, hos, *arg, **kwa):\n        super().__init__(*arg, **kwa)\n\n    def add(self, key2, val, tim=DEFAULT_TIMEOUT, ver=None):\n        self.make_and_validate_key(key2, version=ver)\n        return True\n\n    def get(self, key3, def2=None, ver2=None):\n        self.make_and_validate_key(key3, version=ver2)\n        return def2\n\n    def set(self, key4, val2, tim2=DEFAULT_TIMEOUT, ver3=None):\n        self.make_and_validate_key(key4, version=ver3)\n\n    def tou(self, key5, tim3=DEFAULT_TIMEOUT, ver4=None):\n        self.make_and_validate_key(key5, version=ver4)\n        return False\n\n    def del2(self, key6, ver5=None):\n        self.make_and_validate_key(key6, version=ver5)\n        return False\n\n    def has(self, key7, ver6=None):\n        self.make_and_validate_key(key7, version=ver6)\n        return False\n\n    def cle(self):\n        pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-7d467defc443fd60", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "36c04e173a918cf99587401a233c864cf68a01a0b362752e0548670801f52953", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 31, "local_path": "identifiers/shorten-identifiers/I02__django__DummyCache__c7db9183.py", "order": 2, "original_content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "parent_variant_id": "pyint-1a772163c099-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/cache/backends/dummy.py#L6-L34", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 43, "identifiers_declared": 28}, "unit_kind": "class", "unit_name": "DummyCache", "variant_id": "pyint-f6b1c7db9183-I02", "group_id": "py-7d467defc443fd60", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 339, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1ea53e05d9ad-I03", "source": "from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\nclass DummyCache(BaseCache):\n    def __init__(self, size, *data, **client):\n        super().__init__(*data, **client)\n\n    def open(self, age, total, nextKey=DEFAULT_TIMEOUT, channel=None):\n        self.make_and_validate_key(age, version=channel)\n        return True\n\n    def sync(self, age, invoice=None, context=None):\n        self.make_and_validate_key(age, version=context)\n        return invoice\n\n    def save(self, age, count, payload=DEFAULT_TIMEOUT, channel=None):\n        self.make_and_validate_key(age, version=channel)\n\n    def visit(self, map, session=DEFAULT_TIMEOUT, feature=None):\n        self.make_and_validate_key(map, version=feature)\n        return False\n\n    def derive(self, age, address=None):\n        self.make_and_validate_key(age, version=address)\n        return False\n\n    def contain(self, map, payload=None):\n        self.make_and_validate_key(map, version=payload)\n        return False\n\n    def parse(self):\n        pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-7d467defc443fd60", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "e55943b20e328d2b0f01a46cf43ba3e16580cf635ddb948e2572c411696efec4", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 31, "local_path": "identifiers/mislead-identifiers/I03__django__DummyCache__3e05d9ad.py", "order": 3, "original_content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "parent_variant_id": "pyint-1a772163c099-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/cache/backends/dummy.py#L6-L34", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 43, "identifiers_declared": 28, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 1, "local_exact_length_matches": 21, "local_random_pool_selections": 21, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 3, "method_exact_length_matches": 4, "method_random_pool_selections": 7, "method_total_length_difference": 3}, "unit_kind": "class", "unit_name": "DummyCache", "variant_id": "pyint-1ea53e05d9ad-I03", "group_id": "py-7d467defc443fd60", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 340, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-34c3e279626b-I04", "source": "from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\nclass DummyCache(BaseCache):\n    def __init__(self, h, *i, **j):\n        super().__init__(*i, **j)\n\n    def a(self, k, l, m=DEFAULT_TIMEOUT, n=None):\n        self.make_and_validate_key(k, version=n)\n        return True\n\n    def b(self, o, p=None, q=None):\n        self.make_and_validate_key(o, version=q)\n        return p\n\n    def c(self, r, s, t=DEFAULT_TIMEOUT, u=None):\n        self.make_and_validate_key(r, version=u)\n\n    def d(self, v, w=DEFAULT_TIMEOUT, x=None):\n        self.make_and_validate_key(v, version=x)\n        return False\n\n    def e(self, y, z=None):\n        self.make_and_validate_key(y, version=z)\n        return False\n\n    def f(self, A, B=None):\n        self.make_and_validate_key(A, version=B)\n        return False\n\n    def g(self):\n        pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-7d467defc443fd60", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "3a1aed46ebeb87197b7984368ca45040b467e65c42b4e94259abeecece9e40f3", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 31, "local_path": "identifiers/garble-identifiers/I04__django__DummyCache__e279626b.py", "order": 4, "original_content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "parent_variant_id": "pyint-1a772163c099-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/cache/backends/dummy.py#L6-L34", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 43, "identifiers_declared": 28}, "unit_kind": "class", "unit_name": "DummyCache", "variant_id": "pyint-34c3e279626b-I04", "group_id": "py-7d467defc443fd60", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 341, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-28236650840d-I05", "source": "from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\nclass DummyCache(BaseCache):\n    def __init__(self, host, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n    def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return True\n\n    def get(self, key, default=None, version=None):\n        self.make_and_validate_key(key, version=version)\n        return default\n\n    def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n\n    def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def delete(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def has_key(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def clear(self):\n        pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-7d467defc443fd60", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 31, "local_path": "expressions/encode-integer-literals/I05__django__DummyCache__6650840d.py", "order": 5, "original_content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "parent_variant_id": "pyint-1a772163c099-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/cache/backends/dummy.py#L6-L34", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "DummyCache", "variant_id": "pyint-28236650840d-I05", "group_id": "py-7d467defc443fd60", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 342, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c107eb707b14-I06", "source": "from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\nclass DummyCache(BaseCache):\n    def __init__(self, host, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n    def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return True\n\n    def get(self, key, default=None, version=None):\n        self.make_and_validate_key(key, version=version)\n        return default\n\n    def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n\n    def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def delete(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def has_key(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def clear(self):\n        pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-7d467defc443fd60", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 31, "local_path": "expressions/invert-conditions/I06__django__DummyCache__eb707b14.py", "order": 6, "original_content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "parent_variant_id": "pyint-1a772163c099-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/cache/backends/dummy.py#L6-L34", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "DummyCache", "variant_id": "pyint-c107eb707b14-I06", "group_id": "py-7d467defc443fd60", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 343, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-64a17ecb29ef-I07", "source": "from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\nclass DummyCache(BaseCache):\n    def __init__(self, host, *args, **kwargs):\n        if ((0x6daa ^ 0x6daa) != 0):\n            raise AssertionError()\n        super().__init__(*args, **kwargs)\n\n    def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        if ((0x42f4 ^ 0x42f4) != 0):\n            raise AssertionError()\n        self.make_and_validate_key(key, version=version)\n        return True\n\n    def get(self, key, default=None, version=None):\n        if ((0xd54e ^ 0xd54e) != 0):\n            raise AssertionError()\n        self.make_and_validate_key(key, version=version)\n        return default\n\n    def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        if ((0xb5ce ^ 0xb5ce) != 0):\n            raise AssertionError()\n        self.make_and_validate_key(key, version=version)\n\n    def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):\n        if ((0x204d ^ 0x204d) != 0):\n            raise AssertionError()\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def delete(self, key, version=None):\n        if ((0x3ca8 ^ 0x3ca8) != 0):\n            raise AssertionError()\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def has_key(self, key, version=None):\n        if ((0xce21 ^ 0xce21) != 0):\n            raise AssertionError()\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def clear(self):\n        if ((0x914a ^ 0x914a) != 0):\n            raise AssertionError()\n        pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-7d467defc443fd60", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "f2ff52d51b923763d41c2e7fd98a9ee890941a40b7d9332ebc3720200e3e5516", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 47, "local_path": "code-injection/insert-dead-branches/I07__django__DummyCache__7ecb29ef.py", "order": 7, "original_content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "parent_variant_id": "pyint-1a772163c099-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/cache/backends/dummy.py#L6-L34", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 8}, "unit_kind": "class", "unit_name": "DummyCache", "variant_id": "pyint-64a17ecb29ef-I07", "group_id": "py-7d467defc443fd60", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 344, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-54e6088948c0-I08", "source": "from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\nclass DummyCache(BaseCache):\n    def __init__(self, host, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n    def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return True\n\n    def get(self, key, default=None, version=None):\n        self.make_and_validate_key(key, version=version)\n        return default\n\n    def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        total_score = 240\n        number_of_scores = 3\n        average_score = total_score / number_of_scores\n        self.make_and_validate_key(key, version=version)\n\n    def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def delete(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def has_key(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def clear(self):\n        pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-7d467defc443fd60", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "b48e54733da2bf4eae4fba7529774f1d8b2c08d7039407f38525683f6da0f507", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 34, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__DummyCache__088948c0.py", "order": 8, "original_content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "parent_variant_id": "pyint-1a772163c099-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/cache/backends/dummy.py#L6-L34", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 5}, "unit_kind": "class", "unit_name": "DummyCache", "variant_id": "pyint-54e6088948c0-I08", "group_id": "py-7d467defc443fd60", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 345, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0b41c05a2103-I09", "source": "from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\nclass DummyCache(BaseCache):\n    def __init__(self, host, *args, **kwargs):\n        lI0O_db7b7209 = 0xc8f8 ^ 0xc8f8\n        if lI0O_db7b7209 != 0:\n            if ((lI0O_db7b7209 | 1) & 1) == 0:\n                lI0O_db7b7209 += 1\n            else:\n                lI0O_db7b7209 -= 1\n        super().__init__(*args, **kwargs)\n\n    def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return True\n\n    def get(self, key, default=None, version=None):\n        self.make_and_validate_key(key, version=version)\n        return default\n\n    def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n\n    def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def delete(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def has_key(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def clear(self):\n        pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-7d467defc443fd60", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "179ca62edfcd73e5946910b6ad1db563bd7a2371c07da7f205516b47b82e5460", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 37, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__DummyCache__c05a2103.py", "order": 9, "original_content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "parent_variant_id": "pyint-1a772163c099-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/cache/backends/dummy.py#L6-L34", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 5}, "unit_kind": "class", "unit_name": "DummyCache", "variant_id": "pyint-0b41c05a2103-I09", "group_id": "py-7d467defc443fd60", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 346, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1e5312c6af50-I10", "source": "from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\nclass DummyCache(BaseCache):\n    def __init__(self, host, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n    def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return True\n    def get(self, key, default=None, version=None):\n        self.make_and_validate_key(key, version=version)\n        return default\n\n    def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n\n    def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def delete(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n    def has_key(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n    def clear(self):\n        pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-7d467defc443fd60", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "9d6124816f6bc3b65f0448fc9ca87bf0ba2b4c0a1d8f3c48168281c7515a6b5c", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 28, "local_path": "layout/partially-compact-layout/I10__django__DummyCache__12c6af50.py", "order": 10, "original_content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "parent_variant_id": "pyint-1a772163c099-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/cache/backends/dummy.py#L6-L34", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 8, "line_break_groups_removed": 3, "line_breaks_removed": 3, "whitespace_characters_removed": 3}, "unit_kind": "class", "unit_name": "DummyCache", "variant_id": "pyint-1e5312c6af50-I10", "group_id": "py-7d467defc443fd60", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 347, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b91d7b161c37-I11", "source": "from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\nclass DummyCache(BaseCache):\n    def __init__(self, host, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n    def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return True\n\n    def get(self, key, default=None, version=None):\n        self.make_and_validate_key(key, version=version)\n        return default\n\n    def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n\n    def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def delete(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def has_key(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def clear(self):\n        pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-7d467defc443fd60", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 31, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__DummyCache__7b161c37.py", "order": 11, "original_content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "parent_variant_id": "pyint-1a772163c099-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/cache/backends/dummy.py#L6-L34", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "DummyCache", "variant_id": "pyint-b91d7b161c37-I11", "group_id": "py-7d467defc443fd60", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 348, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e7d0884686e7-I12", "source": "from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\nclass DummyCache(BaseCache):\n    def __init__(self, host, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n    def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return True\n\n    def get(self, key, default=None, version=None):\n        self.make_and_validate_key(key, version=version)\n        return default\n\n    def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n\n    def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def delete(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def has_key(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def clear(self):\n        pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-7d467defc443fd60", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 31, "local_path": "data-flow/inline-intermediate-variables/I12__django__DummyCache__884686e7.py", "order": 12, "original_content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "parent_variant_id": "pyint-1a772163c099-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/cache/backends/dummy.py#L6-L34", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "DummyCache", "variant_id": "pyint-e7d0884686e7-I12", "group_id": "py-7d467defc443fd60", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 349, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a09f59ad5b20-I13", "source": "from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\nclass DummyCache(BaseCache):\n    def __init__(self, host, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n    def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return True\n\n    def get(self, key, default=None, version=None):\n        self.make_and_validate_key(key, version=version)\n        return default\n\n    def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n\n    def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def delete(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def has_key(self, key, version=None):\n        self.make_and_validate_key(key, version=version)\n        return False\n\n    def clear(self):\n        pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-7d467defc443fd60", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 31, "local_path": "control-flow/lower-for-to-while/I13__django__DummyCache__59ad5b20.py", "order": 13, "original_content_sha256": "36b2e2ba2b2bcd7b44817e56566d1c58593cde9ee2d062a38259a309aaabe909", "parent_variant_id": "pyint-1a772163c099-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/cache/backends/dummy.py#L6-L34", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "DummyCache", "variant_id": "pyint-a09f59ad5b20-I13", "group_id": "py-7d467defc443fd60", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 350, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b66b443d6c80-SRC", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-7ecd969f3c5fd998", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 19, "local_path": "source-original/SRC__requests__AuthBase__443d6c80.py", "order": 0, "original_content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L78-L82", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "AuthBase", "variant_id": "pyint-b66b443d6c80-SRC", "group_id": "py-7ecd969f3c5fd998", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 743, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8e2175591b9a-I01", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass AuthBase:\n    \n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-7ecd969f3c5fd998", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "57b75747b2b9cefb13a92e420a643ee13b96a7bbec92441a84ce94ae86f7585a", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 19, "local_path": "comments/remove-comments/I01__requests__AuthBase__75591b9a.py", "order": 1, "original_content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "parent_variant_id": "pyint-b66b443d6c80-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L78-L82", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 58, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "AuthBase", "variant_id": "pyint-8e2175591b9a-I01", "group_id": "py-7ecd969f3c5fd998", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 744, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ec2b6c2211fa-I02", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-7ecd969f3c5fd998", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 19, "local_path": "identifiers/shorten-identifiers/I02__requests__AuthBase__6c2211fa.py", "order": 2, "original_content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "parent_variant_id": "pyint-b66b443d6c80-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L78-L82", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "AuthBase", "variant_id": "pyint-ec2b6c2211fa-I02", "group_id": "py-7ecd969f3c5fd998", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 745, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3a2cbb943e96-I03", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, key: PreparedRequest) -> PreparedRequest:\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-7ecd969f3c5fd998", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "a091589aee3d5a2776cb2c8ab3d686eac0eaf874d16c020de8e647c68a3f75c6", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 19, "local_path": "identifiers/mislead-identifiers/I03__requests__AuthBase__bb943e96.py", "order": 3, "original_content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "parent_variant_id": "pyint-b66b443d6c80-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L78-L82", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 0, "local_random_pool_selections": 1, "local_total_length_difference": 2, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "AuthBase", "variant_id": "pyint-3a2cbb943e96-I03", "group_id": "py-7ecd969f3c5fd998", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 746, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-12fdcf57320c-I04", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, a: PreparedRequest) -> PreparedRequest:\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-7ecd969f3c5fd998", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "17176a67a2b10b9abd40d46a8ce4cf7d0639ab9e099128b3e9f9e3abfb004915", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 19, "local_path": "identifiers/garble-identifiers/I04__requests__AuthBase__cf57320c.py", "order": 4, "original_content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "parent_variant_id": "pyint-b66b443d6c80-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L78-L82", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "AuthBase", "variant_id": "pyint-12fdcf57320c-I04", "group_id": "py-7ecd969f3c5fd998", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 747, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-11c5aefb5636-I05", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-7ecd969f3c5fd998", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 19, "local_path": "expressions/encode-integer-literals/I05__requests__AuthBase__aefb5636.py", "order": 5, "original_content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "parent_variant_id": "pyint-b66b443d6c80-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L78-L82", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "AuthBase", "variant_id": "pyint-11c5aefb5636-I05", "group_id": "py-7ecd969f3c5fd998", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 748, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-695299a2e2eb-I06", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-7ecd969f3c5fd998", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 19, "local_path": "expressions/invert-conditions/I06__requests__AuthBase__99a2e2eb.py", "order": 6, "original_content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "parent_variant_id": "pyint-b66b443d6c80-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L78-L82", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "AuthBase", "variant_id": "pyint-695299a2e2eb-I06", "group_id": "py-7ecd969f3c5fd998", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 749, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0f0c26d97474-I07", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        if ((0x67b ^ 0x67b) != 0):\n            raise AssertionError()\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-7ecd969f3c5fd998", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "49f0bcc5d22ef89186f1bb8884ed1223235679d453616ec904bac83efd2820c6", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 21, "local_path": "code-injection/insert-dead-branches/I07__requests__AuthBase__26d97474.py", "order": 7, "original_content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "parent_variant_id": "pyint-b66b443d6c80-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L78-L82", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "AuthBase", "variant_id": "pyint-0f0c26d97474-I07", "group_id": "py-7ecd969f3c5fd998", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 750, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b3d905701afd-I08", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        running_total = 0\n        for current_number in range(1, 6):\n            running_total += current_number\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-7ecd969f3c5fd998", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "32225d53d511d0b9563ba68428e4b5fc93f3e1e5a10c34217fb3c700d2f90c72", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 22, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__AuthBase__05701afd.py", "order": 8, "original_content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "parent_variant_id": "pyint-b66b443d6c80-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L78-L82", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 0}, "unit_kind": "class", "unit_name": "AuthBase", "variant_id": "pyint-b3d905701afd-I08", "group_id": "py-7ecd969f3c5fd998", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 751, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-05ac707aebdc-I09", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        lI0O_1bbe088e = 0xdcbf - 0xdcbf\n        lI0O_1bbe088e = (lI0O_1bbe088e | 0) if lI0O_1bbe088e == 0 else (lI0O_1bbe088e & 0)\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-7ecd969f3c5fd998", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "10f10f4a834ae6742ca40df46f784dab9bd098b3f52102eec3218f6fbb948d12", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 21, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__AuthBase__707aebdc.py", "order": 9, "original_content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "parent_variant_id": "pyint-b66b443d6c80-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L78-L82", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 1}, "unit_kind": "class", "unit_name": "AuthBase", "variant_id": "pyint-05ac707aebdc-I09", "group_id": "py-7ecd969f3c5fd998", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 752, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1ca001ba821f-I10", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-7ecd969f3c5fd998", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 19, "local_path": "layout/partially-compact-layout/I10__requests__AuthBase__01ba821f.py", "order": 10, "original_content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "parent_variant_id": "pyint-b66b443d6c80-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L78-L82", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 2, "line_break_groups_removed": 0, "line_breaks_removed": 0, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "AuthBase", "variant_id": "pyint-1ca001ba821f-I10", "group_id": "py-7ecd969f3c5fd998", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 753, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-323ce7dea43c-I11", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-7ecd969f3c5fd998", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 19, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__AuthBase__e7dea43c.py", "order": 11, "original_content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "parent_variant_id": "pyint-b66b443d6c80-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L78-L82", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "AuthBase", "variant_id": "pyint-323ce7dea43c-I11", "group_id": "py-7ecd969f3c5fd998", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 754, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6aca69356e3a-I12", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-7ecd969f3c5fd998", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 19, "local_path": "data-flow/inline-intermediate-variables/I12__requests__AuthBase__69356e3a.py", "order": 12, "original_content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "parent_variant_id": "pyint-b66b443d6c80-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L78-L82", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "AuthBase", "variant_id": "pyint-6aca69356e3a-I12", "group_id": "py-7ecd969f3c5fd998", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 755, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ce33b361f99e-I13", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-7ecd969f3c5fd998", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 19, "local_path": "control-flow/lower-for-to-while/I13__requests__AuthBase__b361f99e.py", "order": 13, "original_content_sha256": "ac505075db3388340ba7ffa5b412d2efc2d7e330bc5fbc79bdfbf2a441244a06", "parent_variant_id": "pyint-b66b443d6c80-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L78-L82", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "AuthBase", "variant_id": "pyint-ce33b361f99e-I13", "group_id": "py-7ecd969f3c5fd998", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 756, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-57e80663d14a-SRC", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass DefaultJSONProvider(JSONProvider):\n    \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n    library. Serializes the following additional data types:\n\n    -   :class:`datetime.datetime` and :class:`datetime.date` are\n        serialized to :rfc:`822` strings. This is the same as the HTTP\n        date format.\n    -   :class:`uuid.UUID` is serialized to a string.\n    -   :class:`dataclasses.dataclass` is passed to\n        :func:`dataclasses.asdict`.\n    -   :class:`~markupsafe.Markup` (or any object with a ``__html__``\n        method) will call the ``__html__`` method to get a string.\n    \"\"\"\n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does\n    not know how to serialize. It should return a valid JSON type or\n    raise a ``TypeError``.\n    \"\"\"\n\n    ensure_ascii = True\n    \"\"\"Replace non-ASCII characters with escape sequences. This may be\n    more compatible with some clients, but can be disabled for better\n    performance and size.\n    \"\"\"\n\n    sort_keys = True\n    \"\"\"Sort the keys in any serialized dicts. This may be useful for\n    some caching situations, but can be disabled for better performance.\n    When enabled, keys must all be strings, they are not converted\n    before sorting.\n    \"\"\"\n\n    compact: bool | None = None\n    \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n    output will not add indentation, newlines, or spaces. If ``False``,\n    or ``None`` in debug mode, it will use a non-compact representation.\n    \"\"\"\n\n    mimetype = \"application/json\"\n    \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON to a string.\n\n        Keyword arguments are passed to :func:`json.dumps`. Sets some\n        parameter defaults from the :attr:`default`,\n        :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n        :param obj: The data to serialize.\n        :param kwargs: Passed to :func:`json.dumps`.\n        \"\"\"\n        kwargs.setdefault(\"default\", self.default)\n        kwargs.setdefault(\"ensure_ascii\", self.ensure_ascii)\n        kwargs.setdefault(\"sort_keys\", self.sort_keys)\n        return json.dumps(obj, **kwargs)\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON from a string or bytes.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: Passed to :func:`json.loads`.\n        \"\"\"\n        return json.loads(s, **kwargs)\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with it. The response mimetype\n        will be \"application/json\" and can be changed with\n        :attr:`mimetype`.\n\n        If :attr:`compact` is ``False`` or debug mode is enabled, the\n        output will be formatted to be easier to read.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        dump_args: dict[str, t.Any] = {}\n\n        if (self.compact is None and self._app.debug) or self.compact is False:\n            dump_args.setdefault(\"indent\", 2)\n        else:\n            dump_args.setdefault(\"separators\", (\",\", \":\"))\n\n        return self._app.response_class(\n            f\"{self.dumps(obj, **dump_args)}\\n\", mimetype=self.mimetype\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-7efffe908fc3f2c2", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 102, "local_path": "source-original/SRC__flask__DefaultJSONProvider__0663d14a.py", "order": 0, "original_content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L124-L215", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "DefaultJSONProvider", "variant_id": "pyint-57e80663d14a-SRC", "group_id": "py-7efffe908fc3f2c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 421, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-41ed8f245767-I01", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass DefaultJSONProvider(JSONProvider):\n    \n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does\n    not know how to serialize. It should return a valid JSON type or\n    raise a ``TypeError``.\n    \"\"\"\n\n    ensure_ascii = True\n    \"\"\"Replace non-ASCII characters with escape sequences. This may be\n    more compatible with some clients, but can be disabled for better\n    performance and size.\n    \"\"\"\n\n    sort_keys = True\n    \"\"\"Sort the keys in any serialized dicts. This may be useful for\n    some caching situations, but can be disabled for better performance.\n    When enabled, keys must all be strings, they are not converted\n    before sorting.\n    \"\"\"\n\n    compact: bool | None = None\n    \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n    output will not add indentation, newlines, or spaces. If ``False``,\n    or ``None`` in debug mode, it will use a non-compact representation.\n    \"\"\"\n\n    mimetype = \"application/json\"\n    \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \n        kwargs.setdefault(\"default\", self.default)\n        kwargs.setdefault(\"ensure_ascii\", self.ensure_ascii)\n        kwargs.setdefault(\"sort_keys\", self.sort_keys)\n        return json.dumps(obj, **kwargs)\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \n        return json.loads(s, **kwargs)\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \n        obj = self._prepare_response_obj(args, kwargs)\n        dump_args: dict[str, t.Any] = {}\n\n        if (self.compact is None and self._app.debug) or self.compact is False:\n            dump_args.setdefault(\"indent\", 2)\n        else:\n            dump_args.setdefault(\"separators\", (\",\", \":\"))\n\n        return self._app.response_class(\n            f\"{self.dumps(obj, **dump_args)}\\n\", mimetype=self.mimetype\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-7efffe908fc3f2c2", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "5d09fefb1db4408d1b5083858b208a731790a3327bc843e76ab5ba0421f188d3", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 65, "local_path": "comments/remove-comments/I01__flask__DefaultJSONProvider__8f245767.py", "order": 1, "original_content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "parent_variant_id": "pyint-57e80663d14a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L124-L215", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 1708, "comments_removed": 4, "docstrings_removed": 4, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "DefaultJSONProvider", "variant_id": "pyint-41ed8f245767-I01", "group_id": "py-7efffe908fc3f2c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 422, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-44b21b4902ed-I02", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass DefaultJSONProvider(JSONProvider):\n    \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n    library. Serializes the following additional data types:\n\n    -   :class:`datetime.datetime` and :class:`datetime.date` are\n        serialized to :rfc:`822` strings. This is the same as the HTTP\n        date format.\n    -   :class:`uuid.UUID` is serialized to a string.\n    -   :class:`dataclasses.dataclass` is passed to\n        :func:`dataclasses.asdict`.\n    -   :class:`~markupsafe.Markup` (or any object with a ``__html__``\n        method) will call the ``__html__`` method to get a string.\n    \"\"\"\n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does\n    not know how to serialize. It should return a valid JSON type or\n    raise a ``TypeError``.\n    \"\"\"\n\n    ensure_ascii = True\n    \"\"\"Replace non-ASCII characters with escape sequences. This may be\n    more compatible with some clients, but can be disabled for better\n    performance and size.\n    \"\"\"\n\n    sort_keys = True\n    \"\"\"Sort the keys in any serialized dicts. This may be useful for\n    some caching situations, but can be disabled for better performance.\n    When enabled, keys must all be strings, they are not converted\n    before sorting.\n    \"\"\"\n\n    compact: bool | None = None\n    \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n    output will not add indentation, newlines, or spaces. If ``False``,\n    or ``None`` in debug mode, it will use a non-compact representation.\n    \"\"\"\n\n    mimetype = \"application/json\"\n    \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n    def dum(self, obj2: t.Any, **kwa: t.Any) -> str:\n        \"\"\"Serialize data as JSON to a string.\n\n        Keyword arguments are passed to :func:`json.dumps`. Sets some\n        parameter defaults from the :attr:`default`,\n        :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n        :param obj: The data to serialize.\n        :param kwargs: Passed to :func:`json.dumps`.\n        \"\"\"\n        kwa.setdefault(\"default\", self.default)\n        kwa.setdefault(\"ensure_ascii\", self.ensure_ascii)\n        kwa.setdefault(\"sort_keys\", self.sort_keys)\n        return json.dumps(obj2, **kwa)\n\n    def loa(self, s2: str | bytes, **kwa2: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON from a string or bytes.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: Passed to :func:`json.loads`.\n        \"\"\"\n        return json.loads(s2, **kwa2)\n\n    def res(self, *arg: t.Any, **kwa3: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with it. The response mimetype\n        will be \"application/json\" and can be changed with\n        :attr:`mimetype`.\n\n        If :attr:`compact` is ``False`` or debug mode is enabled, the\n        output will be formatted to be easier to read.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj3 = self._prepare_response_obj(arg, kwa3)\n        dump: dict[str, t.Any] = {}\n\n        if (self.compact is None and self._app.debug) or self.compact is False:\n            dump.setdefault(\"indent\", 2)\n        else:\n            dump.setdefault(\"separators\", (\",\", \":\"))\n\n        return self._app.response_class(\n            f\"{self.dum(obj3, **dump)}\\n\", mimetype=self.mimetype\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-7efffe908fc3f2c2", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "2c39428e9e22c8cac45bb06cc5cabfc16af3dd09316b80f5f8ef7efc0052a997", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 102, "local_path": "identifiers/shorten-identifiers/I02__flask__DefaultJSONProvider__1b4902ed.py", "order": 2, "original_content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "parent_variant_id": "pyint-57e80663d14a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L124-L215", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 25, "identifiers_declared": 11}, "unit_kind": "class", "unit_name": "DefaultJSONProvider", "variant_id": "pyint-44b21b4902ed-I02", "group_id": "py-7efffe908fc3f2c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 423, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9970de029cb8-I03", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass DefaultJSONProvider(JSONProvider):\n    \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n    library. Serializes the following additional data types:\n\n    -   :class:`datetime.datetime` and :class:`datetime.date` are\n        serialized to :rfc:`822` strings. This is the same as the HTTP\n        date format.\n    -   :class:`uuid.UUID` is serialized to a string.\n    -   :class:`dataclasses.dataclass` is passed to\n        :func:`dataclasses.asdict`.\n    -   :class:`~markupsafe.Markup` (or any object with a ``__html__``\n        method) will call the ``__html__`` method to get a string.\n    \"\"\"\n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does\n    not know how to serialize. It should return a valid JSON type or\n    raise a ``TypeError``.\n    \"\"\"\n\n    ensure_ascii = True\n    \"\"\"Replace non-ASCII characters with escape sequences. This may be\n    more compatible with some clients, but can be disabled for better\n    performance and size.\n    \"\"\"\n\n    sort_keys = True\n    \"\"\"Sort the keys in any serialized dicts. This may be useful for\n    some caching situations, but can be disabled for better performance.\n    When enabled, keys must all be strings, they are not converted\n    before sorting.\n    \"\"\"\n\n    compact: bool | None = None\n    \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n    output will not add indentation, newlines, or spaces. If ``False``,\n    or ``None`` in debug mode, it will use a non-compact representation.\n    \"\"\"\n\n    mimetype = \"application/json\"\n    \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n    def close(self, map: t.Any, **client: t.Any) -> str:\n        \"\"\"Serialize data as JSON to a string.\n\n        Keyword arguments are passed to :func:`json.dumps`. Sets some\n        parameter defaults from the :attr:`default`,\n        :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n        :param obj: The data to serialize.\n        :param kwargs: Passed to :func:`json.dumps`.\n        \"\"\"\n        client.setdefault(\"default\", self.default)\n        client.setdefault(\"ensure_ascii\", self.ensure_ascii)\n        client.setdefault(\"sort_keys\", self.sort_keys)\n        return json.dumps(map, **client)\n\n    def apply(self, key: str | bytes, **target: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON from a string or bytes.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: Passed to :func:`json.loads`.\n        \"\"\"\n        return json.loads(key, **target)\n\n    def sendNode(self, *user: t.Any, **buffer: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with it. The response mimetype\n        will be \"application/json\" and can be changed with\n        :attr:`mimetype`.\n\n        If :attr:`compact` is ``False`` or debug mode is enabled, the\n        output will be formatted to be easier to read.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        map = self._prepare_response_obj(user, buffer)\n        finalMode: dict[str, t.Any] = {}\n\n        if (self.compact is None and self._app.debug) or self.compact is False:\n            finalMode.setdefault(\"indent\", 2)\n        else:\n            finalMode.setdefault(\"separators\", (\",\", \":\"))\n\n        return self._app.response_class(\n            f\"{self.close(map, **finalMode)}\\n\", mimetype=self.mimetype\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-7efffe908fc3f2c2", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "f1e6f8e160a59ee7bf28aca788a90ace762d75043b1ae16bdae19d83f93aa56c", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 102, "local_path": "identifiers/mislead-identifiers/I03__flask__DefaultJSONProvider__de029cb8.py", "order": 3, "original_content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "parent_variant_id": "pyint-57e80663d14a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L124-L215", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 25, "identifiers_declared": 11, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 7, "local_random_pool_selections": 8, "local_total_length_difference": 2, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 3, "method_random_pool_selections": 3, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "DefaultJSONProvider", "variant_id": "pyint-9970de029cb8-I03", "group_id": "py-7efffe908fc3f2c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 424, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3ab24647bd38-I04", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass DefaultJSONProvider(JSONProvider):\n    \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n    library. Serializes the following additional data types:\n\n    -   :class:`datetime.datetime` and :class:`datetime.date` are\n        serialized to :rfc:`822` strings. This is the same as the HTTP\n        date format.\n    -   :class:`uuid.UUID` is serialized to a string.\n    -   :class:`dataclasses.dataclass` is passed to\n        :func:`dataclasses.asdict`.\n    -   :class:`~markupsafe.Markup` (or any object with a ``__html__``\n        method) will call the ``__html__`` method to get a string.\n    \"\"\"\n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does\n    not know how to serialize. It should return a valid JSON type or\n    raise a ``TypeError``.\n    \"\"\"\n\n    ensure_ascii = True\n    \"\"\"Replace non-ASCII characters with escape sequences. This may be\n    more compatible with some clients, but can be disabled for better\n    performance and size.\n    \"\"\"\n\n    sort_keys = True\n    \"\"\"Sort the keys in any serialized dicts. This may be useful for\n    some caching situations, but can be disabled for better performance.\n    When enabled, keys must all be strings, they are not converted\n    before sorting.\n    \"\"\"\n\n    compact: bool | None = None\n    \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n    output will not add indentation, newlines, or spaces. If ``False``,\n    or ``None`` in debug mode, it will use a non-compact representation.\n    \"\"\"\n\n    mimetype = \"application/json\"\n    \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n    def a(self, d: t.Any, **e: t.Any) -> str:\n        \"\"\"Serialize data as JSON to a string.\n\n        Keyword arguments are passed to :func:`json.dumps`. Sets some\n        parameter defaults from the :attr:`default`,\n        :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n        :param obj: The data to serialize.\n        :param kwargs: Passed to :func:`json.dumps`.\n        \"\"\"\n        e.setdefault(\"default\", self.default)\n        e.setdefault(\"ensure_ascii\", self.ensure_ascii)\n        e.setdefault(\"sort_keys\", self.sort_keys)\n        return json.dumps(d, **e)\n\n    def b(self, f: str | bytes, **g: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON from a string or bytes.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: Passed to :func:`json.loads`.\n        \"\"\"\n        return json.loads(f, **g)\n\n    def c(self, *h: t.Any, **i: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with it. The response mimetype\n        will be \"application/json\" and can be changed with\n        :attr:`mimetype`.\n\n        If :attr:`compact` is ``False`` or debug mode is enabled, the\n        output will be formatted to be easier to read.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        j = self._prepare_response_obj(h, i)\n        k: dict[str, t.Any] = {}\n\n        if (self.compact is None and self._app.debug) or self.compact is False:\n            k.setdefault(\"indent\", 2)\n        else:\n            k.setdefault(\"separators\", (\",\", \":\"))\n\n        return self._app.response_class(\n            f\"{self.a(j, **k)}\\n\", mimetype=self.mimetype\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-7efffe908fc3f2c2", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "dd6fbe14cef9f6c77f7d7fd0cc8209908ddd2263c42f3d6a77dd7de7b8abab3b", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 102, "local_path": "identifiers/garble-identifiers/I04__flask__DefaultJSONProvider__4647bd38.py", "order": 4, "original_content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "parent_variant_id": "pyint-57e80663d14a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L124-L215", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 25, "identifiers_declared": 11}, "unit_kind": "class", "unit_name": "DefaultJSONProvider", "variant_id": "pyint-3ab24647bd38-I04", "group_id": "py-7efffe908fc3f2c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 425, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a77ba7bb03d2-I05", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass DefaultJSONProvider(JSONProvider):\n    \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n    library. Serializes the following additional data types:\n\n    -   :class:`datetime.datetime` and :class:`datetime.date` are\n        serialized to :rfc:`822` strings. This is the same as the HTTP\n        date format.\n    -   :class:`uuid.UUID` is serialized to a string.\n    -   :class:`dataclasses.dataclass` is passed to\n        :func:`dataclasses.asdict`.\n    -   :class:`~markupsafe.Markup` (or any object with a ``__html__``\n        method) will call the ``__html__`` method to get a string.\n    \"\"\"\n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does\n    not know how to serialize. It should return a valid JSON type or\n    raise a ``TypeError``.\n    \"\"\"\n\n    ensure_ascii = True\n    \"\"\"Replace non-ASCII characters with escape sequences. This may be\n    more compatible with some clients, but can be disabled for better\n    performance and size.\n    \"\"\"\n\n    sort_keys = True\n    \"\"\"Sort the keys in any serialized dicts. This may be useful for\n    some caching situations, but can be disabled for better performance.\n    When enabled, keys must all be strings, they are not converted\n    before sorting.\n    \"\"\"\n\n    compact: bool | None = None\n    \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n    output will not add indentation, newlines, or spaces. If ``False``,\n    or ``None`` in debug mode, it will use a non-compact representation.\n    \"\"\"\n\n    mimetype = \"application/json\"\n    \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON to a string.\n\n        Keyword arguments are passed to :func:`json.dumps`. Sets some\n        parameter defaults from the :attr:`default`,\n        :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n        :param obj: The data to serialize.\n        :param kwargs: Passed to :func:`json.dumps`.\n        \"\"\"\n        kwargs.setdefault(\"default\", self.default)\n        kwargs.setdefault(\"ensure_ascii\", self.ensure_ascii)\n        kwargs.setdefault(\"sort_keys\", self.sort_keys)\n        return json.dumps(obj, **kwargs)\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON from a string or bytes.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: Passed to :func:`json.loads`.\n        \"\"\"\n        return json.loads(s, **kwargs)\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with it. The response mimetype\n        will be \"application/json\" and can be changed with\n        :attr:`mimetype`.\n\n        If :attr:`compact` is ``False`` or debug mode is enabled, the\n        output will be formatted to be easier to read.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        dump_args: dict[str, t.Any] = {}\n\n        if (self.compact is None and self._app.debug) or self.compact is False:\n            dump_args.setdefault(\"indent\", 0x2)\n        else:\n            dump_args.setdefault(\"separators\", (\",\", \":\"))\n\n        return self._app.response_class(\n            f\"{self.dumps(obj, **dump_args)}\\n\", mimetype=self.mimetype\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-7efffe908fc3f2c2", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "3cc3b5b8487d7be117ff50484f883c951af7c65a27ef8ad5e773951758d14457", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 102, "local_path": "expressions/encode-integer-literals/I05__flask__DefaultJSONProvider__a7bb03d2.py", "order": 5, "original_content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "parent_variant_id": "pyint-57e80663d14a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L124-L215", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 1}, "unit_kind": "class", "unit_name": "DefaultJSONProvider", "variant_id": "pyint-a77ba7bb03d2-I05", "group_id": "py-7efffe908fc3f2c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 426, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ed772478c221-I06", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass DefaultJSONProvider(JSONProvider):\n    \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n    library. Serializes the following additional data types:\n\n    -   :class:`datetime.datetime` and :class:`datetime.date` are\n        serialized to :rfc:`822` strings. This is the same as the HTTP\n        date format.\n    -   :class:`uuid.UUID` is serialized to a string.\n    -   :class:`dataclasses.dataclass` is passed to\n        :func:`dataclasses.asdict`.\n    -   :class:`~markupsafe.Markup` (or any object with a ``__html__``\n        method) will call the ``__html__`` method to get a string.\n    \"\"\"\n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does\n    not know how to serialize. It should return a valid JSON type or\n    raise a ``TypeError``.\n    \"\"\"\n\n    ensure_ascii = True\n    \"\"\"Replace non-ASCII characters with escape sequences. This may be\n    more compatible with some clients, but can be disabled for better\n    performance and size.\n    \"\"\"\n\n    sort_keys = True\n    \"\"\"Sort the keys in any serialized dicts. This may be useful for\n    some caching situations, but can be disabled for better performance.\n    When enabled, keys must all be strings, they are not converted\n    before sorting.\n    \"\"\"\n\n    compact: bool | None = None\n    \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n    output will not add indentation, newlines, or spaces. If ``False``,\n    or ``None`` in debug mode, it will use a non-compact representation.\n    \"\"\"\n\n    mimetype = \"application/json\"\n    \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON to a string.\n\n        Keyword arguments are passed to :func:`json.dumps`. Sets some\n        parameter defaults from the :attr:`default`,\n        :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n        :param obj: The data to serialize.\n        :param kwargs: Passed to :func:`json.dumps`.\n        \"\"\"\n        kwargs.setdefault(\"default\", self.default)\n        kwargs.setdefault(\"ensure_ascii\", self.ensure_ascii)\n        kwargs.setdefault(\"sort_keys\", self.sort_keys)\n        return json.dumps(obj, **kwargs)\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON from a string or bytes.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: Passed to :func:`json.loads`.\n        \"\"\"\n        return json.loads(s, **kwargs)\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with it. The response mimetype\n        will be \"application/json\" and can be changed with\n        :attr:`mimetype`.\n\n        If :attr:`compact` is ``False`` or debug mode is enabled, the\n        output will be formatted to be easier to read.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        dump_args: dict[str, t.Any] = {}\n\n        if not ((self.compact is None and self._app.debug) or self.compact is False):\n            dump_args.setdefault(\"separators\", (\",\", \":\"))\n        else:\n            dump_args.setdefault(\"indent\", 2)\n\n        return self._app.response_class(\n            f\"{self.dumps(obj, **dump_args)}\\n\", mimetype=self.mimetype\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-7efffe908fc3f2c2", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "96d9f7c8c28451918af2a218e7d5df60171a38dae848f6bf6c661921ff74b4b9", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 102, "local_path": "expressions/invert-conditions/I06__flask__DefaultJSONProvider__2478c221.py", "order": 6, "original_content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "parent_variant_id": "pyint-57e80663d14a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L124-L215", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "DefaultJSONProvider", "variant_id": "pyint-ed772478c221-I06", "group_id": "py-7efffe908fc3f2c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 427, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c27aa3967b8c-I07", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass DefaultJSONProvider(JSONProvider):\n    \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n    library. Serializes the following additional data types:\n\n    -   :class:`datetime.datetime` and :class:`datetime.date` are\n        serialized to :rfc:`822` strings. This is the same as the HTTP\n        date format.\n    -   :class:`uuid.UUID` is serialized to a string.\n    -   :class:`dataclasses.dataclass` is passed to\n        :func:`dataclasses.asdict`.\n    -   :class:`~markupsafe.Markup` (or any object with a ``__html__``\n        method) will call the ``__html__`` method to get a string.\n    \"\"\"\n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does\n    not know how to serialize. It should return a valid JSON type or\n    raise a ``TypeError``.\n    \"\"\"\n\n    ensure_ascii = True\n    \"\"\"Replace non-ASCII characters with escape sequences. This may be\n    more compatible with some clients, but can be disabled for better\n    performance and size.\n    \"\"\"\n\n    sort_keys = True\n    \"\"\"Sort the keys in any serialized dicts. This may be useful for\n    some caching situations, but can be disabled for better performance.\n    When enabled, keys must all be strings, they are not converted\n    before sorting.\n    \"\"\"\n\n    compact: bool | None = None\n    \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n    output will not add indentation, newlines, or spaces. If ``False``,\n    or ``None`` in debug mode, it will use a non-compact representation.\n    \"\"\"\n\n    mimetype = \"application/json\"\n    \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON to a string.\n\n        Keyword arguments are passed to :func:`json.dumps`. Sets some\n        parameter defaults from the :attr:`default`,\n        :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n        :param obj: The data to serialize.\n        :param kwargs: Passed to :func:`json.dumps`.\n        \"\"\"\n        if ((0x3cec ^ 0x3cec) != 0):\n            raise AssertionError()\n        kwargs.setdefault(\"default\", self.default)\n        kwargs.setdefault(\"ensure_ascii\", self.ensure_ascii)\n        kwargs.setdefault(\"sort_keys\", self.sort_keys)\n        return json.dumps(obj, **kwargs)\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON from a string or bytes.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: Passed to :func:`json.loads`.\n        \"\"\"\n        if ((0xbf3d ^ 0xbf3d) != 0):\n            raise AssertionError()\n        return json.loads(s, **kwargs)\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with it. The response mimetype\n        will be \"application/json\" and can be changed with\n        :attr:`mimetype`.\n\n        If :attr:`compact` is ``False`` or debug mode is enabled, the\n        output will be formatted to be easier to read.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        if ((0x19e1 ^ 0x19e1) != 0):\n            raise AssertionError()\n        obj = self._prepare_response_obj(args, kwargs)\n        dump_args: dict[str, t.Any] = {}\n\n        if (self.compact is None and self._app.debug) or self.compact is False:\n            dump_args.setdefault(\"indent\", 2)\n        else:\n            dump_args.setdefault(\"separators\", (\",\", \":\"))\n\n        return self._app.response_class(\n            f\"{self.dumps(obj, **dump_args)}\\n\", mimetype=self.mimetype\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-7efffe908fc3f2c2", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "278f44c47b5ac5265f6ac52f6f0e6d652dec85d0eb5038d6489603b052060b2f", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 108, "local_path": "code-injection/insert-dead-branches/I07__flask__DefaultJSONProvider__a3967b8c.py", "order": 7, "original_content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "parent_variant_id": "pyint-57e80663d14a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L124-L215", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 3}, "unit_kind": "class", "unit_name": "DefaultJSONProvider", "variant_id": "pyint-c27aa3967b8c-I07", "group_id": "py-7efffe908fc3f2c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 428, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-804c228cd491-I08", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass DefaultJSONProvider(JSONProvider):\n    \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n    library. Serializes the following additional data types:\n\n    -   :class:`datetime.datetime` and :class:`datetime.date` are\n        serialized to :rfc:`822` strings. This is the same as the HTTP\n        date format.\n    -   :class:`uuid.UUID` is serialized to a string.\n    -   :class:`dataclasses.dataclass` is passed to\n        :func:`dataclasses.asdict`.\n    -   :class:`~markupsafe.Markup` (or any object with a ``__html__``\n        method) will call the ``__html__`` method to get a string.\n    \"\"\"\n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does\n    not know how to serialize. It should return a valid JSON type or\n    raise a ``TypeError``.\n    \"\"\"\n\n    ensure_ascii = True\n    \"\"\"Replace non-ASCII characters with escape sequences. This may be\n    more compatible with some clients, but can be disabled for better\n    performance and size.\n    \"\"\"\n\n    sort_keys = True\n    \"\"\"Sort the keys in any serialized dicts. This may be useful for\n    some caching situations, but can be disabled for better performance.\n    When enabled, keys must all be strings, they are not converted\n    before sorting.\n    \"\"\"\n\n    compact: bool | None = None\n    \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n    output will not add indentation, newlines, or spaces. If ``False``,\n    or ``None`` in debug mode, it will use a non-compact representation.\n    \"\"\"\n\n    mimetype = \"application/json\"\n    \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON to a string.\n\n        Keyword arguments are passed to :func:`json.dumps`. Sets some\n        parameter defaults from the :attr:`default`,\n        :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n        :param obj: The data to serialize.\n        :param kwargs: Passed to :func:`json.dumps`.\n        \"\"\"\n        kwargs.setdefault(\"default\", self.default)\n        kwargs.setdefault(\"ensure_ascii\", self.ensure_ascii)\n        kwargs.setdefault(\"sort_keys\", self.sort_keys)\n        return json.dumps(obj, **kwargs)\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON from a string or bytes.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: Passed to :func:`json.loads`.\n        \"\"\"\n        return json.loads(s, **kwargs)\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with it. The response mimetype\n        will be \"application/json\" and can be changed with\n        :attr:`mimetype`.\n\n        If :attr:`compact` is ``False`` or debug mode is enabled, the\n        output will be formatted to be easier to read.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        first_score = 72\n        second_score = 85\n        if first_score > second_score:\n            higher_score = first_score\n        else:\n            higher_score = second_score\n        obj = self._prepare_response_obj(args, kwargs)\n        dump_args: dict[str, t.Any] = {}\n\n        if (self.compact is None and self._app.debug) or self.compact is False:\n            dump_args.setdefault(\"indent\", 2)\n        else:\n            dump_args.setdefault(\"separators\", (\",\", \":\"))\n\n        return self._app.response_class(\n            f\"{self.dumps(obj, **dump_args)}\\n\", mimetype=self.mimetype\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-7efffe908fc3f2c2", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d80c9c01d0bd5b75a79fca8b5b812258f4d423524b303b30f1b62a7a31d84078", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 108, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__DefaultJSONProvider__228cd491.py", "order": 8, "original_content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "parent_variant_id": "pyint-57e80663d14a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L124-L215", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 3}, "unit_kind": "class", "unit_name": "DefaultJSONProvider", "variant_id": "pyint-804c228cd491-I08", "group_id": "py-7efffe908fc3f2c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 429, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3fb5a9e27d5a-I09", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass DefaultJSONProvider(JSONProvider):\n    \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n    library. Serializes the following additional data types:\n\n    -   :class:`datetime.datetime` and :class:`datetime.date` are\n        serialized to :rfc:`822` strings. This is the same as the HTTP\n        date format.\n    -   :class:`uuid.UUID` is serialized to a string.\n    -   :class:`dataclasses.dataclass` is passed to\n        :func:`dataclasses.asdict`.\n    -   :class:`~markupsafe.Markup` (or any object with a ``__html__``\n        method) will call the ``__html__`` method to get a string.\n    \"\"\"\n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does\n    not know how to serialize. It should return a valid JSON type or\n    raise a ``TypeError``.\n    \"\"\"\n\n    ensure_ascii = True\n    \"\"\"Replace non-ASCII characters with escape sequences. This may be\n    more compatible with some clients, but can be disabled for better\n    performance and size.\n    \"\"\"\n\n    sort_keys = True\n    \"\"\"Sort the keys in any serialized dicts. This may be useful for\n    some caching situations, but can be disabled for better performance.\n    When enabled, keys must all be strings, they are not converted\n    before sorting.\n    \"\"\"\n\n    compact: bool | None = None\n    \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n    output will not add indentation, newlines, or spaces. If ``False``,\n    or ``None`` in debug mode, it will use a non-compact representation.\n    \"\"\"\n\n    mimetype = \"application/json\"\n    \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON to a string.\n\n        Keyword arguments are passed to :func:`json.dumps`. Sets some\n        parameter defaults from the :attr:`default`,\n        :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n        :param obj: The data to serialize.\n        :param kwargs: Passed to :func:`json.dumps`.\n        \"\"\"\n        kwargs.setdefault(\"default\", self.default)\n        kwargs.setdefault(\"ensure_ascii\", self.ensure_ascii)\n        kwargs.setdefault(\"sort_keys\", self.sort_keys)\n        return json.dumps(obj, **kwargs)\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON from a string or bytes.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: Passed to :func:`json.loads`.\n        \"\"\"\n        lI0O_ffc556b2 = 0xfb8a\n        lI0O_ffc556b2 = ((lI0O_ffc556b2 ^ 0xfb8a) | 0) & -1\n        if (lI0O_ffc556b2 & 1) == 1:\n            lI0O_ffc556b2 ^= lI0O_ffc556b2\n        return json.loads(s, **kwargs)\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with it. The response mimetype\n        will be \"application/json\" and can be changed with\n        :attr:`mimetype`.\n\n        If :attr:`compact` is ``False`` or debug mode is enabled, the\n        output will be formatted to be easier to read.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        dump_args: dict[str, t.Any] = {}\n\n        if (self.compact is None and self._app.debug) or self.compact is False:\n            dump_args.setdefault(\"indent\", 2)\n        else:\n            dump_args.setdefault(\"separators\", (\",\", \":\"))\n\n        return self._app.response_class(\n            f\"{self.dumps(obj, **dump_args)}\\n\", mimetype=self.mimetype\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-7efffe908fc3f2c2", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "c40c5bbdf307404f4dc0321c227c2711d5c6d0cc6d929279b7da946f9334bf64", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 106, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__DefaultJSONProvider__a9e27d5a.py", "order": 9, "original_content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "parent_variant_id": "pyint-57e80663d14a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L124-L215", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 0}, "unit_kind": "class", "unit_name": "DefaultJSONProvider", "variant_id": "pyint-3fb5a9e27d5a-I09", "group_id": "py-7efffe908fc3f2c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 430, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fb7313aa1651-I10", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass DefaultJSONProvider(JSONProvider):\n    \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n    library. Serializes the following additional data types:\n\n    -   :class:`datetime.datetime` and :class:`datetime.date` are\n        serialized to :rfc:`822` strings. This is the same as the HTTP\n        date format.\n    -   :class:`uuid.UUID` is serialized to a string.\n    -   :class:`dataclasses.dataclass` is passed to\n        :func:`dataclasses.asdict`.\n    -   :class:`~markupsafe.Markup` (or any object with a ``__html__``\n        method) will call the ``__html__`` method to get a string.\n    \"\"\"\n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does\n    not know how to serialize. It should return a valid JSON type or\n    raise a ``TypeError``.\n    \"\"\"\n    ensure_ascii = True\n    \"\"\"Replace non-ASCII characters with escape sequences. This may be\n    more compatible with some clients, but can be disabled for better\n    performance and size.\n    \"\"\"\n    sort_keys = True\n    \"\"\"Sort the keys in any serialized dicts. This may be useful for\n    some caching situations, but can be disabled for better performance.\n    When enabled, keys must all be strings, they are not converted\n    before sorting.\n    \"\"\"\n\n    compact: bool | None = None\n    \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n    output will not add indentation, newlines, or spaces. If ``False``,\n    or ``None`` in debug mode, it will use a non-compact representation.\n    \"\"\"\n    mimetype = \"application/json\"\n    \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON to a string.\n        Keyword arguments are passed to :func:`json.dumps`. Sets some\n        parameter defaults from the :attr:`default`,\n        :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n        :param obj: The data to serialize.\n        :param kwargs: Passed to :func:`json.dumps`.\n        \"\"\"\n        kwargs.setdefault(\"default\", self.default)\n        kwargs.setdefault(\"ensure_ascii\", self.ensure_ascii)\n        kwargs.setdefault(\"sort_keys\", self.sort_keys)\n        return json.dumps(obj, **kwargs)\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON from a string or bytes.\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: Passed to :func:`json.loads`.\n        \"\"\"\n        return json.loads(s, **kwargs)\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with it. The response mimetype\n        will be \"application/json\" and can be changed with\n        :attr:`mimetype`.\n        If :attr:`compact` is ``False`` or debug mode is enabled, the\n        output will be formatted to be easier to read.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        dump_args: dict[str, t.Any] = {}\n\n        if (self.compact is None and self._app.debug) or self.compact is False:\n            dump_args.setdefault(\"indent\", 2)\n        else:\n            dump_args.setdefault(\"separators\", (\",\", \":\"))\n\n        return self._app.response_class(             f\"{self.dumps(obj, **dump_args)}\\n\", mimetype=self.mimetype\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-7efffe908fc3f2c2", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "ed8e4095a02a0d32fdb6c4beb48754816a73d7c8e4b32186990230bddb4181b5", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 94, "local_path": "layout/partially-compact-layout/I10__flask__DefaultJSONProvider__13aa1651.py", "order": 10, "original_content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "parent_variant_id": "pyint-57e80663d14a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L124-L215", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 20, "line_break_groups_removed": 8, "line_breaks_removed": 8, "whitespace_characters_removed": 7}, "unit_kind": "class", "unit_name": "DefaultJSONProvider", "variant_id": "pyint-fb7313aa1651-I10", "group_id": "py-7efffe908fc3f2c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 431, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d8f7a9429937-I11", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass DefaultJSONProvider(JSONProvider):\n    \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n    library. Serializes the following additional data types:\n\n    -   :class:`datetime.datetime` and :class:`datetime.date` are\n        serialized to :rfc:`822` strings. This is the same as the HTTP\n        date format.\n    -   :class:`uuid.UUID` is serialized to a string.\n    -   :class:`dataclasses.dataclass` is passed to\n        :func:`dataclasses.asdict`.\n    -   :class:`~markupsafe.Markup` (or any object with a ``__html__``\n        method) will call the ``__html__`` method to get a string.\n    \"\"\"\n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does\n    not know how to serialize. It should return a valid JSON type or\n    raise a ``TypeError``.\n    \"\"\"\n\n    ensure_ascii = True\n    \"\"\"Replace non-ASCII characters with escape sequences. This may be\n    more compatible with some clients, but can be disabled for better\n    performance and size.\n    \"\"\"\n\n    sort_keys = True\n    \"\"\"Sort the keys in any serialized dicts. This may be useful for\n    some caching situations, but can be disabled for better performance.\n    When enabled, keys must all be strings, they are not converted\n    before sorting.\n    \"\"\"\n\n    compact: bool | None = None\n    \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n    output will not add indentation, newlines, or spaces. If ``False``,\n    or ``None`` in debug mode, it will use a non-compact representation.\n    \"\"\"\n\n    mimetype = \"application/json\"\n    \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON to a string.\n\n        Keyword arguments are passed to :func:`json.dumps`. Sets some\n        parameter defaults from the :attr:`default`,\n        :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n        :param obj: The data to serialize.\n        :param kwargs: Passed to :func:`json.dumps`.\n        \"\"\"\n        kwargs.setdefault(\"default\", self.default)\n        kwargs.setdefault(\"ensure_ascii\", self.ensure_ascii)\n        kwargs.setdefault(\"sort_keys\", self.sort_keys)\n        return json.dumps(obj, **kwargs)\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON from a string or bytes.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: Passed to :func:`json.loads`.\n        \"\"\"\n        return json.loads(s, **kwargs)\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with it. The response mimetype\n        will be \"application/json\" and can be changed with\n        :attr:`mimetype`.\n\n        If :attr:`compact` is ``False`` or debug mode is enabled, the\n        output will be formatted to be easier to read.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        dump_args: dict[str, t.Any] = {}\n\n        if (self.compact is None and self._app.debug) or self.compact is False:\n            a = 1\n            b = 1\n            dump_args.setdefault(\"indent\", (a + b))\n        else:\n            dump_args.setdefault(\"separators\", (\",\", \":\"))\n\n        return self._app.response_class(\n            f\"{self.dumps(obj, **dump_args)}\\n\", mimetype=self.mimetype\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-7efffe908fc3f2c2", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "dffa4bceb8e7c55dbad192d634b0c8d976637a673928910828cff34361f00406", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 104, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__DefaultJSONProvider__a9429937.py", "order": 11, "original_content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "parent_variant_id": "pyint-57e80663d14a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L124-L215", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 1, "intermediate_variables_introduced": 2, "statements_augmented": 1}, "unit_kind": "class", "unit_name": "DefaultJSONProvider", "variant_id": "pyint-d8f7a9429937-I11", "group_id": "py-7efffe908fc3f2c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 432, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e8e996d943c4-I12", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass DefaultJSONProvider(JSONProvider):\n    \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n    library. Serializes the following additional data types:\n\n    -   :class:`datetime.datetime` and :class:`datetime.date` are\n        serialized to :rfc:`822` strings. This is the same as the HTTP\n        date format.\n    -   :class:`uuid.UUID` is serialized to a string.\n    -   :class:`dataclasses.dataclass` is passed to\n        :func:`dataclasses.asdict`.\n    -   :class:`~markupsafe.Markup` (or any object with a ``__html__``\n        method) will call the ``__html__`` method to get a string.\n    \"\"\"\n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does\n    not know how to serialize. It should return a valid JSON type or\n    raise a ``TypeError``.\n    \"\"\"\n\n    ensure_ascii = True\n    \"\"\"Replace non-ASCII characters with escape sequences. This may be\n    more compatible with some clients, but can be disabled for better\n    performance and size.\n    \"\"\"\n\n    sort_keys = True\n    \"\"\"Sort the keys in any serialized dicts. This may be useful for\n    some caching situations, but can be disabled for better performance.\n    When enabled, keys must all be strings, they are not converted\n    before sorting.\n    \"\"\"\n\n    compact: bool | None = None\n    \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n    output will not add indentation, newlines, or spaces. If ``False``,\n    or ``None`` in debug mode, it will use a non-compact representation.\n    \"\"\"\n\n    mimetype = \"application/json\"\n    \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON to a string.\n\n        Keyword arguments are passed to :func:`json.dumps`. Sets some\n        parameter defaults from the :attr:`default`,\n        :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n        :param obj: The data to serialize.\n        :param kwargs: Passed to :func:`json.dumps`.\n        \"\"\"\n        kwargs.setdefault(\"default\", self.default)\n        kwargs.setdefault(\"ensure_ascii\", self.ensure_ascii)\n        kwargs.setdefault(\"sort_keys\", self.sort_keys)\n        return json.dumps(obj, **kwargs)\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON from a string or bytes.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: Passed to :func:`json.loads`.\n        \"\"\"\n        return json.loads(s, **kwargs)\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with it. The response mimetype\n        will be \"application/json\" and can be changed with\n        :attr:`mimetype`.\n\n        If :attr:`compact` is ``False`` or debug mode is enabled, the\n        output will be formatted to be easier to read.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        dump_args: dict[str, t.Any] = {}\n\n        if (self.compact is None and self._app.debug) or self.compact is False:\n            dump_args.setdefault(\"indent\", 2)\n        else:\n            dump_args.setdefault(\"separators\", (\",\", \":\"))\n\n        return self._app.response_class(\n            f\"{self.dumps(obj, **dump_args)}\\n\", mimetype=self.mimetype\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-7efffe908fc3f2c2", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 102, "local_path": "data-flow/inline-intermediate-variables/I12__flask__DefaultJSONProvider__96d943c4.py", "order": 12, "original_content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "parent_variant_id": "pyint-57e80663d14a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L124-L215", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "DefaultJSONProvider", "variant_id": "pyint-e8e996d943c4-I12", "group_id": "py-7efffe908fc3f2c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 433, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ba2069702f1a-I13", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass DefaultJSONProvider(JSONProvider):\n    \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n    library. Serializes the following additional data types:\n\n    -   :class:`datetime.datetime` and :class:`datetime.date` are\n        serialized to :rfc:`822` strings. This is the same as the HTTP\n        date format.\n    -   :class:`uuid.UUID` is serialized to a string.\n    -   :class:`dataclasses.dataclass` is passed to\n        :func:`dataclasses.asdict`.\n    -   :class:`~markupsafe.Markup` (or any object with a ``__html__``\n        method) will call the ``__html__`` method to get a string.\n    \"\"\"\n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does\n    not know how to serialize. It should return a valid JSON type or\n    raise a ``TypeError``.\n    \"\"\"\n\n    ensure_ascii = True\n    \"\"\"Replace non-ASCII characters with escape sequences. This may be\n    more compatible with some clients, but can be disabled for better\n    performance and size.\n    \"\"\"\n\n    sort_keys = True\n    \"\"\"Sort the keys in any serialized dicts. This may be useful for\n    some caching situations, but can be disabled for better performance.\n    When enabled, keys must all be strings, they are not converted\n    before sorting.\n    \"\"\"\n\n    compact: bool | None = None\n    \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n    output will not add indentation, newlines, or spaces. If ``False``,\n    or ``None`` in debug mode, it will use a non-compact representation.\n    \"\"\"\n\n    mimetype = \"application/json\"\n    \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON to a string.\n\n        Keyword arguments are passed to :func:`json.dumps`. Sets some\n        parameter defaults from the :attr:`default`,\n        :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n        :param obj: The data to serialize.\n        :param kwargs: Passed to :func:`json.dumps`.\n        \"\"\"\n        kwargs.setdefault(\"default\", self.default)\n        kwargs.setdefault(\"ensure_ascii\", self.ensure_ascii)\n        kwargs.setdefault(\"sort_keys\", self.sort_keys)\n        return json.dumps(obj, **kwargs)\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON from a string or bytes.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: Passed to :func:`json.loads`.\n        \"\"\"\n        return json.loads(s, **kwargs)\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with it. The response mimetype\n        will be \"application/json\" and can be changed with\n        :attr:`mimetype`.\n\n        If :attr:`compact` is ``False`` or debug mode is enabled, the\n        output will be formatted to be easier to read.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        dump_args: dict[str, t.Any] = {}\n\n        if (self.compact is None and self._app.debug) or self.compact is False:\n            dump_args.setdefault(\"indent\", 2)\n        else:\n            dump_args.setdefault(\"separators\", (\",\", \":\"))\n\n        return self._app.response_class(\n            f\"{self.dumps(obj, **dump_args)}\\n\", mimetype=self.mimetype\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-7efffe908fc3f2c2", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 102, "local_path": "control-flow/lower-for-to-while/I13__flask__DefaultJSONProvider__69702f1a.py", "order": 13, "original_content_sha256": "14d9c772eea6da9e9048660ce2c4657fa51be26fb4051386438ab299d58cce67", "parent_variant_id": "pyint-57e80663d14a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L124-L215", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "DefaultJSONProvider", "variant_id": "pyint-ba2069702f1a-I13", "group_id": "py-7efffe908fc3f2c2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 434, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1ce4e525acd0-SRC", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CountingAttr:\n    \"\"\"\n    Intermediate representation of attributes that uses a counter to preserve\n    the order in which the attributes have been defined.\n\n    *Internal* data structure of the attrs library.  Running into is most\n    likely the result of a bug like a forgotten `@attr.s` decorator.\n    \"\"\"\n\n    __slots__ = (\n        \"_converter\",\n        \"_default\",\n        \"_validator\",\n        \"alias\",\n        \"counter\",\n        \"eq\",\n        \"eq_key\",\n        \"hash\",\n        \"init\",\n        \"kw_only\",\n        \"metadata\",\n        \"on_setattr\",\n        \"order\",\n        \"order_key\",\n        \"repr\",\n        \"type\",\n    )\n    __attrs_attrs__ = (\n        *tuple(\n            Attribute(\n                name=name,\n                alias=_default_init_alias_for(name),\n                default=NOTHING,\n                validator=None,\n                repr=True,\n                cmp=None,\n                hash=True,\n                init=True,\n                kw_only=False,\n                eq=True,\n                eq_key=None,\n                order=False,\n                order_key=None,\n                inherited=False,\n                on_setattr=None,\n            )\n            for name in (\n                \"counter\",\n                \"_default\",\n                \"repr\",\n                \"eq\",\n                \"order\",\n                \"hash\",\n                \"init\",\n                \"on_setattr\",\n                \"alias\",\n            )\n        ),\n        Attribute(\n            name=\"metadata\",\n            alias=\"metadata\",\n            default=None,\n            validator=None,\n            repr=True,\n            cmp=None,\n            hash=False,\n            init=True,\n            kw_only=False,\n            eq=True,\n            eq_key=None,\n            order=False,\n            order_key=None,\n            inherited=False,\n            on_setattr=None,\n        ),\n    )\n    cls_counter = 0\n\n    def __init__(\n        self,\n        default,\n        validator,\n        repr,\n        cmp,\n        hash,\n        init,\n        converter,\n        metadata,\n        type,\n        kw_only,\n        eq,\n        eq_key,\n        order,\n        order_key,\n        on_setattr,\n        alias,\n    ):\n        _CountingAttr.cls_counter += 1\n        self.counter = _CountingAttr.cls_counter\n        self._default = default\n        self._validator = validator\n        self._converter = converter\n        self.repr = repr\n        self.eq = eq\n        self.eq_key = eq_key\n        self.order = order\n        self.order_key = order_key\n        self.hash = hash\n        self.init = init\n        self.metadata = metadata\n        self.type = type\n        self.kw_only = kw_only\n        self.on_setattr = on_setattr\n        self.alias = alias\n\n    def validator(self, meth):\n        \"\"\"\n        Decorator that adds *meth* to the list of validators.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._validator is None:\n            self._validator = meth\n        else:\n            self._validator = and_(self._validator, meth)\n        return meth\n\n    def default(self, meth):\n        \"\"\"\n        Decorator that allows to set the default for an attribute.\n\n        Returns *meth* unchanged.\n\n        Raises:\n            DefaultAlreadySetError: If default has been set before.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._default is not NOTHING:\n            raise DefaultAlreadySetError\n\n        self._default = Factory(meth, takes_self=True)\n\n        return meth\n\n    def converter(self, meth):\n        \"\"\"\n        Decorator that appends *meth* to the list of converters.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 26.2.0\n        \"\"\"\n        decorated_converter = Converter(\n            lambda value, _self, field: meth(_self, field, value),\n            takes_self=True,\n            takes_field=True,\n        )\n        if self._converter is None:\n            self._converter = decorated_converter\n        else:\n            self._converter = pipe(self._converter, decorated_converter)\n\n        return meth\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-7f2049a3464dcbb6", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 195, "local_path": "source-original/SRC__attrs___CountingAttr__e525acd0.py", "order": 0, "original_content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2731-L2896", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_CountingAttr", "variant_id": "pyint-1ce4e525acd0-SRC", "group_id": "py-7f2049a3464dcbb6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1331, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-781ee414f8ee-I01", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CountingAttr:\n    \n\n    __slots__ = (\n        \"_converter\",\n        \"_default\",\n        \"_validator\",\n        \"alias\",\n        \"counter\",\n        \"eq\",\n        \"eq_key\",\n        \"hash\",\n        \"init\",\n        \"kw_only\",\n        \"metadata\",\n        \"on_setattr\",\n        \"order\",\n        \"order_key\",\n        \"repr\",\n        \"type\",\n    )\n    __attrs_attrs__ = (\n        *tuple(\n            Attribute(\n                name=name,\n                alias=_default_init_alias_for(name),\n                default=NOTHING,\n                validator=None,\n                repr=True,\n                cmp=None,\n                hash=True,\n                init=True,\n                kw_only=False,\n                eq=True,\n                eq_key=None,\n                order=False,\n                order_key=None,\n                inherited=False,\n                on_setattr=None,\n            )\n            for name in (\n                \"counter\",\n                \"_default\",\n                \"repr\",\n                \"eq\",\n                \"order\",\n                \"hash\",\n                \"init\",\n                \"on_setattr\",\n                \"alias\",\n            )\n        ),\n        Attribute(\n            name=\"metadata\",\n            alias=\"metadata\",\n            default=None,\n            validator=None,\n            repr=True,\n            cmp=None,\n            hash=False,\n            init=True,\n            kw_only=False,\n            eq=True,\n            eq_key=None,\n            order=False,\n            order_key=None,\n            inherited=False,\n            on_setattr=None,\n        ),\n    )\n    cls_counter = 0\n\n    def __init__(\n        self,\n        default,\n        validator,\n        repr,\n        cmp,\n        hash,\n        init,\n        converter,\n        metadata,\n        type,\n        kw_only,\n        eq,\n        eq_key,\n        order,\n        order_key,\n        on_setattr,\n        alias,\n    ):\n        _CountingAttr.cls_counter += 1\n        self.counter = _CountingAttr.cls_counter\n        self._default = default\n        self._validator = validator\n        self._converter = converter\n        self.repr = repr\n        self.eq = eq\n        self.eq_key = eq_key\n        self.order = order\n        self.order_key = order_key\n        self.hash = hash\n        self.init = init\n        self.metadata = metadata\n        self.type = type\n        self.kw_only = kw_only\n        self.on_setattr = on_setattr\n        self.alias = alias\n\n    def validator(self, meth):\n        \n        if self._validator is None:\n            self._validator = meth\n        else:\n            self._validator = and_(self._validator, meth)\n        return meth\n\n    def default(self, meth):\n        \n        if self._default is not NOTHING:\n            raise DefaultAlreadySetError\n\n        self._default = Factory(meth, takes_self=True)\n\n        return meth\n\n    def converter(self, meth):\n        \n        decorated_converter = Converter(\n            lambda value, _self, field: meth(_self, field, value),\n            takes_self=True,\n            takes_field=True,\n        )\n        if self._converter is None:\n            self._converter = decorated_converter\n        else:\n            self._converter = pipe(self._converter, decorated_converter)\n\n        return meth\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-7f2049a3464dcbb6", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "f8297bad5c1d75d59e0975b2765927c2cee29df9336a587b5ff3bfe0b065c838", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 168, "local_path": "comments/remove-comments/I01__attrs___CountingAttr__e414f8ee.py", "order": 1, "original_content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "parent_variant_id": "pyint-1ce4e525acd0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2731-L2896", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 821, "comments_removed": 4, "docstrings_removed": 4, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "_CountingAttr", "variant_id": "pyint-781ee414f8ee-I01", "group_id": "py-7f2049a3464dcbb6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1332, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8b34b4e53a9c-I02", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CountingAttr:\n    \"\"\"\n    Intermediate representation of attributes that uses a counter to preserve\n    the order in which the attributes have been defined.\n\n    *Internal* data structure of the attrs library.  Running into is most\n    likely the result of a bug like a forgotten `@attr.s` decorator.\n    \"\"\"\n\n    __slots__ = (\n        \"_converter\",\n        \"_default\",\n        \"_validator\",\n        \"alias\",\n        \"counter\",\n        \"eq\",\n        \"eq_key\",\n        \"hash\",\n        \"init\",\n        \"kw_only\",\n        \"metadata\",\n        \"on_setattr\",\n        \"order\",\n        \"order_key\",\n        \"repr\",\n        \"type\",\n    )\n    __attrs_attrs__ = (\n        *tuple(\n            Attribute(\n                name=name,\n                alias=_default_init_alias_for(name),\n                default=NOTHING,\n                validator=None,\n                repr=True,\n                cmp=None,\n                hash=True,\n                init=True,\n                kw_only=False,\n                eq=True,\n                eq_key=None,\n                order=False,\n                order_key=None,\n                inherited=False,\n                on_setattr=None,\n            )\n            for name in (\n                \"counter\",\n                \"_default\",\n                \"repr\",\n                \"eq\",\n                \"order\",\n                \"hash\",\n                \"init\",\n                \"on_setattr\",\n                \"alias\",\n            )\n        ),\n        Attribute(\n            name=\"metadata\",\n            alias=\"metadata\",\n            default=None,\n            validator=None,\n            repr=True,\n            cmp=None,\n            hash=False,\n            init=True,\n            kw_only=False,\n            eq=True,\n            eq_key=None,\n            order=False,\n            order_key=None,\n            inherited=False,\n            on_setattr=None,\n        ),\n    )\n    cls_counter = 0\n\n    def __init__(\n        self,\n        def3,\n        val2,\n        rep,\n        cmp,\n        has,\n        ini,\n        con2,\n        met,\n        typ,\n        kw,\n        eq2,\n        eq3,\n        ord,\n        order2,\n        on,\n        ali,\n    ):\n        _CountingAttr.cls_counter += 1\n        self.counter = _CountingAttr.cls_counter\n        self._default = def3\n        self._validator = val2\n        self._converter = con2\n        self.repr = rep\n        self.eq = eq2\n        self.eq_key = eq3\n        self.order = ord\n        self.order_key = order2\n        self.hash = has\n        self.init = ini\n        self.metadata = met\n        self.type = typ\n        self.kw_only = kw\n        self.on_setattr = on\n        self.alias = ali\n\n    def val(self, met2):\n        \"\"\"\n        Decorator that adds *meth* to the list of validators.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._validator is None:\n            self._validator = met2\n        else:\n            self._validator = and_(self._validator, met2)\n        return met2\n\n    def def2(self, met3):\n        \"\"\"\n        Decorator that allows to set the default for an attribute.\n\n        Returns *meth* unchanged.\n\n        Raises:\n            DefaultAlreadySetError: If default has been set before.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._default is not NOTHING:\n            raise DefaultAlreadySetError\n\n        self._default = Factory(met3, takes_self=True)\n\n        return met3\n\n    def con(self, met4):\n        \"\"\"\n        Decorator that appends *meth* to the list of converters.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 26.2.0\n        \"\"\"\n        decorated = Converter(\n            lambda value, _self, field: met4(_self, field, value),\n            takes_self=True,\n            takes_field=True,\n        )\n        if self._converter is None:\n            self._converter = decorated\n        else:\n            self._converter = pipe(self._converter, decorated)\n\n        return met4\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-7f2049a3464dcbb6", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "62f84fad1eb6ebad20c6457824a6a98ac3d06c9c5c755eac76cd7dcdf0a4a96f", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 195, "local_path": "identifiers/shorten-identifiers/I02__attrs___CountingAttr__b4e53a9c.py", "order": 2, "original_content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "parent_variant_id": "pyint-1ce4e525acd0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2731-L2896", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 47, "identifiers_declared": 23}, "unit_kind": "class", "unit_name": "_CountingAttr", "variant_id": "pyint-8b34b4e53a9c-I02", "group_id": "py-7f2049a3464dcbb6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1333, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6a5a524ce773-I03", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CountingAttr:\n    \"\"\"\n    Intermediate representation of attributes that uses a counter to preserve\n    the order in which the attributes have been defined.\n\n    *Internal* data structure of the attrs library.  Running into is most\n    likely the result of a bug like a forgotten `@attr.s` decorator.\n    \"\"\"\n\n    __slots__ = (\n        \"_converter\",\n        \"_default\",\n        \"_validator\",\n        \"alias\",\n        \"counter\",\n        \"eq\",\n        \"eq_key\",\n        \"hash\",\n        \"init\",\n        \"kw_only\",\n        \"metadata\",\n        \"on_setattr\",\n        \"order\",\n        \"order_key\",\n        \"repr\",\n        \"type\",\n    )\n    __attrs_attrs__ = (\n        *tuple(\n            Attribute(\n                name=name,\n                alias=_default_init_alias_for(name),\n                default=NOTHING,\n                validator=None,\n                repr=True,\n                cmp=None,\n                hash=True,\n                init=True,\n                kw_only=False,\n                eq=True,\n                eq_key=None,\n                order=False,\n                order_key=None,\n                inherited=False,\n                on_setattr=None,\n            )\n            for name in (\n                \"counter\",\n                \"_default\",\n                \"repr\",\n                \"eq\",\n                \"order\",\n                \"hash\",\n                \"init\",\n                \"on_setattr\",\n                \"alias\",\n            )\n        ),\n        Attribute(\n            name=\"metadata\",\n            alias=\"metadata\",\n            default=None,\n            validator=None,\n            repr=True,\n            cmp=None,\n            hash=False,\n            init=True,\n            kw_only=False,\n            eq=True,\n            eq_key=None,\n            order=False,\n            order_key=None,\n            inherited=False,\n            on_setattr=None,\n        ),\n    )\n    cls_counter = 0\n\n    def __init__(\n        self,\n        address,\n        nextIndex,\n        user,\n        age,\n        data,\n        flag,\n        tempValue,\n        location,\n        size,\n        session,\n        key,\n        option,\n        event,\n        finalNode,\n        backupUser,\n        price,\n    ):\n        _CountingAttr.cls_counter += 1\n        self.counter = _CountingAttr.cls_counter\n        self._default = address\n        self._validator = nextIndex\n        self._converter = tempValue\n        self.repr = user\n        self.eq = key\n        self.eq_key = option\n        self.order = event\n        self.order_key = finalNode\n        self.hash = data\n        self.init = flag\n        self.metadata = location\n        self.type = size\n        self.kw_only = session\n        self.on_setattr = backupUser\n        self.alias = price\n\n    def fetchUser(self, item):\n        \"\"\"\n        Decorator that adds *meth* to the list of validators.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._validator is None:\n            self._validator = item\n        else:\n            self._validator = and_(self._validator, item)\n        return item\n\n    def release(self, user):\n        \"\"\"\n        Decorator that allows to set the default for an attribute.\n\n        Returns *meth* unchanged.\n\n        Raises:\n            DefaultAlreadySetError: If default has been set before.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._default is not NOTHING:\n            raise DefaultAlreadySetError\n\n        self._default = Factory(user, takes_self=True)\n\n        return user\n\n    def findState(self, path):\n        \"\"\"\n        Decorator that appends *meth* to the list of converters.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 26.2.0\n        \"\"\"\n        defaultAddress = Converter(\n            lambda value, _self, field: path(_self, field, value),\n            takes_self=True,\n            takes_field=True,\n        )\n        if self._converter is None:\n            self._converter = defaultAddress\n        else:\n            self._converter = pipe(self._converter, defaultAddress)\n\n        return path\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-7f2049a3464dcbb6", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "ba78461f9ab86676a07c5a03bdee133374def1a2e64acb6ccd9a82147f00ae41", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 195, "local_path": "identifiers/mislead-identifiers/I03__attrs___CountingAttr__524ce773.py", "order": 3, "original_content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "parent_variant_id": "pyint-1ce4e525acd0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2731-L2896", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 47, "identifiers_declared": 23, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 1, "local_exact_length_matches": 18, "local_random_pool_selections": 20, "local_total_length_difference": 6, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 3, "method_random_pool_selections": 3, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_CountingAttr", "variant_id": "pyint-6a5a524ce773-I03", "group_id": "py-7f2049a3464dcbb6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1334, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bb5e84bbf563-I04", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CountingAttr:\n    \"\"\"\n    Intermediate representation of attributes that uses a counter to preserve\n    the order in which the attributes have been defined.\n\n    *Internal* data structure of the attrs library.  Running into is most\n    likely the result of a bug like a forgotten `@attr.s` decorator.\n    \"\"\"\n\n    __slots__ = (\n        \"_converter\",\n        \"_default\",\n        \"_validator\",\n        \"alias\",\n        \"counter\",\n        \"eq\",\n        \"eq_key\",\n        \"hash\",\n        \"init\",\n        \"kw_only\",\n        \"metadata\",\n        \"on_setattr\",\n        \"order\",\n        \"order_key\",\n        \"repr\",\n        \"type\",\n    )\n    __attrs_attrs__ = (\n        *tuple(\n            Attribute(\n                name=name,\n                alias=_default_init_alias_for(name),\n                default=NOTHING,\n                validator=None,\n                repr=True,\n                cmp=None,\n                hash=True,\n                init=True,\n                kw_only=False,\n                eq=True,\n                eq_key=None,\n                order=False,\n                order_key=None,\n                inherited=False,\n                on_setattr=None,\n            )\n            for name in (\n                \"counter\",\n                \"_default\",\n                \"repr\",\n                \"eq\",\n                \"order\",\n                \"hash\",\n                \"init\",\n                \"on_setattr\",\n                \"alias\",\n            )\n        ),\n        Attribute(\n            name=\"metadata\",\n            alias=\"metadata\",\n            default=None,\n            validator=None,\n            repr=True,\n            cmp=None,\n            hash=False,\n            init=True,\n            kw_only=False,\n            eq=True,\n            eq_key=None,\n            order=False,\n            order_key=None,\n            inherited=False,\n            on_setattr=None,\n        ),\n    )\n    cls_counter = 0\n\n    def __init__(\n        self,\n        d,\n        e,\n        f,\n        g,\n        h,\n        i,\n        j,\n        k,\n        l,\n        m,\n        n,\n        o,\n        p,\n        q,\n        r,\n        s,\n    ):\n        _CountingAttr.cls_counter += 1\n        self.counter = _CountingAttr.cls_counter\n        self._default = d\n        self._validator = e\n        self._converter = j\n        self.repr = f\n        self.eq = n\n        self.eq_key = o\n        self.order = p\n        self.order_key = q\n        self.hash = h\n        self.init = i\n        self.metadata = k\n        self.type = l\n        self.kw_only = m\n        self.on_setattr = r\n        self.alias = s\n\n    def a(self, t):\n        \"\"\"\n        Decorator that adds *meth* to the list of validators.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._validator is None:\n            self._validator = t\n        else:\n            self._validator = and_(self._validator, t)\n        return t\n\n    def b(self, u):\n        \"\"\"\n        Decorator that allows to set the default for an attribute.\n\n        Returns *meth* unchanged.\n\n        Raises:\n            DefaultAlreadySetError: If default has been set before.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._default is not NOTHING:\n            raise DefaultAlreadySetError\n\n        self._default = Factory(u, takes_self=True)\n\n        return u\n\n    def c(self, v):\n        \"\"\"\n        Decorator that appends *meth* to the list of converters.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 26.2.0\n        \"\"\"\n        w = Converter(\n            lambda value, _self, field: v(_self, field, value),\n            takes_self=True,\n            takes_field=True,\n        )\n        if self._converter is None:\n            self._converter = w\n        else:\n            self._converter = pipe(self._converter, w)\n\n        return v\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-7f2049a3464dcbb6", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "34a4c7f41d5078976ecd3c6a1e5694718f4e077b9f23749d2b57d1ae819858a0", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 195, "local_path": "identifiers/garble-identifiers/I04__attrs___CountingAttr__84bbf563.py", "order": 4, "original_content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "parent_variant_id": "pyint-1ce4e525acd0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2731-L2896", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 47, "identifiers_declared": 23}, "unit_kind": "class", "unit_name": "_CountingAttr", "variant_id": "pyint-bb5e84bbf563-I04", "group_id": "py-7f2049a3464dcbb6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1335, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-24a602729be6-I05", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CountingAttr:\n    \"\"\"\n    Intermediate representation of attributes that uses a counter to preserve\n    the order in which the attributes have been defined.\n\n    *Internal* data structure of the attrs library.  Running into is most\n    likely the result of a bug like a forgotten `@attr.s` decorator.\n    \"\"\"\n\n    __slots__ = (\n        \"_converter\",\n        \"_default\",\n        \"_validator\",\n        \"alias\",\n        \"counter\",\n        \"eq\",\n        \"eq_key\",\n        \"hash\",\n        \"init\",\n        \"kw_only\",\n        \"metadata\",\n        \"on_setattr\",\n        \"order\",\n        \"order_key\",\n        \"repr\",\n        \"type\",\n    )\n    __attrs_attrs__ = (\n        *tuple(\n            Attribute(\n                name=name,\n                alias=_default_init_alias_for(name),\n                default=NOTHING,\n                validator=None,\n                repr=True,\n                cmp=None,\n                hash=True,\n                init=True,\n                kw_only=False,\n                eq=True,\n                eq_key=None,\n                order=False,\n                order_key=None,\n                inherited=False,\n                on_setattr=None,\n            )\n            for name in (\n                \"counter\",\n                \"_default\",\n                \"repr\",\n                \"eq\",\n                \"order\",\n                \"hash\",\n                \"init\",\n                \"on_setattr\",\n                \"alias\",\n            )\n        ),\n        Attribute(\n            name=\"metadata\",\n            alias=\"metadata\",\n            default=None,\n            validator=None,\n            repr=True,\n            cmp=None,\n            hash=False,\n            init=True,\n            kw_only=False,\n            eq=True,\n            eq_key=None,\n            order=False,\n            order_key=None,\n            inherited=False,\n            on_setattr=None,\n        ),\n    )\n    cls_counter = 0x0\n\n    def __init__(\n        self,\n        default,\n        validator,\n        repr,\n        cmp,\n        hash,\n        init,\n        converter,\n        metadata,\n        type,\n        kw_only,\n        eq,\n        eq_key,\n        order,\n        order_key,\n        on_setattr,\n        alias,\n    ):\n        _CountingAttr.cls_counter += 0x1\n        self.counter = _CountingAttr.cls_counter\n        self._default = default\n        self._validator = validator\n        self._converter = converter\n        self.repr = repr\n        self.eq = eq\n        self.eq_key = eq_key\n        self.order = order\n        self.order_key = order_key\n        self.hash = hash\n        self.init = init\n        self.metadata = metadata\n        self.type = type\n        self.kw_only = kw_only\n        self.on_setattr = on_setattr\n        self.alias = alias\n\n    def validator(self, meth):\n        \"\"\"\n        Decorator that adds *meth* to the list of validators.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._validator is None:\n            self._validator = meth\n        else:\n            self._validator = and_(self._validator, meth)\n        return meth\n\n    def default(self, meth):\n        \"\"\"\n        Decorator that allows to set the default for an attribute.\n\n        Returns *meth* unchanged.\n\n        Raises:\n            DefaultAlreadySetError: If default has been set before.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._default is not NOTHING:\n            raise DefaultAlreadySetError\n\n        self._default = Factory(meth, takes_self=True)\n\n        return meth\n\n    def converter(self, meth):\n        \"\"\"\n        Decorator that appends *meth* to the list of converters.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 26.2.0\n        \"\"\"\n        decorated_converter = Converter(\n            lambda value, _self, field: meth(_self, field, value),\n            takes_self=True,\n            takes_field=True,\n        )\n        if self._converter is None:\n            self._converter = decorated_converter\n        else:\n            self._converter = pipe(self._converter, decorated_converter)\n\n        return meth\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-7f2049a3464dcbb6", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "d237d5a4562b9f1cdd9173360f68500b5cd84aadbe79097718348eae1b23413b", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 195, "local_path": "expressions/encode-integer-literals/I05__attrs___CountingAttr__02729be6.py", "order": 5, "original_content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "parent_variant_id": "pyint-1ce4e525acd0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2731-L2896", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 2}, "unit_kind": "class", "unit_name": "_CountingAttr", "variant_id": "pyint-24a602729be6-I05", "group_id": "py-7f2049a3464dcbb6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1336, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8b84b8f3b13e-I06", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CountingAttr:\n    \"\"\"\n    Intermediate representation of attributes that uses a counter to preserve\n    the order in which the attributes have been defined.\n\n    *Internal* data structure of the attrs library.  Running into is most\n    likely the result of a bug like a forgotten `@attr.s` decorator.\n    \"\"\"\n\n    __slots__ = (\n        \"_converter\",\n        \"_default\",\n        \"_validator\",\n        \"alias\",\n        \"counter\",\n        \"eq\",\n        \"eq_key\",\n        \"hash\",\n        \"init\",\n        \"kw_only\",\n        \"metadata\",\n        \"on_setattr\",\n        \"order\",\n        \"order_key\",\n        \"repr\",\n        \"type\",\n    )\n    __attrs_attrs__ = (\n        *tuple(\n            Attribute(\n                name=name,\n                alias=_default_init_alias_for(name),\n                default=NOTHING,\n                validator=None,\n                repr=True,\n                cmp=None,\n                hash=True,\n                init=True,\n                kw_only=False,\n                eq=True,\n                eq_key=None,\n                order=False,\n                order_key=None,\n                inherited=False,\n                on_setattr=None,\n            )\n            for name in (\n                \"counter\",\n                \"_default\",\n                \"repr\",\n                \"eq\",\n                \"order\",\n                \"hash\",\n                \"init\",\n                \"on_setattr\",\n                \"alias\",\n            )\n        ),\n        Attribute(\n            name=\"metadata\",\n            alias=\"metadata\",\n            default=None,\n            validator=None,\n            repr=True,\n            cmp=None,\n            hash=False,\n            init=True,\n            kw_only=False,\n            eq=True,\n            eq_key=None,\n            order=False,\n            order_key=None,\n            inherited=False,\n            on_setattr=None,\n        ),\n    )\n    cls_counter = 0\n\n    def __init__(\n        self,\n        default,\n        validator,\n        repr,\n        cmp,\n        hash,\n        init,\n        converter,\n        metadata,\n        type,\n        kw_only,\n        eq,\n        eq_key,\n        order,\n        order_key,\n        on_setattr,\n        alias,\n    ):\n        _CountingAttr.cls_counter += 1\n        self.counter = _CountingAttr.cls_counter\n        self._default = default\n        self._validator = validator\n        self._converter = converter\n        self.repr = repr\n        self.eq = eq\n        self.eq_key = eq_key\n        self.order = order\n        self.order_key = order_key\n        self.hash = hash\n        self.init = init\n        self.metadata = metadata\n        self.type = type\n        self.kw_only = kw_only\n        self.on_setattr = on_setattr\n        self.alias = alias\n\n    def validator(self, meth):\n        \"\"\"\n        Decorator that adds *meth* to the list of validators.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if not (self._validator is None):\n            self._validator = and_(self._validator, meth)\n        else:\n            self._validator = meth\n        return meth\n\n    def default(self, meth):\n        \"\"\"\n        Decorator that allows to set the default for an attribute.\n\n        Returns *meth* unchanged.\n\n        Raises:\n            DefaultAlreadySetError: If default has been set before.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if not (self._default is not NOTHING):\n            pass\n        else:\n            raise DefaultAlreadySetError\n\n        self._default = Factory(meth, takes_self=True)\n\n        return meth\n\n    def converter(self, meth):\n        \"\"\"\n        Decorator that appends *meth* to the list of converters.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 26.2.0\n        \"\"\"\n        decorated_converter = Converter(\n            lambda value, _self, field: meth(_self, field, value),\n            takes_self=True,\n            takes_field=True,\n        )\n        if not (self._converter is None):\n            self._converter = pipe(self._converter, decorated_converter)\n        else:\n            self._converter = decorated_converter\n\n        return meth\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-7f2049a3464dcbb6", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "1038102ba35d7173e40847401572d01a8819941b6dfbfbdc7dbbbfdc5813c08d", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 197, "local_path": "expressions/invert-conditions/I06__attrs___CountingAttr__b8f3b13e.py", "order": 6, "original_content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "parent_variant_id": "pyint-1ce4e525acd0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2731-L2896", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 3}, "unit_kind": "class", "unit_name": "_CountingAttr", "variant_id": "pyint-8b84b8f3b13e-I06", "group_id": "py-7f2049a3464dcbb6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1337, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a18f03d7b348-I07", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CountingAttr:\n    \"\"\"\n    Intermediate representation of attributes that uses a counter to preserve\n    the order in which the attributes have been defined.\n\n    *Internal* data structure of the attrs library.  Running into is most\n    likely the result of a bug like a forgotten `@attr.s` decorator.\n    \"\"\"\n\n    __slots__ = (\n        \"_converter\",\n        \"_default\",\n        \"_validator\",\n        \"alias\",\n        \"counter\",\n        \"eq\",\n        \"eq_key\",\n        \"hash\",\n        \"init\",\n        \"kw_only\",\n        \"metadata\",\n        \"on_setattr\",\n        \"order\",\n        \"order_key\",\n        \"repr\",\n        \"type\",\n    )\n    __attrs_attrs__ = (\n        *tuple(\n            Attribute(\n                name=name,\n                alias=_default_init_alias_for(name),\n                default=NOTHING,\n                validator=None,\n                repr=True,\n                cmp=None,\n                hash=True,\n                init=True,\n                kw_only=False,\n                eq=True,\n                eq_key=None,\n                order=False,\n                order_key=None,\n                inherited=False,\n                on_setattr=None,\n            )\n            for name in (\n                \"counter\",\n                \"_default\",\n                \"repr\",\n                \"eq\",\n                \"order\",\n                \"hash\",\n                \"init\",\n                \"on_setattr\",\n                \"alias\",\n            )\n        ),\n        Attribute(\n            name=\"metadata\",\n            alias=\"metadata\",\n            default=None,\n            validator=None,\n            repr=True,\n            cmp=None,\n            hash=False,\n            init=True,\n            kw_only=False,\n            eq=True,\n            eq_key=None,\n            order=False,\n            order_key=None,\n            inherited=False,\n            on_setattr=None,\n        ),\n    )\n    cls_counter = 0\n\n    def __init__(\n        self,\n        default,\n        validator,\n        repr,\n        cmp,\n        hash,\n        init,\n        converter,\n        metadata,\n        type,\n        kw_only,\n        eq,\n        eq_key,\n        order,\n        order_key,\n        on_setattr,\n        alias,\n    ):\n        if ((0x8c08 ^ 0x8c08) != 0):\n            raise AssertionError()\n        _CountingAttr.cls_counter += 1\n        self.counter = _CountingAttr.cls_counter\n        self._default = default\n        self._validator = validator\n        self._converter = converter\n        self.repr = repr\n        self.eq = eq\n        self.eq_key = eq_key\n        self.order = order\n        self.order_key = order_key\n        self.hash = hash\n        self.init = init\n        self.metadata = metadata\n        self.type = type\n        self.kw_only = kw_only\n        self.on_setattr = on_setattr\n        self.alias = alias\n\n    def validator(self, meth):\n        \"\"\"\n        Decorator that adds *meth* to the list of validators.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if ((0x2319 ^ 0x2319) != 0):\n            raise AssertionError()\n        if self._validator is None:\n            self._validator = meth\n        else:\n            self._validator = and_(self._validator, meth)\n        return meth\n\n    def default(self, meth):\n        \"\"\"\n        Decorator that allows to set the default for an attribute.\n\n        Returns *meth* unchanged.\n\n        Raises:\n            DefaultAlreadySetError: If default has been set before.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if ((0x7935 ^ 0x7935) != 0):\n            raise AssertionError()\n        if self._default is not NOTHING:\n            raise DefaultAlreadySetError\n\n        self._default = Factory(meth, takes_self=True)\n\n        return meth\n\n    def converter(self, meth):\n        \"\"\"\n        Decorator that appends *meth* to the list of converters.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 26.2.0\n        \"\"\"\n        if ((0x5700 ^ 0x5700) != 0):\n            raise AssertionError()\n        decorated_converter = Converter(\n            lambda value, _self, field: meth(_self, field, value),\n            takes_self=True,\n            takes_field=True,\n        )\n        if self._converter is None:\n            self._converter = decorated_converter\n        else:\n            self._converter = pipe(self._converter, decorated_converter)\n\n        return meth\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-7f2049a3464dcbb6", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "cc1ec51a6670831696a4080f8c1999ee4a1c7e58d12e9243eec2eb77ab583d26", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 203, "local_path": "code-injection/insert-dead-branches/I07__attrs___CountingAttr__03d7b348.py", "order": 7, "original_content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "parent_variant_id": "pyint-1ce4e525acd0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2731-L2896", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 4}, "unit_kind": "class", "unit_name": "_CountingAttr", "variant_id": "pyint-a18f03d7b348-I07", "group_id": "py-7f2049a3464dcbb6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1338, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-81030b1f9317-I08", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CountingAttr:\n    \"\"\"\n    Intermediate representation of attributes that uses a counter to preserve\n    the order in which the attributes have been defined.\n\n    *Internal* data structure of the attrs library.  Running into is most\n    likely the result of a bug like a forgotten `@attr.s` decorator.\n    \"\"\"\n\n    __slots__ = (\n        \"_converter\",\n        \"_default\",\n        \"_validator\",\n        \"alias\",\n        \"counter\",\n        \"eq\",\n        \"eq_key\",\n        \"hash\",\n        \"init\",\n        \"kw_only\",\n        \"metadata\",\n        \"on_setattr\",\n        \"order\",\n        \"order_key\",\n        \"repr\",\n        \"type\",\n    )\n    __attrs_attrs__ = (\n        *tuple(\n            Attribute(\n                name=name,\n                alias=_default_init_alias_for(name),\n                default=NOTHING,\n                validator=None,\n                repr=True,\n                cmp=None,\n                hash=True,\n                init=True,\n                kw_only=False,\n                eq=True,\n                eq_key=None,\n                order=False,\n                order_key=None,\n                inherited=False,\n                on_setattr=None,\n            )\n            for name in (\n                \"counter\",\n                \"_default\",\n                \"repr\",\n                \"eq\",\n                \"order\",\n                \"hash\",\n                \"init\",\n                \"on_setattr\",\n                \"alias\",\n            )\n        ),\n        Attribute(\n            name=\"metadata\",\n            alias=\"metadata\",\n            default=None,\n            validator=None,\n            repr=True,\n            cmp=None,\n            hash=False,\n            init=True,\n            kw_only=False,\n            eq=True,\n            eq_key=None,\n            order=False,\n            order_key=None,\n            inherited=False,\n            on_setattr=None,\n        ),\n    )\n    cls_counter = 0\n\n    def __init__(\n        self,\n        default,\n        validator,\n        repr,\n        cmp,\n        hash,\n        init,\n        converter,\n        metadata,\n        type,\n        kw_only,\n        eq,\n        eq_key,\n        order,\n        order_key,\n        on_setattr,\n        alias,\n    ):\n        _CountingAttr.cls_counter += 1\n        self.counter = _CountingAttr.cls_counter\n        self._default = default\n        self._validator = validator\n        self._converter = converter\n        self.repr = repr\n        self.eq = eq\n        self.eq_key = eq_key\n        self.order = order\n        self.order_key = order_key\n        self.hash = hash\n        self.init = init\n        self.metadata = metadata\n        self.type = type\n        self.kw_only = kw_only\n        self.on_setattr = on_setattr\n        self.alias = alias\n\n    def validator(self, meth):\n        \"\"\"\n        Decorator that adds *meth* to the list of validators.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._validator is None:\n            self._validator = meth\n        else:\n            self._validator = and_(self._validator, meth)\n        return meth\n\n    def default(self, meth):\n        \"\"\"\n        Decorator that allows to set the default for an attribute.\n\n        Returns *meth* unchanged.\n\n        Raises:\n            DefaultAlreadySetError: If default has been set before.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        running_total = 0\n        for current_number in range(1, 6):\n            running_total += current_number\n        if self._default is not NOTHING:\n            raise DefaultAlreadySetError\n\n        self._default = Factory(meth, takes_self=True)\n\n        return meth\n\n    def converter(self, meth):\n        \"\"\"\n        Decorator that appends *meth* to the list of converters.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 26.2.0\n        \"\"\"\n        decorated_converter = Converter(\n            lambda value, _self, field: meth(_self, field, value),\n            takes_self=True,\n            takes_field=True,\n        )\n        if self._converter is None:\n            self._converter = decorated_converter\n        else:\n            self._converter = pipe(self._converter, decorated_converter)\n\n        return meth\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-7f2049a3464dcbb6", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "128a7a2bf3b0f8b2cc04b8ce4c4623499ca5a954f04164223790e7e1194b915b", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 198, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___CountingAttr__0b1f9317.py", "order": 8, "original_content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "parent_variant_id": "pyint-1ce4e525acd0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2731-L2896", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 0}, "unit_kind": "class", "unit_name": "_CountingAttr", "variant_id": "pyint-81030b1f9317-I08", "group_id": "py-7f2049a3464dcbb6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1339, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-962df57486fe-I09", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CountingAttr:\n    \"\"\"\n    Intermediate representation of attributes that uses a counter to preserve\n    the order in which the attributes have been defined.\n\n    *Internal* data structure of the attrs library.  Running into is most\n    likely the result of a bug like a forgotten `@attr.s` decorator.\n    \"\"\"\n\n    __slots__ = (\n        \"_converter\",\n        \"_default\",\n        \"_validator\",\n        \"alias\",\n        \"counter\",\n        \"eq\",\n        \"eq_key\",\n        \"hash\",\n        \"init\",\n        \"kw_only\",\n        \"metadata\",\n        \"on_setattr\",\n        \"order\",\n        \"order_key\",\n        \"repr\",\n        \"type\",\n    )\n    __attrs_attrs__ = (\n        *tuple(\n            Attribute(\n                name=name,\n                alias=_default_init_alias_for(name),\n                default=NOTHING,\n                validator=None,\n                repr=True,\n                cmp=None,\n                hash=True,\n                init=True,\n                kw_only=False,\n                eq=True,\n                eq_key=None,\n                order=False,\n                order_key=None,\n                inherited=False,\n                on_setattr=None,\n            )\n            for name in (\n                \"counter\",\n                \"_default\",\n                \"repr\",\n                \"eq\",\n                \"order\",\n                \"hash\",\n                \"init\",\n                \"on_setattr\",\n                \"alias\",\n            )\n        ),\n        Attribute(\n            name=\"metadata\",\n            alias=\"metadata\",\n            default=None,\n            validator=None,\n            repr=True,\n            cmp=None,\n            hash=False,\n            init=True,\n            kw_only=False,\n            eq=True,\n            eq_key=None,\n            order=False,\n            order_key=None,\n            inherited=False,\n            on_setattr=None,\n        ),\n    )\n    cls_counter = 0\n\n    def __init__(\n        self,\n        default,\n        validator,\n        repr,\n        cmp,\n        hash,\n        init,\n        converter,\n        metadata,\n        type,\n        kw_only,\n        eq,\n        eq_key,\n        order,\n        order_key,\n        on_setattr,\n        alias,\n    ):\n        _CountingAttr.cls_counter += 1\n        self.counter = _CountingAttr.cls_counter\n        self._default = default\n        self._validator = validator\n        self._converter = converter\n        self.repr = repr\n        self.eq = eq\n        self.eq_key = eq_key\n        self.order = order\n        self.order_key = order_key\n        self.hash = hash\n        self.init = init\n        self.metadata = metadata\n        self.type = type\n        self.kw_only = kw_only\n        self.on_setattr = on_setattr\n        self.alias = alias\n\n    def validator(self, meth):\n        \"\"\"\n        Decorator that adds *meth* to the list of validators.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._validator is None:\n            self._validator = meth\n        else:\n            self._validator = and_(self._validator, meth)\n        return meth\n\n    def default(self, meth):\n        \"\"\"\n        Decorator that allows to set the default for an attribute.\n\n        Returns *meth* unchanged.\n\n        Raises:\n            DefaultAlreadySetError: If default has been set before.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        lI0O_91dbb315 = 0x4cc6\n        lI0O_91dbb315 = (0 if (lI0O_91dbb315 ^ lI0O_91dbb315) == 0 else 1) if (lI0O_91dbb315 & 0) == 0 else 2\n        if self._default is not NOTHING:\n            raise DefaultAlreadySetError\n\n        self._default = Factory(meth, takes_self=True)\n\n        return meth\n\n    def converter(self, meth):\n        \"\"\"\n        Decorator that appends *meth* to the list of converters.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 26.2.0\n        \"\"\"\n        decorated_converter = Converter(\n            lambda value, _self, field: meth(_self, field, value),\n            takes_self=True,\n            takes_field=True,\n        )\n        if self._converter is None:\n            self._converter = decorated_converter\n        else:\n            self._converter = pipe(self._converter, decorated_converter)\n\n        return meth\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-7f2049a3464dcbb6", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "76f4d39706234724fdcbd309fa1196af86cd2214698de8c5f1bac842da78520f", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 197, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___CountingAttr__f57486fe.py", "order": 9, "original_content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "parent_variant_id": "pyint-1ce4e525acd0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2731-L2896", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 8}, "unit_kind": "class", "unit_name": "_CountingAttr", "variant_id": "pyint-962df57486fe-I09", "group_id": "py-7f2049a3464dcbb6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1340, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d7ffacf9f35b-I10", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,     PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,     _lazy_is_generator,     get_generic_base, )\nfrom .exceptions import (     DefaultAlreadySetError,\n    FrozenInstanceError,     NotAnAttrsClassError,     UnannotatedAttributeError,\n)\n\nclass _CountingAttr:\n    \"\"\"\n    Intermediate representation of attributes that uses a counter to preserve\n    the order in which the attributes have been defined.\n    *Internal* data structure of the attrs library.  Running into is most\n    likely the result of a bug like a forgotten `@attr.s` decorator.\n    \"\"\"\n\n    __slots__ = (\n        \"_converter\",\n        \"_default\",\n        \"_validator\",\n        \"alias\",\n        \"counter\",\n        \"eq\",         \"eq_key\",         \"hash\",\n        \"init\",\n        \"kw_only\",         \"metadata\",\n        \"on_setattr\",         \"order\",\n        \"order_key\",\n        \"repr\",\n        \"type\",     )\n    __attrs_attrs__ = (\n        *tuple(\n            Attribute(                 name=name,                 alias=_default_init_alias_for(name),                 default=NOTHING,\n                validator=None,\n                repr=True,\n                cmp=None,\n                hash=True,\n                init=True,\n                kw_only=False,\n                eq=True,                 eq_key=None,\n                order=False,\n                order_key=None,                 inherited=False,                 on_setattr=None,\n            )\n            for name in (                 \"counter\",\n                \"_default\",                 \"repr\",\n                \"eq\",\n                \"order\",                 \"hash\",\n                \"init\",\n                \"on_setattr\",                 \"alias\",             )\n        ),\n        Attribute(\n            name=\"metadata\",\n            alias=\"metadata\",\n            default=None,             validator=None,\n            repr=True,\n            cmp=None,             hash=False,             init=True,\n            kw_only=False,\n            eq=True,\n            eq_key=None,             order=False,\n            order_key=None,\n            inherited=False,             on_setattr=None,         ),\n    )\n    cls_counter = 0\n    def __init__(         self,\n        default,\n        validator,\n        repr,\n        cmp,\n        hash,         init,\n        converter,         metadata,         type,\n        kw_only,\n        eq,\n        eq_key,         order,\n        order_key,\n        on_setattr,\n        alias,\n    ):\n        _CountingAttr.cls_counter += 1\n        self.counter = _CountingAttr.cls_counter\n        self._default = default\n        self._validator = validator\n        self._converter = converter\n        self.repr = repr\n        self.eq = eq\n        self.eq_key = eq_key\n        self.order = order\n        self.order_key = order_key\n        self.hash = hash\n        self.init = init\n        self.metadata = metadata\n        self.type = type\n        self.kw_only = kw_only\n        self.on_setattr = on_setattr\n        self.alias = alias\n\n    def validator(self, meth):\n        \"\"\"\n        Decorator that adds *meth* to the list of validators.\n        Returns *meth* unchanged.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._validator is None:\n            self._validator = meth\n        else:\n            self._validator = and_(self._validator, meth)\n        return meth\n    def default(self, meth):\n        \"\"\"\n        Decorator that allows to set the default for an attribute.\n        Returns *meth* unchanged.\n\n        Raises:\n            DefaultAlreadySetError: If default has been set before.\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._default is not NOTHING:\n            raise DefaultAlreadySetError\n\n        self._default = Factory(meth, takes_self=True)\n        return meth\n\n    def converter(self, meth):\n        \"\"\"\n        Decorator that appends *meth* to the list of converters.\n\n        Returns *meth* unchanged.\n        .. versionadded:: 26.2.0\n        \"\"\"\n        decorated_converter = Converter(             lambda value, _self, field: meth(_self, field, value),             takes_self=True,\n            takes_field=True,         )\n        if self._converter is None:\n            self._converter = decorated_converter\n        else:\n            self._converter = pipe(self._converter, decorated_converter)\n        return meth\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-7f2049a3464dcbb6", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "6b6d1fda30891854dfb6448bab6085a9841c86def24421367c6458ec14ed2db8", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 149, "local_path": "layout/partially-compact-layout/I10__attrs___CountingAttr__acf9f35b.py", "order": 10, "original_content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "parent_variant_id": "pyint-1ce4e525acd0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2731-L2896", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 116, "line_break_groups_removed": 46, "line_breaks_removed": 46, "whitespace_characters_removed": 9}, "unit_kind": "class", "unit_name": "_CountingAttr", "variant_id": "pyint-d7ffacf9f35b-I10", "group_id": "py-7f2049a3464dcbb6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1341, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dbcf7536b486-I11", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CountingAttr:\n    \"\"\"\n    Intermediate representation of attributes that uses a counter to preserve\n    the order in which the attributes have been defined.\n\n    *Internal* data structure of the attrs library.  Running into is most\n    likely the result of a bug like a forgotten `@attr.s` decorator.\n    \"\"\"\n\n    __slots__ = (\n        \"_converter\",\n        \"_default\",\n        \"_validator\",\n        \"alias\",\n        \"counter\",\n        \"eq\",\n        \"eq_key\",\n        \"hash\",\n        \"init\",\n        \"kw_only\",\n        \"metadata\",\n        \"on_setattr\",\n        \"order\",\n        \"order_key\",\n        \"repr\",\n        \"type\",\n    )\n    __attrs_attrs__ = (\n        *tuple(\n            Attribute(\n                name=name,\n                alias=_default_init_alias_for(name),\n                default=NOTHING,\n                validator=None,\n                repr=True,\n                cmp=None,\n                hash=True,\n                init=True,\n                kw_only=False,\n                eq=True,\n                eq_key=None,\n                order=False,\n                order_key=None,\n                inherited=False,\n                on_setattr=None,\n            )\n            for name in (\n                \"counter\",\n                \"_default\",\n                \"repr\",\n                \"eq\",\n                \"order\",\n                \"hash\",\n                \"init\",\n                \"on_setattr\",\n                \"alias\",\n            )\n        ),\n        Attribute(\n            name=\"metadata\",\n            alias=\"metadata\",\n            default=None,\n            validator=None,\n            repr=True,\n            cmp=None,\n            hash=False,\n            init=True,\n            kw_only=False,\n            eq=True,\n            eq_key=None,\n            order=False,\n            order_key=None,\n            inherited=False,\n            on_setattr=None,\n        ),\n    )\n    cls_counter = 0\n\n    def __init__(\n        self,\n        default,\n        validator,\n        repr,\n        cmp,\n        hash,\n        init,\n        converter,\n        metadata,\n        type,\n        kw_only,\n        eq,\n        eq_key,\n        order,\n        order_key,\n        on_setattr,\n        alias,\n    ):\n        a = 2\n        b = -1\n        _CountingAttr.cls_counter += (a + b)\n        self.counter = _CountingAttr.cls_counter\n        self._default = default\n        self._validator = validator\n        self._converter = converter\n        self.repr = repr\n        self.eq = eq\n        self.eq_key = eq_key\n        self.order = order\n        self.order_key = order_key\n        self.hash = hash\n        self.init = init\n        self.metadata = metadata\n        self.type = type\n        self.kw_only = kw_only\n        self.on_setattr = on_setattr\n        self.alias = alias\n\n    def validator(self, meth):\n        \"\"\"\n        Decorator that adds *meth* to the list of validators.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._validator is None:\n            self._validator = meth\n        else:\n            self._validator = and_(self._validator, meth)\n        return meth\n\n    def default(self, meth):\n        \"\"\"\n        Decorator that allows to set the default for an attribute.\n\n        Returns *meth* unchanged.\n\n        Raises:\n            DefaultAlreadySetError: If default has been set before.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._default is not NOTHING:\n            raise DefaultAlreadySetError\n\n        self._default = Factory(meth, takes_self=True)\n\n        return meth\n\n    def converter(self, meth):\n        \"\"\"\n        Decorator that appends *meth* to the list of converters.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 26.2.0\n        \"\"\"\n        decorated_converter = Converter(\n            lambda value, _self, field: meth(_self, field, value),\n            takes_self=True,\n            takes_field=True,\n        )\n        if self._converter is None:\n            self._converter = decorated_converter\n        else:\n            self._converter = pipe(self._converter, decorated_converter)\n\n        return meth\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-7f2049a3464dcbb6", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "457f2743a6449d1a59acb6d90343671eeaedb11ce463f97a58939b705849c03e", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 197, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___CountingAttr__7536b486.py", "order": 11, "original_content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "parent_variant_id": "pyint-1ce4e525acd0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2731-L2896", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 1, "intermediate_variables_introduced": 2, "statements_augmented": 1}, "unit_kind": "class", "unit_name": "_CountingAttr", "variant_id": "pyint-dbcf7536b486-I11", "group_id": "py-7f2049a3464dcbb6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1342, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1710f28428ed-I12", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CountingAttr:\n    \"\"\"\n    Intermediate representation of attributes that uses a counter to preserve\n    the order in which the attributes have been defined.\n\n    *Internal* data structure of the attrs library.  Running into is most\n    likely the result of a bug like a forgotten `@attr.s` decorator.\n    \"\"\"\n\n    __slots__ = (\n        \"_converter\",\n        \"_default\",\n        \"_validator\",\n        \"alias\",\n        \"counter\",\n        \"eq\",\n        \"eq_key\",\n        \"hash\",\n        \"init\",\n        \"kw_only\",\n        \"metadata\",\n        \"on_setattr\",\n        \"order\",\n        \"order_key\",\n        \"repr\",\n        \"type\",\n    )\n    __attrs_attrs__ = (\n        *tuple(\n            Attribute(\n                name=name,\n                alias=_default_init_alias_for(name),\n                default=NOTHING,\n                validator=None,\n                repr=True,\n                cmp=None,\n                hash=True,\n                init=True,\n                kw_only=False,\n                eq=True,\n                eq_key=None,\n                order=False,\n                order_key=None,\n                inherited=False,\n                on_setattr=None,\n            )\n            for name in (\n                \"counter\",\n                \"_default\",\n                \"repr\",\n                \"eq\",\n                \"order\",\n                \"hash\",\n                \"init\",\n                \"on_setattr\",\n                \"alias\",\n            )\n        ),\n        Attribute(\n            name=\"metadata\",\n            alias=\"metadata\",\n            default=None,\n            validator=None,\n            repr=True,\n            cmp=None,\n            hash=False,\n            init=True,\n            kw_only=False,\n            eq=True,\n            eq_key=None,\n            order=False,\n            order_key=None,\n            inherited=False,\n            on_setattr=None,\n        ),\n    )\n    cls_counter = 0\n\n    def __init__(\n        self,\n        default,\n        validator,\n        repr,\n        cmp,\n        hash,\n        init,\n        converter,\n        metadata,\n        type,\n        kw_only,\n        eq,\n        eq_key,\n        order,\n        order_key,\n        on_setattr,\n        alias,\n    ):\n        _CountingAttr.cls_counter += 1\n        self.counter = _CountingAttr.cls_counter\n        self._default = default\n        self._validator = validator\n        self._converter = converter\n        self.repr = repr\n        self.eq = eq\n        self.eq_key = eq_key\n        self.order = order\n        self.order_key = order_key\n        self.hash = hash\n        self.init = init\n        self.metadata = metadata\n        self.type = type\n        self.kw_only = kw_only\n        self.on_setattr = on_setattr\n        self.alias = alias\n\n    def validator(self, meth):\n        \"\"\"\n        Decorator that adds *meth* to the list of validators.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._validator is None:\n            self._validator = meth\n        else:\n            self._validator = and_(self._validator, meth)\n        return meth\n\n    def default(self, meth):\n        \"\"\"\n        Decorator that allows to set the default for an attribute.\n\n        Returns *meth* unchanged.\n\n        Raises:\n            DefaultAlreadySetError: If default has been set before.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._default is not NOTHING:\n            raise DefaultAlreadySetError\n\n        self._default = Factory(meth, takes_self=True)\n\n        return meth\n\n    def converter(self, meth):\n        \"\"\"\n        Decorator that appends *meth* to the list of converters.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 26.2.0\n        \"\"\"\n        decorated_converter = Converter(\n            lambda value, _self, field: meth(_self, field, value),\n            takes_self=True,\n            takes_field=True,\n        )\n        if self._converter is None:\n            self._converter = decorated_converter\n        else:\n            self._converter = pipe(self._converter, decorated_converter)\n\n        return meth\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-7f2049a3464dcbb6", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 195, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___CountingAttr__f28428ed.py", "order": 12, "original_content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "parent_variant_id": "pyint-1ce4e525acd0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2731-L2896", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_CountingAttr", "variant_id": "pyint-1710f28428ed-I12", "group_id": "py-7f2049a3464dcbb6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1343, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a4685cb58319-I13", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _CountingAttr:\n    \"\"\"\n    Intermediate representation of attributes that uses a counter to preserve\n    the order in which the attributes have been defined.\n\n    *Internal* data structure of the attrs library.  Running into is most\n    likely the result of a bug like a forgotten `@attr.s` decorator.\n    \"\"\"\n\n    __slots__ = (\n        \"_converter\",\n        \"_default\",\n        \"_validator\",\n        \"alias\",\n        \"counter\",\n        \"eq\",\n        \"eq_key\",\n        \"hash\",\n        \"init\",\n        \"kw_only\",\n        \"metadata\",\n        \"on_setattr\",\n        \"order\",\n        \"order_key\",\n        \"repr\",\n        \"type\",\n    )\n    __attrs_attrs__ = (\n        *tuple(\n            Attribute(\n                name=name,\n                alias=_default_init_alias_for(name),\n                default=NOTHING,\n                validator=None,\n                repr=True,\n                cmp=None,\n                hash=True,\n                init=True,\n                kw_only=False,\n                eq=True,\n                eq_key=None,\n                order=False,\n                order_key=None,\n                inherited=False,\n                on_setattr=None,\n            )\n            for name in (\n                \"counter\",\n                \"_default\",\n                \"repr\",\n                \"eq\",\n                \"order\",\n                \"hash\",\n                \"init\",\n                \"on_setattr\",\n                \"alias\",\n            )\n        ),\n        Attribute(\n            name=\"metadata\",\n            alias=\"metadata\",\n            default=None,\n            validator=None,\n            repr=True,\n            cmp=None,\n            hash=False,\n            init=True,\n            kw_only=False,\n            eq=True,\n            eq_key=None,\n            order=False,\n            order_key=None,\n            inherited=False,\n            on_setattr=None,\n        ),\n    )\n    cls_counter = 0\n\n    def __init__(\n        self,\n        default,\n        validator,\n        repr,\n        cmp,\n        hash,\n        init,\n        converter,\n        metadata,\n        type,\n        kw_only,\n        eq,\n        eq_key,\n        order,\n        order_key,\n        on_setattr,\n        alias,\n    ):\n        _CountingAttr.cls_counter += 1\n        self.counter = _CountingAttr.cls_counter\n        self._default = default\n        self._validator = validator\n        self._converter = converter\n        self.repr = repr\n        self.eq = eq\n        self.eq_key = eq_key\n        self.order = order\n        self.order_key = order_key\n        self.hash = hash\n        self.init = init\n        self.metadata = metadata\n        self.type = type\n        self.kw_only = kw_only\n        self.on_setattr = on_setattr\n        self.alias = alias\n\n    def validator(self, meth):\n        \"\"\"\n        Decorator that adds *meth* to the list of validators.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._validator is None:\n            self._validator = meth\n        else:\n            self._validator = and_(self._validator, meth)\n        return meth\n\n    def default(self, meth):\n        \"\"\"\n        Decorator that allows to set the default for an attribute.\n\n        Returns *meth* unchanged.\n\n        Raises:\n            DefaultAlreadySetError: If default has been set before.\n\n        .. versionadded:: 17.1.0\n        \"\"\"\n        if self._default is not NOTHING:\n            raise DefaultAlreadySetError\n\n        self._default = Factory(meth, takes_self=True)\n\n        return meth\n\n    def converter(self, meth):\n        \"\"\"\n        Decorator that appends *meth* to the list of converters.\n\n        Returns *meth* unchanged.\n\n        .. versionadded:: 26.2.0\n        \"\"\"\n        decorated_converter = Converter(\n            lambda value, _self, field: meth(_self, field, value),\n            takes_self=True,\n            takes_field=True,\n        )\n        if self._converter is None:\n            self._converter = decorated_converter\n        else:\n            self._converter = pipe(self._converter, decorated_converter)\n\n        return meth\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-7f2049a3464dcbb6", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 195, "local_path": "control-flow/lower-for-to-while/I13__attrs___CountingAttr__5cb58319.py", "order": 13, "original_content_sha256": "1a615f741b1eda2bf143b90b4bd22df36b99d47a0e9b756f7d31285f57085b26", "parent_variant_id": "pyint-1ce4e525acd0-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2731-L2896", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "_CountingAttr", "variant_id": "pyint-a4685cb58319-I13", "group_id": "py-7f2049a3464dcbb6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1344, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-14eacc325bde-SRC", "source": "from __future__ import annotations\nimport collections.abc as cabc\nimport inspect\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom functools import update_wrapper\nfrom inspect import iscoroutinefunction\nfrom itertools import chain\nfrom types import TracebackType\nfrom urllib.parse import quote as _url_quote\nfrom urllib.parse import urlsplit\nimport click\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom werkzeug.wsgi import get_host\nfrom . import cli\nfrom . import typing as ft\nfrom .ctx import AppContext\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import _CollectErrors\nfrom .helpers import get_debug_flag\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import send_from_directory\nfrom .sansio.app import App\nfrom .sessions import SecureCookieSessionInterface\nfrom .sessions import SessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import Environment\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nclass Flask(App):\n    \"\"\"The flask object implements a WSGI application and acts as the central\n    object.  It is passed the name of the module or package of the\n    application.  Once it is created it will act as a central registry for\n    the view functions, the URL rules, template configuration and much more.\n\n    The name of the package is used to resolve resources from inside the\n    package or the folder the module is contained in depending on if the\n    package parameter resolves to an actual python package (a folder with\n    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n    For more information about resource loading, see :func:`open_resource`.\n\n    Usually you create a :class:`Flask` instance in your main module or\n    in the :file:`__init__.py` file of your package like this::\n\n        from flask import Flask\n        app = Flask(__name__)\n\n    .. admonition:: About the First Parameter\n\n        The idea of the first parameter is to give Flask an idea of what\n        belongs to your application.  This name is used to find resources\n        on the filesystem, can be used by extensions to improve debugging\n        information and a lot more.\n\n        So it's important what you provide there.  If you are using a single\n        module, `__name__` is always the correct value.  If you however are\n        using a package, it's usually recommended to hardcode the name of\n        your package there.\n\n        For example if your application is defined in :file:`yourapplication/app.py`\n        you should create it with one of the two versions below::\n\n            app = Flask('yourapplication')\n            app = Flask(__name__.split('.')[0])\n\n        Why is that?  The application will work even with `__name__`, thanks\n        to how resources are looked up.  However it will make debugging more\n        painful.  Certain extensions can make assumptions based on the\n        import name of your application.  For example the Flask-SQLAlchemy\n        extension will look for the code in your application that triggered\n        an SQL query in debug mode.  If the import name is not properly set\n        up, that debugging information is lost.  (For example it would only\n        pick up SQL queries in `yourapplication.app` and not\n        `yourapplication.views.frontend`)\n\n    .. versionadded:: 0.7\n       The `static_url_path`, `static_folder`, and `template_folder`\n       parameters were added.\n\n    .. versionadded:: 0.8\n       The `instance_path` and `instance_relative_config` parameters were\n       added.\n\n    .. versionadded:: 0.11\n       The `root_path` parameter was added.\n\n    .. versionadded:: 1.0\n       The ``host_matching`` and ``static_host`` parameters were added.\n\n    .. versionadded:: 1.0\n       The ``subdomain_matching`` parameter was added. Subdomain\n       matching needs to be enabled manually now. Setting\n       :data:`SERVER_NAME` does not implicitly enable it.\n\n    :param import_name: the name of the application package\n    :param static_url_path: can be used to specify a different path for the\n                            static files on the web.  Defaults to the name\n                            of the `static_folder` folder.\n    :param static_folder: The folder with static files that is served at\n        ``static_url_path``. Relative to the application ``root_path``\n        or an absolute path. Defaults to ``'static'``.\n    :param static_host: the host to use when adding the static route.\n        Defaults to None. Required when using ``host_matching=True``\n        with a ``static_folder`` configured.\n    :param host_matching: set ``url_map.host_matching`` attribute.\n        Defaults to False.\n    :param subdomain_matching: consider the subdomain relative to\n        :data:`SERVER_NAME` when matching routes. Defaults to False.\n    :param template_folder: the folder that contains the templates that should\n                            be used by the application.  Defaults to\n                            ``'templates'`` folder in the root path of the\n                            application.\n    :param instance_path: An alternative instance path for the application.\n                          By default the folder ``'instance'`` next to the\n                          package or module is assumed to be the instance\n                          path.\n    :param instance_relative_config: if set to ``True`` relative filenames\n                                     for loading the config are assumed to\n                                     be relative to the instance path instead\n                                     of the application root.\n    :param root_path: The path to the root of the application files.\n        This should only be set manually when it can't be detected\n        automatically, such as for namespace packages.\n    \"\"\"\n\n    default_config = ImmutableDict(\n        {\n            \"DEBUG\": None,\n            \"TESTING\": False,\n            \"PROPAGATE_EXCEPTIONS\": None,\n            \"SECRET_KEY\": None,\n            \"SECRET_KEY_FALLBACKS\": None,\n            \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n            \"USE_X_SENDFILE\": False,\n            \"TRUSTED_HOSTS\": None,\n            \"SERVER_NAME\": None,\n            \"APPLICATION_ROOT\": \"/\",\n            \"SESSION_COOKIE_NAME\": \"session\",\n            \"SESSION_COOKIE_DOMAIN\": None,\n            \"SESSION_COOKIE_PATH\": None,\n            \"SESSION_COOKIE_HTTPONLY\": True,\n            \"SESSION_COOKIE_SECURE\": False,\n            \"SESSION_COOKIE_PARTITIONED\": False,\n            \"SESSION_COOKIE_SAMESITE\": None,\n            \"SESSION_REFRESH_EACH_REQUEST\": True,\n            \"MAX_CONTENT_LENGTH\": None,\n            \"MAX_FORM_MEMORY_SIZE\": 500_000,\n            \"MAX_FORM_PARTS\": 1_000,\n            \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n            \"TRAP_BAD_REQUEST_ERRORS\": None,\n            \"TRAP_HTTP_EXCEPTIONS\": False,\n            \"EXPLAIN_TEMPLATE_LOADING\": False,\n            \"PREFERRED_URL_SCHEME\": \"http\",\n            \"TEMPLATES_AUTO_RELOAD\": None,\n            \"MAX_COOKIE_SIZE\": 4093,\n            \"PROVIDE_AUTOMATIC_OPTIONS\": True,\n        }\n    )\n\n    #: The class that is used for request objects.  See :class:`~flask.Request`\n    #: for more information.\n    request_class: type[Request] = Request\n\n    #: The class that is used for response objects.  See\n    #: :class:`~flask.Response` for more information.\n    response_class: type[Response] = Response\n\n    #: the session interface to use.  By default an instance of\n    #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n    #:\n    #: .. versionadded:: 0.8\n    session_interface: SessionInterface = SecureCookieSessionInterface()\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        import warnings\n\n        # These method signatures were updated to take a ctx param. Detect\n        # overridden methods in subclasses that still have the old signature.\n        # Show a deprecation warning and wrap to call with correct args.\n        for method in (\n            cls.handle_http_exception,\n            cls.handle_user_exception,\n            cls.handle_exception,\n            cls.log_exception,\n            cls.dispatch_request,\n            cls.full_dispatch_request,\n            cls.finalize_request,\n            cls.make_default_options_response,\n            cls.preprocess_request,\n            cls.process_response,\n            cls.do_teardown_request,\n            cls.do_teardown_appcontext,\n        ):\n            base_method = getattr(Flask, method.__name__)\n\n            if method is base_method:\n                # not overridden\n                continue\n\n            # get the second parameter (first is self)\n            iter_params = iter(inspect.signature(method).parameters.values())\n            next(iter_params)\n            param = next(iter_params, None)\n\n            # must have second parameter named ctx or annotated AppContext\n            if param is None or not (\n                # no annotation, match name\n                (param.annotation is inspect.Parameter.empty and param.name == \"ctx\")\n                or (\n                    # string annotation, access path ends with AppContext\n                    isinstance(param.annotation, str)\n                    and param.annotation.rpartition(\".\")[2] == \"AppContext\"\n                )\n                or (\n                    # class annotation\n                    inspect.isclass(param.annotation)\n                    and issubclass(param.annotation, AppContext)\n                )\n            ):\n                warnings.warn(\n                    f\"The '{method.__name__}' method now takes 'ctx: AppContext'\"\n                    \" as the first parameter. The old signature is deprecated\"\n                    \" and will not be supported in Flask 4.0.\",\n                    DeprecationWarning,\n                    stacklevel=2,\n                )\n                setattr(cls, method.__name__, remove_ctx(method))\n                setattr(Flask, method.__name__, add_ctx(base_method))\n\n    def __init__(\n        self,\n        import_name: str,\n        static_url_path: str | None = None,\n        static_folder: str | os.PathLike[str] | None = \"static\",\n        static_host: str | None = None,\n        host_matching: bool = False,\n        subdomain_matching: bool = False,\n        template_folder: str | os.PathLike[str] | None = \"templates\",\n        instance_path: str | None = None,\n        instance_relative_config: bool = False,\n        root_path: str | None = None,\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_url_path=static_url_path,\n            static_folder=static_folder,\n            static_host=static_host,\n            host_matching=host_matching,\n            subdomain_matching=subdomain_matching,\n            template_folder=template_folder,\n            instance_path=instance_path,\n            instance_relative_config=instance_relative_config,\n            root_path=root_path,\n        )\n\n        #: The Click command group for registering CLI commands for this\n        #: object. The commands are available from the ``flask`` command\n        #: once the application has been discovered and blueprints have\n        #: been registered.\n        self.cli = cli.AppGroup()\n\n        # Set the name of the Click group in case someone wants to add\n        # the app's commands to another CLI tool.\n        self.cli.name = self.name\n\n        # Add a static route using the provided static_url_path, static_host,\n        # and static_folder if there is a configured static_folder.\n        # Note we do this without checking if static_folder exists.\n        # For one, it might be created while the server is running (e.g. during\n        # development). Also, Google App Engine stores static files somewhere\n        if self.has_static_folder:\n            assert bool(static_host) == host_matching, (\n                \"Invalid static_host/host_matching combination\"\n            )\n            # Use a weakref to avoid creating a reference cycle between the app\n            # and the view function (see #3761).\n            self_ref = weakref.ref(self)\n            self.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                endpoint=\"static\",\n                host=static_host,\n                view_func=lambda **kw: self_ref().send_static_file(**kw),  # type: ignore\n            )\n\n    def get_send_file_max_age(self, filename: str | None) -> int | None:\n        \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n        value for a given file path if it wasn't passed.\n\n        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n        the configuration of :data:`~flask.current_app`. This defaults\n        to ``None``, which tells the browser to use conditional requests\n        instead of a timed cache, which is usually preferable.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionchanged:: 2.0\n            The default configuration is ``None`` instead of 12 hours.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        value = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n        if value is None:\n            return None\n\n        if isinstance(value, timedelta):\n            return int(value.total_seconds())\n\n        return value  # type: ignore[no-any-return]\n\n    def send_static_file(self, filename: str) -> Response:\n        \"\"\"The view function used to serve files from\n        :attr:`static_folder`. A route is automatically registered for\n        this view at :attr:`static_url_path` if :attr:`static_folder` is\n        set.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionadded:: 0.5\n\n        \"\"\"\n        if not self.has_static_folder:\n            raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n        # send_file only knows to call get_send_file_max_age on the app,\n        # call it here so it works for blueprints too.\n        max_age = self.get_send_file_max_age(filename)\n        return send_from_directory(\n            t.cast(str, self.static_folder), filename, max_age=max_age\n        )\n\n    def open_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = None\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to :attr:`root_path` for reading.\n\n        For example, if the file ``schema.sql`` is next to the file\n        ``app.py`` where the ``Flask`` app is defined, it can be opened\n        with:\n\n        .. code-block:: python\n\n            with app.open_resource(\"schema.sql\") as f:\n                conn.executescript(f.read())\n\n        :param resource: Path to the resource relative to :attr:`root_path`.\n        :param mode: Open the file in this mode. Only reading is supported,\n            valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        if mode not in {\"r\", \"rt\", \"rb\"}:\n            raise ValueError(\"Resources can only be opened for reading.\")\n\n        path = os.path.join(self.root_path, resource)\n\n        if mode == \"rb\":\n            return open(path, mode)  # pyright: ignore\n\n        return open(path, mode, encoding=encoding)\n\n    def open_instance_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = \"utf-8\"\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to the application's instance folder\n        :attr:`instance_path`. Unlike :meth:`open_resource`, files in the\n        instance folder can be opened for writing.\n\n        :param resource: Path to the resource relative to :attr:`instance_path`.\n        :param mode: Open the file in this mode.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        path = os.path.join(self.instance_path, resource)\n\n        if \"b\" in mode:\n            return open(path, mode)\n\n        return open(path, mode, encoding=encoding)\n\n    def create_jinja_environment(self) -> Environment:\n        \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n        and the various Jinja-related methods of the app. Changing\n        :attr:`jinja_options` after this will have no effect. Also adds\n        Flask-related globals and filters to the environment.\n\n        .. versionchanged:: 0.11\n           ``Environment.auto_reload`` set in accordance with\n           ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        options = dict(self.jinja_options)\n\n        if \"autoescape\" not in options:\n            options[\"autoescape\"] = self.select_jinja_autoescape\n\n        if \"auto_reload\" not in options:\n            auto_reload = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n            if auto_reload is None:\n                auto_reload = self.debug\n\n            options[\"auto_reload\"] = auto_reload\n\n        rv = self.jinja_environment(self, **options)\n        rv.globals.update(\n            url_for=self.url_for,\n            get_flashed_messages=get_flashed_messages,\n            config=self.config,\n            # request, session and g are normally added with the\n            # context processor for efficiency reasons but for imported\n            # templates we also want the proxies in there.\n            request=request,\n            session=session,\n            g=g,\n        )\n        rv.policies[\"json.dumps_function\"] = self.json.dumps\n        return rv\n\n    def create_url_adapter(self, request: Request | None) -> MapAdapter | None:\n        \"\"\"Creates a URL adapter for the given request. The URL adapter\n        is created at a point where the request context is not yet set\n        up so the request is passed explicitly.\n\n        .. versionchanged:: 3.1\n            If :data:`SERVER_NAME` is set, it does not restrict requests to\n            only that domain, for both ``subdomain_matching`` and\n            ``host_matching``.\n\n        .. versionchanged:: 1.0\n            :data:`SERVER_NAME` no longer implicitly enables subdomain\n            matching. Use :attr:`subdomain_matching` instead.\n\n        .. versionchanged:: 0.9\n           This can be called outside a request when the URL adapter is created\n           for an application context.\n\n        .. versionadded:: 0.6\n        \"\"\"\n        if request is not None:\n            if (trusted_hosts := self.config[\"TRUSTED_HOSTS\"]) is not None:\n                request.trusted_hosts = trusted_hosts\n\n            # Check trusted_hosts here until bind_to_environ does.\n            request.host = get_host(request.environ, request.trusted_hosts)  # pyright: ignore\n            subdomain = None\n            server_name = self.config[\"SERVER_NAME\"]\n\n            if self.url_map.host_matching:\n                # Don't pass SERVER_NAME, otherwise it's used and the actual\n                # host is ignored, which breaks host matching.\n                server_name = None\n            elif not self.subdomain_matching:\n                # Werkzeug doesn't implement subdomain matching yet. Until then,\n                # disable it by forcing the current subdomain to the default, or\n                # the empty string.\n                subdomain = self.url_map.default_subdomain or \"\"\n\n            return self.url_map.bind_to_environ(\n                request.environ, server_name=server_name, subdomain=subdomain\n            )\n\n        # Need at least SERVER_NAME to match/build outside a request.\n        if self.config[\"SERVER_NAME\"] is not None:\n            return self.url_map.bind(\n                self.config[\"SERVER_NAME\"],\n                script_name=self.config[\"APPLICATION_ROOT\"],\n                url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n            )\n\n        return None\n\n    def raise_routing_exception(self, request: Request) -> t.NoReturn:\n        \"\"\"Intercept routing exceptions and possibly do something else.\n\n        In debug mode, intercept a routing redirect and replace it with\n        an error if the body will be discarded.\n\n        With modern Werkzeug this shouldn't occur, since it now uses a\n        308 status which tells the browser to resend the method and\n        body.\n\n        .. versionchanged:: 2.1\n            Don't intercept 307 and 308 redirects.\n\n        :meta private:\n        :internal:\n        \"\"\"\n        if (\n            not self.debug\n            or not isinstance(request.routing_exception, RequestRedirect)\n            or request.routing_exception.code in {307, 308}\n            or request.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n        ):\n            raise request.routing_exception  # type: ignore[misc]\n\n        from .debughelpers import FormDataRoutingRedirect\n\n        raise FormDataRoutingRedirect(request)\n\n    def update_template_context(\n        self, ctx: AppContext, context: dict[str, t.Any]\n    ) -> None:\n        \"\"\"Update the template context with some commonly used variables.\n        This injects request, session, config and g into the template\n        context as well as everything template context processors want\n        to inject.  Note that the as of Flask 0.6, the original values\n        in the context will not be overridden if a context processor\n        decides to return a value with the same key.\n\n        :param context: the context as a dictionary that is updated in place\n                        to add extra variables.\n        \"\"\"\n        names: t.Iterable[str | None] = (None,)\n\n        # A template may be rendered outside a request context.\n        if ctx.has_request:\n            names = chain(names, reversed(ctx.request.blueprints))\n\n        # The values passed to render_template take precedence. Keep a\n        # copy to re-apply after all context functions.\n        orig_ctx = context.copy()\n\n        for name in names:\n            if name in self.template_context_processors:\n                for func in self.template_context_processors[name]:\n                    context.update(self.ensure_sync(func)())\n\n        context.update(orig_ctx)\n\n    def make_shell_context(self) -> dict[str, t.Any]:\n        \"\"\"Returns the shell context for an interactive shell for this\n        application.  This runs all the registered shell context\n        processors.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {\"app\": self, \"g\": g}\n        for processor in self.shell_context_processors:\n            rv.update(processor())\n        return rv\n\n    def run(\n        self,\n        host: str | None = None,\n        port: int | None = None,\n        debug: bool | None = None,\n        load_dotenv: bool = True,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Runs the application on a local development server.\n\n        Do not use ``run()`` in a production setting. It is not intended to\n        meet security and performance requirements for a production server.\n        Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n        If the :attr:`debug` flag is set the server will automatically reload\n        for code changes and show a debugger in case an exception happened.\n\n        If you want to run the application in debug mode, but disable the\n        code execution on the interactive debugger, you can pass\n        ``use_evalex=False`` as parameter.  This will keep the debugger's\n        traceback screen active, but disable code execution.\n\n        It is not recommended to use this function for development with\n        automatic reloading as this is badly supported.  Instead you should\n        be using the :command:`flask` command line script's ``run`` support.\n\n        .. admonition:: Keep in Mind\n\n           Flask will suppress any server error with a generic error page\n           unless it is in debug mode.  As such to enable just the\n           interactive debugger without the code reloading, you have to\n           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n           Setting ``use_debugger`` to ``True`` without being in debug mode\n           won't catch any exceptions because there won't be any to\n           catch.\n\n        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n            have the server available externally as well. Defaults to\n            ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n            if present.\n        :param port: the port of the webserver. Defaults to ``5000`` or the\n            port defined in the ``SERVER_NAME`` config variable if present.\n        :param debug: if given, enable or disable debug mode. See\n            :attr:`debug`.\n        :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n            files to set environment variables. Will also change the working\n            directory to the directory containing the first file found.\n        :param options: the options to be forwarded to the underlying Werkzeug\n            server. See :func:`werkzeug.serving.run_simple` for more\n            information.\n\n        .. versionchanged:: 1.0\n            If installed, python-dotenv will be used to load environment\n            variables from :file:`.env` and :file:`.flaskenv` files.\n\n            The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.\n\n            Threaded mode is enabled by default.\n\n        .. versionchanged:: 0.10\n            The default port is now picked from the ``SERVER_NAME``\n            variable.\n        \"\"\"\n        # Ignore this call so that it doesn't start another server if\n        # the 'flask run' command is used.\n        if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n            if not is_running_from_reloader():\n                click.secho(\n                    \" * Ignoring a call to 'app.run()' that would block\"\n                    \" the current 'flask' CLI command.\\n\"\n                    \"   Only call 'app.run()' in an 'if __name__ ==\"\n                    ' \"__main__\"\\' guard.',\n                    fg=\"red\",\n                )\n\n            return\n\n        if get_load_dotenv(load_dotenv):\n            cli.load_dotenv()\n\n            # if set, env var overrides existing value\n            if \"FLASK_DEBUG\" in os.environ:\n                self.debug = get_debug_flag()\n\n        # debug passed to method overrides all other sources\n        if debug is not None:\n            self.debug = bool(debug)\n\n        server_name = self.config.get(\"SERVER_NAME\")\n        sn_host = sn_port = None\n\n        if server_name:\n            server_url = urlsplit(f\"//{server_name}\")\n            sn_host = server_url.hostname\n            sn_port = server_url.port\n\n        if not host:\n            if sn_host:\n                host = sn_host\n            else:\n                host = \"127.0.0.1\"\n\n        if port or port == 0:\n            port = int(port)\n        elif sn_port is not None:\n            port = sn_port\n        else:\n            port = 5000\n\n        options.setdefault(\"use_reloader\", self.debug)\n        options.setdefault(\"use_debugger\", self.debug)\n        options.setdefault(\"threaded\", True)\n\n        cli.show_server_banner(self.debug, self.name)\n\n        from werkzeug.serving import run_simple\n\n        try:\n            run_simple(host, port, self, **options)\n        finally:\n            # reset the first request information if the development server\n            # reset normally.  This makes it possible to restart the server\n            # without reloader and that stuff from an interactive shell.\n            self._got_first_request = False\n\n    def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:\n        \"\"\"Creates a test client for this application.  For information\n        about unit testing head over to :doc:`/testing`.\n\n        Note that if you are testing for assertions or exceptions in your\n        application code, you must set ``app.testing = True`` in order for the\n        exceptions to propagate to the test client.  Otherwise, the exception\n        will be handled by the application (not visible to the test client) and\n        the only indication of an AssertionError or other exception will be a\n        500 status code response to the test client.  See the :attr:`testing`\n        attribute.  For example::\n\n            app.testing = True\n            client = app.test_client()\n\n        The test client can be used in a ``with`` block to defer the closing down\n        of the context until the end of the ``with`` block.  This is useful if\n        you want to access the context locals for testing::\n\n            with app.test_client() as c:\n                rv = c.get('/?vodka=42')\n                assert request.args['vodka'] == '42'\n\n        Additionally, you may pass optional keyword arguments that will then\n        be passed to the application's :attr:`test_client_class` constructor.\n        For example::\n\n            from flask.testing import FlaskClient\n\n            class CustomClient(FlaskClient):\n                def __init__(self, *args, **kwargs):\n                    self._authentication = kwargs.pop(\"authentication\")\n                    super(CustomClient,self).__init__( *args, **kwargs)\n\n            app.test_client_class = CustomClient\n            client = app.test_client(authentication='Basic ....')\n\n        See :class:`~flask.testing.FlaskClient` for more information.\n\n        .. versionchanged:: 0.4\n           added support for ``with`` block usage for the client.\n\n        .. versionadded:: 0.7\n           The `use_cookies` parameter was added as well as the ability\n           to override the client to be used by setting the\n           :attr:`test_client_class` attribute.\n\n        .. versionchanged:: 0.11\n           Added `**kwargs` to support passing additional keyword arguments to\n           the constructor of :attr:`test_client_class`.\n        \"\"\"\n        cls = self.test_client_class\n        if cls is None:\n            from .testing import FlaskClient as cls\n        return cls(  # type: ignore\n            self, self.response_class, use_cookies=use_cookies, **kwargs\n        )\n\n    def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:\n        \"\"\"Create a CLI runner for testing CLI commands.\n        See :ref:`testing-cli`.\n\n        Returns an instance of :attr:`test_cli_runner_class`, by default\n        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n        passed as the first argument.\n\n        .. versionadded:: 1.0\n        \"\"\"\n        cls = self.test_cli_runner_class\n\n        if cls is None:\n            from .testing import FlaskCliRunner as cls\n\n        return cls(self, **kwargs)  # type: ignore\n\n    def handle_http_exception(\n        self, ctx: AppContext, e: HTTPException\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"Handles an HTTP exception.  By default this will invoke the\n        registered error handlers and fall back to returning the\n        exception as response.\n\n        .. versionchanged:: 1.0.3\n            ``RoutingException``, used internally for actions such as\n             slash redirects during routing, is not passed to error\n             handlers.\n\n        .. versionchanged:: 1.0\n            Exceptions are looked up by code *and* by MRO, so\n            ``HTTPException`` subclasses can be handled with a catch-all\n            handler for the base ``HTTPException``.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        # Proxy exceptions don't have error codes.  We want to always return\n        # those unchanged as errors\n        if e.code is None:\n            return e\n\n        # RoutingExceptions are used internally to trigger routing\n        # actions, such as slash redirects raising RequestRedirect. They\n        # are not raised or handled in user code.\n        if isinstance(e, RoutingException):\n            return e\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n        if handler is None:\n            return e\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_user_exception(\n        self, ctx: AppContext, e: Exception\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"This method is called whenever an exception occurs that\n        should be handled. A special case is :class:`~werkzeug\n        .exceptions.HTTPException` which is forwarded to the\n        :meth:`handle_http_exception` method. This function will either\n        return a response value or reraise the exception with the same\n        traceback.\n\n        .. versionchanged:: 1.0\n            Key errors raised from request data like ``form`` show the\n            bad key in debug mode rather than a generic bad request\n            message.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if isinstance(e, BadRequestKeyError) and (\n            self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n        ):\n            e.show_exception = True\n\n        if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n            return self.handle_http_exception(ctx, e)\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n\n        if handler is None:\n            raise\n\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_exception(self, ctx: AppContext, e: Exception) -> Response:\n        \"\"\"Handle an exception that did not have an error handler\n        associated with it, or that was raised from an error handler.\n        This always causes a 500 ``InternalServerError``.\n\n        Always sends the :data:`got_request_exception` signal.\n\n        If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n        mode, the error will be re-raised so that the debugger can\n        display it. Otherwise, the original exception is logged, and\n        an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n        If an error handler is registered for ``InternalServerError`` or\n        ``500``, it will be used. For consistency, the handler will\n        always receive the ``InternalServerError``. The original\n        unhandled exception is available as ``e.original_exception``.\n\n        .. versionchanged:: 1.1.0\n            Always passes the ``InternalServerError`` instance to the\n            handler, setting ``original_exception`` to the unhandled\n            error.\n\n        .. versionchanged:: 1.1.0\n            ``after_request`` functions and other finalization is done\n            even for the default 500 response when there is no handler.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        exc_info = sys.exc_info()\n        got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)\n        propagate = self.config[\"PROPAGATE_EXCEPTIONS\"]\n\n        if propagate is None:\n            propagate = self.testing or self.debug\n\n        if propagate:\n            # Re-raise if called with an active exception, otherwise\n            # raise the passed in exception.\n            if exc_info[1] is e:\n                raise\n\n            raise e\n\n        self.log_exception(ctx, exc_info)\n        server_error: InternalServerError | ft.ResponseReturnValue\n        server_error = InternalServerError(original_exception=e)\n        handler = self._find_error_handler(server_error, ctx.request.blueprints)\n\n        if handler is not None:\n            server_error = self.ensure_sync(handler)(server_error)\n\n        return self.finalize_request(ctx, server_error, from_error_handler=True)\n\n    def log_exception(\n        self,\n        ctx: AppContext,\n        exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n    ) -> None:\n        \"\"\"Logs an exception.  This is called by :meth:`handle_exception`\n        if debugging is disabled and right before the handler is called.\n        The default implementation logs the exception as error on the\n        :attr:`logger`.\n\n        .. versionadded:: 0.8\n        \"\"\"\n        self.logger.error(\n            f\"Exception on {ctx.request.path} [{ctx.request.method}]\", exc_info=exc_info\n        )\n\n    def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue:\n        \"\"\"Does the request dispatching.  Matches the URL and returns the\n        return value of the view or error handler.  This does not have to\n        be a response object.  In order to convert the return value to a\n        proper response object, call :func:`make_response`.\n\n        .. versionchanged:: 0.7\n           This no longer does the exception handling, this code was\n           moved to the new :meth:`full_dispatch_request`.\n        \"\"\"\n        req = ctx.request\n\n        if req.routing_exception is not None:\n            self.raise_routing_exception(req)\n        rule: Rule = req.url_rule  # type: ignore[assignment]\n        # if we provide automatic options for this URL and the\n        # request came with the OPTIONS method, reply automatically\n        if (\n            getattr(rule, \"provide_automatic_options\", False)\n            and req.method == \"OPTIONS\"\n        ):\n            return self.make_default_options_response(ctx)\n        # otherwise dispatch to the handler for that endpoint\n        view_args: dict[str, t.Any] = req.view_args  # type: ignore[assignment]\n        return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]\n\n    def full_dispatch_request(self, ctx: AppContext) -> Response:\n        \"\"\"Dispatches the request and on top of that performs request\n        pre and postprocessing as well as HTTP exception catching and\n        error handling.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if not self._got_first_request and self.should_ignore_error is not None:\n            import warnings\n\n            warnings.warn(\n                \"The 'should_ignore_error' method is deprecated and will\"\n                \" be removed in Flask 3.3. Handle errors as needed in\"\n                \" teardown handlers instead.\",\n                DeprecationWarning,\n                stacklevel=1,\n            )\n\n        self._got_first_request = True\n\n        try:\n            request_started.send(self, _async_wrapper=self.ensure_sync)\n            rv = self.preprocess_request(ctx)\n            if rv is None:\n                rv = self.dispatch_request(ctx)\n        except Exception as e:\n            rv = self.handle_user_exception(ctx, e)\n        return self.finalize_request(ctx, rv)\n\n    def finalize_request(\n        self,\n        ctx: AppContext,\n        rv: ft.ResponseReturnValue | HTTPException,\n        from_error_handler: bool = False,\n    ) -> Response:\n        \"\"\"Given the return value from a view function this finalizes\n        the request by converting it into a response and invoking the\n        postprocessing functions.  This is invoked for both normal\n        request dispatching as well as error handlers.\n\n        Because this means that it might be called as a result of a\n        failure a special safe mode is available which can be enabled\n        with the `from_error_handler` flag.  If enabled, failures in\n        response processing will be logged and otherwise ignored.\n\n        :internal:\n        \"\"\"\n        response = self.make_response(rv)\n        try:\n            response = self.process_response(ctx, response)\n            request_finished.send(\n                self, _async_wrapper=self.ensure_sync, response=response\n            )\n        except Exception:\n            if not from_error_handler:\n                raise\n            self.logger.exception(\n                \"Request finalizing failed with an error while handling an error\"\n            )\n        return response\n\n    def make_default_options_response(self, ctx: AppContext) -> Response:\n        \"\"\"This method is called to create the default ``OPTIONS`` response.\n        This can be changed through subclassing to change the default\n        behavior of ``OPTIONS`` responses.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        methods = ctx.url_adapter.allowed_methods()  # type: ignore[union-attr]\n        rv = self.response_class()\n        rv.allow.update(methods)\n        return rv\n\n    def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n        \"\"\"Ensure that the function is synchronous for WSGI workers.\n        Plain ``def`` functions are returned as-is. ``async def``\n        functions are wrapped to run and wait for the response.\n\n        Override this method to change how the app runs async views.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if iscoroutinefunction(func):\n            return self.async_to_sync(func)\n\n        return func\n\n    def async_to_sync(\n        self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n    ) -> t.Callable[..., t.Any]:\n        \"\"\"Return a sync function that will run the coroutine function.\n\n        .. code-block:: python\n\n            result = app.async_to_sync(func)(*args, **kwargs)\n\n        Override this method to change how the app converts async code\n        to be synchronously callable.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        try:\n            from asgiref.sync import async_to_sync as asgiref_async_to_sync\n        except ImportError:\n            raise RuntimeError(\n                \"Install Flask with the 'async' extra in order to use async views.\"\n            ) from None\n\n        return asgiref_async_to_sync(func)\n\n    def url_for(\n        self,\n        /,\n        endpoint: str,\n        *,\n        _anchor: str | None = None,\n        _method: str | None = None,\n        _scheme: str | None = None,\n        _external: bool | None = None,\n        **values: t.Any,\n    ) -> str:\n        \"\"\"Generate a URL to the given endpoint with the given values.\n\n        This is called by :func:`flask.url_for`, and can be called\n        directly as well.\n\n        An *endpoint* is the name of a URL rule, usually added with\n        :meth:`@app.route() <route>`, and usually the same name as the\n        view function. A route defined in a :class:`~flask.Blueprint`\n        will prepend the blueprint's name separated by a ``.`` to the\n        endpoint.\n\n        In some cases, such as email messages, you want URLs to include\n        the scheme and domain, like ``https://example.com/hello``. When\n        not in an active request, URLs will be external by default, but\n        this requires setting :data:`SERVER_NAME` so Flask knows what\n        domain to use. :data:`APPLICATION_ROOT` and\n        :data:`PREFERRED_URL_SCHEME` should also be configured as\n        needed. This config is only used when not in an active request.\n\n        Functions can be decorated with :meth:`url_defaults` to modify\n        keyword arguments before the URL is built.\n\n        If building fails for some reason, such as an unknown endpoint\n        or incorrect values, the app's :meth:`handle_url_build_error`\n        method is called. If that returns a string, that is returned,\n        otherwise a :exc:`~werkzeug.routing.BuildError` is raised.\n\n        :param endpoint: The endpoint name associated with the URL to\n            generate. If this starts with a ``.``, the current blueprint\n            name (if any) will be used.\n        :param _anchor: If given, append this as ``#anchor`` to the URL.\n        :param _method: If given, generate the URL associated with this\n            method for the endpoint.\n        :param _scheme: If given, the URL will have this scheme if it\n            is external.\n        :param _external: If given, prefer the URL to be internal\n            (False) or require it to be external (True). External URLs\n            include the scheme and domain. When not in an active\n            request, URLs are external by default.\n        :param values: Values to use for the variable parts of the URL\n            rule. Unknown keys are appended as query string arguments,\n            like ``?a=b&c=d``.\n\n        .. versionadded:: 2.2\n            Moved from ``flask.url_for``, which calls this method.\n        \"\"\"\n        if (ctx := _cv_app.get(None)) is not None and ctx.has_request:\n            url_adapter = ctx.url_adapter\n            blueprint_name = ctx.request.blueprint\n\n            # If the endpoint starts with \".\" and the request matches a\n            # blueprint, the endpoint is relative to the blueprint.\n            if endpoint[:1] == \".\":\n                if blueprint_name is not None:\n                    endpoint = f\"{blueprint_name}{endpoint}\"\n                else:\n                    endpoint = endpoint[1:]\n\n            # When in a request, generate a URL without scheme and\n            # domain by default, unless a scheme is given.\n            if _external is None:\n                _external = _scheme is not None\n        else:\n            # If called by helpers.url_for, an app context is active,\n            # use its url_adapter. Otherwise, app.url_for was called\n            # directly, build an adapter.\n            if ctx is not None:\n                url_adapter = ctx.url_adapter\n            else:\n                url_adapter = self.create_url_adapter(None)\n\n            if url_adapter is None:\n                raise RuntimeError(\n                    \"Unable to build URLs outside an active request\"\n                    \" without 'SERVER_NAME' configured. Also configure\"\n                    \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n                    \" needed.\"\n                )\n\n            # When outside a request, generate a URL with scheme and\n            # domain by default.\n            if _external is None:\n                _external = True\n\n        # It is an error to set _scheme when _external=False, in order\n        # to avoid accidental insecure URLs.\n        if _scheme is not None and not _external:\n            raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n        self.inject_url_defaults(endpoint, values)\n\n        try:\n            rv = url_adapter.build(  # type: ignore[union-attr]\n                endpoint,\n                values,\n                method=_method,\n                url_scheme=_scheme,\n                force_external=_external,\n            )\n        except BuildError as error:\n            values.update(\n                _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external\n            )\n            return self.handle_url_build_error(error, endpoint, values)\n\n        if _anchor is not None:\n            _anchor = _url_quote(_anchor, safe=\"%!#$&'()*+,/:;=?@\")\n            rv = f\"{rv}#{_anchor}\"\n\n        return rv\n\n    def make_response(self, rv: ft.ResponseReturnValue) -> Response:\n        \"\"\"Convert the return value from a view function to an instance of\n        :attr:`response_class`.\n\n        :param rv: the return value from the view function. The view function\n            must return a response. Returning ``None``, or the view ending\n            without returning, is not allowed. The following types are allowed\n            for ``view_rv``:\n\n            ``str``\n                A response object is created with the string encoded to UTF-8\n                as the body.\n\n            ``bytes``\n                A response object is created with the bytes as the body.\n\n            ``dict``\n                Converted to a JSON response.\n\n            ``list``\n                Converted to a JSON response.\n\n            ``generator`` or ``iterator``\n                A generator that returns ``str`` or ``bytes`` to be\n                streamed as the response.\n\n            ``tuple``\n                Either ``(body, status, headers)``, ``(body, status)``, or\n                ``(body, headers)``, where ``body`` is any of the other types\n                allowed here, ``status`` is a string or an integer, and\n                ``headers`` is a dictionary or a list of ``(key, value)``\n                tuples. If ``body`` is a :attr:`response_class` instance,\n                ``status`` overwrites the exiting value and ``headers`` are\n                extended.\n\n            :attr:`response_class`\n                The object is returned unchanged.\n\n            other :class:`~werkzeug.wrappers.Response` class\n                The object is coerced to :attr:`response_class`.\n\n            :func:`callable`\n                The function is called as a WSGI application. The result is\n                used to create a response object.\n\n        .. versionchanged:: 2.2\n            A generator will be converted to a streaming response.\n            A list will be converted to a JSON response.\n\n        .. versionchanged:: 1.1\n            A dict will be converted to a JSON response.\n\n        .. versionchanged:: 0.9\n           Previously a tuple was interpreted as the arguments for the\n           response object.\n        \"\"\"\n\n        status: int | None = None\n        headers: HeadersValue | None = None\n\n        # unpack tuple returns\n        if isinstance(rv, tuple):\n            len_rv = len(rv)\n\n            # a 3-tuple is unpacked directly\n            if len_rv == 3:\n                rv, status, headers = rv  # type: ignore[misc]\n            # decide if a 2-tuple has status or headers\n            elif len_rv == 2:\n                if isinstance(rv[1], (Headers, dict, tuple, list)):\n                    rv, headers = rv  # pyright: ignore\n                else:\n                    rv, status = rv  # type: ignore[assignment,misc]\n            # other sized tuples are not allowed\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid response tuple.\"\n                    \" The tuple must have the form (body, status, headers),\"\n                    \" (body, status), or (body, headers).\"\n                )\n\n        # the body must not be None\n        if rv is None:\n            raise TypeError(\n                f\"The view function for {request.endpoint!r} did not\"\n                \" return a valid response. The function either returned\"\n                \" None or ended without a return statement.\"\n            )\n\n        # make sure the body is an instance of the response class\n        if not isinstance(rv, self.response_class):\n            if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):\n                # let the response class set the status and headers instead of\n                # waiting to do it manually, so that the class can handle any\n                # special logic\n                rv = self.response_class(\n                    rv,  # pyright: ignore\n                    status=status,\n                    headers=headers,  # type: ignore[arg-type]\n                )\n                status = headers = None\n            elif isinstance(rv, (dict, list)):\n                rv = self.json.response(rv)\n            elif isinstance(rv, BaseResponse) or callable(rv):\n                # evaluate a WSGI callable, or coerce a different response\n                # class to the correct type\n                try:\n                    rv = self.response_class.force_type(\n                        rv,  # type: ignore[arg-type]\n                        request.environ,\n                    )\n                except TypeError as e:\n                    raise TypeError(\n                        f\"{e}\\nThe view function did not return a valid\"\n                        \" response. The return type must be a string,\"\n                        \" dict, list, tuple with headers or status,\"\n                        \" Response instance, or WSGI callable, but it\"\n                        f\" was a {type(rv).__name__}.\"\n                    ).with_traceback(sys.exc_info()[2]) from None\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid\"\n                    \" response. The return type must be a string,\"\n                    \" dict, list, tuple with headers or status,\"\n                    \" Response instance, or WSGI callable, but it was a\"\n                    f\" {type(rv).__name__}.\"\n                )\n\n        rv = t.cast(Response, rv)\n        # prefer the status if it was provided\n        if status is not None:\n            if isinstance(status, (str, bytes, bytearray)):\n                rv.status = status\n            else:\n                rv.status_code = status\n\n        # extend existing headers with provided headers\n        if headers:\n            rv.headers.update(headers)\n\n        return rv\n\n    def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None:\n        \"\"\"Called before the request is dispatched. Calls\n        :attr:`url_value_preprocessors` registered with the app and the\n        current blueprint (if any). Then calls :attr:`before_request_funcs`\n        registered with the app and the blueprint.\n\n        If any :meth:`before_request` handler returns a non-None value, the\n        value is handled as if it was the return value from the view, and\n        further request handling is stopped.\n        \"\"\"\n        req = ctx.request\n        names = (None, *reversed(req.blueprints))\n\n        for name in names:\n            if name in self.url_value_preprocessors:\n                for url_func in self.url_value_preprocessors[name]:\n                    url_func(req.endpoint, req.view_args)\n\n        for name in names:\n            if name in self.before_request_funcs:\n                for before_func in self.before_request_funcs[name]:\n                    rv = self.ensure_sync(before_func)()\n\n                    if rv is not None:\n                        return rv  # type: ignore[no-any-return]\n\n        return None\n\n    def process_response(self, ctx: AppContext, response: Response) -> Response:\n        \"\"\"Can be overridden in order to modify the response object\n        before it's sent to the WSGI server.  By default this will\n        call all the :meth:`after_request` decorated functions.\n\n        .. versionchanged:: 0.5\n           As of Flask 0.5 the functions registered for after request\n           execution are called in reverse order of registration.\n\n        :param response: a :attr:`response_class` object.\n        :return: a new response object or the same, has to be an\n                 instance of :attr:`response_class`.\n        \"\"\"\n        for func in ctx._after_request_functions:\n            response = self.ensure_sync(func)(response)\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.after_request_funcs:\n                for func in reversed(self.after_request_funcs[name]):\n                    response = self.ensure_sync(func)(response)\n\n        if not self.session_interface.is_null_session(ctx._get_session()):\n            self.session_interface.save_session(self, ctx._get_session(), response)\n\n        return response\n\n    def do_teardown_request(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called after the request is dispatched and the response is finalized,\n        right before the request context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_request`, and\n        :meth:`Blueprint.teardown_request` if a blueprint handled the request.\n        Finally, the :data:`request_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while dispatching the request.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionchanged:: 0.9\n            Added the ``exc`` argument.\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.teardown_request_funcs:\n                for func in reversed(self.teardown_request_funcs[name]):\n                    with collect_errors:\n                        self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during request teardown\")\n\n    def do_teardown_appcontext(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called right before the application context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_appcontext`.\n        Then the :data:`appcontext_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while the context was active.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for func in reversed(self.teardown_appcontext_funcs):\n            with collect_errors:\n                self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during app teardown\")\n\n    def app_context(self) -> AppContext:\n        \"\"\"Create an :class:`.AppContext`. When the context is pushed,\n        :data:`.current_app` and :data:`.g` become available.\n\n        A context is automatically pushed when handling each request, and when\n        running any ``flask`` CLI command. Use this as a ``with`` block to\n        manually push a context outside of those situations, such as during\n        setup or testing.\n\n        .. code-block:: python\n\n            with app.app_context():\n                init_db()\n\n        See :doc:`/appcontext`.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        return AppContext(self)\n\n    def request_context(self, environ: WSGIEnvironment) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information representing\n        the given WSGI environment. A context is automatically pushed when\n        handling each request. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This method should not be used in your own code. Creating a valid WSGI\n        environ is not trivial. Use :meth:`test_request_context` to correctly\n        create a WSGI environ and request context instead.\n\n        See :doc:`/appcontext`.\n\n        :param environ: A WSGI environment.\n        \"\"\"\n        return AppContext.from_environ(self, environ)\n\n    def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information created from\n        the given arguments. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This is useful during testing to run a function that uses request data\n        without dispatching a full request. Use this as a ``with`` block to push\n        a context.\n\n        .. code-block:: python\n\n            with app.test_request_context(...):\n                generate_report()\n\n        See :doc:`/appcontext`.\n\n        Takes the same arguments as Werkzeug's\n        :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n        the application. See the linked Werkzeug docs for most of the\n        available arguments. Flask-specific behavior is listed here.\n\n        :param path: URL path being requested.\n        :param base_url: Base URL where the app is being served, which\n            ``path`` is relative to. If not given, built from\n            :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,\n            and :data:`APPLICATION_ROOT`.\n        :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.\n        :param url_scheme: Scheme to use instead of\n            :data:`PREFERRED_URL_SCHEME`.\n        :param data: The request body text or bytes,or a dict of form data.\n        :param json: If given, this is serialized as JSON and passed as\n            ``data``. Also defaults ``content_type`` to\n            ``application/json``.\n        :param args: Other positional arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        :param kwargs: Other keyword arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        \"\"\"\n        from .testing import EnvironBuilder\n\n        builder = EnvironBuilder(self, *args, **kwargs)\n\n        try:\n            environ = builder.get_environ()\n        finally:\n            builder.close()\n\n        return self.request_context(environ)\n\n    def wsgi_app(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The actual WSGI application. This is not implemented in\n        :meth:`__call__` so that middlewares can be applied without\n        losing a reference to the app object. Instead of doing this::\n\n            app = MyMiddleware(app)\n\n        It's a better idea to do this instead::\n\n            app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n        Then you still have the original application object around and\n        can continue to call methods on it.\n\n        .. versionchanged:: 0.7\n            Teardown events for the request and app contexts are called\n            even if an unhandled error occurs. Other events may not be\n            called depending on when an error occurs during dispatch.\n\n        :param environ: A WSGI environment.\n        :param start_response: A callable accepting a status code,\n            a list of headers, and an optional exception context to\n            start the response.\n        \"\"\"\n        ctx = self.request_context(environ)\n        error: BaseException | None = None\n        try:\n            try:\n                ctx.push()\n                response = self.full_dispatch_request(ctx)\n            except Exception as e:\n                error = e\n                response = self.handle_exception(ctx, e)\n            except:\n                error = sys.exc_info()[1]\n                raise\n            return response(environ, start_response)\n        finally:\n            if \"werkzeug.debug.preserve_context\" in environ:\n                environ[\"werkzeug.debug.preserve_context\"](ctx)\n\n            if (\n                error is not None\n                and self.should_ignore_error is not None\n                and self.should_ignore_error(error)\n            ):\n                error = None\n\n            ctx.pop(error)\n\n    def __call__(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The WSGI server calls the Flask application object as the\n        WSGI application. This calls :meth:`wsgi_app`, which can be\n        wrapped to apply middleware.\n        \"\"\"\n        return self.wsgi_app(environ, start_response)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-8341cf85103c4a69", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 1572, "local_path": "source-original/SRC__flask__Flask__cc325bde.py", "order": 0, "original_content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/app.py#L110-L1628", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Flask", "variant_id": "pyint-14eacc325bde-SRC", "group_id": "py-8341cf85103c4a69", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 631, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-333af2874e83-I01", "source": "from __future__ import annotations\nimport collections.abc as cabc\nimport inspect\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom functools import update_wrapper\nfrom inspect import iscoroutinefunction\nfrom itertools import chain\nfrom types import TracebackType\nfrom urllib.parse import quote as _url_quote\nfrom urllib.parse import urlsplit\nimport click\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom werkzeug.wsgi import get_host\nfrom . import cli\nfrom . import typing as ft\nfrom .ctx import AppContext\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import _CollectErrors\nfrom .helpers import get_debug_flag\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import send_from_directory\nfrom .sansio.app import App\nfrom .sessions import SecureCookieSessionInterface\nfrom .sessions import SessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import Environment\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nclass Flask(App):\n    \n\n    default_config = ImmutableDict(\n        {\n            \"DEBUG\": None,\n            \"TESTING\": False,\n            \"PROPAGATE_EXCEPTIONS\": None,\n            \"SECRET_KEY\": None,\n            \"SECRET_KEY_FALLBACKS\": None,\n            \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n            \"USE_X_SENDFILE\": False,\n            \"TRUSTED_HOSTS\": None,\n            \"SERVER_NAME\": None,\n            \"APPLICATION_ROOT\": \"/\",\n            \"SESSION_COOKIE_NAME\": \"session\",\n            \"SESSION_COOKIE_DOMAIN\": None,\n            \"SESSION_COOKIE_PATH\": None,\n            \"SESSION_COOKIE_HTTPONLY\": True,\n            \"SESSION_COOKIE_SECURE\": False,\n            \"SESSION_COOKIE_PARTITIONED\": False,\n            \"SESSION_COOKIE_SAMESITE\": None,\n            \"SESSION_REFRESH_EACH_REQUEST\": True,\n            \"MAX_CONTENT_LENGTH\": None,\n            \"MAX_FORM_MEMORY_SIZE\": 500_000,\n            \"MAX_FORM_PARTS\": 1_000,\n            \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n            \"TRAP_BAD_REQUEST_ERRORS\": None,\n            \"TRAP_HTTP_EXCEPTIONS\": False,\n            \"EXPLAIN_TEMPLATE_LOADING\": False,\n            \"PREFERRED_URL_SCHEME\": \"http\",\n            \"TEMPLATES_AUTO_RELOAD\": None,\n            \"MAX_COOKIE_SIZE\": 4093,\n            \"PROVIDE_AUTOMATIC_OPTIONS\": True,\n        }\n    )\n\n     \n     \n    request_class: type[Request] = Request\n\n     \n     \n    response_class: type[Response] = Response\n\n     \n     \n     \n     \n    session_interface: SessionInterface = SecureCookieSessionInterface()\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        import warnings\n\n         \n         \n         \n        for method in (\n            cls.handle_http_exception,\n            cls.handle_user_exception,\n            cls.handle_exception,\n            cls.log_exception,\n            cls.dispatch_request,\n            cls.full_dispatch_request,\n            cls.finalize_request,\n            cls.make_default_options_response,\n            cls.preprocess_request,\n            cls.process_response,\n            cls.do_teardown_request,\n            cls.do_teardown_appcontext,\n        ):\n            base_method = getattr(Flask, method.__name__)\n\n            if method is base_method:\n                 \n                continue\n\n             \n            iter_params = iter(inspect.signature(method).parameters.values())\n            next(iter_params)\n            param = next(iter_params, None)\n\n             \n            if param is None or not (\n                 \n                (param.annotation is inspect.Parameter.empty and param.name == \"ctx\")\n                or (\n                     \n                    isinstance(param.annotation, str)\n                    and param.annotation.rpartition(\".\")[2] == \"AppContext\"\n                )\n                or (\n                     \n                    inspect.isclass(param.annotation)\n                    and issubclass(param.annotation, AppContext)\n                )\n            ):\n                warnings.warn(\n                    f\"The '{method.__name__}' method now takes 'ctx: AppContext'\"\n                    \" as the first parameter. The old signature is deprecated\"\n                    \" and will not be supported in Flask 4.0.\",\n                    DeprecationWarning,\n                    stacklevel=2,\n                )\n                setattr(cls, method.__name__, remove_ctx(method))\n                setattr(Flask, method.__name__, add_ctx(base_method))\n\n    def __init__(\n        self,\n        import_name: str,\n        static_url_path: str | None = None,\n        static_folder: str | os.PathLike[str] | None = \"static\",\n        static_host: str | None = None,\n        host_matching: bool = False,\n        subdomain_matching: bool = False,\n        template_folder: str | os.PathLike[str] | None = \"templates\",\n        instance_path: str | None = None,\n        instance_relative_config: bool = False,\n        root_path: str | None = None,\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_url_path=static_url_path,\n            static_folder=static_folder,\n            static_host=static_host,\n            host_matching=host_matching,\n            subdomain_matching=subdomain_matching,\n            template_folder=template_folder,\n            instance_path=instance_path,\n            instance_relative_config=instance_relative_config,\n            root_path=root_path,\n        )\n\n         \n         \n         \n         \n        self.cli = cli.AppGroup()\n\n         \n         \n        self.cli.name = self.name\n\n         \n         \n         \n         \n         \n        if self.has_static_folder:\n            assert bool(static_host) == host_matching, (\n                \"Invalid static_host/host_matching combination\"\n            )\n             \n             \n            self_ref = weakref.ref(self)\n            self.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                endpoint=\"static\",\n                host=static_host,\n                view_func=lambda **kw: self_ref().send_static_file(**kw),   \n            )\n\n    def get_send_file_max_age(self, filename: str | None) -> int | None:\n        \n        value = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n        if value is None:\n            return None\n\n        if isinstance(value, timedelta):\n            return int(value.total_seconds())\n\n        return value   \n\n    def send_static_file(self, filename: str) -> Response:\n        \n        if not self.has_static_folder:\n            raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n         \n         \n        max_age = self.get_send_file_max_age(filename)\n        return send_from_directory(\n            t.cast(str, self.static_folder), filename, max_age=max_age\n        )\n\n    def open_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = None\n    ) -> t.IO[t.AnyStr]:\n        \n        if mode not in {\"r\", \"rt\", \"rb\"}:\n            raise ValueError(\"Resources can only be opened for reading.\")\n\n        path = os.path.join(self.root_path, resource)\n\n        if mode == \"rb\":\n            return open(path, mode)   \n\n        return open(path, mode, encoding=encoding)\n\n    def open_instance_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = \"utf-8\"\n    ) -> t.IO[t.AnyStr]:\n        \n        path = os.path.join(self.instance_path, resource)\n\n        if \"b\" in mode:\n            return open(path, mode)\n\n        return open(path, mode, encoding=encoding)\n\n    def create_jinja_environment(self) -> Environment:\n        \n        options = dict(self.jinja_options)\n\n        if \"autoescape\" not in options:\n            options[\"autoescape\"] = self.select_jinja_autoescape\n\n        if \"auto_reload\" not in options:\n            auto_reload = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n            if auto_reload is None:\n                auto_reload = self.debug\n\n            options[\"auto_reload\"] = auto_reload\n\n        rv = self.jinja_environment(self, **options)\n        rv.globals.update(\n            url_for=self.url_for,\n            get_flashed_messages=get_flashed_messages,\n            config=self.config,\n             \n             \n             \n            request=request,\n            session=session,\n            g=g,\n        )\n        rv.policies[\"json.dumps_function\"] = self.json.dumps\n        return rv\n\n    def create_url_adapter(self, request: Request | None) -> MapAdapter | None:\n        \n        if request is not None:\n            if (trusted_hosts := self.config[\"TRUSTED_HOSTS\"]) is not None:\n                request.trusted_hosts = trusted_hosts\n\n             \n            request.host = get_host(request.environ, request.trusted_hosts)   \n            subdomain = None\n            server_name = self.config[\"SERVER_NAME\"]\n\n            if self.url_map.host_matching:\n                 \n                 \n                server_name = None\n            elif not self.subdomain_matching:\n                 \n                 \n                 \n                subdomain = self.url_map.default_subdomain or \"\"\n\n            return self.url_map.bind_to_environ(\n                request.environ, server_name=server_name, subdomain=subdomain\n            )\n\n         \n        if self.config[\"SERVER_NAME\"] is not None:\n            return self.url_map.bind(\n                self.config[\"SERVER_NAME\"],\n                script_name=self.config[\"APPLICATION_ROOT\"],\n                url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n            )\n\n        return None\n\n    def raise_routing_exception(self, request: Request) -> t.NoReturn:\n        \n        if (\n            not self.debug\n            or not isinstance(request.routing_exception, RequestRedirect)\n            or request.routing_exception.code in {307, 308}\n            or request.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n        ):\n            raise request.routing_exception   \n\n        from .debughelpers import FormDataRoutingRedirect\n\n        raise FormDataRoutingRedirect(request)\n\n    def update_template_context(\n        self, ctx: AppContext, context: dict[str, t.Any]\n    ) -> None:\n        \n        names: t.Iterable[str | None] = (None,)\n\n         \n        if ctx.has_request:\n            names = chain(names, reversed(ctx.request.blueprints))\n\n         \n         \n        orig_ctx = context.copy()\n\n        for name in names:\n            if name in self.template_context_processors:\n                for func in self.template_context_processors[name]:\n                    context.update(self.ensure_sync(func)())\n\n        context.update(orig_ctx)\n\n    def make_shell_context(self) -> dict[str, t.Any]:\n        \n        rv = {\"app\": self, \"g\": g}\n        for processor in self.shell_context_processors:\n            rv.update(processor())\n        return rv\n\n    def run(\n        self,\n        host: str | None = None,\n        port: int | None = None,\n        debug: bool | None = None,\n        load_dotenv: bool = True,\n        **options: t.Any,\n    ) -> None:\n        \n         \n         \n        if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n            if not is_running_from_reloader():\n                click.secho(\n                    \" * Ignoring a call to 'app.run()' that would block\"\n                    \" the current 'flask' CLI command.\\n\"\n                    \"   Only call 'app.run()' in an 'if __name__ ==\"\n                    ' \"__main__\"\\' guard.',\n                    fg=\"red\",\n                )\n\n            return\n\n        if get_load_dotenv(load_dotenv):\n            cli.load_dotenv()\n\n             \n            if \"FLASK_DEBUG\" in os.environ:\n                self.debug = get_debug_flag()\n\n         \n        if debug is not None:\n            self.debug = bool(debug)\n\n        server_name = self.config.get(\"SERVER_NAME\")\n        sn_host = sn_port = None\n\n        if server_name:\n            server_url = urlsplit(f\"//{server_name}\")\n            sn_host = server_url.hostname\n            sn_port = server_url.port\n\n        if not host:\n            if sn_host:\n                host = sn_host\n            else:\n                host = \"127.0.0.1\"\n\n        if port or port == 0:\n            port = int(port)\n        elif sn_port is not None:\n            port = sn_port\n        else:\n            port = 5000\n\n        options.setdefault(\"use_reloader\", self.debug)\n        options.setdefault(\"use_debugger\", self.debug)\n        options.setdefault(\"threaded\", True)\n\n        cli.show_server_banner(self.debug, self.name)\n\n        from werkzeug.serving import run_simple\n\n        try:\n            run_simple(host, port, self, **options)\n        finally:\n             \n             \n             \n            self._got_first_request = False\n\n    def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:\n        \n        cls = self.test_client_class\n        if cls is None:\n            from .testing import FlaskClient as cls\n        return cls(   \n            self, self.response_class, use_cookies=use_cookies, **kwargs\n        )\n\n    def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:\n        \n        cls = self.test_cli_runner_class\n\n        if cls is None:\n            from .testing import FlaskCliRunner as cls\n\n        return cls(self, **kwargs)   \n\n    def handle_http_exception(\n        self, ctx: AppContext, e: HTTPException\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \n         \n         \n        if e.code is None:\n            return e\n\n         \n         \n         \n        if isinstance(e, RoutingException):\n            return e\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n        if handler is None:\n            return e\n        return self.ensure_sync(handler)(e)   \n\n    def handle_user_exception(\n        self, ctx: AppContext, e: Exception\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \n        if isinstance(e, BadRequestKeyError) and (\n            self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n        ):\n            e.show_exception = True\n\n        if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n            return self.handle_http_exception(ctx, e)\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n\n        if handler is None:\n            raise\n\n        return self.ensure_sync(handler)(e)   \n\n    def handle_exception(self, ctx: AppContext, e: Exception) -> Response:\n        \n        exc_info = sys.exc_info()\n        got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)\n        propagate = self.config[\"PROPAGATE_EXCEPTIONS\"]\n\n        if propagate is None:\n            propagate = self.testing or self.debug\n\n        if propagate:\n             \n             \n            if exc_info[1] is e:\n                raise\n\n            raise e\n\n        self.log_exception(ctx, exc_info)\n        server_error: InternalServerError | ft.ResponseReturnValue\n        server_error = InternalServerError(original_exception=e)\n        handler = self._find_error_handler(server_error, ctx.request.blueprints)\n\n        if handler is not None:\n            server_error = self.ensure_sync(handler)(server_error)\n\n        return self.finalize_request(ctx, server_error, from_error_handler=True)\n\n    def log_exception(\n        self,\n        ctx: AppContext,\n        exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n    ) -> None:\n        \n        self.logger.error(\n            f\"Exception on {ctx.request.path} [{ctx.request.method}]\", exc_info=exc_info\n        )\n\n    def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue:\n        \n        req = ctx.request\n\n        if req.routing_exception is not None:\n            self.raise_routing_exception(req)\n        rule: Rule = req.url_rule   \n         \n         \n        if (\n            getattr(rule, \"provide_automatic_options\", False)\n            and req.method == \"OPTIONS\"\n        ):\n            return self.make_default_options_response(ctx)\n         \n        view_args: dict[str, t.Any] = req.view_args   \n        return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)   \n\n    def full_dispatch_request(self, ctx: AppContext) -> Response:\n        \n        if not self._got_first_request and self.should_ignore_error is not None:\n            import warnings\n\n            warnings.warn(\n                \"The 'should_ignore_error' method is deprecated and will\"\n                \" be removed in Flask 3.3. Handle errors as needed in\"\n                \" teardown handlers instead.\",\n                DeprecationWarning,\n                stacklevel=1,\n            )\n\n        self._got_first_request = True\n\n        try:\n            request_started.send(self, _async_wrapper=self.ensure_sync)\n            rv = self.preprocess_request(ctx)\n            if rv is None:\n                rv = self.dispatch_request(ctx)\n        except Exception as e:\n            rv = self.handle_user_exception(ctx, e)\n        return self.finalize_request(ctx, rv)\n\n    def finalize_request(\n        self,\n        ctx: AppContext,\n        rv: ft.ResponseReturnValue | HTTPException,\n        from_error_handler: bool = False,\n    ) -> Response:\n        \n        response = self.make_response(rv)\n        try:\n            response = self.process_response(ctx, response)\n            request_finished.send(\n                self, _async_wrapper=self.ensure_sync, response=response\n            )\n        except Exception:\n            if not from_error_handler:\n                raise\n            self.logger.exception(\n                \"Request finalizing failed with an error while handling an error\"\n            )\n        return response\n\n    def make_default_options_response(self, ctx: AppContext) -> Response:\n        \n        methods = ctx.url_adapter.allowed_methods()   \n        rv = self.response_class()\n        rv.allow.update(methods)\n        return rv\n\n    def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n        \n        if iscoroutinefunction(func):\n            return self.async_to_sync(func)\n\n        return func\n\n    def async_to_sync(\n        self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n    ) -> t.Callable[..., t.Any]:\n        \n        try:\n            from asgiref.sync import async_to_sync as asgiref_async_to_sync\n        except ImportError:\n            raise RuntimeError(\n                \"Install Flask with the 'async' extra in order to use async views.\"\n            ) from None\n\n        return asgiref_async_to_sync(func)\n\n    def url_for(\n        self,\n        /,\n        endpoint: str,\n        *,\n        _anchor: str | None = None,\n        _method: str | None = None,\n        _scheme: str | None = None,\n        _external: bool | None = None,\n        **values: t.Any,\n    ) -> str:\n        \n        if (ctx := _cv_app.get(None)) is not None and ctx.has_request:\n            url_adapter = ctx.url_adapter\n            blueprint_name = ctx.request.blueprint\n\n             \n             \n            if endpoint[:1] == \".\":\n                if blueprint_name is not None:\n                    endpoint = f\"{blueprint_name}{endpoint}\"\n                else:\n                    endpoint = endpoint[1:]\n\n             \n             \n            if _external is None:\n                _external = _scheme is not None\n        else:\n             \n             \n             \n            if ctx is not None:\n                url_adapter = ctx.url_adapter\n            else:\n                url_adapter = self.create_url_adapter(None)\n\n            if url_adapter is None:\n                raise RuntimeError(\n                    \"Unable to build URLs outside an active request\"\n                    \" without 'SERVER_NAME' configured. Also configure\"\n                    \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n                    \" needed.\"\n                )\n\n             \n             \n            if _external is None:\n                _external = True\n\n         \n         \n        if _scheme is not None and not _external:\n            raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n        self.inject_url_defaults(endpoint, values)\n\n        try:\n            rv = url_adapter.build(   \n                endpoint,\n                values,\n                method=_method,\n                url_scheme=_scheme,\n                force_external=_external,\n            )\n        except BuildError as error:\n            values.update(\n                _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external\n            )\n            return self.handle_url_build_error(error, endpoint, values)\n\n        if _anchor is not None:\n            _anchor = _url_quote(_anchor, safe=\"%!#$&'()*+,/:;=?@\")\n            rv = f\"{rv}#{_anchor}\"\n\n        return rv\n\n    def make_response(self, rv: ft.ResponseReturnValue) -> Response:\n        \n\n        status: int | None = None\n        headers: HeadersValue | None = None\n\n         \n        if isinstance(rv, tuple):\n            len_rv = len(rv)\n\n             \n            if len_rv == 3:\n                rv, status, headers = rv   \n             \n            elif len_rv == 2:\n                if isinstance(rv[1], (Headers, dict, tuple, list)):\n                    rv, headers = rv   \n                else:\n                    rv, status = rv   \n             \n            else:\n                raise TypeError(\n                    \"The view function did not return a valid response tuple.\"\n                    \" The tuple must have the form (body, status, headers),\"\n                    \" (body, status), or (body, headers).\"\n                )\n\n         \n        if rv is None:\n            raise TypeError(\n                f\"The view function for {request.endpoint!r} did not\"\n                \" return a valid response. The function either returned\"\n                \" None or ended without a return statement.\"\n            )\n\n         \n        if not isinstance(rv, self.response_class):\n            if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):\n                 \n                 \n                 \n                rv = self.response_class(\n                    rv,   \n                    status=status,\n                    headers=headers,   \n                )\n                status = headers = None\n            elif isinstance(rv, (dict, list)):\n                rv = self.json.response(rv)\n            elif isinstance(rv, BaseResponse) or callable(rv):\n                 \n                 \n                try:\n                    rv = self.response_class.force_type(\n                        rv,   \n                        request.environ,\n                    )\n                except TypeError as e:\n                    raise TypeError(\n                        f\"{e}\\nThe view function did not return a valid\"\n                        \" response. The return type must be a string,\"\n                        \" dict, list, tuple with headers or status,\"\n                        \" Response instance, or WSGI callable, but it\"\n                        f\" was a {type(rv).__name__}.\"\n                    ).with_traceback(sys.exc_info()[2]) from None\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid\"\n                    \" response. The return type must be a string,\"\n                    \" dict, list, tuple with headers or status,\"\n                    \" Response instance, or WSGI callable, but it was a\"\n                    f\" {type(rv).__name__}.\"\n                )\n\n        rv = t.cast(Response, rv)\n         \n        if status is not None:\n            if isinstance(status, (str, bytes, bytearray)):\n                rv.status = status\n            else:\n                rv.status_code = status\n\n         \n        if headers:\n            rv.headers.update(headers)\n\n        return rv\n\n    def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None:\n        \n        req = ctx.request\n        names = (None, *reversed(req.blueprints))\n\n        for name in names:\n            if name in self.url_value_preprocessors:\n                for url_func in self.url_value_preprocessors[name]:\n                    url_func(req.endpoint, req.view_args)\n\n        for name in names:\n            if name in self.before_request_funcs:\n                for before_func in self.before_request_funcs[name]:\n                    rv = self.ensure_sync(before_func)()\n\n                    if rv is not None:\n                        return rv   \n\n        return None\n\n    def process_response(self, ctx: AppContext, response: Response) -> Response:\n        \n        for func in ctx._after_request_functions:\n            response = self.ensure_sync(func)(response)\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.after_request_funcs:\n                for func in reversed(self.after_request_funcs[name]):\n                    response = self.ensure_sync(func)(response)\n\n        if not self.session_interface.is_null_session(ctx._get_session()):\n            self.session_interface.save_session(self, ctx._get_session(), response)\n\n        return response\n\n    def do_teardown_request(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \n        collect_errors = _CollectErrors()\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.teardown_request_funcs:\n                for func in reversed(self.teardown_request_funcs[name]):\n                    with collect_errors:\n                        self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during request teardown\")\n\n    def do_teardown_appcontext(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \n        collect_errors = _CollectErrors()\n\n        for func in reversed(self.teardown_appcontext_funcs):\n            with collect_errors:\n                self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during app teardown\")\n\n    def app_context(self) -> AppContext:\n        \n        return AppContext(self)\n\n    def request_context(self, environ: WSGIEnvironment) -> AppContext:\n        \n        return AppContext.from_environ(self, environ)\n\n    def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext:\n        \n        from .testing import EnvironBuilder\n\n        builder = EnvironBuilder(self, *args, **kwargs)\n\n        try:\n            environ = builder.get_environ()\n        finally:\n            builder.close()\n\n        return self.request_context(environ)\n\n    def wsgi_app(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \n        ctx = self.request_context(environ)\n        error: BaseException | None = None\n        try:\n            try:\n                ctx.push()\n                response = self.full_dispatch_request(ctx)\n            except Exception as e:\n                error = e\n                response = self.handle_exception(ctx, e)\n            except:\n                error = sys.exc_info()[1]\n                raise\n            return response(environ, start_response)\n        finally:\n            if \"werkzeug.debug.preserve_context\" in environ:\n                environ[\"werkzeug.debug.preserve_context\"](ctx)\n\n            if (\n                error is not None\n                and self.should_ignore_error is not None\n                and self.should_ignore_error(error)\n            ):\n                error = None\n\n            ctx.pop(error)\n\n    def __call__(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \n        return self.wsgi_app(environ, start_response)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-8341cf85103c4a69", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "978920078c1f3c6fe17848c9e3dff56009f1b2db26f85a1fadc9c46e3ce4e131", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 914, "local_path": "comments/remove-comments/I01__flask__Flask__f2874e83.py", "order": 1, "original_content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "parent_variant_id": "pyint-14eacc325bde-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/app.py#L110-L1628", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 34925, "comments_removed": 141, "docstrings_removed": 34, "line_comments_removed": 107}, "unit_kind": "class", "unit_name": "Flask", "variant_id": "pyint-333af2874e83-I01", "group_id": "py-8341cf85103c4a69", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 632, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bfe2297cf678-I02", "source": "from __future__ import annotations\nimport collections.abc as cabc\nimport inspect\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom functools import update_wrapper\nfrom inspect import iscoroutinefunction\nfrom itertools import chain\nfrom types import TracebackType\nfrom urllib.parse import quote as _url_quote\nfrom urllib.parse import urlsplit\nimport click\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom werkzeug.wsgi import get_host\nfrom . import cli\nfrom . import typing as ft\nfrom .ctx import AppContext\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import _CollectErrors\nfrom .helpers import get_debug_flag\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import send_from_directory\nfrom .sansio.app import App\nfrom .sessions import SecureCookieSessionInterface\nfrom .sessions import SessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import Environment\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nclass Flask(App):\n    \"\"\"The flask object implements a WSGI application and acts as the central\n    object.  It is passed the name of the module or package of the\n    application.  Once it is created it will act as a central registry for\n    the view functions, the URL rules, template configuration and much more.\n\n    The name of the package is used to resolve resources from inside the\n    package or the folder the module is contained in depending on if the\n    package parameter resolves to an actual python package (a folder with\n    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n    For more information about resource loading, see :func:`open_resource`.\n\n    Usually you create a :class:`Flask` instance in your main module or\n    in the :file:`__init__.py` file of your package like this::\n\n        from flask import Flask\n        app = Flask(__name__)\n\n    .. admonition:: About the First Parameter\n\n        The idea of the first parameter is to give Flask an idea of what\n        belongs to your application.  This name is used to find resources\n        on the filesystem, can be used by extensions to improve debugging\n        information and a lot more.\n\n        So it's important what you provide there.  If you are using a single\n        module, `__name__` is always the correct value.  If you however are\n        using a package, it's usually recommended to hardcode the name of\n        your package there.\n\n        For example if your application is defined in :file:`yourapplication/app.py`\n        you should create it with one of the two versions below::\n\n            app = Flask('yourapplication')\n            app = Flask(__name__.split('.')[0])\n\n        Why is that?  The application will work even with `__name__`, thanks\n        to how resources are looked up.  However it will make debugging more\n        painful.  Certain extensions can make assumptions based on the\n        import name of your application.  For example the Flask-SQLAlchemy\n        extension will look for the code in your application that triggered\n        an SQL query in debug mode.  If the import name is not properly set\n        up, that debugging information is lost.  (For example it would only\n        pick up SQL queries in `yourapplication.app` and not\n        `yourapplication.views.frontend`)\n\n    .. versionadded:: 0.7\n       The `static_url_path`, `static_folder`, and `template_folder`\n       parameters were added.\n\n    .. versionadded:: 0.8\n       The `instance_path` and `instance_relative_config` parameters were\n       added.\n\n    .. versionadded:: 0.11\n       The `root_path` parameter was added.\n\n    .. versionadded:: 1.0\n       The ``host_matching`` and ``static_host`` parameters were added.\n\n    .. versionadded:: 1.0\n       The ``subdomain_matching`` parameter was added. Subdomain\n       matching needs to be enabled manually now. Setting\n       :data:`SERVER_NAME` does not implicitly enable it.\n\n    :param import_name: the name of the application package\n    :param static_url_path: can be used to specify a different path for the\n                            static files on the web.  Defaults to the name\n                            of the `static_folder` folder.\n    :param static_folder: The folder with static files that is served at\n        ``static_url_path``. Relative to the application ``root_path``\n        or an absolute path. Defaults to ``'static'``.\n    :param static_host: the host to use when adding the static route.\n        Defaults to None. Required when using ``host_matching=True``\n        with a ``static_folder`` configured.\n    :param host_matching: set ``url_map.host_matching`` attribute.\n        Defaults to False.\n    :param subdomain_matching: consider the subdomain relative to\n        :data:`SERVER_NAME` when matching routes. Defaults to False.\n    :param template_folder: the folder that contains the templates that should\n                            be used by the application.  Defaults to\n                            ``'templates'`` folder in the root path of the\n                            application.\n    :param instance_path: An alternative instance path for the application.\n                          By default the folder ``'instance'`` next to the\n                          package or module is assumed to be the instance\n                          path.\n    :param instance_relative_config: if set to ``True`` relative filenames\n                                     for loading the config are assumed to\n                                     be relative to the instance path instead\n                                     of the application root.\n    :param root_path: The path to the root of the application files.\n        This should only be set manually when it can't be detected\n        automatically, such as for namespace packages.\n    \"\"\"\n\n    default_config = ImmutableDict(\n        {\n            \"DEBUG\": None,\n            \"TESTING\": False,\n            \"PROPAGATE_EXCEPTIONS\": None,\n            \"SECRET_KEY\": None,\n            \"SECRET_KEY_FALLBACKS\": None,\n            \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n            \"USE_X_SENDFILE\": False,\n            \"TRUSTED_HOSTS\": None,\n            \"SERVER_NAME\": None,\n            \"APPLICATION_ROOT\": \"/\",\n            \"SESSION_COOKIE_NAME\": \"session\",\n            \"SESSION_COOKIE_DOMAIN\": None,\n            \"SESSION_COOKIE_PATH\": None,\n            \"SESSION_COOKIE_HTTPONLY\": True,\n            \"SESSION_COOKIE_SECURE\": False,\n            \"SESSION_COOKIE_PARTITIONED\": False,\n            \"SESSION_COOKIE_SAMESITE\": None,\n            \"SESSION_REFRESH_EACH_REQUEST\": True,\n            \"MAX_CONTENT_LENGTH\": None,\n            \"MAX_FORM_MEMORY_SIZE\": 500_000,\n            \"MAX_FORM_PARTS\": 1_000,\n            \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n            \"TRAP_BAD_REQUEST_ERRORS\": None,\n            \"TRAP_HTTP_EXCEPTIONS\": False,\n            \"EXPLAIN_TEMPLATE_LOADING\": False,\n            \"PREFERRED_URL_SCHEME\": \"http\",\n            \"TEMPLATES_AUTO_RELOAD\": None,\n            \"MAX_COOKIE_SIZE\": 4093,\n            \"PROVIDE_AUTOMATIC_OPTIONS\": True,\n        }\n    )\n\n    #: The class that is used for request objects.  See :class:`~flask.Request`\n    #: for more information.\n    request_class: type[Request] = Request\n\n    #: The class that is used for response objects.  See\n    #: :class:`~flask.Response` for more information.\n    response_class: type[Response] = Response\n\n    #: the session interface to use.  By default an instance of\n    #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n    #:\n    #: .. versionadded:: 0.8\n    session_interface: SessionInterface = SecureCookieSessionInterface()\n\n    def __init_subclass__(cls, **kwa: t.Any) -> None:\n        import warnings\n\n        # These method signatures were updated to take a ctx param. Detect\n        # overridden methods in subclasses that still have the old signature.\n        # Show a deprecation warning and wrap to call with correct args.\n        for met in (\n            cls.handle,\n            cls.handle2,\n            cls.handle3,\n            cls.log,\n            cls.dispatch,\n            cls.full,\n            cls.finalize,\n            cls.make2,\n            cls.preprocess,\n            cls.process,\n            cls.do,\n            cls.do2,\n        ):\n            base = getattr(Flask, met.__name__)\n\n            if met is base:\n                # not overridden\n                continue\n\n            # get the second parameter (first is self)\n            iter2 = iter(inspect.signature(met).parameters.values())\n            next(iter2)\n            par = next(iter2, None)\n\n            # must have second parameter named ctx or annotated AppContext\n            if par is None or not (\n                # no annotation, match name\n                (par.annotation is inspect.Parameter.empty and par.name == \"ctx\")\n                or (\n                    # string annotation, access path ends with AppContext\n                    isinstance(par.annotation, str)\n                    and par.annotation.rpartition(\".\")[2] == \"AppContext\"\n                )\n                or (\n                    # class annotation\n                    inspect.isclass(par.annotation)\n                    and issubclass(par.annotation, AppContext)\n                )\n            ):\n                warnings.warn(\n                    f\"The '{met.__name__}' method now takes 'ctx: AppContext'\"\n                    \" as the first parameter. The old signature is deprecated\"\n                    \" and will not be supported in Flask 4.0.\",\n                    DeprecationWarning,\n                    stacklevel=2,\n                )\n                setattr(cls, met.__name__, remove_ctx(met))\n                setattr(Flask, met.__name__, add_ctx(base))\n\n    def __init__(\n        self,\n        import2: str,\n        static: str | None = None,\n        static2: str | os.PathLike[str] | None = \"static\",\n        static3: str | None = None,\n        host2: bool = False,\n        subdomain2: bool = False,\n        template: str | os.PathLike[str] | None = \"templates\",\n        instance: str | None = None,\n        instance2: bool = False,\n        root: str | None = None,\n    ):\n        super().__init__(\n            import_name=import2,\n            static_url_path=static,\n            static_folder=static2,\n            static_host=static3,\n            host_matching=host2,\n            subdomain_matching=subdomain2,\n            template_folder=template,\n            instance_path=instance,\n            instance_relative_config=instance2,\n            root_path=root,\n        )\n\n        #: The Click command group for registering CLI commands for this\n        #: object. The commands are available from the ``flask`` command\n        #: once the application has been discovered and blueprints have\n        #: been registered.\n        self.cli = cli.AppGroup()\n\n        # Set the name of the Click group in case someone wants to add\n        # the app's commands to another CLI tool.\n        self.cli.name = self.name\n\n        # Add a static route using the provided static_url_path, static_host,\n        # and static_folder if there is a configured static_folder.\n        # Note we do this without checking if static_folder exists.\n        # For one, it might be created while the server is running (e.g. during\n        # development). Also, Google App Engine stores static files somewhere\n        if self.has_static_folder:\n            assert bool(static3) == host2, (\n                \"Invalid static_host/host_matching combination\"\n            )\n            # Use a weakref to avoid creating a reference cycle between the app\n            # and the view function (see #3761).\n            self2 = weakref.ref(self)\n            self.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                endpoint=\"static\",\n                host=static3,\n                view_func=lambda **kw: self2().send_static_file(**kw),  # type: ignore\n            )\n\n    def get2(self, fil: str | None) -> int | None:\n        \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n        value for a given file path if it wasn't passed.\n\n        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n        the configuration of :data:`~flask.current_app`. This defaults\n        to ``None``, which tells the browser to use conditional requests\n        instead of a timed cache, which is usually preferable.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionchanged:: 2.0\n            The default configuration is ``None`` instead of 12 hours.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        val = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n        if val is None:\n            return None\n\n        if isinstance(val, timedelta):\n            return int(val.total_seconds())\n\n        return val  # type: ignore[no-any-return]\n\n    def send2(self, fil2: str) -> Response:\n        \"\"\"The view function used to serve files from\n        :attr:`static_folder`. A route is automatically registered for\n        this view at :attr:`static_url_path` if :attr:`static_folder` is\n        set.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionadded:: 0.5\n\n        \"\"\"\n        if not self.has_static_folder:\n            raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n        # send_file only knows to call get_send_file_max_age on the app,\n        # call it here so it works for blueprints too.\n        max = self.get2(fil2)\n        return send_from_directory(\n            t.cast(str, self.static_folder), fil2, max_age=max\n        )\n\n    def open2(\n        self, res: str, mod: str = \"rb\", enc: str | None = None\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to :attr:`root_path` for reading.\n\n        For example, if the file ``schema.sql`` is next to the file\n        ``app.py`` where the ``Flask`` app is defined, it can be opened\n        with:\n\n        .. code-block:: python\n\n            with app.open_resource(\"schema.sql\") as f:\n                conn.executescript(f.read())\n\n        :param resource: Path to the resource relative to :attr:`root_path`.\n        :param mode: Open the file in this mode. Only reading is supported,\n            valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        if mod not in {\"r\", \"rt\", \"rb\"}:\n            raise ValueError(\"Resources can only be opened for reading.\")\n\n        pat = os.path.join(self.root_path, res)\n\n        if mod == \"rb\":\n            return open(pat, mod)  # pyright: ignore\n\n        return open(pat, mod, encoding=enc)\n\n    def open3(\n        self, res2: str, mod2: str = \"rb\", enc2: str | None = \"utf-8\"\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to the application's instance folder\n        :attr:`instance_path`. Unlike :meth:`open_resource`, files in the\n        instance folder can be opened for writing.\n\n        :param resource: Path to the resource relative to :attr:`instance_path`.\n        :param mode: Open the file in this mode.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        pat2 = os.path.join(self.instance_path, res2)\n\n        if \"b\" in mod2:\n            return open(pat2, mod2)\n\n        return open(pat2, mod2, encoding=enc2)\n\n    def create(self) -> Environment:\n        \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n        and the various Jinja-related methods of the app. Changing\n        :attr:`jinja_options` after this will have no effect. Also adds\n        Flask-related globals and filters to the environment.\n\n        .. versionchanged:: 0.11\n           ``Environment.auto_reload`` set in accordance with\n           ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        opt = dict(self.jinja_options)\n\n        if \"autoescape\" not in opt:\n            opt[\"autoescape\"] = self.select_jinja_autoescape\n\n        if \"auto_reload\" not in opt:\n            auto = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n            if auto is None:\n                auto = self.debug\n\n            opt[\"auto_reload\"] = auto\n\n        rv2 = self.jinja_environment(self, **opt)\n        rv2.globals.update(\n            url_for=self.url,\n            get_flashed_messages=get_flashed_messages,\n            config=self.config,\n            # request, session and g are normally added with the\n            # context processor for efficiency reasons but for imported\n            # templates we also want the proxies in there.\n            request=request,\n            session=session,\n            g=g,\n        )\n        rv2.policies[\"json.dumps_function\"] = self.json.dumps\n        return rv2\n\n    def create2(self, req2: Request | None) -> MapAdapter | None:\n        \"\"\"Creates a URL adapter for the given request. The URL adapter\n        is created at a point where the request context is not yet set\n        up so the request is passed explicitly.\n\n        .. versionchanged:: 3.1\n            If :data:`SERVER_NAME` is set, it does not restrict requests to\n            only that domain, for both ``subdomain_matching`` and\n            ``host_matching``.\n\n        .. versionchanged:: 1.0\n            :data:`SERVER_NAME` no longer implicitly enables subdomain\n            matching. Use :attr:`subdomain_matching` instead.\n\n        .. versionchanged:: 0.9\n           This can be called outside a request when the URL adapter is created\n           for an application context.\n\n        .. versionadded:: 0.6\n        \"\"\"\n        if req2 is not None:\n            if (trusted := self.config[\"TRUSTED_HOSTS\"]) is not None:\n                req2.trusted_hosts = trusted\n\n            # Check trusted_hosts here until bind_to_environ does.\n            req2.host = get_host(req2.environ, req2.trusted_hosts)  # pyright: ignore\n            sub = None\n            server = self.config[\"SERVER_NAME\"]\n\n            if self.url_map.host_matching:\n                # Don't pass SERVER_NAME, otherwise it's used and the actual\n                # host is ignored, which breaks host matching.\n                server = None\n            elif not self.subdomain_matching:\n                # Werkzeug doesn't implement subdomain matching yet. Until then,\n                # disable it by forcing the current subdomain to the default, or\n                # the empty string.\n                sub = self.url_map.default_subdomain or \"\"\n\n            return self.url_map.bind_to_environ(\n                req2.environ, server_name=server, subdomain=sub\n            )\n\n        # Need at least SERVER_NAME to match/build outside a request.\n        if self.config[\"SERVER_NAME\"] is not None:\n            return self.url_map.bind(\n                self.config[\"SERVER_NAME\"],\n                script_name=self.config[\"APPLICATION_ROOT\"],\n                url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n            )\n\n        return None\n\n    def raise2(self, req3: Request) -> t.NoReturn:\n        \"\"\"Intercept routing exceptions and possibly do something else.\n\n        In debug mode, intercept a routing redirect and replace it with\n        an error if the body will be discarded.\n\n        With modern Werkzeug this shouldn't occur, since it now uses a\n        308 status which tells the browser to resend the method and\n        body.\n\n        .. versionchanged:: 2.1\n            Don't intercept 307 and 308 redirects.\n\n        :meta private:\n        :internal:\n        \"\"\"\n        if (\n            not self.debug\n            or not isinstance(req3.routing_exception, RequestRedirect)\n            or req3.routing_exception.code in {307, 308}\n            or req3.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n        ):\n            raise req3.routing_exception  # type: ignore[misc]\n\n        from .debughelpers import FormDataRoutingRedirect\n\n        raise FormDataRoutingRedirect(req3)\n\n    def update2(\n        self, ctx2: AppContext, con: dict[str, t.Any]\n    ) -> None:\n        \"\"\"Update the template context with some commonly used variables.\n        This injects request, session, config and g into the template\n        context as well as everything template context processors want\n        to inject.  Note that the as of Flask 0.6, the original values\n        in the context will not be overridden if a context processor\n        decides to return a value with the same key.\n\n        :param context: the context as a dictionary that is updated in place\n                        to add extra variables.\n        \"\"\"\n        nam: t.Iterable[str | None] = (None,)\n\n        # A template may be rendered outside a request context.\n        if ctx2.has_request:\n            nam = chain(nam, reversed(ctx2.request.blueprints))\n\n        # The values passed to render_template take precedence. Keep a\n        # copy to re-apply after all context functions.\n        orig = con.copy()\n\n        for nam2 in nam:\n            if nam2 in self.template_context_processors:\n                for fun in self.template_context_processors[nam2]:\n                    con.update(self.ensure(fun)())\n\n        con.update(orig)\n\n    def make(self) -> dict[str, t.Any]:\n        \"\"\"Returns the shell context for an interactive shell for this\n        application.  This runs all the registered shell context\n        processors.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv3 = {\"app\": self, \"g\": g}\n        for pro in self.shell_context_processors:\n            rv3.update(pro())\n        return rv3\n\n    def run(\n        self,\n        hos: str | None = None,\n        por: int | None = None,\n        deb: bool | None = None,\n        load: bool = True,\n        **opt2: t.Any,\n    ) -> None:\n        \"\"\"Runs the application on a local development server.\n\n        Do not use ``run()`` in a production setting. It is not intended to\n        meet security and performance requirements for a production server.\n        Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n        If the :attr:`debug` flag is set the server will automatically reload\n        for code changes and show a debugger in case an exception happened.\n\n        If you want to run the application in debug mode, but disable the\n        code execution on the interactive debugger, you can pass\n        ``use_evalex=False`` as parameter.  This will keep the debugger's\n        traceback screen active, but disable code execution.\n\n        It is not recommended to use this function for development with\n        automatic reloading as this is badly supported.  Instead you should\n        be using the :command:`flask` command line script's ``run`` support.\n\n        .. admonition:: Keep in Mind\n\n           Flask will suppress any server error with a generic error page\n           unless it is in debug mode.  As such to enable just the\n           interactive debugger without the code reloading, you have to\n           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n           Setting ``use_debugger`` to ``True`` without being in debug mode\n           won't catch any exceptions because there won't be any to\n           catch.\n\n        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n            have the server available externally as well. Defaults to\n            ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n            if present.\n        :param port: the port of the webserver. Defaults to ``5000`` or the\n            port defined in the ``SERVER_NAME`` config variable if present.\n        :param debug: if given, enable or disable debug mode. See\n            :attr:`debug`.\n        :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n            files to set environment variables. Will also change the working\n            directory to the directory containing the first file found.\n        :param options: the options to be forwarded to the underlying Werkzeug\n            server. See :func:`werkzeug.serving.run_simple` for more\n            information.\n\n        .. versionchanged:: 1.0\n            If installed, python-dotenv will be used to load environment\n            variables from :file:`.env` and :file:`.flaskenv` files.\n\n            The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.\n\n            Threaded mode is enabled by default.\n\n        .. versionchanged:: 0.10\n            The default port is now picked from the ``SERVER_NAME``\n            variable.\n        \"\"\"\n        # Ignore this call so that it doesn't start another server if\n        # the 'flask run' command is used.\n        if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n            if not is_running_from_reloader():\n                click.secho(\n                    \" * Ignoring a call to 'app.run()' that would block\"\n                    \" the current 'flask' CLI command.\\n\"\n                    \"   Only call 'app.run()' in an 'if __name__ ==\"\n                    ' \"__main__\"\\' guard.',\n                    fg=\"red\",\n                )\n\n            return\n\n        if get_load_dotenv(load):\n            cli.load_dotenv()\n\n            # if set, env var overrides existing value\n            if \"FLASK_DEBUG\" in os.environ:\n                self.debug = get_debug_flag()\n\n        # debug passed to method overrides all other sources\n        if deb is not None:\n            self.debug = bool(deb)\n\n        server2 = self.config.get(\"SERVER_NAME\")\n        sn = sn2 = None\n\n        if server2:\n            server3 = urlsplit(f\"//{server2}\")\n            sn = server3.hostname\n            sn2 = server3.port\n\n        if not hos:\n            if sn:\n                hos = sn\n            else:\n                hos = \"127.0.0.1\"\n\n        if por or por == 0:\n            por = int(por)\n        elif sn2 is not None:\n            por = sn2\n        else:\n            por = 5000\n\n        opt2.setdefault(\"use_reloader\", self.debug)\n        opt2.setdefault(\"use_debugger\", self.debug)\n        opt2.setdefault(\"threaded\", True)\n\n        cli.show_server_banner(self.debug, self.name)\n\n        from werkzeug.serving import run_simple\n\n        try:\n            run_simple(hos, por, self, **opt2)\n        finally:\n            # reset the first request information if the development server\n            # reset normally.  This makes it possible to restart the server\n            # without reloader and that stuff from an interactive shell.\n            self._got_first_request = False\n\n    def test(self, use: bool = True, **kwa2: t.Any) -> FlaskClient:\n        \"\"\"Creates a test client for this application.  For information\n        about unit testing head over to :doc:`/testing`.\n\n        Note that if you are testing for assertions or exceptions in your\n        application code, you must set ``app.testing = True`` in order for the\n        exceptions to propagate to the test client.  Otherwise, the exception\n        will be handled by the application (not visible to the test client) and\n        the only indication of an AssertionError or other exception will be a\n        500 status code response to the test client.  See the :attr:`testing`\n        attribute.  For example::\n\n            app.testing = True\n            client = app.test_client()\n\n        The test client can be used in a ``with`` block to defer the closing down\n        of the context until the end of the ``with`` block.  This is useful if\n        you want to access the context locals for testing::\n\n            with app.test_client() as c:\n                rv = c.get('/?vodka=42')\n                assert request.args['vodka'] == '42'\n\n        Additionally, you may pass optional keyword arguments that will then\n        be passed to the application's :attr:`test_client_class` constructor.\n        For example::\n\n            from flask.testing import FlaskClient\n\n            class CustomClient(FlaskClient):\n                def __init__(self, *args, **kwargs):\n                    self._authentication = kwargs.pop(\"authentication\")\n                    super(CustomClient,self).__init__( *args, **kwargs)\n\n            app.test_client_class = CustomClient\n            client = app.test_client(authentication='Basic ....')\n\n        See :class:`~flask.testing.FlaskClient` for more information.\n\n        .. versionchanged:: 0.4\n           added support for ``with`` block usage for the client.\n\n        .. versionadded:: 0.7\n           The `use_cookies` parameter was added as well as the ability\n           to override the client to be used by setting the\n           :attr:`test_client_class` attribute.\n\n        .. versionchanged:: 0.11\n           Added `**kwargs` to support passing additional keyword arguments to\n           the constructor of :attr:`test_client_class`.\n        \"\"\"\n        cls2 = self.test_client_class\n        if cls2 is None:\n            from .testing import FlaskClient as cls\n        return cls2(  # type: ignore\n            self, self.response_class, use_cookies=use, **kwa2\n        )\n\n    def test2(self, **kwa3: t.Any) -> FlaskCliRunner:\n        \"\"\"Create a CLI runner for testing CLI commands.\n        See :ref:`testing-cli`.\n\n        Returns an instance of :attr:`test_cli_runner_class`, by default\n        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n        passed as the first argument.\n\n        .. versionadded:: 1.0\n        \"\"\"\n        cls3 = self.test_cli_runner_class\n\n        if cls3 is None:\n            from .testing import FlaskCliRunner as cls\n\n        return cls3(self, **kwa3)  # type: ignore\n\n    def handle(\n        self, ctx3: AppContext, e2: HTTPException\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"Handles an HTTP exception.  By default this will invoke the\n        registered error handlers and fall back to returning the\n        exception as response.\n\n        .. versionchanged:: 1.0.3\n            ``RoutingException``, used internally for actions such as\n             slash redirects during routing, is not passed to error\n             handlers.\n\n        .. versionchanged:: 1.0\n            Exceptions are looked up by code *and* by MRO, so\n            ``HTTPException`` subclasses can be handled with a catch-all\n            handler for the base ``HTTPException``.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        # Proxy exceptions don't have error codes.  We want to always return\n        # those unchanged as errors\n        if e2.code is None:\n            return e2\n\n        # RoutingExceptions are used internally to trigger routing\n        # actions, such as slash redirects raising RequestRedirect. They\n        # are not raised or handled in user code.\n        if isinstance(e2, RoutingException):\n            return e2\n\n        han = self._find_error_handler(e2, ctx3.request.blueprints)\n        if han is None:\n            return e2\n        return self.ensure(han)(e2)  # type: ignore[no-any-return]\n\n    def handle2(\n        self, ctx4: AppContext, e3: Exception\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"This method is called whenever an exception occurs that\n        should be handled. A special case is :class:`~werkzeug\n        .exceptions.HTTPException` which is forwarded to the\n        :meth:`handle_http_exception` method. This function will either\n        return a response value or reraise the exception with the same\n        traceback.\n\n        .. versionchanged:: 1.0\n            Key errors raised from request data like ``form`` show the\n            bad key in debug mode rather than a generic bad request\n            message.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if isinstance(e3, BadRequestKeyError) and (\n            self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n        ):\n            e3.show_exception = True\n\n        if isinstance(e3, HTTPException) and not self.trap_http_exception(e3):\n            return self.handle(ctx4, e3)\n\n        han2 = self._find_error_handler(e3, ctx4.request.blueprints)\n\n        if han2 is None:\n            raise\n\n        return self.ensure(han2)(e3)  # type: ignore[no-any-return]\n\n    def handle3(self, ctx5: AppContext, e4: Exception) -> Response:\n        \"\"\"Handle an exception that did not have an error handler\n        associated with it, or that was raised from an error handler.\n        This always causes a 500 ``InternalServerError``.\n\n        Always sends the :data:`got_request_exception` signal.\n\n        If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n        mode, the error will be re-raised so that the debugger can\n        display it. Otherwise, the original exception is logged, and\n        an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n        If an error handler is registered for ``InternalServerError`` or\n        ``500``, it will be used. For consistency, the handler will\n        always receive the ``InternalServerError``. The original\n        unhandled exception is available as ``e.original_exception``.\n\n        .. versionchanged:: 1.1.0\n            Always passes the ``InternalServerError`` instance to the\n            handler, setting ``original_exception`` to the unhandled\n            error.\n\n        .. versionchanged:: 1.1.0\n            ``after_request`` functions and other finalization is done\n            even for the default 500 response when there is no handler.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        exc2 = sys.exc_info()\n        got_request_exception.send(self, _async_wrapper=self.ensure, exception=e4)\n        pro2 = self.config[\"PROPAGATE_EXCEPTIONS\"]\n\n        if pro2 is None:\n            pro2 = self.testing or self.debug\n\n        if pro2:\n            # Re-raise if called with an active exception, otherwise\n            # raise the passed in exception.\n            if exc2[1] is e4:\n                raise\n\n            raise e4\n\n        self.log(ctx5, exc2)\n        server4: InternalServerError | ft.ResponseReturnValue\n        server4 = InternalServerError(original_exception=e4)\n        han3 = self._find_error_handler(server4, ctx5.request.blueprints)\n\n        if han3 is not None:\n            server4 = self.ensure(han3)(server4)\n\n        return self.finalize(ctx5, server4, from_error_handler=True)\n\n    def log(\n        self,\n        ctx6: AppContext,\n        exc3: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n    ) -> None:\n        \"\"\"Logs an exception.  This is called by :meth:`handle_exception`\n        if debugging is disabled and right before the handler is called.\n        The default implementation logs the exception as error on the\n        :attr:`logger`.\n\n        .. versionadded:: 0.8\n        \"\"\"\n        self.logger.error(\n            f\"Exception on {ctx6.request.path} [{ctx6.request.method}]\", exc_info=exc3\n        )\n\n    def dispatch(self, ctx7: AppContext) -> ft.ResponseReturnValue:\n        \"\"\"Does the request dispatching.  Matches the URL and returns the\n        return value of the view or error handler.  This does not have to\n        be a response object.  In order to convert the return value to a\n        proper response object, call :func:`make_response`.\n\n        .. versionchanged:: 0.7\n           This no longer does the exception handling, this code was\n           moved to the new :meth:`full_dispatch_request`.\n        \"\"\"\n        req4 = ctx7.request\n\n        if req4.routing_exception is not None:\n            self.raise2(req4)\n        rul: Rule = req4.url_rule  # type: ignore[assignment]\n        # if we provide automatic options for this URL and the\n        # request came with the OPTIONS method, reply automatically\n        if (\n            getattr(rul, \"provide_automatic_options\", False)\n            and req4.method == \"OPTIONS\"\n        ):\n            return self.make2(ctx7)\n        # otherwise dispatch to the handler for that endpoint\n        view: dict[str, t.Any] = req4.view_args  # type: ignore[assignment]\n        return self.ensure(self.view_functions[rul.endpoint])(**view)  # type: ignore[no-any-return]\n\n    def full(self, ctx8: AppContext) -> Response:\n        \"\"\"Dispatches the request and on top of that performs request\n        pre and postprocessing as well as HTTP exception catching and\n        error handling.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if not self._got_first_request and self.should_ignore_error is not None:\n            import warnings\n\n            warnings.warn(\n                \"The 'should_ignore_error' method is deprecated and will\"\n                \" be removed in Flask 3.3. Handle errors as needed in\"\n                \" teardown handlers instead.\",\n                DeprecationWarning,\n                stacklevel=1,\n            )\n\n        self._got_first_request = True\n\n        try:\n            request_started.send(self, _async_wrapper=self.ensure)\n            rv4 = self.preprocess(ctx8)\n            if rv4 is None:\n                rv4 = self.dispatch(ctx8)\n        except Exception as e:\n            rv4 = self.handle2(ctx8, e)\n        return self.finalize(ctx8, rv4)\n\n    def finalize(\n        self,\n        ctx9: AppContext,\n        rv5: ft.ResponseReturnValue | HTTPException,\n        from2: bool = False,\n    ) -> Response:\n        \"\"\"Given the return value from a view function this finalizes\n        the request by converting it into a response and invoking the\n        postprocessing functions.  This is invoked for both normal\n        request dispatching as well as error handlers.\n\n        Because this means that it might be called as a result of a\n        failure a special safe mode is available which can be enabled\n        with the `from_error_handler` flag.  If enabled, failures in\n        response processing will be logged and otherwise ignored.\n\n        :internal:\n        \"\"\"\n        res3 = self.make3(rv5)\n        try:\n            res3 = self.process(ctx9, res3)\n            request_finished.send(\n                self, _async_wrapper=self.ensure, response=res3\n            )\n        except Exception:\n            if not from2:\n                raise\n            self.logger.exception(\n                \"Request finalizing failed with an error while handling an error\"\n            )\n        return res3\n\n    def make2(self, ctx10: AppContext) -> Response:\n        \"\"\"This method is called to create the default ``OPTIONS`` response.\n        This can be changed through subclassing to change the default\n        behavior of ``OPTIONS`` responses.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        met2 = ctx10.url_adapter.allowed_methods()  # type: ignore[union-attr]\n        rv6 = self.response_class()\n        rv6.allow.update(met2)\n        return rv6\n\n    def ensure(self, fun2: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n        \"\"\"Ensure that the function is synchronous for WSGI workers.\n        Plain ``def`` functions are returned as-is. ``async def``\n        functions are wrapped to run and wait for the response.\n\n        Override this method to change how the app runs async views.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if iscoroutinefunction(fun2):\n            return self.async2(fun2)\n\n        return fun2\n\n    def async2(\n        self, fun3: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n    ) -> t.Callable[..., t.Any]:\n        \"\"\"Return a sync function that will run the coroutine function.\n\n        .. code-block:: python\n\n            result = app.async_to_sync(func)(*args, **kwargs)\n\n        Override this method to change how the app converts async code\n        to be synchronously callable.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        try:\n            from asgiref.sync import async_to_sync as asgiref_async_to_sync\n        except ImportError:\n            raise RuntimeError(\n                \"Install Flask with the 'async' extra in order to use async views.\"\n            ) from None\n\n        return asgiref_async_to_sync(fun3)\n\n    def url(\n        self,\n        /,\n        end: str,\n        *,\n        anc: str | None = None,\n        met3: str | None = None,\n        sch: str | None = None,\n        ext: bool | None = None,\n        **val2: t.Any,\n    ) -> str:\n        \"\"\"Generate a URL to the given endpoint with the given values.\n\n        This is called by :func:`flask.url_for`, and can be called\n        directly as well.\n\n        An *endpoint* is the name of a URL rule, usually added with\n        :meth:`@app.route() <route>`, and usually the same name as the\n        view function. A route defined in a :class:`~flask.Blueprint`\n        will prepend the blueprint's name separated by a ``.`` to the\n        endpoint.\n\n        In some cases, such as email messages, you want URLs to include\n        the scheme and domain, like ``https://example.com/hello``. When\n        not in an active request, URLs will be external by default, but\n        this requires setting :data:`SERVER_NAME` so Flask knows what\n        domain to use. :data:`APPLICATION_ROOT` and\n        :data:`PREFERRED_URL_SCHEME` should also be configured as\n        needed. This config is only used when not in an active request.\n\n        Functions can be decorated with :meth:`url_defaults` to modify\n        keyword arguments before the URL is built.\n\n        If building fails for some reason, such as an unknown endpoint\n        or incorrect values, the app's :meth:`handle_url_build_error`\n        method is called. If that returns a string, that is returned,\n        otherwise a :exc:`~werkzeug.routing.BuildError` is raised.\n\n        :param endpoint: The endpoint name associated with the URL to\n            generate. If this starts with a ``.``, the current blueprint\n            name (if any) will be used.\n        :param _anchor: If given, append this as ``#anchor`` to the URL.\n        :param _method: If given, generate the URL associated with this\n            method for the endpoint.\n        :param _scheme: If given, the URL will have this scheme if it\n            is external.\n        :param _external: If given, prefer the URL to be internal\n            (False) or require it to be external (True). External URLs\n            include the scheme and domain. When not in an active\n            request, URLs are external by default.\n        :param values: Values to use for the variable parts of the URL\n            rule. Unknown keys are appended as query string arguments,\n            like ``?a=b&c=d``.\n\n        .. versionadded:: 2.2\n            Moved from ``flask.url_for``, which calls this method.\n        \"\"\"\n        if (ctx11 := _cv_app.get(None)) is not None and ctx11.has_request:\n            url2 = ctx11.url_adapter\n            blueprint2 = ctx11.request.blueprint\n\n            # If the endpoint starts with \".\" and the request matches a\n            # blueprint, the endpoint is relative to the blueprint.\n            if end[:1] == \".\":\n                if blueprint2 is not None:\n                    end = f\"{blueprint2}{end}\"\n                else:\n                    end = end[1:]\n\n            # When in a request, generate a URL without scheme and\n            # domain by default, unless a scheme is given.\n            if ext is None:\n                ext = sch is not None\n        else:\n            # If called by helpers.url_for, an app context is active,\n            # use its url_adapter. Otherwise, app.url_for was called\n            # directly, build an adapter.\n            if ctx11 is not None:\n                url2 = ctx11.url_adapter\n            else:\n                url2 = self.create2(None)\n\n            if url2 is None:\n                raise RuntimeError(\n                    \"Unable to build URLs outside an active request\"\n                    \" without 'SERVER_NAME' configured. Also configure\"\n                    \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n                    \" needed.\"\n                )\n\n            # When outside a request, generate a URL with scheme and\n            # domain by default.\n            if ext is None:\n                ext = True\n\n        # It is an error to set _scheme when _external=False, in order\n        # to avoid accidental insecure URLs.\n        if sch is not None and not ext:\n            raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n        self.inject_url_defaults(end, val2)\n\n        try:\n            rv7 = url2.build(  # type: ignore[union-attr]\n                end,\n                val2,\n                method=met3,\n                url_scheme=sch,\n                force_external=ext,\n            )\n        except BuildError as error:\n            val2.update(\n                _anchor=anc, _method=met3, _scheme=sch, _external=ext\n            )\n            return self.handle_url_build_error(error, end, val2)\n\n        if anc is not None:\n            anc = _url_quote(anc, safe=\"%!#$&'()*+,/:;=?@\")\n            rv7 = f\"{rv7}#{anc}\"\n\n        return rv7\n\n    def make3(self, rv8: ft.ResponseReturnValue) -> Response:\n        \"\"\"Convert the return value from a view function to an instance of\n        :attr:`response_class`.\n\n        :param rv: the return value from the view function. The view function\n            must return a response. Returning ``None``, or the view ending\n            without returning, is not allowed. The following types are allowed\n            for ``view_rv``:\n\n            ``str``\n                A response object is created with the string encoded to UTF-8\n                as the body.\n\n            ``bytes``\n                A response object is created with the bytes as the body.\n\n            ``dict``\n                Converted to a JSON response.\n\n            ``list``\n                Converted to a JSON response.\n\n            ``generator`` or ``iterator``\n                A generator that returns ``str`` or ``bytes`` to be\n                streamed as the response.\n\n            ``tuple``\n                Either ``(body, status, headers)``, ``(body, status)``, or\n                ``(body, headers)``, where ``body`` is any of the other types\n                allowed here, ``status`` is a string or an integer, and\n                ``headers`` is a dictionary or a list of ``(key, value)``\n                tuples. If ``body`` is a :attr:`response_class` instance,\n                ``status`` overwrites the exiting value and ``headers`` are\n                extended.\n\n            :attr:`response_class`\n                The object is returned unchanged.\n\n            other :class:`~werkzeug.wrappers.Response` class\n                The object is coerced to :attr:`response_class`.\n\n            :func:`callable`\n                The function is called as a WSGI application. The result is\n                used to create a response object.\n\n        .. versionchanged:: 2.2\n            A generator will be converted to a streaming response.\n            A list will be converted to a JSON response.\n\n        .. versionchanged:: 1.1\n            A dict will be converted to a JSON response.\n\n        .. versionchanged:: 0.9\n           Previously a tuple was interpreted as the arguments for the\n           response object.\n        \"\"\"\n\n        sta: int | None = None\n        hea: HeadersValue | None = None\n\n        # unpack tuple returns\n        if isinstance(rv8, tuple):\n            len2 = len(rv8)\n\n            # a 3-tuple is unpacked directly\n            if len2 == 3:\n                rv8, sta, hea = rv8  # type: ignore[misc]\n            # decide if a 2-tuple has status or headers\n            elif len2 == 2:\n                if isinstance(rv8[1], (Headers, dict, tuple, list)):\n                    rv8, hea = rv8  # pyright: ignore\n                else:\n                    rv8, sta = rv8  # type: ignore[assignment,misc]\n            # other sized tuples are not allowed\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid response tuple.\"\n                    \" The tuple must have the form (body, status, headers),\"\n                    \" (body, status), or (body, headers).\"\n                )\n\n        # the body must not be None\n        if rv8 is None:\n            raise TypeError(\n                f\"The view function for {request.endpoint!r} did not\"\n                \" return a valid response. The function either returned\"\n                \" None or ended without a return statement.\"\n            )\n\n        # make sure the body is an instance of the response class\n        if not isinstance(rv8, self.response_class):\n            if isinstance(rv8, (str, bytes, bytearray)) or isinstance(rv8, cabc.Iterator):\n                # let the response class set the status and headers instead of\n                # waiting to do it manually, so that the class can handle any\n                # special logic\n                rv8 = self.response_class(\n                    rv8,  # pyright: ignore\n                    status=sta,\n                    headers=hea,  # type: ignore[arg-type]\n                )\n                sta = hea = None\n            elif isinstance(rv8, (dict, list)):\n                rv8 = self.json.response(rv8)\n            elif isinstance(rv8, BaseResponse) or callable(rv8):\n                # evaluate a WSGI callable, or coerce a different response\n                # class to the correct type\n                try:\n                    rv8 = self.response_class.force_type(\n                        rv8,  # type: ignore[arg-type]\n                        request.environ,\n                    )\n                except TypeError as e:\n                    raise TypeError(\n                        f\"{e}\\nThe view function did not return a valid\"\n                        \" response. The return type must be a string,\"\n                        \" dict, list, tuple with headers or status,\"\n                        \" Response instance, or WSGI callable, but it\"\n                        f\" was a {type(rv8).__name__}.\"\n                    ).with_traceback(sys.exc_info()[2]) from None\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid\"\n                    \" response. The return type must be a string,\"\n                    \" dict, list, tuple with headers or status,\"\n                    \" Response instance, or WSGI callable, but it was a\"\n                    f\" {type(rv8).__name__}.\"\n                )\n\n        rv8 = t.cast(Response, rv8)\n        # prefer the status if it was provided\n        if sta is not None:\n            if isinstance(sta, (str, bytes, bytearray)):\n                rv8.status = sta\n            else:\n                rv8.status_code = sta\n\n        # extend existing headers with provided headers\n        if hea:\n            rv8.headers.update(hea)\n\n        return rv8\n\n    def preprocess(self, ctx12: AppContext) -> ft.ResponseReturnValue | None:\n        \"\"\"Called before the request is dispatched. Calls\n        :attr:`url_value_preprocessors` registered with the app and the\n        current blueprint (if any). Then calls :attr:`before_request_funcs`\n        registered with the app and the blueprint.\n\n        If any :meth:`before_request` handler returns a non-None value, the\n        value is handled as if it was the return value from the view, and\n        further request handling is stopped.\n        \"\"\"\n        req5 = ctx12.request\n        nam3 = (None, *reversed(req5.blueprints))\n\n        for nam4 in nam3:\n            if nam4 in self.url_value_preprocessors:\n                for url3 in self.url_value_preprocessors[nam4]:\n                    url3(req5.endpoint, req5.view_args)\n\n        for nam4 in nam3:\n            if nam4 in self.before_request_funcs:\n                for before in self.before_request_funcs[nam4]:\n                    rv9 = self.ensure(before)()\n\n                    if rv9 is not None:\n                        return rv9  # type: ignore[no-any-return]\n\n        return None\n\n    def process(self, ctx13: AppContext, res4: Response) -> Response:\n        \"\"\"Can be overridden in order to modify the response object\n        before it's sent to the WSGI server.  By default this will\n        call all the :meth:`after_request` decorated functions.\n\n        .. versionchanged:: 0.5\n           As of Flask 0.5 the functions registered for after request\n           execution are called in reverse order of registration.\n\n        :param response: a :attr:`response_class` object.\n        :return: a new response object or the same, has to be an\n                 instance of :attr:`response_class`.\n        \"\"\"\n        for fun4 in ctx13._after_request_functions:\n            res4 = self.ensure(fun4)(res4)\n\n        for nam5 in chain(ctx13.request.blueprints, (None,)):\n            if nam5 in self.after_request_funcs:\n                for fun4 in reversed(self.after_request_funcs[nam5]):\n                    res4 = self.ensure(fun4)(res4)\n\n        if not self.session_interface.is_null_session(ctx13._get_session()):\n            self.session_interface.save_session(self, ctx13._get_session(), res4)\n\n        return res4\n\n    def do(\n        self, ctx14: AppContext, exc4: BaseException | None = None\n    ) -> None:\n        \"\"\"Called after the request is dispatched and the response is finalized,\n        right before the request context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_request`, and\n        :meth:`Blueprint.teardown_request` if a blueprint handled the request.\n        Finally, the :data:`request_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while dispatching the request.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionchanged:: 0.9\n            Added the ``exc`` argument.\n        \"\"\"\n        collect = _CollectErrors()\n\n        for nam6 in chain(ctx14.request.blueprints, (None,)):\n            if nam6 in self.teardown_request_funcs:\n                for fun5 in reversed(self.teardown_request_funcs[nam6]):\n                    with collect:\n                        self.ensure(fun5)(exc4)\n\n        with collect:\n            request_tearing_down.send(self, _async_wrapper=self.ensure, exc=exc4)\n\n        collect.raise_any(\"Errors during request teardown\")\n\n    def do2(\n        self, ctx15: AppContext, exc5: BaseException | None = None\n    ) -> None:\n        \"\"\"Called right before the application context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_appcontext`.\n        Then the :data:`appcontext_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while the context was active.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        collect2 = _CollectErrors()\n\n        for fun6 in reversed(self.teardown_appcontext_funcs):\n            with collect2:\n                self.ensure(fun6)(exc5)\n\n        with collect2:\n            appcontext_tearing_down.send(self, _async_wrapper=self.ensure, exc=exc5)\n\n        collect2.raise_any(\"Errors during app teardown\")\n\n    def app(self) -> AppContext:\n        \"\"\"Create an :class:`.AppContext`. When the context is pushed,\n        :data:`.current_app` and :data:`.g` become available.\n\n        A context is automatically pushed when handling each request, and when\n        running any ``flask`` CLI command. Use this as a ``with`` block to\n        manually push a context outside of those situations, such as during\n        setup or testing.\n\n        .. code-block:: python\n\n            with app.app_context():\n                init_db()\n\n        See :doc:`/appcontext`.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        return AppContext(self)\n\n    def request2(self, env: WSGIEnvironment) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information representing\n        the given WSGI environment. A context is automatically pushed when\n        handling each request. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This method should not be used in your own code. Creating a valid WSGI\n        environ is not trivial. Use :meth:`test_request_context` to correctly\n        create a WSGI environ and request context instead.\n\n        See :doc:`/appcontext`.\n\n        :param environ: A WSGI environment.\n        \"\"\"\n        return AppContext.from_environ(self, env)\n\n    def test3(self, *arg: t.Any, **kwa4: t.Any) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information created from\n        the given arguments. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This is useful during testing to run a function that uses request data\n        without dispatching a full request. Use this as a ``with`` block to push\n        a context.\n\n        .. code-block:: python\n\n            with app.test_request_context(...):\n                generate_report()\n\n        See :doc:`/appcontext`.\n\n        Takes the same arguments as Werkzeug's\n        :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n        the application. See the linked Werkzeug docs for most of the\n        available arguments. Flask-specific behavior is listed here.\n\n        :param path: URL path being requested.\n        :param base_url: Base URL where the app is being served, which\n            ``path`` is relative to. If not given, built from\n            :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,\n            and :data:`APPLICATION_ROOT`.\n        :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.\n        :param url_scheme: Scheme to use instead of\n            :data:`PREFERRED_URL_SCHEME`.\n        :param data: The request body text or bytes,or a dict of form data.\n        :param json: If given, this is serialized as JSON and passed as\n            ``data``. Also defaults ``content_type`` to\n            ``application/json``.\n        :param args: Other positional arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        :param kwargs: Other keyword arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        \"\"\"\n        from .testing import EnvironBuilder\n\n        bui = EnvironBuilder(self, *arg, **kwa4)\n\n        try:\n            env2 = bui.get_environ()\n        finally:\n            bui.close()\n\n        return self.request2(env2)\n\n    def wsgi(\n        self, env3: WSGIEnvironment, start: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The actual WSGI application. This is not implemented in\n        :meth:`__call__` so that middlewares can be applied without\n        losing a reference to the app object. Instead of doing this::\n\n            app = MyMiddleware(app)\n\n        It's a better idea to do this instead::\n\n            app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n        Then you still have the original application object around and\n        can continue to call methods on it.\n\n        .. versionchanged:: 0.7\n            Teardown events for the request and app contexts are called\n            even if an unhandled error occurs. Other events may not be\n            called depending on when an error occurs during dispatch.\n\n        :param environ: A WSGI environment.\n        :param start_response: A callable accepting a status code,\n            a list of headers, and an optional exception context to\n            start the response.\n        \"\"\"\n        ctx16 = self.request2(env3)\n        err: BaseException | None = None\n        try:\n            try:\n                ctx16.push()\n                res5 = self.full(ctx16)\n            except Exception as e:\n                err = e\n                res5 = self.handle3(ctx16, e)\n            except:\n                err = sys.exc_info()[1]\n                raise\n            return res5(env3, start)\n        finally:\n            if \"werkzeug.debug.preserve_context\" in env3:\n                env3[\"werkzeug.debug.preserve_context\"](ctx16)\n\n            if (\n                err is not None\n                and self.should_ignore_error is not None\n                and self.should_ignore_error(err)\n            ):\n                err = None\n\n            ctx16.pop(err)\n\n    def __call__(\n        self, env4: WSGIEnvironment, start2: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The WSGI server calls the Flask application object as the\n        WSGI application. This calls :meth:`wsgi_app`, which can be\n        wrapped to apply middleware.\n        \"\"\"\n        return self.wsgi(env4, start2)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-8341cf85103c4a69", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "1db4fb1e3d2080d304b3e596af0114ce83a03a94377fae49f306ab226fbc08b0", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 1572, "local_path": "identifiers/shorten-identifiers/I02__flask__Flask__297cf678.py", "order": 2, "original_content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "parent_variant_id": "pyint-14eacc325bde-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/app.py#L110-L1628", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 580, "identifiers_declared": 165}, "unit_kind": "class", "unit_name": "Flask", "variant_id": "pyint-bfe2297cf678-I02", "group_id": "py-8341cf85103c4a69", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 633, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6d5b27018db2-I03", "source": "from __future__ import annotations\nimport collections.abc as cabc\nimport inspect\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom functools import update_wrapper\nfrom inspect import iscoroutinefunction\nfrom itertools import chain\nfrom types import TracebackType\nfrom urllib.parse import quote as _url_quote\nfrom urllib.parse import urlsplit\nimport click\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom werkzeug.wsgi import get_host\nfrom . import cli\nfrom . import typing as ft\nfrom .ctx import AppContext\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import _CollectErrors\nfrom .helpers import get_debug_flag\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import send_from_directory\nfrom .sansio.app import App\nfrom .sessions import SecureCookieSessionInterface\nfrom .sessions import SessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import Environment\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nclass Flask(App):\n    \"\"\"The flask object implements a WSGI application and acts as the central\n    object.  It is passed the name of the module or package of the\n    application.  Once it is created it will act as a central registry for\n    the view functions, the URL rules, template configuration and much more.\n\n    The name of the package is used to resolve resources from inside the\n    package or the folder the module is contained in depending on if the\n    package parameter resolves to an actual python package (a folder with\n    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n    For more information about resource loading, see :func:`open_resource`.\n\n    Usually you create a :class:`Flask` instance in your main module or\n    in the :file:`__init__.py` file of your package like this::\n\n        from flask import Flask\n        app = Flask(__name__)\n\n    .. admonition:: About the First Parameter\n\n        The idea of the first parameter is to give Flask an idea of what\n        belongs to your application.  This name is used to find resources\n        on the filesystem, can be used by extensions to improve debugging\n        information and a lot more.\n\n        So it's important what you provide there.  If you are using a single\n        module, `__name__` is always the correct value.  If you however are\n        using a package, it's usually recommended to hardcode the name of\n        your package there.\n\n        For example if your application is defined in :file:`yourapplication/app.py`\n        you should create it with one of the two versions below::\n\n            app = Flask('yourapplication')\n            app = Flask(__name__.split('.')[0])\n\n        Why is that?  The application will work even with `__name__`, thanks\n        to how resources are looked up.  However it will make debugging more\n        painful.  Certain extensions can make assumptions based on the\n        import name of your application.  For example the Flask-SQLAlchemy\n        extension will look for the code in your application that triggered\n        an SQL query in debug mode.  If the import name is not properly set\n        up, that debugging information is lost.  (For example it would only\n        pick up SQL queries in `yourapplication.app` and not\n        `yourapplication.views.frontend`)\n\n    .. versionadded:: 0.7\n       The `static_url_path`, `static_folder`, and `template_folder`\n       parameters were added.\n\n    .. versionadded:: 0.8\n       The `instance_path` and `instance_relative_config` parameters were\n       added.\n\n    .. versionadded:: 0.11\n       The `root_path` parameter was added.\n\n    .. versionadded:: 1.0\n       The ``host_matching`` and ``static_host`` parameters were added.\n\n    .. versionadded:: 1.0\n       The ``subdomain_matching`` parameter was added. Subdomain\n       matching needs to be enabled manually now. Setting\n       :data:`SERVER_NAME` does not implicitly enable it.\n\n    :param import_name: the name of the application package\n    :param static_url_path: can be used to specify a different path for the\n                            static files on the web.  Defaults to the name\n                            of the `static_folder` folder.\n    :param static_folder: The folder with static files that is served at\n        ``static_url_path``. Relative to the application ``root_path``\n        or an absolute path. Defaults to ``'static'``.\n    :param static_host: the host to use when adding the static route.\n        Defaults to None. Required when using ``host_matching=True``\n        with a ``static_folder`` configured.\n    :param host_matching: set ``url_map.host_matching`` attribute.\n        Defaults to False.\n    :param subdomain_matching: consider the subdomain relative to\n        :data:`SERVER_NAME` when matching routes. Defaults to False.\n    :param template_folder: the folder that contains the templates that should\n                            be used by the application.  Defaults to\n                            ``'templates'`` folder in the root path of the\n                            application.\n    :param instance_path: An alternative instance path for the application.\n                          By default the folder ``'instance'`` next to the\n                          package or module is assumed to be the instance\n                          path.\n    :param instance_relative_config: if set to ``True`` relative filenames\n                                     for loading the config are assumed to\n                                     be relative to the instance path instead\n                                     of the application root.\n    :param root_path: The path to the root of the application files.\n        This should only be set manually when it can't be detected\n        automatically, such as for namespace packages.\n    \"\"\"\n\n    default_config = ImmutableDict(\n        {\n            \"DEBUG\": None,\n            \"TESTING\": False,\n            \"PROPAGATE_EXCEPTIONS\": None,\n            \"SECRET_KEY\": None,\n            \"SECRET_KEY_FALLBACKS\": None,\n            \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n            \"USE_X_SENDFILE\": False,\n            \"TRUSTED_HOSTS\": None,\n            \"SERVER_NAME\": None,\n            \"APPLICATION_ROOT\": \"/\",\n            \"SESSION_COOKIE_NAME\": \"session\",\n            \"SESSION_COOKIE_DOMAIN\": None,\n            \"SESSION_COOKIE_PATH\": None,\n            \"SESSION_COOKIE_HTTPONLY\": True,\n            \"SESSION_COOKIE_SECURE\": False,\n            \"SESSION_COOKIE_PARTITIONED\": False,\n            \"SESSION_COOKIE_SAMESITE\": None,\n            \"SESSION_REFRESH_EACH_REQUEST\": True,\n            \"MAX_CONTENT_LENGTH\": None,\n            \"MAX_FORM_MEMORY_SIZE\": 500_000,\n            \"MAX_FORM_PARTS\": 1_000,\n            \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n            \"TRAP_BAD_REQUEST_ERRORS\": None,\n            \"TRAP_HTTP_EXCEPTIONS\": False,\n            \"EXPLAIN_TEMPLATE_LOADING\": False,\n            \"PREFERRED_URL_SCHEME\": \"http\",\n            \"TEMPLATES_AUTO_RELOAD\": None,\n            \"MAX_COOKIE_SIZE\": 4093,\n            \"PROVIDE_AUTOMATIC_OPTIONS\": True,\n        }\n    )\n\n    #: The class that is used for request objects.  See :class:`~flask.Request`\n    #: for more information.\n    request_class: type[Request] = Request\n\n    #: The class that is used for response objects.  See\n    #: :class:`~flask.Response` for more information.\n    response_class: type[Response] = Response\n\n    #: the session interface to use.  By default an instance of\n    #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n    #:\n    #: .. versionadded:: 0.8\n    session_interface: SessionInterface = SecureCookieSessionInterface()\n\n    def __init_subclass__(cls, **option: t.Any) -> None:\n        import warnings\n\n        # These method signatures were updated to take a ctx param. Detect\n        # overridden methods in subclasses that still have the old signature.\n        # Show a deprecation warning and wrap to call with correct args.\n        for status in (\n            cls.validateWindow,\n            cls.validateClient,\n            cls.refreshRequest,\n            cls.createMessage,\n            cls.validateStatus,\n            cls.refreshAddress,\n            cls.validateRecord,\n            cls.validateBuffer,\n            cls.validateConfig,\n            cls.refreshSession,\n            cls.refreshBalance,\n            cls.refreshResult,\n        ):\n            defaultMode = getattr(Flask, status.__name__)\n\n            if status is defaultMode:\n                # not overridden\n                continue\n\n            # get the second parameter (first is self)\n            remoteScore = iter(inspect.signature(status).parameters.values())\n            next(remoteScore)\n            cache = next(remoteScore, None)\n\n            # must have second parameter named ctx or annotated AppContext\n            if cache is None or not (\n                # no annotation, match name\n                (cache.annotation is inspect.Parameter.empty and cache.name == \"ctx\")\n                or (\n                    # string annotation, access path ends with AppContext\n                    isinstance(cache.annotation, str)\n                    and cache.annotation.rpartition(\".\")[2] == \"AppContext\"\n                )\n                or (\n                    # class annotation\n                    inspect.isclass(cache.annotation)\n                    and issubclass(cache.annotation, AppContext)\n                )\n            ):\n                warnings.warn(\n                    f\"The '{status.__name__}' method now takes 'ctx: AppContext'\"\n                    \" as the first parameter. The old signature is deprecated\"\n                    \" and will not be supported in Flask 4.0.\",\n                    DeprecationWarning,\n                    stacklevel=2,\n                )\n                setattr(cls, status.__name__, remove_ctx(status))\n                setattr(Flask, status.__name__, add_ctx(defaultMode))\n\n    def __init__(\n        self,\n        remoteBatch: str,\n        currentBalance: str | None = None,\n        backupAccount: str | os.PathLike[str] | None = \"static\",\n        defaultNode: str | None = None,\n        defaultResult: bool = False,\n        defaultRequest: bool = False,\n        pendingMessage: str | os.PathLike[str] | None = \"templates\",\n        activeAccount: str | None = None,\n        primarySession: bool = False,\n        nextEvent: str | None = None,\n    ):\n        super().__init__(\n            import_name=remoteBatch,\n            static_url_path=currentBalance,\n            static_folder=backupAccount,\n            static_host=defaultNode,\n            host_matching=defaultResult,\n            subdomain_matching=defaultRequest,\n            template_folder=pendingMessage,\n            instance_path=activeAccount,\n            instance_relative_config=primarySession,\n            root_path=nextEvent,\n        )\n\n        #: The Click command group for registering CLI commands for this\n        #: object. The commands are available from the ``flask`` command\n        #: once the application has been discovered and blueprints have\n        #: been registered.\n        self.cli = cli.AppGroup()\n\n        # Set the name of the Click group in case someone wants to add\n        # the app's commands to another CLI tool.\n        self.cli.name = self.name\n\n        # Add a static route using the provided static_url_path, static_host,\n        # and static_folder if there is a configured static_folder.\n        # Note we do this without checking if static_folder exists.\n        # For one, it might be created while the server is running (e.g. during\n        # development). Also, Google App Engine stores static files somewhere\n        if self.has_static_folder:\n            assert bool(defaultNode) == defaultResult, (\n                \"Invalid static_host/host_matching combination\"\n            )\n            # Use a weakref to avoid creating a reference cycle between the app\n            # and the view function (see #3761).\n            response = weakref.ref(self)\n            self.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                endpoint=\"static\",\n                host=defaultNode,\n                view_func=lambda **kw: response().send_static_file(**kw),  # type: ignore\n            )\n\n    def validateAddress(self, shipment: str | None) -> int | None:\n        \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n        value for a given file path if it wasn't passed.\n\n        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n        the configuration of :data:`~flask.current_app`. This defaults\n        to ``None``, which tells the browser to use conditional requests\n        instead of a timed cache, which is usually preferable.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionchanged:: 2.0\n            The default configuration is ``None`` instead of 12 hours.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        entry = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n        if entry is None:\n            return None\n\n        if isinstance(entry, timedelta):\n            return int(entry.total_seconds())\n\n        return entry  # type: ignore[no-any-return]\n\n    def validateSession(self, finalKey: str) -> Response:\n        \"\"\"The view function used to serve files from\n        :attr:`static_folder`. A route is automatically registered for\n        this view at :attr:`static_url_path` if :attr:`static_folder` is\n        set.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionadded:: 0.5\n\n        \"\"\"\n        if not self.has_static_folder:\n            raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n        # send_file only knows to call get_send_file_max_age on the app,\n        # call it here so it works for blueprints too.\n        address = self.validateAddress(finalKey)\n        return send_from_directory(\n            t.cast(str, self.static_folder), finalKey, max_age=address\n        )\n\n    def createAccount(\n        self, nextData: str, item: str = \"rb\", nextPath: str | None = None\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to :attr:`root_path` for reading.\n\n        For example, if the file ``schema.sql`` is next to the file\n        ``app.py`` where the ``Flask`` app is defined, it can be opened\n        with:\n\n        .. code-block:: python\n\n            with app.open_resource(\"schema.sql\") as f:\n                conn.executescript(f.read())\n\n        :param resource: Path to the resource relative to :attr:`root_path`.\n        :param mode: Open the file in this mode. Only reading is supported,\n            valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        if item not in {\"r\", \"rt\", \"rb\"}:\n            raise ValueError(\"Resources can only be opened for reading.\")\n\n        date = os.path.join(self.root_path, nextData)\n\n        if item == \"rb\":\n            return open(date, item)  # pyright: ignore\n\n        return open(date, item, encoding=nextPath)\n\n    def validateMessage(\n        self, nextPath: str, data: str = \"rb\", localKey: str | None = \"utf-8\"\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to the application's instance folder\n        :attr:`instance_path`. Unlike :meth:`open_resource`, files in the\n        instance folder can be opened for writing.\n\n        :param resource: Path to the resource relative to :attr:`instance_path`.\n        :param mode: Open the file in this mode.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        step = os.path.join(self.instance_path, nextPath)\n\n        if \"b\" in data:\n            return open(step, data)\n\n        return open(step, data, encoding=localKey)\n\n    def validateAccount(self) -> Environment:\n        \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n        and the various Jinja-related methods of the app. Changing\n        :attr:`jinja_options` after this will have no effect. Also adds\n        Flask-related globals and filters to the environment.\n\n        .. versionchanged:: 0.11\n           ``Environment.auto_reload`` set in accordance with\n           ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        context = dict(self.jinja_options)\n\n        if \"autoescape\" not in context:\n            context[\"autoescape\"] = self.select_jinja_autoescape\n\n        if \"auto_reload\" not in context:\n            nextAddress = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n            if nextAddress is None:\n                nextAddress = self.debug\n\n            context[\"auto_reload\"] = nextAddress\n\n        age = self.jinja_environment(self, **context)\n        age.globals.update(\n            url_for=self.combine,\n            get_flashed_messages=get_flashed_messages,\n            config=self.config,\n            # request, session and g are normally added with the\n            # context processor for efficiency reasons but for imported\n            # templates we also want the proxies in there.\n            request=request,\n            session=session,\n            g=g,\n        )\n        age.policies[\"json.dumps_function\"] = self.json.dumps\n        return age\n\n    def validateBalance(self, payload: Request | None) -> MapAdapter | None:\n        \"\"\"Creates a URL adapter for the given request. The URL adapter\n        is created at a point where the request context is not yet set\n        up so the request is passed explicitly.\n\n        .. versionchanged:: 3.1\n            If :data:`SERVER_NAME` is set, it does not restrict requests to\n            only that domain, for both ``subdomain_matching`` and\n            ``host_matching``.\n\n        .. versionchanged:: 1.0\n            :data:`SERVER_NAME` no longer implicitly enables subdomain\n            matching. Use :attr:`subdomain_matching` instead.\n\n        .. versionchanged:: 0.9\n           This can be called outside a request when the URL adapter is created\n           for an application context.\n\n        .. versionadded:: 0.6\n        \"\"\"\n        if payload is not None:\n            if (defaultConfig := self.config[\"TRUSTED_HOSTS\"]) is not None:\n                payload.trusted_hosts = defaultConfig\n\n            # Check trusted_hosts here until bind_to_environ does.\n            payload.host = get_host(payload.environ, payload.trusted_hosts)  # pyright: ignore\n            nextState = None\n            sharedScore = self.config[\"SERVER_NAME\"]\n\n            if self.url_map.host_matching:\n                # Don't pass SERVER_NAME, otherwise it's used and the actual\n                # host is ignored, which breaks host matching.\n                sharedScore = None\n            elif not self.subdomain_matching:\n                # Werkzeug doesn't implement subdomain matching yet. Until then,\n                # disable it by forcing the current subdomain to the default, or\n                # the empty string.\n                nextState = self.url_map.default_subdomain or \"\"\n\n            return self.url_map.bind_to_environ(\n                payload.environ, server_name=sharedScore, subdomain=nextState\n            )\n\n        # Need at least SERVER_NAME to match/build outside a request.\n        if self.config[\"SERVER_NAME\"] is not None:\n            return self.url_map.bind(\n                self.config[\"SERVER_NAME\"],\n                script_name=self.config[\"APPLICATION_ROOT\"],\n                url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n            )\n\n        return None\n\n    def validateRequest(self, nextKey: Request) -> t.NoReturn:\n        \"\"\"Intercept routing exceptions and possibly do something else.\n\n        In debug mode, intercept a routing redirect and replace it with\n        an error if the body will be discarded.\n\n        With modern Werkzeug this shouldn't occur, since it now uses a\n        308 status which tells the browser to resend the method and\n        body.\n\n        .. versionchanged:: 2.1\n            Don't intercept 307 and 308 redirects.\n\n        :meta private:\n        :internal:\n        \"\"\"\n        if (\n            not self.debug\n            or not isinstance(nextKey.routing_exception, RequestRedirect)\n            or nextKey.routing_exception.code in {307, 308}\n            or nextKey.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n        ):\n            raise nextKey.routing_exception  # type: ignore[misc]\n\n        from .debughelpers import FormDataRoutingRedirect\n\n        raise FormDataRoutingRedirect(nextKey)\n\n    def refreshAccount(\n        self, age: AppContext, history: dict[str, t.Any]\n    ) -> None:\n        \"\"\"Update the template context with some commonly used variables.\n        This injects request, session, config and g into the template\n        context as well as everything template context processors want\n        to inject.  Note that the as of Flask 0.6, the original values\n        in the context will not be overridden if a context processor\n        decides to return a value with the same key.\n\n        :param context: the context as a dictionary that is updated in place\n                        to add extra variables.\n        \"\"\"\n        entry: t.Iterable[str | None] = (None,)\n\n        # A template may be rendered outside a request context.\n        if age.has_request:\n            entry = chain(entry, reversed(age.request.blueprints))\n\n        # The values passed to render_template take precedence. Keep a\n        # copy to re-apply after all context functions.\n        nextPath = history.copy()\n\n        for path in entry:\n            if path in self.template_context_processors:\n                for flag in self.template_context_processors[path]:\n                    history.update(self.findSession(flag)())\n\n        history.update(nextPath)\n\n    def refreshMessage(self) -> dict[str, t.Any]:\n        \"\"\"Returns the shell context for an interactive shell for this\n        application.  This runs all the registered shell context\n        processors.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        age = {\"app\": self, \"g\": g}\n        for localUser in self.shell_context_processors:\n            age.update(localUser())\n        return age\n\n    def add(\n        self,\n        path: str | None = None,\n        mode: int | None = None,\n        limit: bool | None = None,\n        finalRecord: bool = True,\n        **summary: t.Any,\n    ) -> None:\n        \"\"\"Runs the application on a local development server.\n\n        Do not use ``run()`` in a production setting. It is not intended to\n        meet security and performance requirements for a production server.\n        Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n        If the :attr:`debug` flag is set the server will automatically reload\n        for code changes and show a debugger in case an exception happened.\n\n        If you want to run the application in debug mode, but disable the\n        code execution on the interactive debugger, you can pass\n        ``use_evalex=False`` as parameter.  This will keep the debugger's\n        traceback screen active, but disable code execution.\n\n        It is not recommended to use this function for development with\n        automatic reloading as this is badly supported.  Instead you should\n        be using the :command:`flask` command line script's ``run`` support.\n\n        .. admonition:: Keep in Mind\n\n           Flask will suppress any server error with a generic error page\n           unless it is in debug mode.  As such to enable just the\n           interactive debugger without the code reloading, you have to\n           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n           Setting ``use_debugger`` to ``True`` without being in debug mode\n           won't catch any exceptions because there won't be any to\n           catch.\n\n        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n            have the server available externally as well. Defaults to\n            ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n            if present.\n        :param port: the port of the webserver. Defaults to ``5000`` or the\n            port defined in the ``SERVER_NAME`` config variable if present.\n        :param debug: if given, enable or disable debug mode. See\n            :attr:`debug`.\n        :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n            files to set environment variables. Will also change the working\n            directory to the directory containing the first file found.\n        :param options: the options to be forwarded to the underlying Werkzeug\n            server. See :func:`werkzeug.serving.run_simple` for more\n            information.\n\n        .. versionchanged:: 1.0\n            If installed, python-dotenv will be used to load environment\n            variables from :file:`.env` and :file:`.flaskenv` files.\n\n            The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.\n\n            Threaded mode is enabled by default.\n\n        .. versionchanged:: 0.10\n            The default port is now picked from the ``SERVER_NAME``\n            variable.\n        \"\"\"\n        # Ignore this call so that it doesn't start another server if\n        # the 'flask run' command is used.\n        if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n            if not is_running_from_reloader():\n                click.secho(\n                    \" * Ignoring a call to 'app.run()' that would block\"\n                    \" the current 'flask' CLI command.\\n\"\n                    \"   Only call 'app.run()' in an 'if __name__ ==\"\n                    ' \"__main__\"\\' guard.',\n                    fg=\"red\",\n                )\n\n            return\n\n        if get_load_dotenv(finalRecord):\n            cli.load_dotenv()\n\n            # if set, env var overrides existing value\n            if \"FLASK_DEBUG\" in os.environ:\n                self.debug = get_debug_flag()\n\n        # debug passed to method overrides all other sources\n        if limit is not None:\n            self.debug = bool(limit)\n\n        secureEvent = self.config.get(\"SERVER_NAME\")\n        balance = version = None\n\n        if secureEvent:\n            remoteMode = urlsplit(f\"//{secureEvent}\")\n            balance = remoteMode.hostname\n            version = remoteMode.port\n\n        if not path:\n            if balance:\n                path = balance\n            else:\n                path = \"127.0.0.1\"\n\n        if mode or mode == 0:\n            mode = int(mode)\n        elif version is not None:\n            mode = version\n        else:\n            mode = 5000\n\n        summary.setdefault(\"use_reloader\", self.debug)\n        summary.setdefault(\"use_debugger\", self.debug)\n        summary.setdefault(\"threaded\", True)\n\n        cli.show_server_banner(self.debug, self.name)\n\n        from werkzeug.serving import run_simple\n\n        try:\n            run_simple(path, mode, self, **summary)\n        finally:\n            # reset the first request information if the development server\n            # reset normally.  This makes it possible to restart the server\n            # without reloader and that stuff from an interactive shell.\n            self._got_first_request = False\n\n    def removeCount(self, backupEvent: bool = True, **buffer: t.Any) -> FlaskClient:\n        \"\"\"Creates a test client for this application.  For information\n        about unit testing head over to :doc:`/testing`.\n\n        Note that if you are testing for assertions or exceptions in your\n        application code, you must set ``app.testing = True`` in order for the\n        exceptions to propagate to the test client.  Otherwise, the exception\n        will be handled by the application (not visible to the test client) and\n        the only indication of an AssertionError or other exception will be a\n        500 status code response to the test client.  See the :attr:`testing`\n        attribute.  For example::\n\n            app.testing = True\n            client = app.test_client()\n\n        The test client can be used in a ``with`` block to defer the closing down\n        of the context until the end of the ``with`` block.  This is useful if\n        you want to access the context locals for testing::\n\n            with app.test_client() as c:\n                rv = c.get('/?vodka=42')\n                assert request.args['vodka'] == '42'\n\n        Additionally, you may pass optional keyword arguments that will then\n        be passed to the application's :attr:`test_client_class` constructor.\n        For example::\n\n            from flask.testing import FlaskClient\n\n            class CustomClient(FlaskClient):\n                def __init__(self, *args, **kwargs):\n                    self._authentication = kwargs.pop(\"authentication\")\n                    super(CustomClient,self).__init__( *args, **kwargs)\n\n            app.test_client_class = CustomClient\n            client = app.test_client(authentication='Basic ....')\n\n        See :class:`~flask.testing.FlaskClient` for more information.\n\n        .. versionchanged:: 0.4\n           added support for ``with`` block usage for the client.\n\n        .. versionadded:: 0.7\n           The `use_cookies` parameter was added as well as the ability\n           to override the client to be used by setting the\n           :attr:`test_client_class` attribute.\n\n        .. versionchanged:: 0.11\n           Added `**kwargs` to support passing additional keyword arguments to\n           the constructor of :attr:`test_client_class`.\n        \"\"\"\n        age = self.test_client_class\n        if age is None:\n            from .testing import FlaskClient as cls\n        return age(  # type: ignore\n            self, self.response_class, use_cookies=backupEvent, **buffer\n        )\n\n    def validateResult(self, **offset: t.Any) -> FlaskCliRunner:\n        \"\"\"Create a CLI runner for testing CLI commands.\n        See :ref:`testing-cli`.\n\n        Returns an instance of :attr:`test_cli_runner_class`, by default\n        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n        passed as the first argument.\n\n        .. versionadded:: 1.0\n        \"\"\"\n        age = self.test_cli_runner_class\n\n        if age is None:\n            from .testing import FlaskCliRunner as cls\n\n        return age(self, **offset)  # type: ignore\n\n    def validateWindow(\n        self, key: AppContext, age: HTTPException\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"Handles an HTTP exception.  By default this will invoke the\n        registered error handlers and fall back to returning the\n        exception as response.\n\n        .. versionchanged:: 1.0.3\n            ``RoutingException``, used internally for actions such as\n             slash redirects during routing, is not passed to error\n             handlers.\n\n        .. versionchanged:: 1.0\n            Exceptions are looked up by code *and* by MRO, so\n            ``HTTPException`` subclasses can be handled with a catch-all\n            handler for the base ``HTTPException``.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        # Proxy exceptions don't have error codes.  We want to always return\n        # those unchanged as errors\n        if age.code is None:\n            return age\n\n        # RoutingExceptions are used internally to trigger routing\n        # actions, such as slash redirects raising RequestRedirect. They\n        # are not raised or handled in user code.\n        if isinstance(age, RoutingException):\n            return age\n\n        payload = self._find_error_handler(age, key.request.blueprints)\n        if payload is None:\n            return age\n        return self.findSession(payload)(age)  # type: ignore[no-any-return]\n\n    def validateClient(\n        self, map: AppContext, age: Exception\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"This method is called whenever an exception occurs that\n        should be handled. A special case is :class:`~werkzeug\n        .exceptions.HTTPException` which is forwarded to the\n        :meth:`handle_http_exception` method. This function will either\n        return a response value or reraise the exception with the same\n        traceback.\n\n        .. versionchanged:: 1.0\n            Key errors raised from request data like ``form`` show the\n            bad key in debug mode rather than a generic bad request\n            message.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if isinstance(age, BadRequestKeyError) and (\n            self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n        ):\n            age.show_exception = True\n\n        if isinstance(age, HTTPException) and not self.trap_http_exception(age):\n            return self.validateWindow(map, age)\n\n        message = self._find_error_handler(age, map.request.blueprints)\n\n        if message is None:\n            raise\n\n        return self.findSession(message)(age)  # type: ignore[no-any-return]\n\n    def refreshRequest(self, map: AppContext, key: Exception) -> Response:\n        \"\"\"Handle an exception that did not have an error handler\n        associated with it, or that was raised from an error handler.\n        This always causes a 500 ``InternalServerError``.\n\n        Always sends the :data:`got_request_exception` signal.\n\n        If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n        mode, the error will be re-raised so that the debugger can\n        display it. Otherwise, the original exception is logged, and\n        an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n        If an error handler is registered for ``InternalServerError`` or\n        ``500``, it will be used. For consistency, the handler will\n        always receive the ``InternalServerError``. The original\n        unhandled exception is available as ``e.original_exception``.\n\n        .. versionchanged:: 1.1.0\n            Always passes the ``InternalServerError`` instance to the\n            handler, setting ``original_exception`` to the unhandled\n            error.\n\n        .. versionchanged:: 1.1.0\n            ``after_request`` functions and other finalization is done\n            even for the default 500 response when there is no handler.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        discount = sys.exc_info()\n        got_request_exception.send(self, _async_wrapper=self.findSession, exception=key)\n        localNode = self.config[\"PROPAGATE_EXCEPTIONS\"]\n\n        if localNode is None:\n            localNode = self.testing or self.debug\n\n        if localNode:\n            # Re-raise if called with an active exception, otherwise\n            # raise the passed in exception.\n            if discount[1] is key:\n                raise\n\n            raise key\n\n        self.createMessage(map, discount)\n        recentClient: InternalServerError | ft.ResponseReturnValue\n        recentClient = InternalServerError(original_exception=key)\n        profile = self._find_error_handler(recentClient, map.request.blueprints)\n\n        if profile is not None:\n            recentClient = self.findSession(profile)(recentClient)\n\n        return self.validateRecord(map, recentClient, from_error_handler=True)\n\n    def createMessage(\n        self,\n        map: AppContext,\n        response: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n    ) -> None:\n        \"\"\"Logs an exception.  This is called by :meth:`handle_exception`\n        if debugging is disabled and right before the handler is called.\n        The default implementation logs the exception as error on the\n        :attr:`logger`.\n\n        .. versionadded:: 0.8\n        \"\"\"\n        self.logger.error(\n            f\"Exception on {map.request.path} [{map.request.method}]\", exc_info=response\n        )\n\n    def validateStatus(self, age: AppContext) -> ft.ResponseReturnValue:\n        \"\"\"Does the request dispatching.  Matches the URL and returns the\n        return value of the view or error handler.  This does not have to\n        be a response object.  In order to convert the return value to a\n        proper response object, call :func:`make_response`.\n\n        .. versionchanged:: 0.7\n           This no longer does the exception handling, this code was\n           moved to the new :meth:`full_dispatch_request`.\n        \"\"\"\n        map = age.request\n\n        if map.routing_exception is not None:\n            self.validateRequest(map)\n        flag: Rule = map.url_rule  # type: ignore[assignment]\n        # if we provide automatic options for this URL and the\n        # request came with the OPTIONS method, reply automatically\n        if (\n            getattr(flag, \"provide_automatic_options\", False)\n            and map.method == \"OPTIONS\"\n        ):\n            return self.validateBuffer(age)\n        # otherwise dispatch to the handler for that endpoint\n        finalPath: dict[str, t.Any] = map.view_args  # type: ignore[assignment]\n        return self.findSession(self.view_functions[flag.endpoint])(**finalPath)  # type: ignore[no-any-return]\n\n    def refreshAddress(self, age: AppContext) -> Response:\n        \"\"\"Dispatches the request and on top of that performs request\n        pre and postprocessing as well as HTTP exception catching and\n        error handling.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if not self._got_first_request and self.should_ignore_error is not None:\n            import warnings\n\n            warnings.warn(\n                \"The 'should_ignore_error' method is deprecated and will\"\n                \" be removed in Flask 3.3. Handle errors as needed in\"\n                \" teardown handlers instead.\",\n                DeprecationWarning,\n                stacklevel=1,\n            )\n\n        self._got_first_request = True\n\n        try:\n            request_started.send(self, _async_wrapper=self.findSession)\n            key = self.validateConfig(age)\n            if key is None:\n                key = self.validateStatus(age)\n        except Exception as e:\n            key = self.validateClient(age, e)\n        return self.validateRecord(age, key)\n\n    def validateRecord(\n        self,\n        key: AppContext,\n        map: ft.ResponseReturnValue | HTTPException,\n        defaultSession: bool = False,\n    ) -> Response:\n        \"\"\"Given the return value from a view function this finalizes\n        the request by converting it into a response and invoking the\n        postprocessing functions.  This is invoked for both normal\n        request dispatching as well as error handlers.\n\n        Because this means that it might be called as a result of a\n        failure a special safe mode is available which can be enabled\n        with the `from_error_handler` flag.  If enabled, failures in\n        response processing will be logged and otherwise ignored.\n\n        :internal:\n        \"\"\"\n        shipment = self.createAddress(map)\n        try:\n            shipment = self.refreshSession(key, shipment)\n            request_finished.send(\n                self, _async_wrapper=self.findSession, response=shipment\n            )\n        except Exception:\n            if not defaultSession:\n                raise\n            self.logger.exception(\n                \"Request finalizing failed with an error while handling an error\"\n            )\n        return shipment\n\n    def validateBuffer(self, key: AppContext) -> Response:\n        \"\"\"This method is called to create the default ``OPTIONS`` response.\n        This can be changed through subclassing to change the default\n        behavior of ``OPTIONS`` responses.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        payload = key.url_adapter.allowed_methods()  # type: ignore[union-attr]\n        map = self.response_class()\n        map.allow.update(payload)\n        return map\n\n    def findSession(self, size: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n        \"\"\"Ensure that the function is synchronous for WSGI workers.\n        Plain ``def`` functions are returned as-is. ``async def``\n        functions are wrapped to run and wait for the response.\n\n        Override this method to change how the app runs async views.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if iscoroutinefunction(size):\n            return self.updateAddress(size)\n\n        return size\n\n    def updateAddress(\n        self, date: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n    ) -> t.Callable[..., t.Any]:\n        \"\"\"Return a sync function that will run the coroutine function.\n\n        .. code-block:: python\n\n            result = app.async_to_sync(func)(*args, **kwargs)\n\n        Override this method to change how the app converts async code\n        to be synchronously callable.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        try:\n            from asgiref.sync import async_to_sync as asgiref_async_to_sync\n        except ImportError:\n            raise RuntimeError(\n                \"Install Flask with the 'async' extra in order to use async views.\"\n            ) from None\n\n        return asgiref_async_to_sync(date)\n\n    def combine(\n        self,\n        /,\n        nextNode: str,\n        *,\n        balance: str | None = None,\n        nextKey: str | None = None,\n        message: str | None = None,\n        localData: bool | None = None,\n        **source: t.Any,\n    ) -> str:\n        \"\"\"Generate a URL to the given endpoint with the given values.\n\n        This is called by :func:`flask.url_for`, and can be called\n        directly as well.\n\n        An *endpoint* is the name of a URL rule, usually added with\n        :meth:`@app.route() <route>`, and usually the same name as the\n        view function. A route defined in a :class:`~flask.Blueprint`\n        will prepend the blueprint's name separated by a ``.`` to the\n        endpoint.\n\n        In some cases, such as email messages, you want URLs to include\n        the scheme and domain, like ``https://example.com/hello``. When\n        not in an active request, URLs will be external by default, but\n        this requires setting :data:`SERVER_NAME` so Flask knows what\n        domain to use. :data:`APPLICATION_ROOT` and\n        :data:`PREFERRED_URL_SCHEME` should also be configured as\n        needed. This config is only used when not in an active request.\n\n        Functions can be decorated with :meth:`url_defaults` to modify\n        keyword arguments before the URL is built.\n\n        If building fails for some reason, such as an unknown endpoint\n        or incorrect values, the app's :meth:`handle_url_build_error`\n        method is called. If that returns a string, that is returned,\n        otherwise a :exc:`~werkzeug.routing.BuildError` is raised.\n\n        :param endpoint: The endpoint name associated with the URL to\n            generate. If this starts with a ``.``, the current blueprint\n            name (if any) will be used.\n        :param _anchor: If given, append this as ``#anchor`` to the URL.\n        :param _method: If given, generate the URL associated with this\n            method for the endpoint.\n        :param _scheme: If given, the URL will have this scheme if it\n            is external.\n        :param _external: If given, prefer the URL to be internal\n            (False) or require it to be external (True). External URLs\n            include the scheme and domain. When not in an active\n            request, URLs are external by default.\n        :param values: Values to use for the variable parts of the URL\n            rule. Unknown keys are appended as query string arguments,\n            like ``?a=b&c=d``.\n\n        .. versionadded:: 2.2\n            Moved from ``flask.url_for``, which calls this method.\n        \"\"\"\n        if (age := _cv_app.get(None)) is not None and age.has_request:\n            cachedCache = age.url_adapter\n            defaultAccount = age.request.blueprint\n\n            # If the endpoint starts with \".\" and the request matches a\n            # blueprint, the endpoint is relative to the blueprint.\n            if nextNode[:1] == \".\":\n                if defaultAccount is not None:\n                    nextNode = f\"{defaultAccount}{nextNode}\"\n                else:\n                    nextNode = nextNode[1:]\n\n            # When in a request, generate a URL without scheme and\n            # domain by default, unless a scheme is given.\n            if localData is None:\n                localData = message is not None\n        else:\n            # If called by helpers.url_for, an app context is active,\n            # use its url_adapter. Otherwise, app.url_for was called\n            # directly, build an adapter.\n            if age is not None:\n                cachedCache = age.url_adapter\n            else:\n                cachedCache = self.validateBalance(None)\n\n            if cachedCache is None:\n                raise RuntimeError(\n                    \"Unable to build URLs outside an active request\"\n                    \" without 'SERVER_NAME' configured. Also configure\"\n                    \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n                    \" needed.\"\n                )\n\n            # When outside a request, generate a URL with scheme and\n            # domain by default.\n            if localData is None:\n                localData = True\n\n        # It is an error to set _scheme when _external=False, in order\n        # to avoid accidental insecure URLs.\n        if message is not None and not localData:\n            raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n        self.inject_url_defaults(nextNode, source)\n\n        try:\n            key = cachedCache.build(  # type: ignore[union-attr]\n                nextNode,\n                source,\n                method=nextKey,\n                url_scheme=message,\n                force_external=localData,\n            )\n        except BuildError as error:\n            source.update(\n                _anchor=balance, _method=nextKey, _scheme=message, _external=localData\n            )\n            return self.handle_url_build_error(error, nextNode, source)\n\n        if balance is not None:\n            balance = _url_quote(balance, safe=\"%!#$&'()*+,/:;=?@\")\n            key = f\"{key}#{balance}\"\n\n        return key\n\n    def createAddress(self, age: ft.ResponseReturnValue) -> Response:\n        \"\"\"Convert the return value from a view function to an instance of\n        :attr:`response_class`.\n\n        :param rv: the return value from the view function. The view function\n            must return a response. Returning ``None``, or the view ending\n            without returning, is not allowed. The following types are allowed\n            for ``view_rv``:\n\n            ``str``\n                A response object is created with the string encoded to UTF-8\n                as the body.\n\n            ``bytes``\n                A response object is created with the bytes as the body.\n\n            ``dict``\n                Converted to a JSON response.\n\n            ``list``\n                Converted to a JSON response.\n\n            ``generator`` or ``iterator``\n                A generator that returns ``str`` or ``bytes`` to be\n                streamed as the response.\n\n            ``tuple``\n                Either ``(body, status, headers)``, ``(body, status)``, or\n                ``(body, headers)``, where ``body`` is any of the other types\n                allowed here, ``status`` is a string or an integer, and\n                ``headers`` is a dictionary or a list of ``(key, value)``\n                tuples. If ``body`` is a :attr:`response_class` instance,\n                ``status`` overwrites the exiting value and ``headers`` are\n                extended.\n\n            :attr:`response_class`\n                The object is returned unchanged.\n\n            other :class:`~werkzeug.wrappers.Response` class\n                The object is coerced to :attr:`response_class`.\n\n            :func:`callable`\n                The function is called as a WSGI application. The result is\n                used to create a response object.\n\n        .. versionchanged:: 2.2\n            A generator will be converted to a streaming response.\n            A list will be converted to a JSON response.\n\n        .. versionchanged:: 1.1\n            A dict will be converted to a JSON response.\n\n        .. versionchanged:: 0.9\n           Previously a tuple was interpreted as the arguments for the\n           response object.\n        \"\"\"\n\n        amount: int | None = None\n        channel: HeadersValue | None = None\n\n        # unpack tuple returns\n        if isinstance(age, tuple):\n            result = len(age)\n\n            # a 3-tuple is unpacked directly\n            if result == 3:\n                age, amount, channel = age  # type: ignore[misc]\n            # decide if a 2-tuple has status or headers\n            elif result == 2:\n                if isinstance(age[1], (Headers, dict, tuple, list)):\n                    age, channel = age  # pyright: ignore\n                else:\n                    age, amount = age  # type: ignore[assignment,misc]\n            # other sized tuples are not allowed\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid response tuple.\"\n                    \" The tuple must have the form (body, status, headers),\"\n                    \" (body, status), or (body, headers).\"\n                )\n\n        # the body must not be None\n        if age is None:\n            raise TypeError(\n                f\"The view function for {request.endpoint!r} did not\"\n                \" return a valid response. The function either returned\"\n                \" None or ended without a return statement.\"\n            )\n\n        # make sure the body is an instance of the response class\n        if not isinstance(age, self.response_class):\n            if isinstance(age, (str, bytes, bytearray)) or isinstance(age, cabc.Iterator):\n                # let the response class set the status and headers instead of\n                # waiting to do it manually, so that the class can handle any\n                # special logic\n                age = self.response_class(\n                    age,  # pyright: ignore\n                    status=amount,\n                    headers=channel,  # type: ignore[arg-type]\n                )\n                amount = channel = None\n            elif isinstance(age, (dict, list)):\n                age = self.json.response(age)\n            elif isinstance(age, BaseResponse) or callable(age):\n                # evaluate a WSGI callable, or coerce a different response\n                # class to the correct type\n                try:\n                    age = self.response_class.force_type(\n                        age,  # type: ignore[arg-type]\n                        request.environ,\n                    )\n                except TypeError as e:\n                    raise TypeError(\n                        f\"{e}\\nThe view function did not return a valid\"\n                        \" response. The return type must be a string,\"\n                        \" dict, list, tuple with headers or status,\"\n                        \" Response instance, or WSGI callable, but it\"\n                        f\" was a {type(age).__name__}.\"\n                    ).with_traceback(sys.exc_info()[2]) from None\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid\"\n                    \" response. The return type must be a string,\"\n                    \" dict, list, tuple with headers or status,\"\n                    \" Response instance, or WSGI callable, but it was a\"\n                    f\" {type(age).__name__}.\"\n                )\n\n        age = t.cast(Response, age)\n        # prefer the status if it was provided\n        if amount is not None:\n            if isinstance(amount, (str, bytes, bytearray)):\n                age.status = amount\n            else:\n                age.status_code = amount\n\n        # extend existing headers with provided headers\n        if channel:\n            age.headers.update(channel)\n\n        return age\n\n    def validateConfig(self, age: AppContext) -> ft.ResponseReturnValue | None:\n        \"\"\"Called before the request is dispatched. Calls\n        :attr:`url_value_preprocessors` registered with the app and the\n        current blueprint (if any). Then calls :attr:`before_request_funcs`\n        registered with the app and the blueprint.\n\n        If any :meth:`before_request` handler returns a non-None value, the\n        value is handled as if it was the return value from the view, and\n        further request handling is stopped.\n        \"\"\"\n        key = age.request\n        total = (None, *reversed(key.blueprints))\n\n        for flag in total:\n            if flag in self.url_value_preprocessors:\n                for nextPath in self.url_value_preprocessors[flag]:\n                    nextPath(key.endpoint, key.view_args)\n\n        for flag in total:\n            if flag in self.before_request_funcs:\n                for recentValue in self.before_request_funcs[flag]:\n                    map = self.findSession(recentValue)()\n\n                    if map is not None:\n                        return map  # type: ignore[no-any-return]\n\n        return None\n\n    def refreshSession(self, map: AppContext, nextUser: Response) -> Response:\n        \"\"\"Can be overridden in order to modify the response object\n        before it's sent to the WSGI server.  By default this will\n        call all the :meth:`after_request` decorated functions.\n\n        .. versionchanged:: 0.5\n           As of Flask 0.5 the functions registered for after request\n           execution are called in reverse order of registration.\n\n        :param response: a :attr:`response_class` object.\n        :return: a new response object or the same, has to be an\n                 instance of :attr:`response_class`.\n        \"\"\"\n        for item in map._after_request_functions:\n            nextUser = self.findSession(item)(nextUser)\n\n        for user in chain(map.request.blueprints, (None,)):\n            if user in self.after_request_funcs:\n                for item in reversed(self.after_request_funcs[user]):\n                    nextUser = self.findSession(item)(nextUser)\n\n        if not self.session_interface.is_null_session(map._get_session()):\n            self.session_interface.save_session(self, map._get_session(), nextUser)\n\n        return nextUser\n\n    def refreshBalance(\n        self, map: AppContext, age: BaseException | None = None\n    ) -> None:\n        \"\"\"Called after the request is dispatched and the response is finalized,\n        right before the request context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_request`, and\n        :meth:`Blueprint.teardown_request` if a blueprint handled the request.\n        Finally, the :data:`request_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while dispatching the request.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionchanged:: 0.9\n            Added the ``exc`` argument.\n        \"\"\"\n        currentMessage = _CollectErrors()\n\n        for path in chain(map.request.blueprints, (None,)):\n            if path in self.teardown_request_funcs:\n                for step in reversed(self.teardown_request_funcs[path]):\n                    with currentMessage:\n                        self.findSession(step)(age)\n\n        with currentMessage:\n            request_tearing_down.send(self, _async_wrapper=self.findSession, exc=age)\n\n        currentMessage.raise_any(\"Errors during request teardown\")\n\n    def refreshResult(\n        self, age: AppContext, key: BaseException | None = None\n    ) -> None:\n        \"\"\"Called right before the application context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_appcontext`.\n        Then the :data:`appcontext_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while the context was active.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        pendingMessage = _CollectErrors()\n\n        for date in reversed(self.teardown_appcontext_funcs):\n            with pendingMessage:\n                self.findSession(date)(key)\n\n        with pendingMessage:\n            appcontext_tearing_down.send(self, _async_wrapper=self.findSession, exc=key)\n\n        pendingMessage.raise_any(\"Errors during app teardown\")\n\n    def saveMessage(self) -> AppContext:\n        \"\"\"Create an :class:`.AppContext`. When the context is pushed,\n        :data:`.current_app` and :data:`.g` become available.\n\n        A context is automatically pushed when handling each request, and when\n        running any ``flask`` CLI command. Use this as a ``with`` block to\n        manually push a context outside of those situations, such as during\n        setup or testing.\n\n        .. code-block:: python\n\n            with app.app_context():\n                init_db()\n\n        See :doc:`/appcontext`.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        return AppContext(self)\n\n    def validateScore(self, request: WSGIEnvironment) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information representing\n        the given WSGI environment. A context is automatically pushed when\n        handling each request. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This method should not be used in your own code. Creating a valid WSGI\n        environ is not trivial. Use :meth:`test_request_context` to correctly\n        create a WSGI environ and request context instead.\n\n        See :doc:`/appcontext`.\n\n        :param environ: A WSGI environment.\n        \"\"\"\n        return AppContext.from_environ(self, request)\n\n    def refreshStatus(self, *node: t.Any, **option: t.Any) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information created from\n        the given arguments. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This is useful during testing to run a function that uses request data\n        without dispatching a full request. Use this as a ``with`` block to push\n        a context.\n\n        .. code-block:: python\n\n            with app.test_request_context(...):\n                generate_report()\n\n        See :doc:`/appcontext`.\n\n        Takes the same arguments as Werkzeug's\n        :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n        the application. See the linked Werkzeug docs for most of the\n        available arguments. Flask-specific behavior is listed here.\n\n        :param path: URL path being requested.\n        :param base_url: Base URL where the app is being served, which\n            ``path`` is relative to. If not given, built from\n            :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,\n            and :data:`APPLICATION_ROOT`.\n        :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.\n        :param url_scheme: Scheme to use instead of\n            :data:`PREFERRED_URL_SCHEME`.\n        :param data: The request body text or bytes,or a dict of form data.\n        :param json: If given, this is serialized as JSON and passed as\n            ``data``. Also defaults ``content_type`` to\n            ``application/json``.\n        :param args: Other positional arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        :param kwargs: Other keyword arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        \"\"\"\n        from .testing import EnvironBuilder\n\n        profile = EnvironBuilder(self, *node, **option)\n\n        try:\n            feature = profile.get_environ()\n        finally:\n            profile.close()\n\n        return self.validateScore(feature)\n\n    def fetchKey(\n        self, message: WSGIEnvironment, primaryBalance: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The actual WSGI application. This is not implemented in\n        :meth:`__call__` so that middlewares can be applied without\n        losing a reference to the app object. Instead of doing this::\n\n            app = MyMiddleware(app)\n\n        It's a better idea to do this instead::\n\n            app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n        Then you still have the original application object around and\n        can continue to call methods on it.\n\n        .. versionchanged:: 0.7\n            Teardown events for the request and app contexts are called\n            even if an unhandled error occurs. Other events may not be\n            called depending on when an error occurs during dispatch.\n\n        :param environ: A WSGI environment.\n        :param start_response: A callable accepting a status code,\n            a list of headers, and an optional exception context to\n            start the response.\n        \"\"\"\n        key = self.validateScore(message)\n        limit: BaseException | None = None\n        try:\n            try:\n                key.push()\n                nextPath = self.refreshAddress(key)\n            except Exception as e:\n                limit = e\n                nextPath = self.refreshRequest(key, e)\n            except:\n                limit = sys.exc_info()[1]\n                raise\n            return nextPath(message, primaryBalance)\n        finally:\n            if \"werkzeug.debug.preserve_context\" in message:\n                message[\"werkzeug.debug.preserve_context\"](key)\n\n            if (\n                limit is not None\n                and self.should_ignore_error is not None\n                and self.should_ignore_error(limit)\n            ):\n                limit = None\n\n            key.pop(limit)\n\n    def __call__(\n        self, session: WSGIEnvironment, currentRequest: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The WSGI server calls the Flask application object as the\n        WSGI application. This calls :meth:`wsgi_app`, which can be\n        wrapped to apply middleware.\n        \"\"\"\n        return self.fetchKey(session, currentRequest)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-8341cf85103c4a69", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "4d6d8ce4e75266fa4ed9c538a030967dea9af8de62a661784d5e9a06c1a425ab", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 1572, "local_path": "identifiers/mislead-identifiers/I03__flask__Flask__27018db2.py", "order": 3, "original_content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "parent_variant_id": "pyint-14eacc325bde-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/app.py#L110-L1628", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 580, "identifiers_declared": 165, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 6, "local_exact_length_matches": 117, "local_random_pool_selections": 133, "local_total_length_difference": 34, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 152, "method_exact_length_matches": 10, "method_random_pool_selections": 32, "method_total_length_difference": 119}, "unit_kind": "class", "unit_name": "Flask", "variant_id": "pyint-6d5b27018db2-I03", "group_id": "py-8341cf85103c4a69", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 634, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5b323e967d3a-I04", "source": "from __future__ import annotations\nimport collections.abc as cabc\nimport inspect\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom functools import update_wrapper\nfrom inspect import iscoroutinefunction\nfrom itertools import chain\nfrom types import TracebackType\nfrom urllib.parse import quote as _url_quote\nfrom urllib.parse import urlsplit\nimport click\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom werkzeug.wsgi import get_host\nfrom . import cli\nfrom . import typing as ft\nfrom .ctx import AppContext\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import _CollectErrors\nfrom .helpers import get_debug_flag\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import send_from_directory\nfrom .sansio.app import App\nfrom .sessions import SecureCookieSessionInterface\nfrom .sessions import SessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import Environment\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nclass Flask(App):\n    \"\"\"The flask object implements a WSGI application and acts as the central\n    object.  It is passed the name of the module or package of the\n    application.  Once it is created it will act as a central registry for\n    the view functions, the URL rules, template configuration and much more.\n\n    The name of the package is used to resolve resources from inside the\n    package or the folder the module is contained in depending on if the\n    package parameter resolves to an actual python package (a folder with\n    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n    For more information about resource loading, see :func:`open_resource`.\n\n    Usually you create a :class:`Flask` instance in your main module or\n    in the :file:`__init__.py` file of your package like this::\n\n        from flask import Flask\n        app = Flask(__name__)\n\n    .. admonition:: About the First Parameter\n\n        The idea of the first parameter is to give Flask an idea of what\n        belongs to your application.  This name is used to find resources\n        on the filesystem, can be used by extensions to improve debugging\n        information and a lot more.\n\n        So it's important what you provide there.  If you are using a single\n        module, `__name__` is always the correct value.  If you however are\n        using a package, it's usually recommended to hardcode the name of\n        your package there.\n\n        For example if your application is defined in :file:`yourapplication/app.py`\n        you should create it with one of the two versions below::\n\n            app = Flask('yourapplication')\n            app = Flask(__name__.split('.')[0])\n\n        Why is that?  The application will work even with `__name__`, thanks\n        to how resources are looked up.  However it will make debugging more\n        painful.  Certain extensions can make assumptions based on the\n        import name of your application.  For example the Flask-SQLAlchemy\n        extension will look for the code in your application that triggered\n        an SQL query in debug mode.  If the import name is not properly set\n        up, that debugging information is lost.  (For example it would only\n        pick up SQL queries in `yourapplication.app` and not\n        `yourapplication.views.frontend`)\n\n    .. versionadded:: 0.7\n       The `static_url_path`, `static_folder`, and `template_folder`\n       parameters were added.\n\n    .. versionadded:: 0.8\n       The `instance_path` and `instance_relative_config` parameters were\n       added.\n\n    .. versionadded:: 0.11\n       The `root_path` parameter was added.\n\n    .. versionadded:: 1.0\n       The ``host_matching`` and ``static_host`` parameters were added.\n\n    .. versionadded:: 1.0\n       The ``subdomain_matching`` parameter was added. Subdomain\n       matching needs to be enabled manually now. Setting\n       :data:`SERVER_NAME` does not implicitly enable it.\n\n    :param import_name: the name of the application package\n    :param static_url_path: can be used to specify a different path for the\n                            static files on the web.  Defaults to the name\n                            of the `static_folder` folder.\n    :param static_folder: The folder with static files that is served at\n        ``static_url_path``. Relative to the application ``root_path``\n        or an absolute path. Defaults to ``'static'``.\n    :param static_host: the host to use when adding the static route.\n        Defaults to None. Required when using ``host_matching=True``\n        with a ``static_folder`` configured.\n    :param host_matching: set ``url_map.host_matching`` attribute.\n        Defaults to False.\n    :param subdomain_matching: consider the subdomain relative to\n        :data:`SERVER_NAME` when matching routes. Defaults to False.\n    :param template_folder: the folder that contains the templates that should\n                            be used by the application.  Defaults to\n                            ``'templates'`` folder in the root path of the\n                            application.\n    :param instance_path: An alternative instance path for the application.\n                          By default the folder ``'instance'`` next to the\n                          package or module is assumed to be the instance\n                          path.\n    :param instance_relative_config: if set to ``True`` relative filenames\n                                     for loading the config are assumed to\n                                     be relative to the instance path instead\n                                     of the application root.\n    :param root_path: The path to the root of the application files.\n        This should only be set manually when it can't be detected\n        automatically, such as for namespace packages.\n    \"\"\"\n\n    default_config = ImmutableDict(\n        {\n            \"DEBUG\": None,\n            \"TESTING\": False,\n            \"PROPAGATE_EXCEPTIONS\": None,\n            \"SECRET_KEY\": None,\n            \"SECRET_KEY_FALLBACKS\": None,\n            \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n            \"USE_X_SENDFILE\": False,\n            \"TRUSTED_HOSTS\": None,\n            \"SERVER_NAME\": None,\n            \"APPLICATION_ROOT\": \"/\",\n            \"SESSION_COOKIE_NAME\": \"session\",\n            \"SESSION_COOKIE_DOMAIN\": None,\n            \"SESSION_COOKIE_PATH\": None,\n            \"SESSION_COOKIE_HTTPONLY\": True,\n            \"SESSION_COOKIE_SECURE\": False,\n            \"SESSION_COOKIE_PARTITIONED\": False,\n            \"SESSION_COOKIE_SAMESITE\": None,\n            \"SESSION_REFRESH_EACH_REQUEST\": True,\n            \"MAX_CONTENT_LENGTH\": None,\n            \"MAX_FORM_MEMORY_SIZE\": 500_000,\n            \"MAX_FORM_PARTS\": 1_000,\n            \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n            \"TRAP_BAD_REQUEST_ERRORS\": None,\n            \"TRAP_HTTP_EXCEPTIONS\": False,\n            \"EXPLAIN_TEMPLATE_LOADING\": False,\n            \"PREFERRED_URL_SCHEME\": \"http\",\n            \"TEMPLATES_AUTO_RELOAD\": None,\n            \"MAX_COOKIE_SIZE\": 4093,\n            \"PROVIDE_AUTOMATIC_OPTIONS\": True,\n        }\n    )\n\n    #: The class that is used for request objects.  See :class:`~flask.Request`\n    #: for more information.\n    request_class: type[Request] = Request\n\n    #: The class that is used for response objects.  See\n    #: :class:`~flask.Response` for more information.\n    response_class: type[Response] = Response\n\n    #: the session interface to use.  By default an instance of\n    #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n    #:\n    #: .. versionadded:: 0.8\n    session_interface: SessionInterface = SecureCookieSessionInterface()\n\n    def __init_subclass__(cls, **J: t.Any) -> None:\n        import warnings\n\n        # These method signatures were updated to take a ctx param. Detect\n        # overridden methods in subclasses that still have the old signature.\n        # Show a deprecation warning and wrap to call with correct args.\n        for K in (\n            cls.o,\n            cls.p,\n            cls.q,\n            cls.r,\n            cls.s,\n            cls.u,\n            cls.v,\n            cls.w,\n            cls.B,\n            cls.C,\n            cls.D,\n            cls.E,\n        ):\n            L = getattr(Flask, K.__name__)\n\n            if K is L:\n                # not overridden\n                continue\n\n            # get the second parameter (first is self)\n            M = iter(inspect.signature(K).parameters.values())\n            next(M)\n            N = next(M, None)\n\n            # must have second parameter named ctx or annotated AppContext\n            if N is None or not (\n                # no annotation, match name\n                (N.annotation is inspect.Parameter.empty and N.name == \"ctx\")\n                or (\n                    # string annotation, access path ends with AppContext\n                    isinstance(N.annotation, str)\n                    and N.annotation.rpartition(\".\")[2] == \"AppContext\"\n                )\n                or (\n                    # class annotation\n                    inspect.isclass(N.annotation)\n                    and issubclass(N.annotation, AppContext)\n                )\n            ):\n                warnings.warn(\n                    f\"The '{K.__name__}' method now takes 'ctx: AppContext'\"\n                    \" as the first parameter. The old signature is deprecated\"\n                    \" and will not be supported in Flask 4.0.\",\n                    DeprecationWarning,\n                    stacklevel=2,\n                )\n                setattr(cls, K.__name__, remove_ctx(K))\n                setattr(Flask, K.__name__, add_ctx(L))\n\n    def __init__(\n        self,\n        O: str,\n        P: str | None = None,\n        Q: str | os.PathLike[str] | None = \"static\",\n        R: str | None = None,\n        S: bool = False,\n        T: bool = False,\n        U: str | os.PathLike[str] | None = \"templates\",\n        V: str | None = None,\n        W: bool = False,\n        X: str | None = None,\n    ):\n        super().__init__(\n            import_name=O,\n            static_url_path=P,\n            static_folder=Q,\n            static_host=R,\n            host_matching=S,\n            subdomain_matching=T,\n            template_folder=U,\n            instance_path=V,\n            instance_relative_config=W,\n            root_path=X,\n        )\n\n        #: The Click command group for registering CLI commands for this\n        #: object. The commands are available from the ``flask`` command\n        #: once the application has been discovered and blueprints have\n        #: been registered.\n        self.cli = cli.AppGroup()\n\n        # Set the name of the Click group in case someone wants to add\n        # the app's commands to another CLI tool.\n        self.cli.name = self.name\n\n        # Add a static route using the provided static_url_path, static_host,\n        # and static_folder if there is a configured static_folder.\n        # Note we do this without checking if static_folder exists.\n        # For one, it might be created while the server is running (e.g. during\n        # development). Also, Google App Engine stores static files somewhere\n        if self.has_static_folder:\n            assert bool(R) == S, (\n                \"Invalid static_host/host_matching combination\"\n            )\n            # Use a weakref to avoid creating a reference cycle between the app\n            # and the view function (see #3761).\n            Y = weakref.ref(self)\n            self.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                endpoint=\"static\",\n                host=R,\n                view_func=lambda **kw: Y().send_static_file(**kw),  # type: ignore\n            )\n\n    def a(self, Z: str | None) -> int | None:\n        \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n        value for a given file path if it wasn't passed.\n\n        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n        the configuration of :data:`~flask.current_app`. This defaults\n        to ``None``, which tells the browser to use conditional requests\n        instead of a timed cache, which is usually preferable.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionchanged:: 2.0\n            The default configuration is ``None`` instead of 12 hours.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        aa = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n        if aa is None:\n            return None\n\n        if isinstance(aa, timedelta):\n            return int(aa.total_seconds())\n\n        return aa  # type: ignore[no-any-return]\n\n    def b(self, ab: str) -> Response:\n        \"\"\"The view function used to serve files from\n        :attr:`static_folder`. A route is automatically registered for\n        this view at :attr:`static_url_path` if :attr:`static_folder` is\n        set.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionadded:: 0.5\n\n        \"\"\"\n        if not self.has_static_folder:\n            raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n        # send_file only knows to call get_send_file_max_age on the app,\n        # call it here so it works for blueprints too.\n        ac = self.a(ab)\n        return send_from_directory(\n            t.cast(str, self.static_folder), ab, max_age=ac\n        )\n\n    def c(\n        self, ad: str, ae: str = \"rb\", af: str | None = None\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to :attr:`root_path` for reading.\n\n        For example, if the file ``schema.sql`` is next to the file\n        ``app.py`` where the ``Flask`` app is defined, it can be opened\n        with:\n\n        .. code-block:: python\n\n            with app.open_resource(\"schema.sql\") as f:\n                conn.executescript(f.read())\n\n        :param resource: Path to the resource relative to :attr:`root_path`.\n        :param mode: Open the file in this mode. Only reading is supported,\n            valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        if ae not in {\"r\", \"rt\", \"rb\"}:\n            raise ValueError(\"Resources can only be opened for reading.\")\n\n        ag = os.path.join(self.root_path, ad)\n\n        if ae == \"rb\":\n            return open(ag, ae)  # pyright: ignore\n\n        return open(ag, ae, encoding=af)\n\n    def d(\n        self, ah: str, ai: str = \"rb\", aj: str | None = \"utf-8\"\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to the application's instance folder\n        :attr:`instance_path`. Unlike :meth:`open_resource`, files in the\n        instance folder can be opened for writing.\n\n        :param resource: Path to the resource relative to :attr:`instance_path`.\n        :param mode: Open the file in this mode.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        ak = os.path.join(self.instance_path, ah)\n\n        if \"b\" in ai:\n            return open(ak, ai)\n\n        return open(ak, ai, encoding=aj)\n\n    def f(self) -> Environment:\n        \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n        and the various Jinja-related methods of the app. Changing\n        :attr:`jinja_options` after this will have no effect. Also adds\n        Flask-related globals and filters to the environment.\n\n        .. versionchanged:: 0.11\n           ``Environment.auto_reload`` set in accordance with\n           ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        al = dict(self.jinja_options)\n\n        if \"autoescape\" not in al:\n            al[\"autoescape\"] = self.select_jinja_autoescape\n\n        if \"auto_reload\" not in al:\n            am = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n            if am is None:\n                am = self.debug\n\n            al[\"auto_reload\"] = am\n\n        an = self.jinja_environment(self, **al)\n        an.globals.update(\n            url_for=self.z,\n            get_flashed_messages=get_flashed_messages,\n            config=self.config,\n            # request, session and g are normally added with the\n            # context processor for efficiency reasons but for imported\n            # templates we also want the proxies in there.\n            request=request,\n            session=session,\n            g=g,\n        )\n        an.policies[\"json.dumps_function\"] = self.json.dumps\n        return an\n\n    def h(self, ao: Request | None) -> MapAdapter | None:\n        \"\"\"Creates a URL adapter for the given request. The URL adapter\n        is created at a point where the request context is not yet set\n        up so the request is passed explicitly.\n\n        .. versionchanged:: 3.1\n            If :data:`SERVER_NAME` is set, it does not restrict requests to\n            only that domain, for both ``subdomain_matching`` and\n            ``host_matching``.\n\n        .. versionchanged:: 1.0\n            :data:`SERVER_NAME` no longer implicitly enables subdomain\n            matching. Use :attr:`subdomain_matching` instead.\n\n        .. versionchanged:: 0.9\n           This can be called outside a request when the URL adapter is created\n           for an application context.\n\n        .. versionadded:: 0.6\n        \"\"\"\n        if ao is not None:\n            if (ap := self.config[\"TRUSTED_HOSTS\"]) is not None:\n                ao.trusted_hosts = ap\n\n            # Check trusted_hosts here until bind_to_environ does.\n            ao.host = get_host(ao.environ, ao.trusted_hosts)  # pyright: ignore\n            aq = None\n            ar = self.config[\"SERVER_NAME\"]\n\n            if self.url_map.host_matching:\n                # Don't pass SERVER_NAME, otherwise it's used and the actual\n                # host is ignored, which breaks host matching.\n                ar = None\n            elif not self.subdomain_matching:\n                # Werkzeug doesn't implement subdomain matching yet. Until then,\n                # disable it by forcing the current subdomain to the default, or\n                # the empty string.\n                aq = self.url_map.default_subdomain or \"\"\n\n            return self.url_map.bind_to_environ(\n                ao.environ, server_name=ar, subdomain=aq\n            )\n\n        # Need at least SERVER_NAME to match/build outside a request.\n        if self.config[\"SERVER_NAME\"] is not None:\n            return self.url_map.bind(\n                self.config[\"SERVER_NAME\"],\n                script_name=self.config[\"APPLICATION_ROOT\"],\n                url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n            )\n\n        return None\n\n    def i(self, at: Request) -> t.NoReturn:\n        \"\"\"Intercept routing exceptions and possibly do something else.\n\n        In debug mode, intercept a routing redirect and replace it with\n        an error if the body will be discarded.\n\n        With modern Werkzeug this shouldn't occur, since it now uses a\n        308 status which tells the browser to resend the method and\n        body.\n\n        .. versionchanged:: 2.1\n            Don't intercept 307 and 308 redirects.\n\n        :meta private:\n        :internal:\n        \"\"\"\n        if (\n            not self.debug\n            or not isinstance(at.routing_exception, RequestRedirect)\n            or at.routing_exception.code in {307, 308}\n            or at.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n        ):\n            raise at.routing_exception  # type: ignore[misc]\n\n        from .debughelpers import FormDataRoutingRedirect\n\n        raise FormDataRoutingRedirect(at)\n\n    def j(\n        self, au: AppContext, av: dict[str, t.Any]\n    ) -> None:\n        \"\"\"Update the template context with some commonly used variables.\n        This injects request, session, config and g into the template\n        context as well as everything template context processors want\n        to inject.  Note that the as of Flask 0.6, the original values\n        in the context will not be overridden if a context processor\n        decides to return a value with the same key.\n\n        :param context: the context as a dictionary that is updated in place\n                        to add extra variables.\n        \"\"\"\n        aw: t.Iterable[str | None] = (None,)\n\n        # A template may be rendered outside a request context.\n        if au.has_request:\n            aw = chain(aw, reversed(au.request.blueprints))\n\n        # The values passed to render_template take precedence. Keep a\n        # copy to re-apply after all context functions.\n        ax = av.copy()\n\n        for ay in aw:\n            if ay in self.template_context_processors:\n                for az in self.template_context_processors[ay]:\n                    av.update(self.x(az)())\n\n        av.update(ax)\n\n    def k(self) -> dict[str, t.Any]:\n        \"\"\"Returns the shell context for an interactive shell for this\n        application.  This runs all the registered shell context\n        processors.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        aA = {\"app\": self, \"g\": g}\n        for aB in self.shell_context_processors:\n            aA.update(aB())\n        return aA\n\n    def l(\n        self,\n        aC: str | None = None,\n        aD: int | None = None,\n        aE: bool | None = None,\n        aF: bool = True,\n        **aG: t.Any,\n    ) -> None:\n        \"\"\"Runs the application on a local development server.\n\n        Do not use ``run()`` in a production setting. It is not intended to\n        meet security and performance requirements for a production server.\n        Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n        If the :attr:`debug` flag is set the server will automatically reload\n        for code changes and show a debugger in case an exception happened.\n\n        If you want to run the application in debug mode, but disable the\n        code execution on the interactive debugger, you can pass\n        ``use_evalex=False`` as parameter.  This will keep the debugger's\n        traceback screen active, but disable code execution.\n\n        It is not recommended to use this function for development with\n        automatic reloading as this is badly supported.  Instead you should\n        be using the :command:`flask` command line script's ``run`` support.\n\n        .. admonition:: Keep in Mind\n\n           Flask will suppress any server error with a generic error page\n           unless it is in debug mode.  As such to enable just the\n           interactive debugger without the code reloading, you have to\n           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n           Setting ``use_debugger`` to ``True`` without being in debug mode\n           won't catch any exceptions because there won't be any to\n           catch.\n\n        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n            have the server available externally as well. Defaults to\n            ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n            if present.\n        :param port: the port of the webserver. Defaults to ``5000`` or the\n            port defined in the ``SERVER_NAME`` config variable if present.\n        :param debug: if given, enable or disable debug mode. See\n            :attr:`debug`.\n        :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n            files to set environment variables. Will also change the working\n            directory to the directory containing the first file found.\n        :param options: the options to be forwarded to the underlying Werkzeug\n            server. See :func:`werkzeug.serving.run_simple` for more\n            information.\n\n        .. versionchanged:: 1.0\n            If installed, python-dotenv will be used to load environment\n            variables from :file:`.env` and :file:`.flaskenv` files.\n\n            The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.\n\n            Threaded mode is enabled by default.\n\n        .. versionchanged:: 0.10\n            The default port is now picked from the ``SERVER_NAME``\n            variable.\n        \"\"\"\n        # Ignore this call so that it doesn't start another server if\n        # the 'flask run' command is used.\n        if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n            if not is_running_from_reloader():\n                click.secho(\n                    \" * Ignoring a call to 'app.run()' that would block\"\n                    \" the current 'flask' CLI command.\\n\"\n                    \"   Only call 'app.run()' in an 'if __name__ ==\"\n                    ' \"__main__\"\\' guard.',\n                    fg=\"red\",\n                )\n\n            return\n\n        if get_load_dotenv(aF):\n            cli.load_dotenv()\n\n            # if set, env var overrides existing value\n            if \"FLASK_DEBUG\" in os.environ:\n                self.debug = get_debug_flag()\n\n        # debug passed to method overrides all other sources\n        if aE is not None:\n            self.debug = bool(aE)\n\n        aH = self.config.get(\"SERVER_NAME\")\n        aI = aJ = None\n\n        if aH:\n            aK = urlsplit(f\"//{aH}\")\n            aI = aK.hostname\n            aJ = aK.port\n\n        if not aC:\n            if aI:\n                aC = aI\n            else:\n                aC = \"127.0.0.1\"\n\n        if aD or aD == 0:\n            aD = int(aD)\n        elif aJ is not None:\n            aD = aJ\n        else:\n            aD = 5000\n\n        aG.setdefault(\"use_reloader\", self.debug)\n        aG.setdefault(\"use_debugger\", self.debug)\n        aG.setdefault(\"threaded\", True)\n\n        cli.show_server_banner(self.debug, self.name)\n\n        from werkzeug.serving import run_simple\n\n        try:\n            run_simple(aC, aD, self, **aG)\n        finally:\n            # reset the first request information if the development server\n            # reset normally.  This makes it possible to restart the server\n            # without reloader and that stuff from an interactive shell.\n            self._got_first_request = False\n\n    def m(self, aL: bool = True, **aM: t.Any) -> FlaskClient:\n        \"\"\"Creates a test client for this application.  For information\n        about unit testing head over to :doc:`/testing`.\n\n        Note that if you are testing for assertions or exceptions in your\n        application code, you must set ``app.testing = True`` in order for the\n        exceptions to propagate to the test client.  Otherwise, the exception\n        will be handled by the application (not visible to the test client) and\n        the only indication of an AssertionError or other exception will be a\n        500 status code response to the test client.  See the :attr:`testing`\n        attribute.  For example::\n\n            app.testing = True\n            client = app.test_client()\n\n        The test client can be used in a ``with`` block to defer the closing down\n        of the context until the end of the ``with`` block.  This is useful if\n        you want to access the context locals for testing::\n\n            with app.test_client() as c:\n                rv = c.get('/?vodka=42')\n                assert request.args['vodka'] == '42'\n\n        Additionally, you may pass optional keyword arguments that will then\n        be passed to the application's :attr:`test_client_class` constructor.\n        For example::\n\n            from flask.testing import FlaskClient\n\n            class CustomClient(FlaskClient):\n                def __init__(self, *args, **kwargs):\n                    self._authentication = kwargs.pop(\"authentication\")\n                    super(CustomClient,self).__init__( *args, **kwargs)\n\n            app.test_client_class = CustomClient\n            client = app.test_client(authentication='Basic ....')\n\n        See :class:`~flask.testing.FlaskClient` for more information.\n\n        .. versionchanged:: 0.4\n           added support for ``with`` block usage for the client.\n\n        .. versionadded:: 0.7\n           The `use_cookies` parameter was added as well as the ability\n           to override the client to be used by setting the\n           :attr:`test_client_class` attribute.\n\n        .. versionchanged:: 0.11\n           Added `**kwargs` to support passing additional keyword arguments to\n           the constructor of :attr:`test_client_class`.\n        \"\"\"\n        aN = self.test_client_class\n        if aN is None:\n            from .testing import FlaskClient as cls\n        return aN(  # type: ignore\n            self, self.response_class, use_cookies=aL, **aM\n        )\n\n    def n(self, **aO: t.Any) -> FlaskCliRunner:\n        \"\"\"Create a CLI runner for testing CLI commands.\n        See :ref:`testing-cli`.\n\n        Returns an instance of :attr:`test_cli_runner_class`, by default\n        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n        passed as the first argument.\n\n        .. versionadded:: 1.0\n        \"\"\"\n        aP = self.test_cli_runner_class\n\n        if aP is None:\n            from .testing import FlaskCliRunner as cls\n\n        return aP(self, **aO)  # type: ignore\n\n    def o(\n        self, aQ: AppContext, aR: HTTPException\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"Handles an HTTP exception.  By default this will invoke the\n        registered error handlers and fall back to returning the\n        exception as response.\n\n        .. versionchanged:: 1.0.3\n            ``RoutingException``, used internally for actions such as\n             slash redirects during routing, is not passed to error\n             handlers.\n\n        .. versionchanged:: 1.0\n            Exceptions are looked up by code *and* by MRO, so\n            ``HTTPException`` subclasses can be handled with a catch-all\n            handler for the base ``HTTPException``.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        # Proxy exceptions don't have error codes.  We want to always return\n        # those unchanged as errors\n        if aR.code is None:\n            return aR\n\n        # RoutingExceptions are used internally to trigger routing\n        # actions, such as slash redirects raising RequestRedirect. They\n        # are not raised or handled in user code.\n        if isinstance(aR, RoutingException):\n            return aR\n\n        aS = self._find_error_handler(aR, aQ.request.blueprints)\n        if aS is None:\n            return aR\n        return self.x(aS)(aR)  # type: ignore[no-any-return]\n\n    def p(\n        self, aT: AppContext, aU: Exception\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"This method is called whenever an exception occurs that\n        should be handled. A special case is :class:`~werkzeug\n        .exceptions.HTTPException` which is forwarded to the\n        :meth:`handle_http_exception` method. This function will either\n        return a response value or reraise the exception with the same\n        traceback.\n\n        .. versionchanged:: 1.0\n            Key errors raised from request data like ``form`` show the\n            bad key in debug mode rather than a generic bad request\n            message.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if isinstance(aU, BadRequestKeyError) and (\n            self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n        ):\n            aU.show_exception = True\n\n        if isinstance(aU, HTTPException) and not self.trap_http_exception(aU):\n            return self.o(aT, aU)\n\n        aV = self._find_error_handler(aU, aT.request.blueprints)\n\n        if aV is None:\n            raise\n\n        return self.x(aV)(aU)  # type: ignore[no-any-return]\n\n    def q(self, aW: AppContext, aX: Exception) -> Response:\n        \"\"\"Handle an exception that did not have an error handler\n        associated with it, or that was raised from an error handler.\n        This always causes a 500 ``InternalServerError``.\n\n        Always sends the :data:`got_request_exception` signal.\n\n        If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n        mode, the error will be re-raised so that the debugger can\n        display it. Otherwise, the original exception is logged, and\n        an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n        If an error handler is registered for ``InternalServerError`` or\n        ``500``, it will be used. For consistency, the handler will\n        always receive the ``InternalServerError``. The original\n        unhandled exception is available as ``e.original_exception``.\n\n        .. versionchanged:: 1.1.0\n            Always passes the ``InternalServerError`` instance to the\n            handler, setting ``original_exception`` to the unhandled\n            error.\n\n        .. versionchanged:: 1.1.0\n            ``after_request`` functions and other finalization is done\n            even for the default 500 response when there is no handler.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        aY = sys.exc_info()\n        got_request_exception.send(self, _async_wrapper=self.x, exception=aX)\n        aZ = self.config[\"PROPAGATE_EXCEPTIONS\"]\n\n        if aZ is None:\n            aZ = self.testing or self.debug\n\n        if aZ:\n            # Re-raise if called with an active exception, otherwise\n            # raise the passed in exception.\n            if aY[1] is aX:\n                raise\n\n            raise aX\n\n        self.r(aW, aY)\n        ba: InternalServerError | ft.ResponseReturnValue\n        ba = InternalServerError(original_exception=aX)\n        bb = self._find_error_handler(ba, aW.request.blueprints)\n\n        if bb is not None:\n            ba = self.x(bb)(ba)\n\n        return self.v(aW, ba, from_error_handler=True)\n\n    def r(\n        self,\n        bc: AppContext,\n        bd: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n    ) -> None:\n        \"\"\"Logs an exception.  This is called by :meth:`handle_exception`\n        if debugging is disabled and right before the handler is called.\n        The default implementation logs the exception as error on the\n        :attr:`logger`.\n\n        .. versionadded:: 0.8\n        \"\"\"\n        self.logger.error(\n            f\"Exception on {bc.request.path} [{bc.request.method}]\", exc_info=bd\n        )\n\n    def s(self, be: AppContext) -> ft.ResponseReturnValue:\n        \"\"\"Does the request dispatching.  Matches the URL and returns the\n        return value of the view or error handler.  This does not have to\n        be a response object.  In order to convert the return value to a\n        proper response object, call :func:`make_response`.\n\n        .. versionchanged:: 0.7\n           This no longer does the exception handling, this code was\n           moved to the new :meth:`full_dispatch_request`.\n        \"\"\"\n        bf = be.request\n\n        if bf.routing_exception is not None:\n            self.i(bf)\n        bg: Rule = bf.url_rule  # type: ignore[assignment]\n        # if we provide automatic options for this URL and the\n        # request came with the OPTIONS method, reply automatically\n        if (\n            getattr(bg, \"provide_automatic_options\", False)\n            and bf.method == \"OPTIONS\"\n        ):\n            return self.w(be)\n        # otherwise dispatch to the handler for that endpoint\n        bh: dict[str, t.Any] = bf.view_args  # type: ignore[assignment]\n        return self.x(self.view_functions[bg.endpoint])(**bh)  # type: ignore[no-any-return]\n\n    def u(self, bi: AppContext) -> Response:\n        \"\"\"Dispatches the request and on top of that performs request\n        pre and postprocessing as well as HTTP exception catching and\n        error handling.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if not self._got_first_request and self.should_ignore_error is not None:\n            import warnings\n\n            warnings.warn(\n                \"The 'should_ignore_error' method is deprecated and will\"\n                \" be removed in Flask 3.3. Handle errors as needed in\"\n                \" teardown handlers instead.\",\n                DeprecationWarning,\n                stacklevel=1,\n            )\n\n        self._got_first_request = True\n\n        try:\n            request_started.send(self, _async_wrapper=self.x)\n            bj = self.B(bi)\n            if bj is None:\n                bj = self.s(bi)\n        except Exception as e:\n            bj = self.p(bi, e)\n        return self.v(bi, bj)\n\n    def v(\n        self,\n        bk: AppContext,\n        bl: ft.ResponseReturnValue | HTTPException,\n        bm: bool = False,\n    ) -> Response:\n        \"\"\"Given the return value from a view function this finalizes\n        the request by converting it into a response and invoking the\n        postprocessing functions.  This is invoked for both normal\n        request dispatching as well as error handlers.\n\n        Because this means that it might be called as a result of a\n        failure a special safe mode is available which can be enabled\n        with the `from_error_handler` flag.  If enabled, failures in\n        response processing will be logged and otherwise ignored.\n\n        :internal:\n        \"\"\"\n        bn = self.A(bl)\n        try:\n            bn = self.C(bk, bn)\n            request_finished.send(\n                self, _async_wrapper=self.x, response=bn\n            )\n        except Exception:\n            if not bm:\n                raise\n            self.logger.exception(\n                \"Request finalizing failed with an error while handling an error\"\n            )\n        return bn\n\n    def w(self, bo: AppContext) -> Response:\n        \"\"\"This method is called to create the default ``OPTIONS`` response.\n        This can be changed through subclassing to change the default\n        behavior of ``OPTIONS`` responses.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        bp = bo.url_adapter.allowed_methods()  # type: ignore[union-attr]\n        bq = self.response_class()\n        bq.allow.update(bp)\n        return bq\n\n    def x(self, br: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n        \"\"\"Ensure that the function is synchronous for WSGI workers.\n        Plain ``def`` functions are returned as-is. ``async def``\n        functions are wrapped to run and wait for the response.\n\n        Override this method to change how the app runs async views.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if iscoroutinefunction(br):\n            return self.y(br)\n\n        return br\n\n    def y(\n        self, bs: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n    ) -> t.Callable[..., t.Any]:\n        \"\"\"Return a sync function that will run the coroutine function.\n\n        .. code-block:: python\n\n            result = app.async_to_sync(func)(*args, **kwargs)\n\n        Override this method to change how the app converts async code\n        to be synchronously callable.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        try:\n            from asgiref.sync import async_to_sync as asgiref_async_to_sync\n        except ImportError:\n            raise RuntimeError(\n                \"Install Flask with the 'async' extra in order to use async views.\"\n            ) from None\n\n        return asgiref_async_to_sync(bs)\n\n    def z(\n        self,\n        /,\n        bt: str,\n        *,\n        bu: str | None = None,\n        bv: str | None = None,\n        bw: str | None = None,\n        bx: bool | None = None,\n        **by: t.Any,\n    ) -> str:\n        \"\"\"Generate a URL to the given endpoint with the given values.\n\n        This is called by :func:`flask.url_for`, and can be called\n        directly as well.\n\n        An *endpoint* is the name of a URL rule, usually added with\n        :meth:`@app.route() <route>`, and usually the same name as the\n        view function. A route defined in a :class:`~flask.Blueprint`\n        will prepend the blueprint's name separated by a ``.`` to the\n        endpoint.\n\n        In some cases, such as email messages, you want URLs to include\n        the scheme and domain, like ``https://example.com/hello``. When\n        not in an active request, URLs will be external by default, but\n        this requires setting :data:`SERVER_NAME` so Flask knows what\n        domain to use. :data:`APPLICATION_ROOT` and\n        :data:`PREFERRED_URL_SCHEME` should also be configured as\n        needed. This config is only used when not in an active request.\n\n        Functions can be decorated with :meth:`url_defaults` to modify\n        keyword arguments before the URL is built.\n\n        If building fails for some reason, such as an unknown endpoint\n        or incorrect values, the app's :meth:`handle_url_build_error`\n        method is called. If that returns a string, that is returned,\n        otherwise a :exc:`~werkzeug.routing.BuildError` is raised.\n\n        :param endpoint: The endpoint name associated with the URL to\n            generate. If this starts with a ``.``, the current blueprint\n            name (if any) will be used.\n        :param _anchor: If given, append this as ``#anchor`` to the URL.\n        :param _method: If given, generate the URL associated with this\n            method for the endpoint.\n        :param _scheme: If given, the URL will have this scheme if it\n            is external.\n        :param _external: If given, prefer the URL to be internal\n            (False) or require it to be external (True). External URLs\n            include the scheme and domain. When not in an active\n            request, URLs are external by default.\n        :param values: Values to use for the variable parts of the URL\n            rule. Unknown keys are appended as query string arguments,\n            like ``?a=b&c=d``.\n\n        .. versionadded:: 2.2\n            Moved from ``flask.url_for``, which calls this method.\n        \"\"\"\n        if (bz := _cv_app.get(None)) is not None and bz.has_request:\n            bA = bz.url_adapter\n            bB = bz.request.blueprint\n\n            # If the endpoint starts with \".\" and the request matches a\n            # blueprint, the endpoint is relative to the blueprint.\n            if bt[:1] == \".\":\n                if bB is not None:\n                    bt = f\"{bB}{bt}\"\n                else:\n                    bt = bt[1:]\n\n            # When in a request, generate a URL without scheme and\n            # domain by default, unless a scheme is given.\n            if bx is None:\n                bx = bw is not None\n        else:\n            # If called by helpers.url_for, an app context is active,\n            # use its url_adapter. Otherwise, app.url_for was called\n            # directly, build an adapter.\n            if bz is not None:\n                bA = bz.url_adapter\n            else:\n                bA = self.h(None)\n\n            if bA is None:\n                raise RuntimeError(\n                    \"Unable to build URLs outside an active request\"\n                    \" without 'SERVER_NAME' configured. Also configure\"\n                    \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n                    \" needed.\"\n                )\n\n            # When outside a request, generate a URL with scheme and\n            # domain by default.\n            if bx is None:\n                bx = True\n\n        # It is an error to set _scheme when _external=False, in order\n        # to avoid accidental insecure URLs.\n        if bw is not None and not bx:\n            raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n        self.inject_url_defaults(bt, by)\n\n        try:\n            bC = bA.build(  # type: ignore[union-attr]\n                bt,\n                by,\n                method=bv,\n                url_scheme=bw,\n                force_external=bx,\n            )\n        except BuildError as error:\n            by.update(\n                _anchor=bu, _method=bv, _scheme=bw, _external=bx\n            )\n            return self.handle_url_build_error(error, bt, by)\n\n        if bu is not None:\n            bu = _url_quote(bu, safe=\"%!#$&'()*+,/:;=?@\")\n            bC = f\"{bC}#{bu}\"\n\n        return bC\n\n    def A(self, bD: ft.ResponseReturnValue) -> Response:\n        \"\"\"Convert the return value from a view function to an instance of\n        :attr:`response_class`.\n\n        :param rv: the return value from the view function. The view function\n            must return a response. Returning ``None``, or the view ending\n            without returning, is not allowed. The following types are allowed\n            for ``view_rv``:\n\n            ``str``\n                A response object is created with the string encoded to UTF-8\n                as the body.\n\n            ``bytes``\n                A response object is created with the bytes as the body.\n\n            ``dict``\n                Converted to a JSON response.\n\n            ``list``\n                Converted to a JSON response.\n\n            ``generator`` or ``iterator``\n                A generator that returns ``str`` or ``bytes`` to be\n                streamed as the response.\n\n            ``tuple``\n                Either ``(body, status, headers)``, ``(body, status)``, or\n                ``(body, headers)``, where ``body`` is any of the other types\n                allowed here, ``status`` is a string or an integer, and\n                ``headers`` is a dictionary or a list of ``(key, value)``\n                tuples. If ``body`` is a :attr:`response_class` instance,\n                ``status`` overwrites the exiting value and ``headers`` are\n                extended.\n\n            :attr:`response_class`\n                The object is returned unchanged.\n\n            other :class:`~werkzeug.wrappers.Response` class\n                The object is coerced to :attr:`response_class`.\n\n            :func:`callable`\n                The function is called as a WSGI application. The result is\n                used to create a response object.\n\n        .. versionchanged:: 2.2\n            A generator will be converted to a streaming response.\n            A list will be converted to a JSON response.\n\n        .. versionchanged:: 1.1\n            A dict will be converted to a JSON response.\n\n        .. versionchanged:: 0.9\n           Previously a tuple was interpreted as the arguments for the\n           response object.\n        \"\"\"\n\n        bE: int | None = None\n        bF: HeadersValue | None = None\n\n        # unpack tuple returns\n        if isinstance(bD, tuple):\n            bG = len(bD)\n\n            # a 3-tuple is unpacked directly\n            if bG == 3:\n                bD, bE, bF = bD  # type: ignore[misc]\n            # decide if a 2-tuple has status or headers\n            elif bG == 2:\n                if isinstance(bD[1], (Headers, dict, tuple, list)):\n                    bD, bF = bD  # pyright: ignore\n                else:\n                    bD, bE = bD  # type: ignore[assignment,misc]\n            # other sized tuples are not allowed\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid response tuple.\"\n                    \" The tuple must have the form (body, status, headers),\"\n                    \" (body, status), or (body, headers).\"\n                )\n\n        # the body must not be None\n        if bD is None:\n            raise TypeError(\n                f\"The view function for {request.endpoint!r} did not\"\n                \" return a valid response. The function either returned\"\n                \" None or ended without a return statement.\"\n            )\n\n        # make sure the body is an instance of the response class\n        if not isinstance(bD, self.response_class):\n            if isinstance(bD, (str, bytes, bytearray)) or isinstance(bD, cabc.Iterator):\n                # let the response class set the status and headers instead of\n                # waiting to do it manually, so that the class can handle any\n                # special logic\n                bD = self.response_class(\n                    bD,  # pyright: ignore\n                    status=bE,\n                    headers=bF,  # type: ignore[arg-type]\n                )\n                bE = bF = None\n            elif isinstance(bD, (dict, list)):\n                bD = self.json.response(bD)\n            elif isinstance(bD, BaseResponse) or callable(bD):\n                # evaluate a WSGI callable, or coerce a different response\n                # class to the correct type\n                try:\n                    bD = self.response_class.force_type(\n                        bD,  # type: ignore[arg-type]\n                        request.environ,\n                    )\n                except TypeError as e:\n                    raise TypeError(\n                        f\"{e}\\nThe view function did not return a valid\"\n                        \" response. The return type must be a string,\"\n                        \" dict, list, tuple with headers or status,\"\n                        \" Response instance, or WSGI callable, but it\"\n                        f\" was a {type(bD).__name__}.\"\n                    ).with_traceback(sys.exc_info()[2]) from None\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid\"\n                    \" response. The return type must be a string,\"\n                    \" dict, list, tuple with headers or status,\"\n                    \" Response instance, or WSGI callable, but it was a\"\n                    f\" {type(bD).__name__}.\"\n                )\n\n        bD = t.cast(Response, bD)\n        # prefer the status if it was provided\n        if bE is not None:\n            if isinstance(bE, (str, bytes, bytearray)):\n                bD.status = bE\n            else:\n                bD.status_code = bE\n\n        # extend existing headers with provided headers\n        if bF:\n            bD.headers.update(bF)\n\n        return bD\n\n    def B(self, bH: AppContext) -> ft.ResponseReturnValue | None:\n        \"\"\"Called before the request is dispatched. Calls\n        :attr:`url_value_preprocessors` registered with the app and the\n        current blueprint (if any). Then calls :attr:`before_request_funcs`\n        registered with the app and the blueprint.\n\n        If any :meth:`before_request` handler returns a non-None value, the\n        value is handled as if it was the return value from the view, and\n        further request handling is stopped.\n        \"\"\"\n        bI = bH.request\n        bJ = (None, *reversed(bI.blueprints))\n\n        for bK in bJ:\n            if bK in self.url_value_preprocessors:\n                for bL in self.url_value_preprocessors[bK]:\n                    bL(bI.endpoint, bI.view_args)\n\n        for bK in bJ:\n            if bK in self.before_request_funcs:\n                for bM in self.before_request_funcs[bK]:\n                    bN = self.x(bM)()\n\n                    if bN is not None:\n                        return bN  # type: ignore[no-any-return]\n\n        return None\n\n    def C(self, bO: AppContext, bP: Response) -> Response:\n        \"\"\"Can be overridden in order to modify the response object\n        before it's sent to the WSGI server.  By default this will\n        call all the :meth:`after_request` decorated functions.\n\n        .. versionchanged:: 0.5\n           As of Flask 0.5 the functions registered for after request\n           execution are called in reverse order of registration.\n\n        :param response: a :attr:`response_class` object.\n        :return: a new response object or the same, has to be an\n                 instance of :attr:`response_class`.\n        \"\"\"\n        for bQ in bO._after_request_functions:\n            bP = self.x(bQ)(bP)\n\n        for bR in chain(bO.request.blueprints, (None,)):\n            if bR in self.after_request_funcs:\n                for bQ in reversed(self.after_request_funcs[bR]):\n                    bP = self.x(bQ)(bP)\n\n        if not self.session_interface.is_null_session(bO._get_session()):\n            self.session_interface.save_session(self, bO._get_session(), bP)\n\n        return bP\n\n    def D(\n        self, bS: AppContext, bT: BaseException | None = None\n    ) -> None:\n        \"\"\"Called after the request is dispatched and the response is finalized,\n        right before the request context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_request`, and\n        :meth:`Blueprint.teardown_request` if a blueprint handled the request.\n        Finally, the :data:`request_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while dispatching the request.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionchanged:: 0.9\n            Added the ``exc`` argument.\n        \"\"\"\n        bU = _CollectErrors()\n\n        for bV in chain(bS.request.blueprints, (None,)):\n            if bV in self.teardown_request_funcs:\n                for bW in reversed(self.teardown_request_funcs[bV]):\n                    with bU:\n                        self.x(bW)(bT)\n\n        with bU:\n            request_tearing_down.send(self, _async_wrapper=self.x, exc=bT)\n\n        bU.raise_any(\"Errors during request teardown\")\n\n    def E(\n        self, bX: AppContext, bY: BaseException | None = None\n    ) -> None:\n        \"\"\"Called right before the application context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_appcontext`.\n        Then the :data:`appcontext_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while the context was active.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        bZ = _CollectErrors()\n\n        for ca in reversed(self.teardown_appcontext_funcs):\n            with bZ:\n                self.x(ca)(bY)\n\n        with bZ:\n            appcontext_tearing_down.send(self, _async_wrapper=self.x, exc=bY)\n\n        bZ.raise_any(\"Errors during app teardown\")\n\n    def F(self) -> AppContext:\n        \"\"\"Create an :class:`.AppContext`. When the context is pushed,\n        :data:`.current_app` and :data:`.g` become available.\n\n        A context is automatically pushed when handling each request, and when\n        running any ``flask`` CLI command. Use this as a ``with`` block to\n        manually push a context outside of those situations, such as during\n        setup or testing.\n\n        .. code-block:: python\n\n            with app.app_context():\n                init_db()\n\n        See :doc:`/appcontext`.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        return AppContext(self)\n\n    def G(self, cb: WSGIEnvironment) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information representing\n        the given WSGI environment. A context is automatically pushed when\n        handling each request. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This method should not be used in your own code. Creating a valid WSGI\n        environ is not trivial. Use :meth:`test_request_context` to correctly\n        create a WSGI environ and request context instead.\n\n        See :doc:`/appcontext`.\n\n        :param environ: A WSGI environment.\n        \"\"\"\n        return AppContext.from_environ(self, cb)\n\n    def H(self, *cc: t.Any, **cd: t.Any) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information created from\n        the given arguments. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This is useful during testing to run a function that uses request data\n        without dispatching a full request. Use this as a ``with`` block to push\n        a context.\n\n        .. code-block:: python\n\n            with app.test_request_context(...):\n                generate_report()\n\n        See :doc:`/appcontext`.\n\n        Takes the same arguments as Werkzeug's\n        :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n        the application. See the linked Werkzeug docs for most of the\n        available arguments. Flask-specific behavior is listed here.\n\n        :param path: URL path being requested.\n        :param base_url: Base URL where the app is being served, which\n            ``path`` is relative to. If not given, built from\n            :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,\n            and :data:`APPLICATION_ROOT`.\n        :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.\n        :param url_scheme: Scheme to use instead of\n            :data:`PREFERRED_URL_SCHEME`.\n        :param data: The request body text or bytes,or a dict of form data.\n        :param json: If given, this is serialized as JSON and passed as\n            ``data``. Also defaults ``content_type`` to\n            ``application/json``.\n        :param args: Other positional arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        :param kwargs: Other keyword arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        \"\"\"\n        from .testing import EnvironBuilder\n\n        ce = EnvironBuilder(self, *cc, **cd)\n\n        try:\n            cf = ce.get_environ()\n        finally:\n            ce.close()\n\n        return self.G(cf)\n\n    def I(\n        self, cg: WSGIEnvironment, ch: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The actual WSGI application. This is not implemented in\n        :meth:`__call__` so that middlewares can be applied without\n        losing a reference to the app object. Instead of doing this::\n\n            app = MyMiddleware(app)\n\n        It's a better idea to do this instead::\n\n            app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n        Then you still have the original application object around and\n        can continue to call methods on it.\n\n        .. versionchanged:: 0.7\n            Teardown events for the request and app contexts are called\n            even if an unhandled error occurs. Other events may not be\n            called depending on when an error occurs during dispatch.\n\n        :param environ: A WSGI environment.\n        :param start_response: A callable accepting a status code,\n            a list of headers, and an optional exception context to\n            start the response.\n        \"\"\"\n        ci = self.G(cg)\n        cj: BaseException | None = None\n        try:\n            try:\n                ci.push()\n                ck = self.u(ci)\n            except Exception as e:\n                cj = e\n                ck = self.q(ci, e)\n            except:\n                cj = sys.exc_info()[1]\n                raise\n            return ck(cg, ch)\n        finally:\n            if \"werkzeug.debug.preserve_context\" in cg:\n                cg[\"werkzeug.debug.preserve_context\"](ci)\n\n            if (\n                cj is not None\n                and self.should_ignore_error is not None\n                and self.should_ignore_error(cj)\n            ):\n                cj = None\n\n            ci.pop(cj)\n\n    def __call__(\n        self, cl: WSGIEnvironment, cm: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The WSGI server calls the Flask application object as the\n        WSGI application. This calls :meth:`wsgi_app`, which can be\n        wrapped to apply middleware.\n        \"\"\"\n        return self.I(cl, cm)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-8341cf85103c4a69", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "5b027a37594b7a876b09ec762c778164dade3a8c93684ce9d836176af3417690", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 1572, "local_path": "identifiers/garble-identifiers/I04__flask__Flask__3e967d3a.py", "order": 4, "original_content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "parent_variant_id": "pyint-14eacc325bde-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/app.py#L110-L1628", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 580, "identifiers_declared": 165}, "unit_kind": "class", "unit_name": "Flask", "variant_id": "pyint-5b323e967d3a-I04", "group_id": "py-8341cf85103c4a69", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 635, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-34d2c5c09ce2-I05", "source": "from __future__ import annotations\nimport collections.abc as cabc\nimport inspect\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom functools import update_wrapper\nfrom inspect import iscoroutinefunction\nfrom itertools import chain\nfrom types import TracebackType\nfrom urllib.parse import quote as _url_quote\nfrom urllib.parse import urlsplit\nimport click\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom werkzeug.wsgi import get_host\nfrom . import cli\nfrom . import typing as ft\nfrom .ctx import AppContext\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import _CollectErrors\nfrom .helpers import get_debug_flag\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import send_from_directory\nfrom .sansio.app import App\nfrom .sessions import SecureCookieSessionInterface\nfrom .sessions import SessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import Environment\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nclass Flask(App):\n    \"\"\"The flask object implements a WSGI application and acts as the central\n    object.  It is passed the name of the module or package of the\n    application.  Once it is created it will act as a central registry for\n    the view functions, the URL rules, template configuration and much more.\n\n    The name of the package is used to resolve resources from inside the\n    package or the folder the module is contained in depending on if the\n    package parameter resolves to an actual python package (a folder with\n    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n    For more information about resource loading, see :func:`open_resource`.\n\n    Usually you create a :class:`Flask` instance in your main module or\n    in the :file:`__init__.py` file of your package like this::\n\n        from flask import Flask\n        app = Flask(__name__)\n\n    .. admonition:: About the First Parameter\n\n        The idea of the first parameter is to give Flask an idea of what\n        belongs to your application.  This name is used to find resources\n        on the filesystem, can be used by extensions to improve debugging\n        information and a lot more.\n\n        So it's important what you provide there.  If you are using a single\n        module, `__name__` is always the correct value.  If you however are\n        using a package, it's usually recommended to hardcode the name of\n        your package there.\n\n        For example if your application is defined in :file:`yourapplication/app.py`\n        you should create it with one of the two versions below::\n\n            app = Flask('yourapplication')\n            app = Flask(__name__.split('.')[0])\n\n        Why is that?  The application will work even with `__name__`, thanks\n        to how resources are looked up.  However it will make debugging more\n        painful.  Certain extensions can make assumptions based on the\n        import name of your application.  For example the Flask-SQLAlchemy\n        extension will look for the code in your application that triggered\n        an SQL query in debug mode.  If the import name is not properly set\n        up, that debugging information is lost.  (For example it would only\n        pick up SQL queries in `yourapplication.app` and not\n        `yourapplication.views.frontend`)\n\n    .. versionadded:: 0.7\n       The `static_url_path`, `static_folder`, and `template_folder`\n       parameters were added.\n\n    .. versionadded:: 0.8\n       The `instance_path` and `instance_relative_config` parameters were\n       added.\n\n    .. versionadded:: 0.11\n       The `root_path` parameter was added.\n\n    .. versionadded:: 1.0\n       The ``host_matching`` and ``static_host`` parameters were added.\n\n    .. versionadded:: 1.0\n       The ``subdomain_matching`` parameter was added. Subdomain\n       matching needs to be enabled manually now. Setting\n       :data:`SERVER_NAME` does not implicitly enable it.\n\n    :param import_name: the name of the application package\n    :param static_url_path: can be used to specify a different path for the\n                            static files on the web.  Defaults to the name\n                            of the `static_folder` folder.\n    :param static_folder: The folder with static files that is served at\n        ``static_url_path``. Relative to the application ``root_path``\n        or an absolute path. Defaults to ``'static'``.\n    :param static_host: the host to use when adding the static route.\n        Defaults to None. Required when using ``host_matching=True``\n        with a ``static_folder`` configured.\n    :param host_matching: set ``url_map.host_matching`` attribute.\n        Defaults to False.\n    :param subdomain_matching: consider the subdomain relative to\n        :data:`SERVER_NAME` when matching routes. Defaults to False.\n    :param template_folder: the folder that contains the templates that should\n                            be used by the application.  Defaults to\n                            ``'templates'`` folder in the root path of the\n                            application.\n    :param instance_path: An alternative instance path for the application.\n                          By default the folder ``'instance'`` next to the\n                          package or module is assumed to be the instance\n                          path.\n    :param instance_relative_config: if set to ``True`` relative filenames\n                                     for loading the config are assumed to\n                                     be relative to the instance path instead\n                                     of the application root.\n    :param root_path: The path to the root of the application files.\n        This should only be set manually when it can't be detected\n        automatically, such as for namespace packages.\n    \"\"\"\n\n    default_config = ImmutableDict(\n        {\n            \"DEBUG\": None,\n            \"TESTING\": False,\n            \"PROPAGATE_EXCEPTIONS\": None,\n            \"SECRET_KEY\": None,\n            \"SECRET_KEY_FALLBACKS\": None,\n            \"PERMANENT_SESSION_LIFETIME\": timedelta(days=0x1f),\n            \"USE_X_SENDFILE\": False,\n            \"TRUSTED_HOSTS\": None,\n            \"SERVER_NAME\": None,\n            \"APPLICATION_ROOT\": \"/\",\n            \"SESSION_COOKIE_NAME\": \"session\",\n            \"SESSION_COOKIE_DOMAIN\": None,\n            \"SESSION_COOKIE_PATH\": None,\n            \"SESSION_COOKIE_HTTPONLY\": True,\n            \"SESSION_COOKIE_SECURE\": False,\n            \"SESSION_COOKIE_PARTITIONED\": False,\n            \"SESSION_COOKIE_SAMESITE\": None,\n            \"SESSION_REFRESH_EACH_REQUEST\": True,\n            \"MAX_CONTENT_LENGTH\": None,\n            \"MAX_FORM_MEMORY_SIZE\": 0x7a120,\n            \"MAX_FORM_PARTS\": 0x3e8,\n            \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n            \"TRAP_BAD_REQUEST_ERRORS\": None,\n            \"TRAP_HTTP_EXCEPTIONS\": False,\n            \"EXPLAIN_TEMPLATE_LOADING\": False,\n            \"PREFERRED_URL_SCHEME\": \"http\",\n            \"TEMPLATES_AUTO_RELOAD\": None,\n            \"MAX_COOKIE_SIZE\": 0xffd,\n            \"PROVIDE_AUTOMATIC_OPTIONS\": True,\n        }\n    )\n\n    #: The class that is used for request objects.  See :class:`~flask.Request`\n    #: for more information.\n    request_class: type[Request] = Request\n\n    #: The class that is used for response objects.  See\n    #: :class:`~flask.Response` for more information.\n    response_class: type[Response] = Response\n\n    #: the session interface to use.  By default an instance of\n    #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n    #:\n    #: .. versionadded:: 0.8\n    session_interface: SessionInterface = SecureCookieSessionInterface()\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        import warnings\n\n        # These method signatures were updated to take a ctx param. Detect\n        # overridden methods in subclasses that still have the old signature.\n        # Show a deprecation warning and wrap to call with correct args.\n        for method in (\n            cls.handle_http_exception,\n            cls.handle_user_exception,\n            cls.handle_exception,\n            cls.log_exception,\n            cls.dispatch_request,\n            cls.full_dispatch_request,\n            cls.finalize_request,\n            cls.make_default_options_response,\n            cls.preprocess_request,\n            cls.process_response,\n            cls.do_teardown_request,\n            cls.do_teardown_appcontext,\n        ):\n            base_method = getattr(Flask, method.__name__)\n\n            if method is base_method:\n                # not overridden\n                continue\n\n            # get the second parameter (first is self)\n            iter_params = iter(inspect.signature(method).parameters.values())\n            next(iter_params)\n            param = next(iter_params, None)\n\n            # must have second parameter named ctx or annotated AppContext\n            if param is None or not (\n                # no annotation, match name\n                (param.annotation is inspect.Parameter.empty and param.name == \"ctx\")\n                or (\n                    # string annotation, access path ends with AppContext\n                    isinstance(param.annotation, str)\n                    and param.annotation.rpartition(\".\")[0x2] == \"AppContext\"\n                )\n                or (\n                    # class annotation\n                    inspect.isclass(param.annotation)\n                    and issubclass(param.annotation, AppContext)\n                )\n            ):\n                warnings.warn(\n                    f\"The '{method.__name__}' method now takes 'ctx: AppContext'\"\n                    \" as the first parameter. The old signature is deprecated\"\n                    \" and will not be supported in Flask 4.0.\",\n                    DeprecationWarning,\n                    stacklevel=0x2,\n                )\n                setattr(cls, method.__name__, remove_ctx(method))\n                setattr(Flask, method.__name__, add_ctx(base_method))\n\n    def __init__(\n        self,\n        import_name: str,\n        static_url_path: str | None = None,\n        static_folder: str | os.PathLike[str] | None = \"static\",\n        static_host: str | None = None,\n        host_matching: bool = False,\n        subdomain_matching: bool = False,\n        template_folder: str | os.PathLike[str] | None = \"templates\",\n        instance_path: str | None = None,\n        instance_relative_config: bool = False,\n        root_path: str | None = None,\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_url_path=static_url_path,\n            static_folder=static_folder,\n            static_host=static_host,\n            host_matching=host_matching,\n            subdomain_matching=subdomain_matching,\n            template_folder=template_folder,\n            instance_path=instance_path,\n            instance_relative_config=instance_relative_config,\n            root_path=root_path,\n        )\n\n        #: The Click command group for registering CLI commands for this\n        #: object. The commands are available from the ``flask`` command\n        #: once the application has been discovered and blueprints have\n        #: been registered.\n        self.cli = cli.AppGroup()\n\n        # Set the name of the Click group in case someone wants to add\n        # the app's commands to another CLI tool.\n        self.cli.name = self.name\n\n        # Add a static route using the provided static_url_path, static_host,\n        # and static_folder if there is a configured static_folder.\n        # Note we do this without checking if static_folder exists.\n        # For one, it might be created while the server is running (e.g. during\n        # development). Also, Google App Engine stores static files somewhere\n        if self.has_static_folder:\n            assert bool(static_host) == host_matching, (\n                \"Invalid static_host/host_matching combination\"\n            )\n            # Use a weakref to avoid creating a reference cycle between the app\n            # and the view function (see #3761).\n            self_ref = weakref.ref(self)\n            self.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                endpoint=\"static\",\n                host=static_host,\n                view_func=lambda **kw: self_ref().send_static_file(**kw),  # type: ignore\n            )\n\n    def get_send_file_max_age(self, filename: str | None) -> int | None:\n        \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n        value for a given file path if it wasn't passed.\n\n        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n        the configuration of :data:`~flask.current_app`. This defaults\n        to ``None``, which tells the browser to use conditional requests\n        instead of a timed cache, which is usually preferable.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionchanged:: 2.0\n            The default configuration is ``None`` instead of 12 hours.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        value = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n        if value is None:\n            return None\n\n        if isinstance(value, timedelta):\n            return int(value.total_seconds())\n\n        return value  # type: ignore[no-any-return]\n\n    def send_static_file(self, filename: str) -> Response:\n        \"\"\"The view function used to serve files from\n        :attr:`static_folder`. A route is automatically registered for\n        this view at :attr:`static_url_path` if :attr:`static_folder` is\n        set.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionadded:: 0.5\n\n        \"\"\"\n        if not self.has_static_folder:\n            raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n        # send_file only knows to call get_send_file_max_age on the app,\n        # call it here so it works for blueprints too.\n        max_age = self.get_send_file_max_age(filename)\n        return send_from_directory(\n            t.cast(str, self.static_folder), filename, max_age=max_age\n        )\n\n    def open_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = None\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to :attr:`root_path` for reading.\n\n        For example, if the file ``schema.sql`` is next to the file\n        ``app.py`` where the ``Flask`` app is defined, it can be opened\n        with:\n\n        .. code-block:: python\n\n            with app.open_resource(\"schema.sql\") as f:\n                conn.executescript(f.read())\n\n        :param resource: Path to the resource relative to :attr:`root_path`.\n        :param mode: Open the file in this mode. Only reading is supported,\n            valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        if mode not in {\"r\", \"rt\", \"rb\"}:\n            raise ValueError(\"Resources can only be opened for reading.\")\n\n        path = os.path.join(self.root_path, resource)\n\n        if mode == \"rb\":\n            return open(path, mode)  # pyright: ignore\n\n        return open(path, mode, encoding=encoding)\n\n    def open_instance_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = \"utf-8\"\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to the application's instance folder\n        :attr:`instance_path`. Unlike :meth:`open_resource`, files in the\n        instance folder can be opened for writing.\n\n        :param resource: Path to the resource relative to :attr:`instance_path`.\n        :param mode: Open the file in this mode.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        path = os.path.join(self.instance_path, resource)\n\n        if \"b\" in mode:\n            return open(path, mode)\n\n        return open(path, mode, encoding=encoding)\n\n    def create_jinja_environment(self) -> Environment:\n        \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n        and the various Jinja-related methods of the app. Changing\n        :attr:`jinja_options` after this will have no effect. Also adds\n        Flask-related globals and filters to the environment.\n\n        .. versionchanged:: 0.11\n           ``Environment.auto_reload`` set in accordance with\n           ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        options = dict(self.jinja_options)\n\n        if \"autoescape\" not in options:\n            options[\"autoescape\"] = self.select_jinja_autoescape\n\n        if \"auto_reload\" not in options:\n            auto_reload = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n            if auto_reload is None:\n                auto_reload = self.debug\n\n            options[\"auto_reload\"] = auto_reload\n\n        rv = self.jinja_environment(self, **options)\n        rv.globals.update(\n            url_for=self.url_for,\n            get_flashed_messages=get_flashed_messages,\n            config=self.config,\n            # request, session and g are normally added with the\n            # context processor for efficiency reasons but for imported\n            # templates we also want the proxies in there.\n            request=request,\n            session=session,\n            g=g,\n        )\n        rv.policies[\"json.dumps_function\"] = self.json.dumps\n        return rv\n\n    def create_url_adapter(self, request: Request | None) -> MapAdapter | None:\n        \"\"\"Creates a URL adapter for the given request. The URL adapter\n        is created at a point where the request context is not yet set\n        up so the request is passed explicitly.\n\n        .. versionchanged:: 3.1\n            If :data:`SERVER_NAME` is set, it does not restrict requests to\n            only that domain, for both ``subdomain_matching`` and\n            ``host_matching``.\n\n        .. versionchanged:: 1.0\n            :data:`SERVER_NAME` no longer implicitly enables subdomain\n            matching. Use :attr:`subdomain_matching` instead.\n\n        .. versionchanged:: 0.9\n           This can be called outside a request when the URL adapter is created\n           for an application context.\n\n        .. versionadded:: 0.6\n        \"\"\"\n        if request is not None:\n            if (trusted_hosts := self.config[\"TRUSTED_HOSTS\"]) is not None:\n                request.trusted_hosts = trusted_hosts\n\n            # Check trusted_hosts here until bind_to_environ does.\n            request.host = get_host(request.environ, request.trusted_hosts)  # pyright: ignore\n            subdomain = None\n            server_name = self.config[\"SERVER_NAME\"]\n\n            if self.url_map.host_matching:\n                # Don't pass SERVER_NAME, otherwise it's used and the actual\n                # host is ignored, which breaks host matching.\n                server_name = None\n            elif not self.subdomain_matching:\n                # Werkzeug doesn't implement subdomain matching yet. Until then,\n                # disable it by forcing the current subdomain to the default, or\n                # the empty string.\n                subdomain = self.url_map.default_subdomain or \"\"\n\n            return self.url_map.bind_to_environ(\n                request.environ, server_name=server_name, subdomain=subdomain\n            )\n\n        # Need at least SERVER_NAME to match/build outside a request.\n        if self.config[\"SERVER_NAME\"] is not None:\n            return self.url_map.bind(\n                self.config[\"SERVER_NAME\"],\n                script_name=self.config[\"APPLICATION_ROOT\"],\n                url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n            )\n\n        return None\n\n    def raise_routing_exception(self, request: Request) -> t.NoReturn:\n        \"\"\"Intercept routing exceptions and possibly do something else.\n\n        In debug mode, intercept a routing redirect and replace it with\n        an error if the body will be discarded.\n\n        With modern Werkzeug this shouldn't occur, since it now uses a\n        308 status which tells the browser to resend the method and\n        body.\n\n        .. versionchanged:: 2.1\n            Don't intercept 307 and 308 redirects.\n\n        :meta private:\n        :internal:\n        \"\"\"\n        if (\n            not self.debug\n            or not isinstance(request.routing_exception, RequestRedirect)\n            or request.routing_exception.code in {0x133, 0x134}\n            or request.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n        ):\n            raise request.routing_exception  # type: ignore[misc]\n\n        from .debughelpers import FormDataRoutingRedirect\n\n        raise FormDataRoutingRedirect(request)\n\n    def update_template_context(\n        self, ctx: AppContext, context: dict[str, t.Any]\n    ) -> None:\n        \"\"\"Update the template context with some commonly used variables.\n        This injects request, session, config and g into the template\n        context as well as everything template context processors want\n        to inject.  Note that the as of Flask 0.6, the original values\n        in the context will not be overridden if a context processor\n        decides to return a value with the same key.\n\n        :param context: the context as a dictionary that is updated in place\n                        to add extra variables.\n        \"\"\"\n        names: t.Iterable[str | None] = (None,)\n\n        # A template may be rendered outside a request context.\n        if ctx.has_request:\n            names = chain(names, reversed(ctx.request.blueprints))\n\n        # The values passed to render_template take precedence. Keep a\n        # copy to re-apply after all context functions.\n        orig_ctx = context.copy()\n\n        for name in names:\n            if name in self.template_context_processors:\n                for func in self.template_context_processors[name]:\n                    context.update(self.ensure_sync(func)())\n\n        context.update(orig_ctx)\n\n    def make_shell_context(self) -> dict[str, t.Any]:\n        \"\"\"Returns the shell context for an interactive shell for this\n        application.  This runs all the registered shell context\n        processors.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {\"app\": self, \"g\": g}\n        for processor in self.shell_context_processors:\n            rv.update(processor())\n        return rv\n\n    def run(\n        self,\n        host: str | None = None,\n        port: int | None = None,\n        debug: bool | None = None,\n        load_dotenv: bool = True,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Runs the application on a local development server.\n\n        Do not use ``run()`` in a production setting. It is not intended to\n        meet security and performance requirements for a production server.\n        Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n        If the :attr:`debug` flag is set the server will automatically reload\n        for code changes and show a debugger in case an exception happened.\n\n        If you want to run the application in debug mode, but disable the\n        code execution on the interactive debugger, you can pass\n        ``use_evalex=False`` as parameter.  This will keep the debugger's\n        traceback screen active, but disable code execution.\n\n        It is not recommended to use this function for development with\n        automatic reloading as this is badly supported.  Instead you should\n        be using the :command:`flask` command line script's ``run`` support.\n\n        .. admonition:: Keep in Mind\n\n           Flask will suppress any server error with a generic error page\n           unless it is in debug mode.  As such to enable just the\n           interactive debugger without the code reloading, you have to\n           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n           Setting ``use_debugger`` to ``True`` without being in debug mode\n           won't catch any exceptions because there won't be any to\n           catch.\n\n        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n            have the server available externally as well. Defaults to\n            ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n            if present.\n        :param port: the port of the webserver. Defaults to ``5000`` or the\n            port defined in the ``SERVER_NAME`` config variable if present.\n        :param debug: if given, enable or disable debug mode. See\n            :attr:`debug`.\n        :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n            files to set environment variables. Will also change the working\n            directory to the directory containing the first file found.\n        :param options: the options to be forwarded to the underlying Werkzeug\n            server. See :func:`werkzeug.serving.run_simple` for more\n            information.\n\n        .. versionchanged:: 1.0\n            If installed, python-dotenv will be used to load environment\n            variables from :file:`.env` and :file:`.flaskenv` files.\n\n            The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.\n\n            Threaded mode is enabled by default.\n\n        .. versionchanged:: 0.10\n            The default port is now picked from the ``SERVER_NAME``\n            variable.\n        \"\"\"\n        # Ignore this call so that it doesn't start another server if\n        # the 'flask run' command is used.\n        if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n            if not is_running_from_reloader():\n                click.secho(\n                    \" * Ignoring a call to 'app.run()' that would block\"\n                    \" the current 'flask' CLI command.\\n\"\n                    \"   Only call 'app.run()' in an 'if __name__ ==\"\n                    ' \"__main__\"\\' guard.',\n                    fg=\"red\",\n                )\n\n            return\n\n        if get_load_dotenv(load_dotenv):\n            cli.load_dotenv()\n\n            # if set, env var overrides existing value\n            if \"FLASK_DEBUG\" in os.environ:\n                self.debug = get_debug_flag()\n\n        # debug passed to method overrides all other sources\n        if debug is not None:\n            self.debug = bool(debug)\n\n        server_name = self.config.get(\"SERVER_NAME\")\n        sn_host = sn_port = None\n\n        if server_name:\n            server_url = urlsplit(f\"//{server_name}\")\n            sn_host = server_url.hostname\n            sn_port = server_url.port\n\n        if not host:\n            if sn_host:\n                host = sn_host\n            else:\n                host = \"127.0.0.1\"\n\n        if port or port == 0x0:\n            port = int(port)\n        elif sn_port is not None:\n            port = sn_port\n        else:\n            port = 0x1388\n\n        options.setdefault(\"use_reloader\", self.debug)\n        options.setdefault(\"use_debugger\", self.debug)\n        options.setdefault(\"threaded\", True)\n\n        cli.show_server_banner(self.debug, self.name)\n\n        from werkzeug.serving import run_simple\n\n        try:\n            run_simple(host, port, self, **options)\n        finally:\n            # reset the first request information if the development server\n            # reset normally.  This makes it possible to restart the server\n            # without reloader and that stuff from an interactive shell.\n            self._got_first_request = False\n\n    def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:\n        \"\"\"Creates a test client for this application.  For information\n        about unit testing head over to :doc:`/testing`.\n\n        Note that if you are testing for assertions or exceptions in your\n        application code, you must set ``app.testing = True`` in order for the\n        exceptions to propagate to the test client.  Otherwise, the exception\n        will be handled by the application (not visible to the test client) and\n        the only indication of an AssertionError or other exception will be a\n        500 status code response to the test client.  See the :attr:`testing`\n        attribute.  For example::\n\n            app.testing = True\n            client = app.test_client()\n\n        The test client can be used in a ``with`` block to defer the closing down\n        of the context until the end of the ``with`` block.  This is useful if\n        you want to access the context locals for testing::\n\n            with app.test_client() as c:\n                rv = c.get('/?vodka=42')\n                assert request.args['vodka'] == '42'\n\n        Additionally, you may pass optional keyword arguments that will then\n        be passed to the application's :attr:`test_client_class` constructor.\n        For example::\n\n            from flask.testing import FlaskClient\n\n            class CustomClient(FlaskClient):\n                def __init__(self, *args, **kwargs):\n                    self._authentication = kwargs.pop(\"authentication\")\n                    super(CustomClient,self).__init__( *args, **kwargs)\n\n            app.test_client_class = CustomClient\n            client = app.test_client(authentication='Basic ....')\n\n        See :class:`~flask.testing.FlaskClient` for more information.\n\n        .. versionchanged:: 0.4\n           added support for ``with`` block usage for the client.\n\n        .. versionadded:: 0.7\n           The `use_cookies` parameter was added as well as the ability\n           to override the client to be used by setting the\n           :attr:`test_client_class` attribute.\n\n        .. versionchanged:: 0.11\n           Added `**kwargs` to support passing additional keyword arguments to\n           the constructor of :attr:`test_client_class`.\n        \"\"\"\n        cls = self.test_client_class\n        if cls is None:\n            from .testing import FlaskClient as cls\n        return cls(  # type: ignore\n            self, self.response_class, use_cookies=use_cookies, **kwargs\n        )\n\n    def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:\n        \"\"\"Create a CLI runner for testing CLI commands.\n        See :ref:`testing-cli`.\n\n        Returns an instance of :attr:`test_cli_runner_class`, by default\n        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n        passed as the first argument.\n\n        .. versionadded:: 1.0\n        \"\"\"\n        cls = self.test_cli_runner_class\n\n        if cls is None:\n            from .testing import FlaskCliRunner as cls\n\n        return cls(self, **kwargs)  # type: ignore\n\n    def handle_http_exception(\n        self, ctx: AppContext, e: HTTPException\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"Handles an HTTP exception.  By default this will invoke the\n        registered error handlers and fall back to returning the\n        exception as response.\n\n        .. versionchanged:: 1.0.3\n            ``RoutingException``, used internally for actions such as\n             slash redirects during routing, is not passed to error\n             handlers.\n\n        .. versionchanged:: 1.0\n            Exceptions are looked up by code *and* by MRO, so\n            ``HTTPException`` subclasses can be handled with a catch-all\n            handler for the base ``HTTPException``.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        # Proxy exceptions don't have error codes.  We want to always return\n        # those unchanged as errors\n        if e.code is None:\n            return e\n\n        # RoutingExceptions are used internally to trigger routing\n        # actions, such as slash redirects raising RequestRedirect. They\n        # are not raised or handled in user code.\n        if isinstance(e, RoutingException):\n            return e\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n        if handler is None:\n            return e\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_user_exception(\n        self, ctx: AppContext, e: Exception\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"This method is called whenever an exception occurs that\n        should be handled. A special case is :class:`~werkzeug\n        .exceptions.HTTPException` which is forwarded to the\n        :meth:`handle_http_exception` method. This function will either\n        return a response value or reraise the exception with the same\n        traceback.\n\n        .. versionchanged:: 1.0\n            Key errors raised from request data like ``form`` show the\n            bad key in debug mode rather than a generic bad request\n            message.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if isinstance(e, BadRequestKeyError) and (\n            self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n        ):\n            e.show_exception = True\n\n        if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n            return self.handle_http_exception(ctx, e)\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n\n        if handler is None:\n            raise\n\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_exception(self, ctx: AppContext, e: Exception) -> Response:\n        \"\"\"Handle an exception that did not have an error handler\n        associated with it, or that was raised from an error handler.\n        This always causes a 500 ``InternalServerError``.\n\n        Always sends the :data:`got_request_exception` signal.\n\n        If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n        mode, the error will be re-raised so that the debugger can\n        display it. Otherwise, the original exception is logged, and\n        an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n        If an error handler is registered for ``InternalServerError`` or\n        ``500``, it will be used. For consistency, the handler will\n        always receive the ``InternalServerError``. The original\n        unhandled exception is available as ``e.original_exception``.\n\n        .. versionchanged:: 1.1.0\n            Always passes the ``InternalServerError`` instance to the\n            handler, setting ``original_exception`` to the unhandled\n            error.\n\n        .. versionchanged:: 1.1.0\n            ``after_request`` functions and other finalization is done\n            even for the default 500 response when there is no handler.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        exc_info = sys.exc_info()\n        got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)\n        propagate = self.config[\"PROPAGATE_EXCEPTIONS\"]\n\n        if propagate is None:\n            propagate = self.testing or self.debug\n\n        if propagate:\n            # Re-raise if called with an active exception, otherwise\n            # raise the passed in exception.\n            if exc_info[0x1] is e:\n                raise\n\n            raise e\n\n        self.log_exception(ctx, exc_info)\n        server_error: InternalServerError | ft.ResponseReturnValue\n        server_error = InternalServerError(original_exception=e)\n        handler = self._find_error_handler(server_error, ctx.request.blueprints)\n\n        if handler is not None:\n            server_error = self.ensure_sync(handler)(server_error)\n\n        return self.finalize_request(ctx, server_error, from_error_handler=True)\n\n    def log_exception(\n        self,\n        ctx: AppContext,\n        exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n    ) -> None:\n        \"\"\"Logs an exception.  This is called by :meth:`handle_exception`\n        if debugging is disabled and right before the handler is called.\n        The default implementation logs the exception as error on the\n        :attr:`logger`.\n\n        .. versionadded:: 0.8\n        \"\"\"\n        self.logger.error(\n            f\"Exception on {ctx.request.path} [{ctx.request.method}]\", exc_info=exc_info\n        )\n\n    def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue:\n        \"\"\"Does the request dispatching.  Matches the URL and returns the\n        return value of the view or error handler.  This does not have to\n        be a response object.  In order to convert the return value to a\n        proper response object, call :func:`make_response`.\n\n        .. versionchanged:: 0.7\n           This no longer does the exception handling, this code was\n           moved to the new :meth:`full_dispatch_request`.\n        \"\"\"\n        req = ctx.request\n\n        if req.routing_exception is not None:\n            self.raise_routing_exception(req)\n        rule: Rule = req.url_rule  # type: ignore[assignment]\n        # if we provide automatic options for this URL and the\n        # request came with the OPTIONS method, reply automatically\n        if (\n            getattr(rule, \"provide_automatic_options\", False)\n            and req.method == \"OPTIONS\"\n        ):\n            return self.make_default_options_response(ctx)\n        # otherwise dispatch to the handler for that endpoint\n        view_args: dict[str, t.Any] = req.view_args  # type: ignore[assignment]\n        return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]\n\n    def full_dispatch_request(self, ctx: AppContext) -> Response:\n        \"\"\"Dispatches the request and on top of that performs request\n        pre and postprocessing as well as HTTP exception catching and\n        error handling.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if not self._got_first_request and self.should_ignore_error is not None:\n            import warnings\n\n            warnings.warn(\n                \"The 'should_ignore_error' method is deprecated and will\"\n                \" be removed in Flask 3.3. Handle errors as needed in\"\n                \" teardown handlers instead.\",\n                DeprecationWarning,\n                stacklevel=0x1,\n            )\n\n        self._got_first_request = True\n\n        try:\n            request_started.send(self, _async_wrapper=self.ensure_sync)\n            rv = self.preprocess_request(ctx)\n            if rv is None:\n                rv = self.dispatch_request(ctx)\n        except Exception as e:\n            rv = self.handle_user_exception(ctx, e)\n        return self.finalize_request(ctx, rv)\n\n    def finalize_request(\n        self,\n        ctx: AppContext,\n        rv: ft.ResponseReturnValue | HTTPException,\n        from_error_handler: bool = False,\n    ) -> Response:\n        \"\"\"Given the return value from a view function this finalizes\n        the request by converting it into a response and invoking the\n        postprocessing functions.  This is invoked for both normal\n        request dispatching as well as error handlers.\n\n        Because this means that it might be called as a result of a\n        failure a special safe mode is available which can be enabled\n        with the `from_error_handler` flag.  If enabled, failures in\n        response processing will be logged and otherwise ignored.\n\n        :internal:\n        \"\"\"\n        response = self.make_response(rv)\n        try:\n            response = self.process_response(ctx, response)\n            request_finished.send(\n                self, _async_wrapper=self.ensure_sync, response=response\n            )\n        except Exception:\n            if not from_error_handler:\n                raise\n            self.logger.exception(\n                \"Request finalizing failed with an error while handling an error\"\n            )\n        return response\n\n    def make_default_options_response(self, ctx: AppContext) -> Response:\n        \"\"\"This method is called to create the default ``OPTIONS`` response.\n        This can be changed through subclassing to change the default\n        behavior of ``OPTIONS`` responses.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        methods = ctx.url_adapter.allowed_methods()  # type: ignore[union-attr]\n        rv = self.response_class()\n        rv.allow.update(methods)\n        return rv\n\n    def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n        \"\"\"Ensure that the function is synchronous for WSGI workers.\n        Plain ``def`` functions are returned as-is. ``async def``\n        functions are wrapped to run and wait for the response.\n\n        Override this method to change how the app runs async views.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if iscoroutinefunction(func):\n            return self.async_to_sync(func)\n\n        return func\n\n    def async_to_sync(\n        self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n    ) -> t.Callable[..., t.Any]:\n        \"\"\"Return a sync function that will run the coroutine function.\n\n        .. code-block:: python\n\n            result = app.async_to_sync(func)(*args, **kwargs)\n\n        Override this method to change how the app converts async code\n        to be synchronously callable.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        try:\n            from asgiref.sync import async_to_sync as asgiref_async_to_sync\n        except ImportError:\n            raise RuntimeError(\n                \"Install Flask with the 'async' extra in order to use async views.\"\n            ) from None\n\n        return asgiref_async_to_sync(func)\n\n    def url_for(\n        self,\n        /,\n        endpoint: str,\n        *,\n        _anchor: str | None = None,\n        _method: str | None = None,\n        _scheme: str | None = None,\n        _external: bool | None = None,\n        **values: t.Any,\n    ) -> str:\n        \"\"\"Generate a URL to the given endpoint with the given values.\n\n        This is called by :func:`flask.url_for`, and can be called\n        directly as well.\n\n        An *endpoint* is the name of a URL rule, usually added with\n        :meth:`@app.route() <route>`, and usually the same name as the\n        view function. A route defined in a :class:`~flask.Blueprint`\n        will prepend the blueprint's name separated by a ``.`` to the\n        endpoint.\n\n        In some cases, such as email messages, you want URLs to include\n        the scheme and domain, like ``https://example.com/hello``. When\n        not in an active request, URLs will be external by default, but\n        this requires setting :data:`SERVER_NAME` so Flask knows what\n        domain to use. :data:`APPLICATION_ROOT` and\n        :data:`PREFERRED_URL_SCHEME` should also be configured as\n        needed. This config is only used when not in an active request.\n\n        Functions can be decorated with :meth:`url_defaults` to modify\n        keyword arguments before the URL is built.\n\n        If building fails for some reason, such as an unknown endpoint\n        or incorrect values, the app's :meth:`handle_url_build_error`\n        method is called. If that returns a string, that is returned,\n        otherwise a :exc:`~werkzeug.routing.BuildError` is raised.\n\n        :param endpoint: The endpoint name associated with the URL to\n            generate. If this starts with a ``.``, the current blueprint\n            name (if any) will be used.\n        :param _anchor: If given, append this as ``#anchor`` to the URL.\n        :param _method: If given, generate the URL associated with this\n            method for the endpoint.\n        :param _scheme: If given, the URL will have this scheme if it\n            is external.\n        :param _external: If given, prefer the URL to be internal\n            (False) or require it to be external (True). External URLs\n            include the scheme and domain. When not in an active\n            request, URLs are external by default.\n        :param values: Values to use for the variable parts of the URL\n            rule. Unknown keys are appended as query string arguments,\n            like ``?a=b&c=d``.\n\n        .. versionadded:: 2.2\n            Moved from ``flask.url_for``, which calls this method.\n        \"\"\"\n        if (ctx := _cv_app.get(None)) is not None and ctx.has_request:\n            url_adapter = ctx.url_adapter\n            blueprint_name = ctx.request.blueprint\n\n            # If the endpoint starts with \".\" and the request matches a\n            # blueprint, the endpoint is relative to the blueprint.\n            if endpoint[:0x1] == \".\":\n                if blueprint_name is not None:\n                    endpoint = f\"{blueprint_name}{endpoint}\"\n                else:\n                    endpoint = endpoint[0x1:]\n\n            # When in a request, generate a URL without scheme and\n            # domain by default, unless a scheme is given.\n            if _external is None:\n                _external = _scheme is not None\n        else:\n            # If called by helpers.url_for, an app context is active,\n            # use its url_adapter. Otherwise, app.url_for was called\n            # directly, build an adapter.\n            if ctx is not None:\n                url_adapter = ctx.url_adapter\n            else:\n                url_adapter = self.create_url_adapter(None)\n\n            if url_adapter is None:\n                raise RuntimeError(\n                    \"Unable to build URLs outside an active request\"\n                    \" without 'SERVER_NAME' configured. Also configure\"\n                    \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n                    \" needed.\"\n                )\n\n            # When outside a request, generate a URL with scheme and\n            # domain by default.\n            if _external is None:\n                _external = True\n\n        # It is an error to set _scheme when _external=False, in order\n        # to avoid accidental insecure URLs.\n        if _scheme is not None and not _external:\n            raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n        self.inject_url_defaults(endpoint, values)\n\n        try:\n            rv = url_adapter.build(  # type: ignore[union-attr]\n                endpoint,\n                values,\n                method=_method,\n                url_scheme=_scheme,\n                force_external=_external,\n            )\n        except BuildError as error:\n            values.update(\n                _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external\n            )\n            return self.handle_url_build_error(error, endpoint, values)\n\n        if _anchor is not None:\n            _anchor = _url_quote(_anchor, safe=\"%!#$&'()*+,/:;=?@\")\n            rv = f\"{rv}#{_anchor}\"\n\n        return rv\n\n    def make_response(self, rv: ft.ResponseReturnValue) -> Response:\n        \"\"\"Convert the return value from a view function to an instance of\n        :attr:`response_class`.\n\n        :param rv: the return value from the view function. The view function\n            must return a response. Returning ``None``, or the view ending\n            without returning, is not allowed. The following types are allowed\n            for ``view_rv``:\n\n            ``str``\n                A response object is created with the string encoded to UTF-8\n                as the body.\n\n            ``bytes``\n                A response object is created with the bytes as the body.\n\n            ``dict``\n                Converted to a JSON response.\n\n            ``list``\n                Converted to a JSON response.\n\n            ``generator`` or ``iterator``\n                A generator that returns ``str`` or ``bytes`` to be\n                streamed as the response.\n\n            ``tuple``\n                Either ``(body, status, headers)``, ``(body, status)``, or\n                ``(body, headers)``, where ``body`` is any of the other types\n                allowed here, ``status`` is a string or an integer, and\n                ``headers`` is a dictionary or a list of ``(key, value)``\n                tuples. If ``body`` is a :attr:`response_class` instance,\n                ``status`` overwrites the exiting value and ``headers`` are\n                extended.\n\n            :attr:`response_class`\n                The object is returned unchanged.\n\n            other :class:`~werkzeug.wrappers.Response` class\n                The object is coerced to :attr:`response_class`.\n\n            :func:`callable`\n                The function is called as a WSGI application. The result is\n                used to create a response object.\n\n        .. versionchanged:: 2.2\n            A generator will be converted to a streaming response.\n            A list will be converted to a JSON response.\n\n        .. versionchanged:: 1.1\n            A dict will be converted to a JSON response.\n\n        .. versionchanged:: 0.9\n           Previously a tuple was interpreted as the arguments for the\n           response object.\n        \"\"\"\n\n        status: int | None = None\n        headers: HeadersValue | None = None\n\n        # unpack tuple returns\n        if isinstance(rv, tuple):\n            len_rv = len(rv)\n\n            # a 3-tuple is unpacked directly\n            if len_rv == 0x3:\n                rv, status, headers = rv  # type: ignore[misc]\n            # decide if a 2-tuple has status or headers\n            elif len_rv == 0x2:\n                if isinstance(rv[0x1], (Headers, dict, tuple, list)):\n                    rv, headers = rv  # pyright: ignore\n                else:\n                    rv, status = rv  # type: ignore[assignment,misc]\n            # other sized tuples are not allowed\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid response tuple.\"\n                    \" The tuple must have the form (body, status, headers),\"\n                    \" (body, status), or (body, headers).\"\n                )\n\n        # the body must not be None\n        if rv is None:\n            raise TypeError(\n                f\"The view function for {request.endpoint!r} did not\"\n                \" return a valid response. The function either returned\"\n                \" None or ended without a return statement.\"\n            )\n\n        # make sure the body is an instance of the response class\n        if not isinstance(rv, self.response_class):\n            if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):\n                # let the response class set the status and headers instead of\n                # waiting to do it manually, so that the class can handle any\n                # special logic\n                rv = self.response_class(\n                    rv,  # pyright: ignore\n                    status=status,\n                    headers=headers,  # type: ignore[arg-type]\n                )\n                status = headers = None\n            elif isinstance(rv, (dict, list)):\n                rv = self.json.response(rv)\n            elif isinstance(rv, BaseResponse) or callable(rv):\n                # evaluate a WSGI callable, or coerce a different response\n                # class to the correct type\n                try:\n                    rv = self.response_class.force_type(\n                        rv,  # type: ignore[arg-type]\n                        request.environ,\n                    )\n                except TypeError as e:\n                    raise TypeError(\n                        f\"{e}\\nThe view function did not return a valid\"\n                        \" response. The return type must be a string,\"\n                        \" dict, list, tuple with headers or status,\"\n                        \" Response instance, or WSGI callable, but it\"\n                        f\" was a {type(rv).__name__}.\"\n                    ).with_traceback(sys.exc_info()[0x2]) from None\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid\"\n                    \" response. The return type must be a string,\"\n                    \" dict, list, tuple with headers or status,\"\n                    \" Response instance, or WSGI callable, but it was a\"\n                    f\" {type(rv).__name__}.\"\n                )\n\n        rv = t.cast(Response, rv)\n        # prefer the status if it was provided\n        if status is not None:\n            if isinstance(status, (str, bytes, bytearray)):\n                rv.status = status\n            else:\n                rv.status_code = status\n\n        # extend existing headers with provided headers\n        if headers:\n            rv.headers.update(headers)\n\n        return rv\n\n    def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None:\n        \"\"\"Called before the request is dispatched. Calls\n        :attr:`url_value_preprocessors` registered with the app and the\n        current blueprint (if any). Then calls :attr:`before_request_funcs`\n        registered with the app and the blueprint.\n\n        If any :meth:`before_request` handler returns a non-None value, the\n        value is handled as if it was the return value from the view, and\n        further request handling is stopped.\n        \"\"\"\n        req = ctx.request\n        names = (None, *reversed(req.blueprints))\n\n        for name in names:\n            if name in self.url_value_preprocessors:\n                for url_func in self.url_value_preprocessors[name]:\n                    url_func(req.endpoint, req.view_args)\n\n        for name in names:\n            if name in self.before_request_funcs:\n                for before_func in self.before_request_funcs[name]:\n                    rv = self.ensure_sync(before_func)()\n\n                    if rv is not None:\n                        return rv  # type: ignore[no-any-return]\n\n        return None\n\n    def process_response(self, ctx: AppContext, response: Response) -> Response:\n        \"\"\"Can be overridden in order to modify the response object\n        before it's sent to the WSGI server.  By default this will\n        call all the :meth:`after_request` decorated functions.\n\n        .. versionchanged:: 0.5\n           As of Flask 0.5 the functions registered for after request\n           execution are called in reverse order of registration.\n\n        :param response: a :attr:`response_class` object.\n        :return: a new response object or the same, has to be an\n                 instance of :attr:`response_class`.\n        \"\"\"\n        for func in ctx._after_request_functions:\n            response = self.ensure_sync(func)(response)\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.after_request_funcs:\n                for func in reversed(self.after_request_funcs[name]):\n                    response = self.ensure_sync(func)(response)\n\n        if not self.session_interface.is_null_session(ctx._get_session()):\n            self.session_interface.save_session(self, ctx._get_session(), response)\n\n        return response\n\n    def do_teardown_request(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called after the request is dispatched and the response is finalized,\n        right before the request context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_request`, and\n        :meth:`Blueprint.teardown_request` if a blueprint handled the request.\n        Finally, the :data:`request_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while dispatching the request.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionchanged:: 0.9\n            Added the ``exc`` argument.\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.teardown_request_funcs:\n                for func in reversed(self.teardown_request_funcs[name]):\n                    with collect_errors:\n                        self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during request teardown\")\n\n    def do_teardown_appcontext(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called right before the application context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_appcontext`.\n        Then the :data:`appcontext_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while the context was active.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for func in reversed(self.teardown_appcontext_funcs):\n            with collect_errors:\n                self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during app teardown\")\n\n    def app_context(self) -> AppContext:\n        \"\"\"Create an :class:`.AppContext`. When the context is pushed,\n        :data:`.current_app` and :data:`.g` become available.\n\n        A context is automatically pushed when handling each request, and when\n        running any ``flask`` CLI command. Use this as a ``with`` block to\n        manually push a context outside of those situations, such as during\n        setup or testing.\n\n        .. code-block:: python\n\n            with app.app_context():\n                init_db()\n\n        See :doc:`/appcontext`.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        return AppContext(self)\n\n    def request_context(self, environ: WSGIEnvironment) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information representing\n        the given WSGI environment. A context is automatically pushed when\n        handling each request. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This method should not be used in your own code. Creating a valid WSGI\n        environ is not trivial. Use :meth:`test_request_context` to correctly\n        create a WSGI environ and request context instead.\n\n        See :doc:`/appcontext`.\n\n        :param environ: A WSGI environment.\n        \"\"\"\n        return AppContext.from_environ(self, environ)\n\n    def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information created from\n        the given arguments. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This is useful during testing to run a function that uses request data\n        without dispatching a full request. Use this as a ``with`` block to push\n        a context.\n\n        .. code-block:: python\n\n            with app.test_request_context(...):\n                generate_report()\n\n        See :doc:`/appcontext`.\n\n        Takes the same arguments as Werkzeug's\n        :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n        the application. See the linked Werkzeug docs for most of the\n        available arguments. Flask-specific behavior is listed here.\n\n        :param path: URL path being requested.\n        :param base_url: Base URL where the app is being served, which\n            ``path`` is relative to. If not given, built from\n            :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,\n            and :data:`APPLICATION_ROOT`.\n        :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.\n        :param url_scheme: Scheme to use instead of\n            :data:`PREFERRED_URL_SCHEME`.\n        :param data: The request body text or bytes,or a dict of form data.\n        :param json: If given, this is serialized as JSON and passed as\n            ``data``. Also defaults ``content_type`` to\n            ``application/json``.\n        :param args: Other positional arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        :param kwargs: Other keyword arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        \"\"\"\n        from .testing import EnvironBuilder\n\n        builder = EnvironBuilder(self, *args, **kwargs)\n\n        try:\n            environ = builder.get_environ()\n        finally:\n            builder.close()\n\n        return self.request_context(environ)\n\n    def wsgi_app(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The actual WSGI application. This is not implemented in\n        :meth:`__call__` so that middlewares can be applied without\n        losing a reference to the app object. Instead of doing this::\n\n            app = MyMiddleware(app)\n\n        It's a better idea to do this instead::\n\n            app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n        Then you still have the original application object around and\n        can continue to call methods on it.\n\n        .. versionchanged:: 0.7\n            Teardown events for the request and app contexts are called\n            even if an unhandled error occurs. Other events may not be\n            called depending on when an error occurs during dispatch.\n\n        :param environ: A WSGI environment.\n        :param start_response: A callable accepting a status code,\n            a list of headers, and an optional exception context to\n            start the response.\n        \"\"\"\n        ctx = self.request_context(environ)\n        error: BaseException | None = None\n        try:\n            try:\n                ctx.push()\n                response = self.full_dispatch_request(ctx)\n            except Exception as e:\n                error = e\n                response = self.handle_exception(ctx, e)\n            except:\n                error = sys.exc_info()[0x1]\n                raise\n            return response(environ, start_response)\n        finally:\n            if \"werkzeug.debug.preserve_context\" in environ:\n                environ[\"werkzeug.debug.preserve_context\"](ctx)\n\n            if (\n                error is not None\n                and self.should_ignore_error is not None\n                and self.should_ignore_error(error)\n            ):\n                error = None\n\n            ctx.pop(error)\n\n    def __call__(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The WSGI server calls the Flask application object as the\n        WSGI application. This calls :meth:`wsgi_app`, which can be\n        wrapped to apply middleware.\n        \"\"\"\n        return self.wsgi_app(environ, start_response)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-8341cf85103c4a69", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "37326369363892b07af32d30d5302b08be55ea2ff53c59513da72a552c45e939", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 1572, "local_path": "expressions/encode-integer-literals/I05__flask__Flask__c5c09ce2.py", "order": 5, "original_content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "parent_variant_id": "pyint-14eacc325bde-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/app.py#L110-L1628", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 19}, "unit_kind": "class", "unit_name": "Flask", "variant_id": "pyint-34d2c5c09ce2-I05", "group_id": "py-8341cf85103c4a69", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 636, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-052587bb1239-I06", "source": "from __future__ import annotations\nimport collections.abc as cabc\nimport inspect\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom functools import update_wrapper\nfrom inspect import iscoroutinefunction\nfrom itertools import chain\nfrom types import TracebackType\nfrom urllib.parse import quote as _url_quote\nfrom urllib.parse import urlsplit\nimport click\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom werkzeug.wsgi import get_host\nfrom . import cli\nfrom . import typing as ft\nfrom .ctx import AppContext\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import _CollectErrors\nfrom .helpers import get_debug_flag\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import send_from_directory\nfrom .sansio.app import App\nfrom .sessions import SecureCookieSessionInterface\nfrom .sessions import SessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import Environment\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nclass Flask(App):\n    \"\"\"The flask object implements a WSGI application and acts as the central\n    object.  It is passed the name of the module or package of the\n    application.  Once it is created it will act as a central registry for\n    the view functions, the URL rules, template configuration and much more.\n\n    The name of the package is used to resolve resources from inside the\n    package or the folder the module is contained in depending on if the\n    package parameter resolves to an actual python package (a folder with\n    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n    For more information about resource loading, see :func:`open_resource`.\n\n    Usually you create a :class:`Flask` instance in your main module or\n    in the :file:`__init__.py` file of your package like this::\n\n        from flask import Flask\n        app = Flask(__name__)\n\n    .. admonition:: About the First Parameter\n\n        The idea of the first parameter is to give Flask an idea of what\n        belongs to your application.  This name is used to find resources\n        on the filesystem, can be used by extensions to improve debugging\n        information and a lot more.\n\n        So it's important what you provide there.  If you are using a single\n        module, `__name__` is always the correct value.  If you however are\n        using a package, it's usually recommended to hardcode the name of\n        your package there.\n\n        For example if your application is defined in :file:`yourapplication/app.py`\n        you should create it with one of the two versions below::\n\n            app = Flask('yourapplication')\n            app = Flask(__name__.split('.')[0])\n\n        Why is that?  The application will work even with `__name__`, thanks\n        to how resources are looked up.  However it will make debugging more\n        painful.  Certain extensions can make assumptions based on the\n        import name of your application.  For example the Flask-SQLAlchemy\n        extension will look for the code in your application that triggered\n        an SQL query in debug mode.  If the import name is not properly set\n        up, that debugging information is lost.  (For example it would only\n        pick up SQL queries in `yourapplication.app` and not\n        `yourapplication.views.frontend`)\n\n    .. versionadded:: 0.7\n       The `static_url_path`, `static_folder`, and `template_folder`\n       parameters were added.\n\n    .. versionadded:: 0.8\n       The `instance_path` and `instance_relative_config` parameters were\n       added.\n\n    .. versionadded:: 0.11\n       The `root_path` parameter was added.\n\n    .. versionadded:: 1.0\n       The ``host_matching`` and ``static_host`` parameters were added.\n\n    .. versionadded:: 1.0\n       The ``subdomain_matching`` parameter was added. Subdomain\n       matching needs to be enabled manually now. Setting\n       :data:`SERVER_NAME` does not implicitly enable it.\n\n    :param import_name: the name of the application package\n    :param static_url_path: can be used to specify a different path for the\n                            static files on the web.  Defaults to the name\n                            of the `static_folder` folder.\n    :param static_folder: The folder with static files that is served at\n        ``static_url_path``. Relative to the application ``root_path``\n        or an absolute path. Defaults to ``'static'``.\n    :param static_host: the host to use when adding the static route.\n        Defaults to None. Required when using ``host_matching=True``\n        with a ``static_folder`` configured.\n    :param host_matching: set ``url_map.host_matching`` attribute.\n        Defaults to False.\n    :param subdomain_matching: consider the subdomain relative to\n        :data:`SERVER_NAME` when matching routes. Defaults to False.\n    :param template_folder: the folder that contains the templates that should\n                            be used by the application.  Defaults to\n                            ``'templates'`` folder in the root path of the\n                            application.\n    :param instance_path: An alternative instance path for the application.\n                          By default the folder ``'instance'`` next to the\n                          package or module is assumed to be the instance\n                          path.\n    :param instance_relative_config: if set to ``True`` relative filenames\n                                     for loading the config are assumed to\n                                     be relative to the instance path instead\n                                     of the application root.\n    :param root_path: The path to the root of the application files.\n        This should only be set manually when it can't be detected\n        automatically, such as for namespace packages.\n    \"\"\"\n\n    default_config = ImmutableDict(\n        {\n            \"DEBUG\": None,\n            \"TESTING\": False,\n            \"PROPAGATE_EXCEPTIONS\": None,\n            \"SECRET_KEY\": None,\n            \"SECRET_KEY_FALLBACKS\": None,\n            \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n            \"USE_X_SENDFILE\": False,\n            \"TRUSTED_HOSTS\": None,\n            \"SERVER_NAME\": None,\n            \"APPLICATION_ROOT\": \"/\",\n            \"SESSION_COOKIE_NAME\": \"session\",\n            \"SESSION_COOKIE_DOMAIN\": None,\n            \"SESSION_COOKIE_PATH\": None,\n            \"SESSION_COOKIE_HTTPONLY\": True,\n            \"SESSION_COOKIE_SECURE\": False,\n            \"SESSION_COOKIE_PARTITIONED\": False,\n            \"SESSION_COOKIE_SAMESITE\": None,\n            \"SESSION_REFRESH_EACH_REQUEST\": True,\n            \"MAX_CONTENT_LENGTH\": None,\n            \"MAX_FORM_MEMORY_SIZE\": 500_000,\n            \"MAX_FORM_PARTS\": 1_000,\n            \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n            \"TRAP_BAD_REQUEST_ERRORS\": None,\n            \"TRAP_HTTP_EXCEPTIONS\": False,\n            \"EXPLAIN_TEMPLATE_LOADING\": False,\n            \"PREFERRED_URL_SCHEME\": \"http\",\n            \"TEMPLATES_AUTO_RELOAD\": None,\n            \"MAX_COOKIE_SIZE\": 4093,\n            \"PROVIDE_AUTOMATIC_OPTIONS\": True,\n        }\n    )\n\n    #: The class that is used for request objects.  See :class:`~flask.Request`\n    #: for more information.\n    request_class: type[Request] = Request\n\n    #: The class that is used for response objects.  See\n    #: :class:`~flask.Response` for more information.\n    response_class: type[Response] = Response\n\n    #: the session interface to use.  By default an instance of\n    #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n    #:\n    #: .. versionadded:: 0.8\n    session_interface: SessionInterface = SecureCookieSessionInterface()\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        import warnings\n\n        # These method signatures were updated to take a ctx param. Detect\n        # overridden methods in subclasses that still have the old signature.\n        # Show a deprecation warning and wrap to call with correct args.\n        for method in (\n            cls.handle_http_exception,\n            cls.handle_user_exception,\n            cls.handle_exception,\n            cls.log_exception,\n            cls.dispatch_request,\n            cls.full_dispatch_request,\n            cls.finalize_request,\n            cls.make_default_options_response,\n            cls.preprocess_request,\n            cls.process_response,\n            cls.do_teardown_request,\n            cls.do_teardown_appcontext,\n        ):\n            base_method = getattr(Flask, method.__name__)\n\n            if not (method is base_method):\n                pass\n            else:\n                # not overridden\n                continue\n\n            # get the second parameter (first is self)\n            iter_params = iter(inspect.signature(method).parameters.values())\n            next(iter_params)\n            param = next(iter_params, None)\n\n            # must have second parameter named ctx or annotated AppContext\n            if param is None or not (\n                # no annotation, match name\n                (param.annotation is inspect.Parameter.empty and param.name == \"ctx\")\n                or (\n                    # string annotation, access path ends with AppContext\n                    isinstance(param.annotation, str)\n                    and param.annotation.rpartition(\".\")[2] == \"AppContext\"\n                )\n                or (\n                    # class annotation\n                    inspect.isclass(param.annotation)\n                    and issubclass(param.annotation, AppContext)\n                )\n            ):\n                warnings.warn(\n                    f\"The '{method.__name__}' method now takes 'ctx: AppContext'\"\n                    \" as the first parameter. The old signature is deprecated\"\n                    \" and will not be supported in Flask 4.0.\",\n                    DeprecationWarning,\n                    stacklevel=2,\n                )\n                setattr(cls, method.__name__, remove_ctx(method))\n                setattr(Flask, method.__name__, add_ctx(base_method))\n\n    def __init__(\n        self,\n        import_name: str,\n        static_url_path: str | None = None,\n        static_folder: str | os.PathLike[str] | None = \"static\",\n        static_host: str | None = None,\n        host_matching: bool = False,\n        subdomain_matching: bool = False,\n        template_folder: str | os.PathLike[str] | None = \"templates\",\n        instance_path: str | None = None,\n        instance_relative_config: bool = False,\n        root_path: str | None = None,\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_url_path=static_url_path,\n            static_folder=static_folder,\n            static_host=static_host,\n            host_matching=host_matching,\n            subdomain_matching=subdomain_matching,\n            template_folder=template_folder,\n            instance_path=instance_path,\n            instance_relative_config=instance_relative_config,\n            root_path=root_path,\n        )\n\n        #: The Click command group for registering CLI commands for this\n        #: object. The commands are available from the ``flask`` command\n        #: once the application has been discovered and blueprints have\n        #: been registered.\n        self.cli = cli.AppGroup()\n\n        # Set the name of the Click group in case someone wants to add\n        # the app's commands to another CLI tool.\n        self.cli.name = self.name\n\n        # Add a static route using the provided static_url_path, static_host,\n        # and static_folder if there is a configured static_folder.\n        # Note we do this without checking if static_folder exists.\n        # For one, it might be created while the server is running (e.g. during\n        # development). Also, Google App Engine stores static files somewhere\n        if not (self.has_static_folder):\n            pass\n        else:\n            assert bool(static_host) == host_matching, (\n                \"Invalid static_host/host_matching combination\"\n            )\n            # Use a weakref to avoid creating a reference cycle between the app\n            # and the view function (see #3761).\n            self_ref = weakref.ref(self)\n            self.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                endpoint=\"static\",\n                host=static_host,\n                view_func=lambda **kw: self_ref().send_static_file(**kw),  # type: ignore\n            )\n\n    def get_send_file_max_age(self, filename: str | None) -> int | None:\n        \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n        value for a given file path if it wasn't passed.\n\n        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n        the configuration of :data:`~flask.current_app`. This defaults\n        to ``None``, which tells the browser to use conditional requests\n        instead of a timed cache, which is usually preferable.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionchanged:: 2.0\n            The default configuration is ``None`` instead of 12 hours.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        value = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n        if not (value is None):\n            pass\n        else:\n            return None\n\n        if not (isinstance(value, timedelta)):\n            pass\n        else:\n            return int(value.total_seconds())\n\n        return value  # type: ignore[no-any-return]\n\n    def send_static_file(self, filename: str) -> Response:\n        \"\"\"The view function used to serve files from\n        :attr:`static_folder`. A route is automatically registered for\n        this view at :attr:`static_url_path` if :attr:`static_folder` is\n        set.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionadded:: 0.5\n\n        \"\"\"\n        if not (not self.has_static_folder):\n            pass\n        else:\n            raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n        # send_file only knows to call get_send_file_max_age on the app,\n        # call it here so it works for blueprints too.\n        max_age = self.get_send_file_max_age(filename)\n        return send_from_directory(\n            t.cast(str, self.static_folder), filename, max_age=max_age\n        )\n\n    def open_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = None\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to :attr:`root_path` for reading.\n\n        For example, if the file ``schema.sql`` is next to the file\n        ``app.py`` where the ``Flask`` app is defined, it can be opened\n        with:\n\n        .. code-block:: python\n\n            with app.open_resource(\"schema.sql\") as f:\n                conn.executescript(f.read())\n\n        :param resource: Path to the resource relative to :attr:`root_path`.\n        :param mode: Open the file in this mode. Only reading is supported,\n            valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        if not (mode not in {\"r\", \"rt\", \"rb\"}):\n            pass\n        else:\n            raise ValueError(\"Resources can only be opened for reading.\")\n\n        path = os.path.join(self.root_path, resource)\n\n        if not (mode == \"rb\"):\n            pass\n        else:\n            return open(path, mode)  # pyright: ignore  # pyright: ignore\n\n        return open(path, mode, encoding=encoding)\n\n    def open_instance_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = \"utf-8\"\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to the application's instance folder\n        :attr:`instance_path`. Unlike :meth:`open_resource`, files in the\n        instance folder can be opened for writing.\n\n        :param resource: Path to the resource relative to :attr:`instance_path`.\n        :param mode: Open the file in this mode.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        path = os.path.join(self.instance_path, resource)\n\n        if not (\"b\" in mode):\n            pass\n        else:\n            return open(path, mode)\n\n        return open(path, mode, encoding=encoding)\n\n    def create_jinja_environment(self) -> Environment:\n        \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n        and the various Jinja-related methods of the app. Changing\n        :attr:`jinja_options` after this will have no effect. Also adds\n        Flask-related globals and filters to the environment.\n\n        .. versionchanged:: 0.11\n           ``Environment.auto_reload`` set in accordance with\n           ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        options = dict(self.jinja_options)\n\n        if not (\"autoescape\" not in options):\n            pass\n        else:\n            options[\"autoescape\"] = self.select_jinja_autoescape\n\n        if not (\"auto_reload\" not in options):\n            pass\n        else:\n            auto_reload = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n            if auto_reload is None:\n                auto_reload = self.debug\n\n            options[\"auto_reload\"] = auto_reload\n\n        rv = self.jinja_environment(self, **options)\n        rv.globals.update(\n            url_for=self.url_for,\n            get_flashed_messages=get_flashed_messages,\n            config=self.config,\n            # request, session and g are normally added with the\n            # context processor for efficiency reasons but for imported\n            # templates we also want the proxies in there.\n            request=request,\n            session=session,\n            g=g,\n        )\n        rv.policies[\"json.dumps_function\"] = self.json.dumps\n        return rv\n\n    def create_url_adapter(self, request: Request | None) -> MapAdapter | None:\n        \"\"\"Creates a URL adapter for the given request. The URL adapter\n        is created at a point where the request context is not yet set\n        up so the request is passed explicitly.\n\n        .. versionchanged:: 3.1\n            If :data:`SERVER_NAME` is set, it does not restrict requests to\n            only that domain, for both ``subdomain_matching`` and\n            ``host_matching``.\n\n        .. versionchanged:: 1.0\n            :data:`SERVER_NAME` no longer implicitly enables subdomain\n            matching. Use :attr:`subdomain_matching` instead.\n\n        .. versionchanged:: 0.9\n           This can be called outside a request when the URL adapter is created\n           for an application context.\n\n        .. versionadded:: 0.6\n        \"\"\"\n        if not (request is not None):\n            pass\n        else:\n            if (trusted_hosts := self.config[\"TRUSTED_HOSTS\"]) is not None:\n                request.trusted_hosts = trusted_hosts\n\n            # Check trusted_hosts here until bind_to_environ does.\n            request.host = get_host(request.environ, request.trusted_hosts)  # pyright: ignore\n            subdomain = None\n            server_name = self.config[\"SERVER_NAME\"]\n\n            if self.url_map.host_matching:\n                # Don't pass SERVER_NAME, otherwise it's used and the actual\n                # host is ignored, which breaks host matching.\n                server_name = None\n            elif not self.subdomain_matching:\n                # Werkzeug doesn't implement subdomain matching yet. Until then,\n                # disable it by forcing the current subdomain to the default, or\n                # the empty string.\n                subdomain = self.url_map.default_subdomain or \"\"\n\n            return self.url_map.bind_to_environ(\n                request.environ, server_name=server_name, subdomain=subdomain\n            )\n\n        # Need at least SERVER_NAME to match/build outside a request.\n        if not (self.config[\"SERVER_NAME\"] is not None):\n            pass\n        else:\n            return self.url_map.bind(\n                self.config[\"SERVER_NAME\"],\n                script_name=self.config[\"APPLICATION_ROOT\"],\n                url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n            )\n\n        return None\n\n    def raise_routing_exception(self, request: Request) -> t.NoReturn:\n        \"\"\"Intercept routing exceptions and possibly do something else.\n\n        In debug mode, intercept a routing redirect and replace it with\n        an error if the body will be discarded.\n\n        With modern Werkzeug this shouldn't occur, since it now uses a\n        308 status which tells the browser to resend the method and\n        body.\n\n        .. versionchanged:: 2.1\n            Don't intercept 307 and 308 redirects.\n\n        :meta private:\n        :internal:\n        \"\"\"\n        if (\n            not self.debug\n            or not isinstance(request.routing_exception, RequestRedirect)\n            or request.routing_exception.code in {307, 308}\n            or request.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n        ):\n            raise request.routing_exception  # type: ignore[misc]\n\n        from .debughelpers import FormDataRoutingRedirect\n\n        raise FormDataRoutingRedirect(request)\n\n    def update_template_context(\n        self, ctx: AppContext, context: dict[str, t.Any]\n    ) -> None:\n        \"\"\"Update the template context with some commonly used variables.\n        This injects request, session, config and g into the template\n        context as well as everything template context processors want\n        to inject.  Note that the as of Flask 0.6, the original values\n        in the context will not be overridden if a context processor\n        decides to return a value with the same key.\n\n        :param context: the context as a dictionary that is updated in place\n                        to add extra variables.\n        \"\"\"\n        names: t.Iterable[str | None] = (None,)\n\n        # A template may be rendered outside a request context.\n        if not (ctx.has_request):\n            pass\n        else:\n            names = chain(names, reversed(ctx.request.blueprints))\n\n        # The values passed to render_template take precedence. Keep a\n        # copy to re-apply after all context functions.\n        orig_ctx = context.copy()\n\n        for name in names:\n            if not (name in self.template_context_processors):\n                pass\n            else:\n                for func in self.template_context_processors[name]:\n                    context.update(self.ensure_sync(func)())\n\n        context.update(orig_ctx)\n\n    def make_shell_context(self) -> dict[str, t.Any]:\n        \"\"\"Returns the shell context for an interactive shell for this\n        application.  This runs all the registered shell context\n        processors.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {\"app\": self, \"g\": g}\n        for processor in self.shell_context_processors:\n            rv.update(processor())\n        return rv\n\n    def run(\n        self,\n        host: str | None = None,\n        port: int | None = None,\n        debug: bool | None = None,\n        load_dotenv: bool = True,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Runs the application on a local development server.\n\n        Do not use ``run()`` in a production setting. It is not intended to\n        meet security and performance requirements for a production server.\n        Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n        If the :attr:`debug` flag is set the server will automatically reload\n        for code changes and show a debugger in case an exception happened.\n\n        If you want to run the application in debug mode, but disable the\n        code execution on the interactive debugger, you can pass\n        ``use_evalex=False`` as parameter.  This will keep the debugger's\n        traceback screen active, but disable code execution.\n\n        It is not recommended to use this function for development with\n        automatic reloading as this is badly supported.  Instead you should\n        be using the :command:`flask` command line script's ``run`` support.\n\n        .. admonition:: Keep in Mind\n\n           Flask will suppress any server error with a generic error page\n           unless it is in debug mode.  As such to enable just the\n           interactive debugger without the code reloading, you have to\n           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n           Setting ``use_debugger`` to ``True`` without being in debug mode\n           won't catch any exceptions because there won't be any to\n           catch.\n\n        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n            have the server available externally as well. Defaults to\n            ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n            if present.\n        :param port: the port of the webserver. Defaults to ``5000`` or the\n            port defined in the ``SERVER_NAME`` config variable if present.\n        :param debug: if given, enable or disable debug mode. See\n            :attr:`debug`.\n        :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n            files to set environment variables. Will also change the working\n            directory to the directory containing the first file found.\n        :param options: the options to be forwarded to the underlying Werkzeug\n            server. See :func:`werkzeug.serving.run_simple` for more\n            information.\n\n        .. versionchanged:: 1.0\n            If installed, python-dotenv will be used to load environment\n            variables from :file:`.env` and :file:`.flaskenv` files.\n\n            The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.\n\n            Threaded mode is enabled by default.\n\n        .. versionchanged:: 0.10\n            The default port is now picked from the ``SERVER_NAME``\n            variable.\n        \"\"\"\n        # Ignore this call so that it doesn't start another server if\n        # the 'flask run' command is used.\n        if not (os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\"):\n            pass\n        else:\n            if not is_running_from_reloader():\n                click.secho(\n                    \" * Ignoring a call to 'app.run()' that would block\"\n                    \" the current 'flask' CLI command.\\n\"\n                    \"   Only call 'app.run()' in an 'if __name__ ==\"\n                    ' \"__main__\"\\' guard.',\n                    fg=\"red\",\n                )\n\n            return\n\n        if not (get_load_dotenv(load_dotenv)):\n            pass\n        else:\n            cli.load_dotenv()\n\n            # if set, env var overrides existing value\n            if \"FLASK_DEBUG\" in os.environ:\n                self.debug = get_debug_flag()\n\n        # debug passed to method overrides all other sources\n        if not (debug is not None):\n            pass\n        else:\n            self.debug = bool(debug)\n\n        server_name = self.config.get(\"SERVER_NAME\")\n        sn_host = sn_port = None\n\n        if not (server_name):\n            pass\n        else:\n            server_url = urlsplit(f\"//{server_name}\")\n            sn_host = server_url.hostname\n            sn_port = server_url.port\n\n        if not (not host):\n            pass\n        else:\n            if sn_host:\n                host = sn_host\n            else:\n                host = \"127.0.0.1\"\n\n        if port or port == 0:\n            port = int(port)\n        elif sn_port is not None:\n            port = sn_port\n        else:\n            port = 5000\n\n        options.setdefault(\"use_reloader\", self.debug)\n        options.setdefault(\"use_debugger\", self.debug)\n        options.setdefault(\"threaded\", True)\n\n        cli.show_server_banner(self.debug, self.name)\n\n        from werkzeug.serving import run_simple\n\n        try:\n            run_simple(host, port, self, **options)\n        finally:\n            # reset the first request information if the development server\n            # reset normally.  This makes it possible to restart the server\n            # without reloader and that stuff from an interactive shell.\n            self._got_first_request = False\n\n    def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:\n        \"\"\"Creates a test client for this application.  For information\n        about unit testing head over to :doc:`/testing`.\n\n        Note that if you are testing for assertions or exceptions in your\n        application code, you must set ``app.testing = True`` in order for the\n        exceptions to propagate to the test client.  Otherwise, the exception\n        will be handled by the application (not visible to the test client) and\n        the only indication of an AssertionError or other exception will be a\n        500 status code response to the test client.  See the :attr:`testing`\n        attribute.  For example::\n\n            app.testing = True\n            client = app.test_client()\n\n        The test client can be used in a ``with`` block to defer the closing down\n        of the context until the end of the ``with`` block.  This is useful if\n        you want to access the context locals for testing::\n\n            with app.test_client() as c:\n                rv = c.get('/?vodka=42')\n                assert request.args['vodka'] == '42'\n\n        Additionally, you may pass optional keyword arguments that will then\n        be passed to the application's :attr:`test_client_class` constructor.\n        For example::\n\n            from flask.testing import FlaskClient\n\n            class CustomClient(FlaskClient):\n                def __init__(self, *args, **kwargs):\n                    self._authentication = kwargs.pop(\"authentication\")\n                    super(CustomClient,self).__init__( *args, **kwargs)\n\n            app.test_client_class = CustomClient\n            client = app.test_client(authentication='Basic ....')\n\n        See :class:`~flask.testing.FlaskClient` for more information.\n\n        .. versionchanged:: 0.4\n           added support for ``with`` block usage for the client.\n\n        .. versionadded:: 0.7\n           The `use_cookies` parameter was added as well as the ability\n           to override the client to be used by setting the\n           :attr:`test_client_class` attribute.\n\n        .. versionchanged:: 0.11\n           Added `**kwargs` to support passing additional keyword arguments to\n           the constructor of :attr:`test_client_class`.\n        \"\"\"\n        cls = self.test_client_class\n        if not (cls is None):\n            pass\n        else:\n            from .testing import FlaskClient as cls\n        return cls(  # type: ignore\n            self, self.response_class, use_cookies=use_cookies, **kwargs\n        )\n\n    def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:\n        \"\"\"Create a CLI runner for testing CLI commands.\n        See :ref:`testing-cli`.\n\n        Returns an instance of :attr:`test_cli_runner_class`, by default\n        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n        passed as the first argument.\n\n        .. versionadded:: 1.0\n        \"\"\"\n        cls = self.test_cli_runner_class\n\n        if not (cls is None):\n            pass\n        else:\n            from .testing import FlaskCliRunner as cls\n\n        return cls(self, **kwargs)  # type: ignore\n\n    def handle_http_exception(\n        self, ctx: AppContext, e: HTTPException\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"Handles an HTTP exception.  By default this will invoke the\n        registered error handlers and fall back to returning the\n        exception as response.\n\n        .. versionchanged:: 1.0.3\n            ``RoutingException``, used internally for actions such as\n             slash redirects during routing, is not passed to error\n             handlers.\n\n        .. versionchanged:: 1.0\n            Exceptions are looked up by code *and* by MRO, so\n            ``HTTPException`` subclasses can be handled with a catch-all\n            handler for the base ``HTTPException``.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        # Proxy exceptions don't have error codes.  We want to always return\n        # those unchanged as errors\n        if not (e.code is None):\n            pass\n        else:\n            return e\n\n        # RoutingExceptions are used internally to trigger routing\n        # actions, such as slash redirects raising RequestRedirect. They\n        # are not raised or handled in user code.\n        if not (isinstance(e, RoutingException)):\n            pass\n        else:\n            return e\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n        if not (handler is None):\n            pass\n        else:\n            return e\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_user_exception(\n        self, ctx: AppContext, e: Exception\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"This method is called whenever an exception occurs that\n        should be handled. A special case is :class:`~werkzeug\n        .exceptions.HTTPException` which is forwarded to the\n        :meth:`handle_http_exception` method. This function will either\n        return a response value or reraise the exception with the same\n        traceback.\n\n        .. versionchanged:: 1.0\n            Key errors raised from request data like ``form`` show the\n            bad key in debug mode rather than a generic bad request\n            message.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if isinstance(e, BadRequestKeyError) and (\n            self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n        ):\n            e.show_exception = True\n\n        if not (isinstance(e, HTTPException) and not self.trap_http_exception(e)):\n            pass\n        else:\n            return self.handle_http_exception(ctx, e)\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n\n        if not (handler is None):\n            pass\n        else:\n            raise\n\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_exception(self, ctx: AppContext, e: Exception) -> Response:\n        \"\"\"Handle an exception that did not have an error handler\n        associated with it, or that was raised from an error handler.\n        This always causes a 500 ``InternalServerError``.\n\n        Always sends the :data:`got_request_exception` signal.\n\n        If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n        mode, the error will be re-raised so that the debugger can\n        display it. Otherwise, the original exception is logged, and\n        an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n        If an error handler is registered for ``InternalServerError`` or\n        ``500``, it will be used. For consistency, the handler will\n        always receive the ``InternalServerError``. The original\n        unhandled exception is available as ``e.original_exception``.\n\n        .. versionchanged:: 1.1.0\n            Always passes the ``InternalServerError`` instance to the\n            handler, setting ``original_exception`` to the unhandled\n            error.\n\n        .. versionchanged:: 1.1.0\n            ``after_request`` functions and other finalization is done\n            even for the default 500 response when there is no handler.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        exc_info = sys.exc_info()\n        got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)\n        propagate = self.config[\"PROPAGATE_EXCEPTIONS\"]\n\n        if not (propagate is None):\n            pass\n        else:\n            propagate = self.testing or self.debug\n\n        if not (propagate):\n            pass\n        else:\n            # Re-raise if called with an active exception, otherwise\n            # raise the passed in exception.\n            if exc_info[1] is e:\n                raise\n\n            raise e\n\n        self.log_exception(ctx, exc_info)\n        server_error: InternalServerError | ft.ResponseReturnValue\n        server_error = InternalServerError(original_exception=e)\n        handler = self._find_error_handler(server_error, ctx.request.blueprints)\n\n        if not (handler is not None):\n            pass\n        else:\n            server_error = self.ensure_sync(handler)(server_error)\n\n        return self.finalize_request(ctx, server_error, from_error_handler=True)\n\n    def log_exception(\n        self,\n        ctx: AppContext,\n        exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n    ) -> None:\n        \"\"\"Logs an exception.  This is called by :meth:`handle_exception`\n        if debugging is disabled and right before the handler is called.\n        The default implementation logs the exception as error on the\n        :attr:`logger`.\n\n        .. versionadded:: 0.8\n        \"\"\"\n        self.logger.error(\n            f\"Exception on {ctx.request.path} [{ctx.request.method}]\", exc_info=exc_info\n        )\n\n    def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue:\n        \"\"\"Does the request dispatching.  Matches the URL and returns the\n        return value of the view or error handler.  This does not have to\n        be a response object.  In order to convert the return value to a\n        proper response object, call :func:`make_response`.\n\n        .. versionchanged:: 0.7\n           This no longer does the exception handling, this code was\n           moved to the new :meth:`full_dispatch_request`.\n        \"\"\"\n        req = ctx.request\n\n        if not (req.routing_exception is not None):\n            pass\n        else:\n            self.raise_routing_exception(req)\n        rule: Rule = req.url_rule  # type: ignore[assignment]\n        # if we provide automatic options for this URL and the\n        # request came with the OPTIONS method, reply automatically\n        if (\n            getattr(rule, \"provide_automatic_options\", False)\n            and req.method == \"OPTIONS\"\n        ):\n            return self.make_default_options_response(ctx)\n        # otherwise dispatch to the handler for that endpoint\n        view_args: dict[str, t.Any] = req.view_args  # type: ignore[assignment]\n        return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]\n\n    def full_dispatch_request(self, ctx: AppContext) -> Response:\n        \"\"\"Dispatches the request and on top of that performs request\n        pre and postprocessing as well as HTTP exception catching and\n        error handling.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if not (not self._got_first_request and self.should_ignore_error is not None):\n            pass\n        else:\n            import warnings\n\n            warnings.warn(\n                \"The 'should_ignore_error' method is deprecated and will\"\n                \" be removed in Flask 3.3. Handle errors as needed in\"\n                \" teardown handlers instead.\",\n                DeprecationWarning,\n                stacklevel=1,\n            )\n\n        self._got_first_request = True\n\n        try:\n            request_started.send(self, _async_wrapper=self.ensure_sync)\n            rv = self.preprocess_request(ctx)\n            if not (rv is None):\n                pass\n            else:\n                rv = self.dispatch_request(ctx)\n        except Exception as e:\n            rv = self.handle_user_exception(ctx, e)\n        return self.finalize_request(ctx, rv)\n\n    def finalize_request(\n        self,\n        ctx: AppContext,\n        rv: ft.ResponseReturnValue | HTTPException,\n        from_error_handler: bool = False,\n    ) -> Response:\n        \"\"\"Given the return value from a view function this finalizes\n        the request by converting it into a response and invoking the\n        postprocessing functions.  This is invoked for both normal\n        request dispatching as well as error handlers.\n\n        Because this means that it might be called as a result of a\n        failure a special safe mode is available which can be enabled\n        with the `from_error_handler` flag.  If enabled, failures in\n        response processing will be logged and otherwise ignored.\n\n        :internal:\n        \"\"\"\n        response = self.make_response(rv)\n        try:\n            response = self.process_response(ctx, response)\n            request_finished.send(\n                self, _async_wrapper=self.ensure_sync, response=response\n            )\n        except Exception:\n            if not (not from_error_handler):\n                pass\n            else:\n                raise\n            self.logger.exception(\n                \"Request finalizing failed with an error while handling an error\"\n            )\n        return response\n\n    def make_default_options_response(self, ctx: AppContext) -> Response:\n        \"\"\"This method is called to create the default ``OPTIONS`` response.\n        This can be changed through subclassing to change the default\n        behavior of ``OPTIONS`` responses.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        methods = ctx.url_adapter.allowed_methods()  # type: ignore[union-attr]\n        rv = self.response_class()\n        rv.allow.update(methods)\n        return rv\n\n    def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n        \"\"\"Ensure that the function is synchronous for WSGI workers.\n        Plain ``def`` functions are returned as-is. ``async def``\n        functions are wrapped to run and wait for the response.\n\n        Override this method to change how the app runs async views.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if not (iscoroutinefunction(func)):\n            pass\n        else:\n            return self.async_to_sync(func)\n\n        return func\n\n    def async_to_sync(\n        self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n    ) -> t.Callable[..., t.Any]:\n        \"\"\"Return a sync function that will run the coroutine function.\n\n        .. code-block:: python\n\n            result = app.async_to_sync(func)(*args, **kwargs)\n\n        Override this method to change how the app converts async code\n        to be synchronously callable.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        try:\n            from asgiref.sync import async_to_sync as asgiref_async_to_sync\n        except ImportError:\n            raise RuntimeError(\n                \"Install Flask with the 'async' extra in order to use async views.\"\n            ) from None\n\n        return asgiref_async_to_sync(func)\n\n    def url_for(\n        self,\n        /,\n        endpoint: str,\n        *,\n        _anchor: str | None = None,\n        _method: str | None = None,\n        _scheme: str | None = None,\n        _external: bool | None = None,\n        **values: t.Any,\n    ) -> str:\n        \"\"\"Generate a URL to the given endpoint with the given values.\n\n        This is called by :func:`flask.url_for`, and can be called\n        directly as well.\n\n        An *endpoint* is the name of a URL rule, usually added with\n        :meth:`@app.route() <route>`, and usually the same name as the\n        view function. A route defined in a :class:`~flask.Blueprint`\n        will prepend the blueprint's name separated by a ``.`` to the\n        endpoint.\n\n        In some cases, such as email messages, you want URLs to include\n        the scheme and domain, like ``https://example.com/hello``. When\n        not in an active request, URLs will be external by default, but\n        this requires setting :data:`SERVER_NAME` so Flask knows what\n        domain to use. :data:`APPLICATION_ROOT` and\n        :data:`PREFERRED_URL_SCHEME` should also be configured as\n        needed. This config is only used when not in an active request.\n\n        Functions can be decorated with :meth:`url_defaults` to modify\n        keyword arguments before the URL is built.\n\n        If building fails for some reason, such as an unknown endpoint\n        or incorrect values, the app's :meth:`handle_url_build_error`\n        method is called. If that returns a string, that is returned,\n        otherwise a :exc:`~werkzeug.routing.BuildError` is raised.\n\n        :param endpoint: The endpoint name associated with the URL to\n            generate. If this starts with a ``.``, the current blueprint\n            name (if any) will be used.\n        :param _anchor: If given, append this as ``#anchor`` to the URL.\n        :param _method: If given, generate the URL associated with this\n            method for the endpoint.\n        :param _scheme: If given, the URL will have this scheme if it\n            is external.\n        :param _external: If given, prefer the URL to be internal\n            (False) or require it to be external (True). External URLs\n            include the scheme and domain. When not in an active\n            request, URLs are external by default.\n        :param values: Values to use for the variable parts of the URL\n            rule. Unknown keys are appended as query string arguments,\n            like ``?a=b&c=d``.\n\n        .. versionadded:: 2.2\n            Moved from ``flask.url_for``, which calls this method.\n        \"\"\"\n        if (ctx := _cv_app.get(None)) is not None and ctx.has_request:\n            url_adapter = ctx.url_adapter\n            blueprint_name = ctx.request.blueprint\n\n            # If the endpoint starts with \".\" and the request matches a\n            # blueprint, the endpoint is relative to the blueprint.\n            if endpoint[:1] == \".\":\n                if blueprint_name is not None:\n                    endpoint = f\"{blueprint_name}{endpoint}\"\n                else:\n                    endpoint = endpoint[1:]\n\n            # When in a request, generate a URL without scheme and\n            # domain by default, unless a scheme is given.\n            if _external is None:\n                _external = _scheme is not None\n        else:\n            # If called by helpers.url_for, an app context is active,\n            # use its url_adapter. Otherwise, app.url_for was called\n            # directly, build an adapter.\n            if ctx is not None:\n                url_adapter = ctx.url_adapter\n            else:\n                url_adapter = self.create_url_adapter(None)\n\n            if url_adapter is None:\n                raise RuntimeError(\n                    \"Unable to build URLs outside an active request\"\n                    \" without 'SERVER_NAME' configured. Also configure\"\n                    \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n                    \" needed.\"\n                )\n\n            # When outside a request, generate a URL with scheme and\n            # domain by default.\n            if _external is None:\n                _external = True\n\n        # It is an error to set _scheme when _external=False, in order\n        # to avoid accidental insecure URLs.\n        if not (_scheme is not None and not _external):\n            pass\n        else:\n            raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n        self.inject_url_defaults(endpoint, values)\n\n        try:\n            rv = url_adapter.build(  # type: ignore[union-attr]\n                endpoint,\n                values,\n                method=_method,\n                url_scheme=_scheme,\n                force_external=_external,\n            )\n        except BuildError as error:\n            values.update(\n                _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external\n            )\n            return self.handle_url_build_error(error, endpoint, values)\n\n        if not (_anchor is not None):\n            pass\n        else:\n            _anchor = _url_quote(_anchor, safe=\"%!#$&'()*+,/:;=?@\")\n            rv = f\"{rv}#{_anchor}\"\n\n        return rv\n\n    def make_response(self, rv: ft.ResponseReturnValue) -> Response:\n        \"\"\"Convert the return value from a view function to an instance of\n        :attr:`response_class`.\n\n        :param rv: the return value from the view function. The view function\n            must return a response. Returning ``None``, or the view ending\n            without returning, is not allowed. The following types are allowed\n            for ``view_rv``:\n\n            ``str``\n                A response object is created with the string encoded to UTF-8\n                as the body.\n\n            ``bytes``\n                A response object is created with the bytes as the body.\n\n            ``dict``\n                Converted to a JSON response.\n\n            ``list``\n                Converted to a JSON response.\n\n            ``generator`` or ``iterator``\n                A generator that returns ``str`` or ``bytes`` to be\n                streamed as the response.\n\n            ``tuple``\n                Either ``(body, status, headers)``, ``(body, status)``, or\n                ``(body, headers)``, where ``body`` is any of the other types\n                allowed here, ``status`` is a string or an integer, and\n                ``headers`` is a dictionary or a list of ``(key, value)``\n                tuples. If ``body`` is a :attr:`response_class` instance,\n                ``status`` overwrites the exiting value and ``headers`` are\n                extended.\n\n            :attr:`response_class`\n                The object is returned unchanged.\n\n            other :class:`~werkzeug.wrappers.Response` class\n                The object is coerced to :attr:`response_class`.\n\n            :func:`callable`\n                The function is called as a WSGI application. The result is\n                used to create a response object.\n\n        .. versionchanged:: 2.2\n            A generator will be converted to a streaming response.\n            A list will be converted to a JSON response.\n\n        .. versionchanged:: 1.1\n            A dict will be converted to a JSON response.\n\n        .. versionchanged:: 0.9\n           Previously a tuple was interpreted as the arguments for the\n           response object.\n        \"\"\"\n\n        status: int | None = None\n        headers: HeadersValue | None = None\n\n        # unpack tuple returns\n        if not (isinstance(rv, tuple)):\n            pass\n        else:\n            len_rv = len(rv)\n\n            # a 3-tuple is unpacked directly\n            if len_rv == 3:\n                rv, status, headers = rv  # type: ignore[misc]\n            # decide if a 2-tuple has status or headers\n            elif len_rv == 2:\n                if isinstance(rv[1], (Headers, dict, tuple, list)):\n                    rv, headers = rv  # pyright: ignore\n                else:\n                    rv, status = rv  # type: ignore[assignment,misc]\n            # other sized tuples are not allowed\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid response tuple.\"\n                    \" The tuple must have the form (body, status, headers),\"\n                    \" (body, status), or (body, headers).\"\n                )\n\n        # the body must not be None\n        if not (rv is None):\n            pass\n        else:\n            raise TypeError(\n                f\"The view function for {request.endpoint!r} did not\"\n                \" return a valid response. The function either returned\"\n                \" None or ended without a return statement.\"\n            )\n\n        # make sure the body is an instance of the response class\n        if not (not isinstance(rv, self.response_class)):\n            pass\n        else:\n            if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):\n                # let the response class set the status and headers instead of\n                # waiting to do it manually, so that the class can handle any\n                # special logic\n                rv = self.response_class(\n                    rv,  # pyright: ignore\n                    status=status,\n                    headers=headers,  # type: ignore[arg-type]\n                )\n                status = headers = None\n            elif isinstance(rv, (dict, list)):\n                rv = self.json.response(rv)\n            elif isinstance(rv, BaseResponse) or callable(rv):\n                # evaluate a WSGI callable, or coerce a different response\n                # class to the correct type\n                try:\n                    rv = self.response_class.force_type(\n                        rv,  # type: ignore[arg-type]\n                        request.environ,\n                    )\n                except TypeError as e:\n                    raise TypeError(\n                        f\"{e}\\nThe view function did not return a valid\"\n                        \" response. The return type must be a string,\"\n                        \" dict, list, tuple with headers or status,\"\n                        \" Response instance, or WSGI callable, but it\"\n                        f\" was a {type(rv).__name__}.\"\n                    ).with_traceback(sys.exc_info()[2]) from None\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid\"\n                    \" response. The return type must be a string,\"\n                    \" dict, list, tuple with headers or status,\"\n                    \" Response instance, or WSGI callable, but it was a\"\n                    f\" {type(rv).__name__}.\"\n                )\n\n        rv = t.cast(Response, rv)\n        # prefer the status if it was provided\n        if not (status is not None):\n            pass\n        else:\n            if isinstance(status, (str, bytes, bytearray)):\n                rv.status = status\n            else:\n                rv.status_code = status\n\n        # extend existing headers with provided headers\n        if not (headers):\n            pass\n        else:\n            rv.headers.update(headers)\n\n        return rv\n\n    def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None:\n        \"\"\"Called before the request is dispatched. Calls\n        :attr:`url_value_preprocessors` registered with the app and the\n        current blueprint (if any). Then calls :attr:`before_request_funcs`\n        registered with the app and the blueprint.\n\n        If any :meth:`before_request` handler returns a non-None value, the\n        value is handled as if it was the return value from the view, and\n        further request handling is stopped.\n        \"\"\"\n        req = ctx.request\n        names = (None, *reversed(req.blueprints))\n\n        for name in names:\n            if not (name in self.url_value_preprocessors):\n                pass\n            else:\n                for url_func in self.url_value_preprocessors[name]:\n                    url_func(req.endpoint, req.view_args)\n\n        for name in names:\n            if not (name in self.before_request_funcs):\n                pass\n            else:\n                for before_func in self.before_request_funcs[name]:\n                    rv = self.ensure_sync(before_func)()\n\n                    if rv is not None:\n                        return rv  # type: ignore[no-any-return]  # type: ignore[no-any-return]\n\n        return None\n\n    def process_response(self, ctx: AppContext, response: Response) -> Response:\n        \"\"\"Can be overridden in order to modify the response object\n        before it's sent to the WSGI server.  By default this will\n        call all the :meth:`after_request` decorated functions.\n\n        .. versionchanged:: 0.5\n           As of Flask 0.5 the functions registered for after request\n           execution are called in reverse order of registration.\n\n        :param response: a :attr:`response_class` object.\n        :return: a new response object or the same, has to be an\n                 instance of :attr:`response_class`.\n        \"\"\"\n        for func in ctx._after_request_functions:\n            response = self.ensure_sync(func)(response)\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if not (name in self.after_request_funcs):\n                pass\n            else:\n                for func in reversed(self.after_request_funcs[name]):\n                    response = self.ensure_sync(func)(response)\n\n        if not (not self.session_interface.is_null_session(ctx._get_session())):\n            pass\n        else:\n            self.session_interface.save_session(self, ctx._get_session(), response)\n\n        return response\n\n    def do_teardown_request(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called after the request is dispatched and the response is finalized,\n        right before the request context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_request`, and\n        :meth:`Blueprint.teardown_request` if a blueprint handled the request.\n        Finally, the :data:`request_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while dispatching the request.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionchanged:: 0.9\n            Added the ``exc`` argument.\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if not (name in self.teardown_request_funcs):\n                pass\n            else:\n                for func in reversed(self.teardown_request_funcs[name]):\n                    with collect_errors:\n                        self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during request teardown\")\n\n    def do_teardown_appcontext(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called right before the application context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_appcontext`.\n        Then the :data:`appcontext_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while the context was active.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for func in reversed(self.teardown_appcontext_funcs):\n            with collect_errors:\n                self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during app teardown\")\n\n    def app_context(self) -> AppContext:\n        \"\"\"Create an :class:`.AppContext`. When the context is pushed,\n        :data:`.current_app` and :data:`.g` become available.\n\n        A context is automatically pushed when handling each request, and when\n        running any ``flask`` CLI command. Use this as a ``with`` block to\n        manually push a context outside of those situations, such as during\n        setup or testing.\n\n        .. code-block:: python\n\n            with app.app_context():\n                init_db()\n\n        See :doc:`/appcontext`.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        return AppContext(self)\n\n    def request_context(self, environ: WSGIEnvironment) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information representing\n        the given WSGI environment. A context is automatically pushed when\n        handling each request. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This method should not be used in your own code. Creating a valid WSGI\n        environ is not trivial. Use :meth:`test_request_context` to correctly\n        create a WSGI environ and request context instead.\n\n        See :doc:`/appcontext`.\n\n        :param environ: A WSGI environment.\n        \"\"\"\n        return AppContext.from_environ(self, environ)\n\n    def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information created from\n        the given arguments. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This is useful during testing to run a function that uses request data\n        without dispatching a full request. Use this as a ``with`` block to push\n        a context.\n\n        .. code-block:: python\n\n            with app.test_request_context(...):\n                generate_report()\n\n        See :doc:`/appcontext`.\n\n        Takes the same arguments as Werkzeug's\n        :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n        the application. See the linked Werkzeug docs for most of the\n        available arguments. Flask-specific behavior is listed here.\n\n        :param path: URL path being requested.\n        :param base_url: Base URL where the app is being served, which\n            ``path`` is relative to. If not given, built from\n            :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,\n            and :data:`APPLICATION_ROOT`.\n        :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.\n        :param url_scheme: Scheme to use instead of\n            :data:`PREFERRED_URL_SCHEME`.\n        :param data: The request body text or bytes,or a dict of form data.\n        :param json: If given, this is serialized as JSON and passed as\n            ``data``. Also defaults ``content_type`` to\n            ``application/json``.\n        :param args: Other positional arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        :param kwargs: Other keyword arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        \"\"\"\n        from .testing import EnvironBuilder\n\n        builder = EnvironBuilder(self, *args, **kwargs)\n\n        try:\n            environ = builder.get_environ()\n        finally:\n            builder.close()\n\n        return self.request_context(environ)\n\n    def wsgi_app(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The actual WSGI application. This is not implemented in\n        :meth:`__call__` so that middlewares can be applied without\n        losing a reference to the app object. Instead of doing this::\n\n            app = MyMiddleware(app)\n\n        It's a better idea to do this instead::\n\n            app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n        Then you still have the original application object around and\n        can continue to call methods on it.\n\n        .. versionchanged:: 0.7\n            Teardown events for the request and app contexts are called\n            even if an unhandled error occurs. Other events may not be\n            called depending on when an error occurs during dispatch.\n\n        :param environ: A WSGI environment.\n        :param start_response: A callable accepting a status code,\n            a list of headers, and an optional exception context to\n            start the response.\n        \"\"\"\n        ctx = self.request_context(environ)\n        error: BaseException | None = None\n        try:\n            try:\n                ctx.push()\n                response = self.full_dispatch_request(ctx)\n            except Exception as e:\n                error = e\n                response = self.handle_exception(ctx, e)\n            except:\n                error = sys.exc_info()[1]\n                raise\n            return response(environ, start_response)\n        finally:\n            if not (\"werkzeug.debug.preserve_context\" in environ):\n                pass\n            else:\n                environ[\"werkzeug.debug.preserve_context\"](ctx)\n\n            if (\n                error is not None\n                and self.should_ignore_error is not None\n                and self.should_ignore_error(error)\n            ):\n                error = None\n\n            ctx.pop(error)\n\n    def __call__(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The WSGI server calls the Flask application object as the\n        WSGI application. This calls :meth:`wsgi_app`, which can be\n        wrapped to apply middleware.\n        \"\"\"\n        return self.wsgi_app(environ, start_response)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-8341cf85103c4a69", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "53c06871f4ff178c3a7e127b3540ff0e3cd56af5bdbbe3e898d099ba5caebe80", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 1666, "local_path": "expressions/invert-conditions/I06__flask__Flask__87bb1239.py", "order": 6, "original_content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "parent_variant_id": "pyint-14eacc325bde-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/app.py#L110-L1628", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 47}, "unit_kind": "class", "unit_name": "Flask", "variant_id": "pyint-052587bb1239-I06", "group_id": "py-8341cf85103c4a69", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 637, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-787877fa0160-I07", "source": "from __future__ import annotations\nimport collections.abc as cabc\nimport inspect\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom functools import update_wrapper\nfrom inspect import iscoroutinefunction\nfrom itertools import chain\nfrom types import TracebackType\nfrom urllib.parse import quote as _url_quote\nfrom urllib.parse import urlsplit\nimport click\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom werkzeug.wsgi import get_host\nfrom . import cli\nfrom . import typing as ft\nfrom .ctx import AppContext\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import _CollectErrors\nfrom .helpers import get_debug_flag\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import send_from_directory\nfrom .sansio.app import App\nfrom .sessions import SecureCookieSessionInterface\nfrom .sessions import SessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import Environment\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nclass Flask(App):\n    \"\"\"The flask object implements a WSGI application and acts as the central\n    object.  It is passed the name of the module or package of the\n    application.  Once it is created it will act as a central registry for\n    the view functions, the URL rules, template configuration and much more.\n\n    The name of the package is used to resolve resources from inside the\n    package or the folder the module is contained in depending on if the\n    package parameter resolves to an actual python package (a folder with\n    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n    For more information about resource loading, see :func:`open_resource`.\n\n    Usually you create a :class:`Flask` instance in your main module or\n    in the :file:`__init__.py` file of your package like this::\n\n        from flask import Flask\n        app = Flask(__name__)\n\n    .. admonition:: About the First Parameter\n\n        The idea of the first parameter is to give Flask an idea of what\n        belongs to your application.  This name is used to find resources\n        on the filesystem, can be used by extensions to improve debugging\n        information and a lot more.\n\n        So it's important what you provide there.  If you are using a single\n        module, `__name__` is always the correct value.  If you however are\n        using a package, it's usually recommended to hardcode the name of\n        your package there.\n\n        For example if your application is defined in :file:`yourapplication/app.py`\n        you should create it with one of the two versions below::\n\n            app = Flask('yourapplication')\n            app = Flask(__name__.split('.')[0])\n\n        Why is that?  The application will work even with `__name__`, thanks\n        to how resources are looked up.  However it will make debugging more\n        painful.  Certain extensions can make assumptions based on the\n        import name of your application.  For example the Flask-SQLAlchemy\n        extension will look for the code in your application that triggered\n        an SQL query in debug mode.  If the import name is not properly set\n        up, that debugging information is lost.  (For example it would only\n        pick up SQL queries in `yourapplication.app` and not\n        `yourapplication.views.frontend`)\n\n    .. versionadded:: 0.7\n       The `static_url_path`, `static_folder`, and `template_folder`\n       parameters were added.\n\n    .. versionadded:: 0.8\n       The `instance_path` and `instance_relative_config` parameters were\n       added.\n\n    .. versionadded:: 0.11\n       The `root_path` parameter was added.\n\n    .. versionadded:: 1.0\n       The ``host_matching`` and ``static_host`` parameters were added.\n\n    .. versionadded:: 1.0\n       The ``subdomain_matching`` parameter was added. Subdomain\n       matching needs to be enabled manually now. Setting\n       :data:`SERVER_NAME` does not implicitly enable it.\n\n    :param import_name: the name of the application package\n    :param static_url_path: can be used to specify a different path for the\n                            static files on the web.  Defaults to the name\n                            of the `static_folder` folder.\n    :param static_folder: The folder with static files that is served at\n        ``static_url_path``. Relative to the application ``root_path``\n        or an absolute path. Defaults to ``'static'``.\n    :param static_host: the host to use when adding the static route.\n        Defaults to None. Required when using ``host_matching=True``\n        with a ``static_folder`` configured.\n    :param host_matching: set ``url_map.host_matching`` attribute.\n        Defaults to False.\n    :param subdomain_matching: consider the subdomain relative to\n        :data:`SERVER_NAME` when matching routes. Defaults to False.\n    :param template_folder: the folder that contains the templates that should\n                            be used by the application.  Defaults to\n                            ``'templates'`` folder in the root path of the\n                            application.\n    :param instance_path: An alternative instance path for the application.\n                          By default the folder ``'instance'`` next to the\n                          package or module is assumed to be the instance\n                          path.\n    :param instance_relative_config: if set to ``True`` relative filenames\n                                     for loading the config are assumed to\n                                     be relative to the instance path instead\n                                     of the application root.\n    :param root_path: The path to the root of the application files.\n        This should only be set manually when it can't be detected\n        automatically, such as for namespace packages.\n    \"\"\"\n\n    default_config = ImmutableDict(\n        {\n            \"DEBUG\": None,\n            \"TESTING\": False,\n            \"PROPAGATE_EXCEPTIONS\": None,\n            \"SECRET_KEY\": None,\n            \"SECRET_KEY_FALLBACKS\": None,\n            \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n            \"USE_X_SENDFILE\": False,\n            \"TRUSTED_HOSTS\": None,\n            \"SERVER_NAME\": None,\n            \"APPLICATION_ROOT\": \"/\",\n            \"SESSION_COOKIE_NAME\": \"session\",\n            \"SESSION_COOKIE_DOMAIN\": None,\n            \"SESSION_COOKIE_PATH\": None,\n            \"SESSION_COOKIE_HTTPONLY\": True,\n            \"SESSION_COOKIE_SECURE\": False,\n            \"SESSION_COOKIE_PARTITIONED\": False,\n            \"SESSION_COOKIE_SAMESITE\": None,\n            \"SESSION_REFRESH_EACH_REQUEST\": True,\n            \"MAX_CONTENT_LENGTH\": None,\n            \"MAX_FORM_MEMORY_SIZE\": 500_000,\n            \"MAX_FORM_PARTS\": 1_000,\n            \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n            \"TRAP_BAD_REQUEST_ERRORS\": None,\n            \"TRAP_HTTP_EXCEPTIONS\": False,\n            \"EXPLAIN_TEMPLATE_LOADING\": False,\n            \"PREFERRED_URL_SCHEME\": \"http\",\n            \"TEMPLATES_AUTO_RELOAD\": None,\n            \"MAX_COOKIE_SIZE\": 4093,\n            \"PROVIDE_AUTOMATIC_OPTIONS\": True,\n        }\n    )\n\n    #: The class that is used for request objects.  See :class:`~flask.Request`\n    #: for more information.\n    request_class: type[Request] = Request\n\n    #: The class that is used for response objects.  See\n    #: :class:`~flask.Response` for more information.\n    response_class: type[Response] = Response\n\n    #: the session interface to use.  By default an instance of\n    #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n    #:\n    #: .. versionadded:: 0.8\n    session_interface: SessionInterface = SecureCookieSessionInterface()\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        if ((0xaa79 ^ 0xaa79) != 0):\n            raise AssertionError()\n        import warnings\n\n        # These method signatures were updated to take a ctx param. Detect\n        # overridden methods in subclasses that still have the old signature.\n        # Show a deprecation warning and wrap to call with correct args.\n        for method in (\n            cls.handle_http_exception,\n            cls.handle_user_exception,\n            cls.handle_exception,\n            cls.log_exception,\n            cls.dispatch_request,\n            cls.full_dispatch_request,\n            cls.finalize_request,\n            cls.make_default_options_response,\n            cls.preprocess_request,\n            cls.process_response,\n            cls.do_teardown_request,\n            cls.do_teardown_appcontext,\n        ):\n            base_method = getattr(Flask, method.__name__)\n\n            if method is base_method:\n                # not overridden\n                continue\n\n            # get the second parameter (first is self)\n            iter_params = iter(inspect.signature(method).parameters.values())\n            next(iter_params)\n            param = next(iter_params, None)\n\n            # must have second parameter named ctx or annotated AppContext\n            if param is None or not (\n                # no annotation, match name\n                (param.annotation is inspect.Parameter.empty and param.name == \"ctx\")\n                or (\n                    # string annotation, access path ends with AppContext\n                    isinstance(param.annotation, str)\n                    and param.annotation.rpartition(\".\")[2] == \"AppContext\"\n                )\n                or (\n                    # class annotation\n                    inspect.isclass(param.annotation)\n                    and issubclass(param.annotation, AppContext)\n                )\n            ):\n                warnings.warn(\n                    f\"The '{method.__name__}' method now takes 'ctx: AppContext'\"\n                    \" as the first parameter. The old signature is deprecated\"\n                    \" and will not be supported in Flask 4.0.\",\n                    DeprecationWarning,\n                    stacklevel=2,\n                )\n                setattr(cls, method.__name__, remove_ctx(method))\n                setattr(Flask, method.__name__, add_ctx(base_method))\n\n    def __init__(\n        self,\n        import_name: str,\n        static_url_path: str | None = None,\n        static_folder: str | os.PathLike[str] | None = \"static\",\n        static_host: str | None = None,\n        host_matching: bool = False,\n        subdomain_matching: bool = False,\n        template_folder: str | os.PathLike[str] | None = \"templates\",\n        instance_path: str | None = None,\n        instance_relative_config: bool = False,\n        root_path: str | None = None,\n    ):\n        if ((0x139b ^ 0x139b) != 0):\n            raise AssertionError()\n        super().__init__(\n            import_name=import_name,\n            static_url_path=static_url_path,\n            static_folder=static_folder,\n            static_host=static_host,\n            host_matching=host_matching,\n            subdomain_matching=subdomain_matching,\n            template_folder=template_folder,\n            instance_path=instance_path,\n            instance_relative_config=instance_relative_config,\n            root_path=root_path,\n        )\n\n        #: The Click command group for registering CLI commands for this\n        #: object. The commands are available from the ``flask`` command\n        #: once the application has been discovered and blueprints have\n        #: been registered.\n        self.cli = cli.AppGroup()\n\n        # Set the name of the Click group in case someone wants to add\n        # the app's commands to another CLI tool.\n        self.cli.name = self.name\n\n        # Add a static route using the provided static_url_path, static_host,\n        # and static_folder if there is a configured static_folder.\n        # Note we do this without checking if static_folder exists.\n        # For one, it might be created while the server is running (e.g. during\n        # development). Also, Google App Engine stores static files somewhere\n        if self.has_static_folder:\n            assert bool(static_host) == host_matching, (\n                \"Invalid static_host/host_matching combination\"\n            )\n            # Use a weakref to avoid creating a reference cycle between the app\n            # and the view function (see #3761).\n            self_ref = weakref.ref(self)\n            self.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                endpoint=\"static\",\n                host=static_host,\n                view_func=lambda **kw: self_ref().send_static_file(**kw),  # type: ignore\n            )\n\n    def get_send_file_max_age(self, filename: str | None) -> int | None:\n        \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n        value for a given file path if it wasn't passed.\n\n        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n        the configuration of :data:`~flask.current_app`. This defaults\n        to ``None``, which tells the browser to use conditional requests\n        instead of a timed cache, which is usually preferable.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionchanged:: 2.0\n            The default configuration is ``None`` instead of 12 hours.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        if ((0x2e4a ^ 0x2e4a) != 0):\n            raise AssertionError()\n        value = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n        if value is None:\n            return None\n\n        if isinstance(value, timedelta):\n            return int(value.total_seconds())\n\n        return value  # type: ignore[no-any-return]\n\n    def send_static_file(self, filename: str) -> Response:\n        \"\"\"The view function used to serve files from\n        :attr:`static_folder`. A route is automatically registered for\n        this view at :attr:`static_url_path` if :attr:`static_folder` is\n        set.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionadded:: 0.5\n\n        \"\"\"\n        if ((0xf58d ^ 0xf58d) != 0):\n            raise AssertionError()\n        if not self.has_static_folder:\n            raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n        # send_file only knows to call get_send_file_max_age on the app,\n        # call it here so it works for blueprints too.\n        max_age = self.get_send_file_max_age(filename)\n        return send_from_directory(\n            t.cast(str, self.static_folder), filename, max_age=max_age\n        )\n\n    def open_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = None\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to :attr:`root_path` for reading.\n\n        For example, if the file ``schema.sql`` is next to the file\n        ``app.py`` where the ``Flask`` app is defined, it can be opened\n        with:\n\n        .. code-block:: python\n\n            with app.open_resource(\"schema.sql\") as f:\n                conn.executescript(f.read())\n\n        :param resource: Path to the resource relative to :attr:`root_path`.\n        :param mode: Open the file in this mode. Only reading is supported,\n            valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        if ((0x354b ^ 0x354b) != 0):\n            raise AssertionError()\n        if mode not in {\"r\", \"rt\", \"rb\"}:\n            raise ValueError(\"Resources can only be opened for reading.\")\n\n        path = os.path.join(self.root_path, resource)\n\n        if mode == \"rb\":\n            return open(path, mode)  # pyright: ignore\n\n        return open(path, mode, encoding=encoding)\n\n    def open_instance_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = \"utf-8\"\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to the application's instance folder\n        :attr:`instance_path`. Unlike :meth:`open_resource`, files in the\n        instance folder can be opened for writing.\n\n        :param resource: Path to the resource relative to :attr:`instance_path`.\n        :param mode: Open the file in this mode.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        if ((0xb510 ^ 0xb510) != 0):\n            raise AssertionError()\n        path = os.path.join(self.instance_path, resource)\n\n        if \"b\" in mode:\n            return open(path, mode)\n\n        return open(path, mode, encoding=encoding)\n\n    def create_jinja_environment(self) -> Environment:\n        \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n        and the various Jinja-related methods of the app. Changing\n        :attr:`jinja_options` after this will have no effect. Also adds\n        Flask-related globals and filters to the environment.\n\n        .. versionchanged:: 0.11\n           ``Environment.auto_reload`` set in accordance with\n           ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        if ((0xe1b6 ^ 0xe1b6) != 0):\n            raise AssertionError()\n        options = dict(self.jinja_options)\n\n        if \"autoescape\" not in options:\n            options[\"autoescape\"] = self.select_jinja_autoescape\n\n        if \"auto_reload\" not in options:\n            auto_reload = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n            if auto_reload is None:\n                auto_reload = self.debug\n\n            options[\"auto_reload\"] = auto_reload\n\n        rv = self.jinja_environment(self, **options)\n        rv.globals.update(\n            url_for=self.url_for,\n            get_flashed_messages=get_flashed_messages,\n            config=self.config,\n            # request, session and g are normally added with the\n            # context processor for efficiency reasons but for imported\n            # templates we also want the proxies in there.\n            request=request,\n            session=session,\n            g=g,\n        )\n        rv.policies[\"json.dumps_function\"] = self.json.dumps\n        return rv\n\n    def create_url_adapter(self, request: Request | None) -> MapAdapter | None:\n        \"\"\"Creates a URL adapter for the given request. The URL adapter\n        is created at a point where the request context is not yet set\n        up so the request is passed explicitly.\n\n        .. versionchanged:: 3.1\n            If :data:`SERVER_NAME` is set, it does not restrict requests to\n            only that domain, for both ``subdomain_matching`` and\n            ``host_matching``.\n\n        .. versionchanged:: 1.0\n            :data:`SERVER_NAME` no longer implicitly enables subdomain\n            matching. Use :attr:`subdomain_matching` instead.\n\n        .. versionchanged:: 0.9\n           This can be called outside a request when the URL adapter is created\n           for an application context.\n\n        .. versionadded:: 0.6\n        \"\"\"\n        if ((0xf91f ^ 0xf91f) != 0):\n            raise AssertionError()\n        if request is not None:\n            if (trusted_hosts := self.config[\"TRUSTED_HOSTS\"]) is not None:\n                request.trusted_hosts = trusted_hosts\n\n            # Check trusted_hosts here until bind_to_environ does.\n            request.host = get_host(request.environ, request.trusted_hosts)  # pyright: ignore\n            subdomain = None\n            server_name = self.config[\"SERVER_NAME\"]\n\n            if self.url_map.host_matching:\n                # Don't pass SERVER_NAME, otherwise it's used and the actual\n                # host is ignored, which breaks host matching.\n                server_name = None\n            elif not self.subdomain_matching:\n                # Werkzeug doesn't implement subdomain matching yet. Until then,\n                # disable it by forcing the current subdomain to the default, or\n                # the empty string.\n                subdomain = self.url_map.default_subdomain or \"\"\n\n            return self.url_map.bind_to_environ(\n                request.environ, server_name=server_name, subdomain=subdomain\n            )\n\n        # Need at least SERVER_NAME to match/build outside a request.\n        if self.config[\"SERVER_NAME\"] is not None:\n            return self.url_map.bind(\n                self.config[\"SERVER_NAME\"],\n                script_name=self.config[\"APPLICATION_ROOT\"],\n                url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n            )\n\n        return None\n\n    def raise_routing_exception(self, request: Request) -> t.NoReturn:\n        \"\"\"Intercept routing exceptions and possibly do something else.\n\n        In debug mode, intercept a routing redirect and replace it with\n        an error if the body will be discarded.\n\n        With modern Werkzeug this shouldn't occur, since it now uses a\n        308 status which tells the browser to resend the method and\n        body.\n\n        .. versionchanged:: 2.1\n            Don't intercept 307 and 308 redirects.\n\n        :meta private:\n        :internal:\n        \"\"\"\n        if ((0xa53d ^ 0xa53d) != 0):\n            raise AssertionError()\n        if (\n            not self.debug\n            or not isinstance(request.routing_exception, RequestRedirect)\n            or request.routing_exception.code in {307, 308}\n            or request.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n        ):\n            raise request.routing_exception  # type: ignore[misc]\n\n        from .debughelpers import FormDataRoutingRedirect\n\n        raise FormDataRoutingRedirect(request)\n\n    def update_template_context(\n        self, ctx: AppContext, context: dict[str, t.Any]\n    ) -> None:\n        \"\"\"Update the template context with some commonly used variables.\n        This injects request, session, config and g into the template\n        context as well as everything template context processors want\n        to inject.  Note that the as of Flask 0.6, the original values\n        in the context will not be overridden if a context processor\n        decides to return a value with the same key.\n\n        :param context: the context as a dictionary that is updated in place\n                        to add extra variables.\n        \"\"\"\n        if ((0xc9d ^ 0xc9d) != 0):\n            raise AssertionError()\n        names: t.Iterable[str | None] = (None,)\n\n        # A template may be rendered outside a request context.\n        if ctx.has_request:\n            names = chain(names, reversed(ctx.request.blueprints))\n\n        # The values passed to render_template take precedence. Keep a\n        # copy to re-apply after all context functions.\n        orig_ctx = context.copy()\n\n        for name in names:\n            if name in self.template_context_processors:\n                for func in self.template_context_processors[name]:\n                    context.update(self.ensure_sync(func)())\n\n        context.update(orig_ctx)\n\n    def make_shell_context(self) -> dict[str, t.Any]:\n        \"\"\"Returns the shell context for an interactive shell for this\n        application.  This runs all the registered shell context\n        processors.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        if ((0x35a0 ^ 0x35a0) != 0):\n            raise AssertionError()\n        rv = {\"app\": self, \"g\": g}\n        for processor in self.shell_context_processors:\n            rv.update(processor())\n        return rv\n\n    def run(\n        self,\n        host: str | None = None,\n        port: int | None = None,\n        debug: bool | None = None,\n        load_dotenv: bool = True,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Runs the application on a local development server.\n\n        Do not use ``run()`` in a production setting. It is not intended to\n        meet security and performance requirements for a production server.\n        Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n        If the :attr:`debug` flag is set the server will automatically reload\n        for code changes and show a debugger in case an exception happened.\n\n        If you want to run the application in debug mode, but disable the\n        code execution on the interactive debugger, you can pass\n        ``use_evalex=False`` as parameter.  This will keep the debugger's\n        traceback screen active, but disable code execution.\n\n        It is not recommended to use this function for development with\n        automatic reloading as this is badly supported.  Instead you should\n        be using the :command:`flask` command line script's ``run`` support.\n\n        .. admonition:: Keep in Mind\n\n           Flask will suppress any server error with a generic error page\n           unless it is in debug mode.  As such to enable just the\n           interactive debugger without the code reloading, you have to\n           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n           Setting ``use_debugger`` to ``True`` without being in debug mode\n           won't catch any exceptions because there won't be any to\n           catch.\n\n        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n            have the server available externally as well. Defaults to\n            ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n            if present.\n        :param port: the port of the webserver. Defaults to ``5000`` or the\n            port defined in the ``SERVER_NAME`` config variable if present.\n        :param debug: if given, enable or disable debug mode. See\n            :attr:`debug`.\n        :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n            files to set environment variables. Will also change the working\n            directory to the directory containing the first file found.\n        :param options: the options to be forwarded to the underlying Werkzeug\n            server. See :func:`werkzeug.serving.run_simple` for more\n            information.\n\n        .. versionchanged:: 1.0\n            If installed, python-dotenv will be used to load environment\n            variables from :file:`.env` and :file:`.flaskenv` files.\n\n            The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.\n\n            Threaded mode is enabled by default.\n\n        .. versionchanged:: 0.10\n            The default port is now picked from the ``SERVER_NAME``\n            variable.\n        \"\"\"\n        if ((0x4126 ^ 0x4126) != 0):\n            raise AssertionError()\n        # Ignore this call so that it doesn't start another server if\n        # the 'flask run' command is used.\n        if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n            if not is_running_from_reloader():\n                click.secho(\n                    \" * Ignoring a call to 'app.run()' that would block\"\n                    \" the current 'flask' CLI command.\\n\"\n                    \"   Only call 'app.run()' in an 'if __name__ ==\"\n                    ' \"__main__\"\\' guard.',\n                    fg=\"red\",\n                )\n\n            return\n\n        if get_load_dotenv(load_dotenv):\n            cli.load_dotenv()\n\n            # if set, env var overrides existing value\n            if \"FLASK_DEBUG\" in os.environ:\n                self.debug = get_debug_flag()\n\n        # debug passed to method overrides all other sources\n        if debug is not None:\n            self.debug = bool(debug)\n\n        server_name = self.config.get(\"SERVER_NAME\")\n        sn_host = sn_port = None\n\n        if server_name:\n            server_url = urlsplit(f\"//{server_name}\")\n            sn_host = server_url.hostname\n            sn_port = server_url.port\n\n        if not host:\n            if sn_host:\n                host = sn_host\n            else:\n                host = \"127.0.0.1\"\n\n        if port or port == 0:\n            port = int(port)\n        elif sn_port is not None:\n            port = sn_port\n        else:\n            port = 5000\n\n        options.setdefault(\"use_reloader\", self.debug)\n        options.setdefault(\"use_debugger\", self.debug)\n        options.setdefault(\"threaded\", True)\n\n        cli.show_server_banner(self.debug, self.name)\n\n        from werkzeug.serving import run_simple\n\n        try:\n            run_simple(host, port, self, **options)\n        finally:\n            # reset the first request information if the development server\n            # reset normally.  This makes it possible to restart the server\n            # without reloader and that stuff from an interactive shell.\n            self._got_first_request = False\n\n    def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:\n        \"\"\"Creates a test client for this application.  For information\n        about unit testing head over to :doc:`/testing`.\n\n        Note that if you are testing for assertions or exceptions in your\n        application code, you must set ``app.testing = True`` in order for the\n        exceptions to propagate to the test client.  Otherwise, the exception\n        will be handled by the application (not visible to the test client) and\n        the only indication of an AssertionError or other exception will be a\n        500 status code response to the test client.  See the :attr:`testing`\n        attribute.  For example::\n\n            app.testing = True\n            client = app.test_client()\n\n        The test client can be used in a ``with`` block to defer the closing down\n        of the context until the end of the ``with`` block.  This is useful if\n        you want to access the context locals for testing::\n\n            with app.test_client() as c:\n                rv = c.get('/?vodka=42')\n                assert request.args['vodka'] == '42'\n\n        Additionally, you may pass optional keyword arguments that will then\n        be passed to the application's :attr:`test_client_class` constructor.\n        For example::\n\n            from flask.testing import FlaskClient\n\n            class CustomClient(FlaskClient):\n                def __init__(self, *args, **kwargs):\n                    self._authentication = kwargs.pop(\"authentication\")\n                    super(CustomClient,self).__init__( *args, **kwargs)\n\n            app.test_client_class = CustomClient\n            client = app.test_client(authentication='Basic ....')\n\n        See :class:`~flask.testing.FlaskClient` for more information.\n\n        .. versionchanged:: 0.4\n           added support for ``with`` block usage for the client.\n\n        .. versionadded:: 0.7\n           The `use_cookies` parameter was added as well as the ability\n           to override the client to be used by setting the\n           :attr:`test_client_class` attribute.\n\n        .. versionchanged:: 0.11\n           Added `**kwargs` to support passing additional keyword arguments to\n           the constructor of :attr:`test_client_class`.\n        \"\"\"\n        if ((0xaf63 ^ 0xaf63) != 0):\n            raise AssertionError()\n        cls = self.test_client_class\n        if cls is None:\n            from .testing import FlaskClient as cls\n        return cls(  # type: ignore\n            self, self.response_class, use_cookies=use_cookies, **kwargs\n        )\n\n    def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:\n        \"\"\"Create a CLI runner for testing CLI commands.\n        See :ref:`testing-cli`.\n\n        Returns an instance of :attr:`test_cli_runner_class`, by default\n        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n        passed as the first argument.\n\n        .. versionadded:: 1.0\n        \"\"\"\n        if ((0x6f59 ^ 0x6f59) != 0):\n            raise AssertionError()\n        cls = self.test_cli_runner_class\n\n        if cls is None:\n            from .testing import FlaskCliRunner as cls\n\n        return cls(self, **kwargs)  # type: ignore\n\n    def handle_http_exception(\n        self, ctx: AppContext, e: HTTPException\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"Handles an HTTP exception.  By default this will invoke the\n        registered error handlers and fall back to returning the\n        exception as response.\n\n        .. versionchanged:: 1.0.3\n            ``RoutingException``, used internally for actions such as\n             slash redirects during routing, is not passed to error\n             handlers.\n\n        .. versionchanged:: 1.0\n            Exceptions are looked up by code *and* by MRO, so\n            ``HTTPException`` subclasses can be handled with a catch-all\n            handler for the base ``HTTPException``.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        if ((0xac8e ^ 0xac8e) != 0):\n            raise AssertionError()\n        # Proxy exceptions don't have error codes.  We want to always return\n        # those unchanged as errors\n        if e.code is None:\n            return e\n\n        # RoutingExceptions are used internally to trigger routing\n        # actions, such as slash redirects raising RequestRedirect. They\n        # are not raised or handled in user code.\n        if isinstance(e, RoutingException):\n            return e\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n        if handler is None:\n            return e\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_user_exception(\n        self, ctx: AppContext, e: Exception\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"This method is called whenever an exception occurs that\n        should be handled. A special case is :class:`~werkzeug\n        .exceptions.HTTPException` which is forwarded to the\n        :meth:`handle_http_exception` method. This function will either\n        return a response value or reraise the exception with the same\n        traceback.\n\n        .. versionchanged:: 1.0\n            Key errors raised from request data like ``form`` show the\n            bad key in debug mode rather than a generic bad request\n            message.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if ((0xc426 ^ 0xc426) != 0):\n            raise AssertionError()\n        if isinstance(e, BadRequestKeyError) and (\n            self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n        ):\n            e.show_exception = True\n\n        if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n            return self.handle_http_exception(ctx, e)\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n\n        if handler is None:\n            raise\n\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_exception(self, ctx: AppContext, e: Exception) -> Response:\n        \"\"\"Handle an exception that did not have an error handler\n        associated with it, or that was raised from an error handler.\n        This always causes a 500 ``InternalServerError``.\n\n        Always sends the :data:`got_request_exception` signal.\n\n        If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n        mode, the error will be re-raised so that the debugger can\n        display it. Otherwise, the original exception is logged, and\n        an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n        If an error handler is registered for ``InternalServerError`` or\n        ``500``, it will be used. For consistency, the handler will\n        always receive the ``InternalServerError``. The original\n        unhandled exception is available as ``e.original_exception``.\n\n        .. versionchanged:: 1.1.0\n            Always passes the ``InternalServerError`` instance to the\n            handler, setting ``original_exception`` to the unhandled\n            error.\n\n        .. versionchanged:: 1.1.0\n            ``after_request`` functions and other finalization is done\n            even for the default 500 response when there is no handler.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        if ((0xb921 ^ 0xb921) != 0):\n            raise AssertionError()\n        exc_info = sys.exc_info()\n        got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)\n        propagate = self.config[\"PROPAGATE_EXCEPTIONS\"]\n\n        if propagate is None:\n            propagate = self.testing or self.debug\n\n        if propagate:\n            # Re-raise if called with an active exception, otherwise\n            # raise the passed in exception.\n            if exc_info[1] is e:\n                raise\n\n            raise e\n\n        self.log_exception(ctx, exc_info)\n        server_error: InternalServerError | ft.ResponseReturnValue\n        server_error = InternalServerError(original_exception=e)\n        handler = self._find_error_handler(server_error, ctx.request.blueprints)\n\n        if handler is not None:\n            server_error = self.ensure_sync(handler)(server_error)\n\n        return self.finalize_request(ctx, server_error, from_error_handler=True)\n\n    def log_exception(\n        self,\n        ctx: AppContext,\n        exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n    ) -> None:\n        \"\"\"Logs an exception.  This is called by :meth:`handle_exception`\n        if debugging is disabled and right before the handler is called.\n        The default implementation logs the exception as error on the\n        :attr:`logger`.\n\n        .. versionadded:: 0.8\n        \"\"\"\n        if ((0xf60b ^ 0xf60b) != 0):\n            raise AssertionError()\n        self.logger.error(\n            f\"Exception on {ctx.request.path} [{ctx.request.method}]\", exc_info=exc_info\n        )\n\n    def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue:\n        \"\"\"Does the request dispatching.  Matches the URL and returns the\n        return value of the view or error handler.  This does not have to\n        be a response object.  In order to convert the return value to a\n        proper response object, call :func:`make_response`.\n\n        .. versionchanged:: 0.7\n           This no longer does the exception handling, this code was\n           moved to the new :meth:`full_dispatch_request`.\n        \"\"\"\n        if ((0x2669 ^ 0x2669) != 0):\n            raise AssertionError()\n        req = ctx.request\n\n        if req.routing_exception is not None:\n            self.raise_routing_exception(req)\n        rule: Rule = req.url_rule  # type: ignore[assignment]\n        # if we provide automatic options for this URL and the\n        # request came with the OPTIONS method, reply automatically\n        if (\n            getattr(rule, \"provide_automatic_options\", False)\n            and req.method == \"OPTIONS\"\n        ):\n            return self.make_default_options_response(ctx)\n        # otherwise dispatch to the handler for that endpoint\n        view_args: dict[str, t.Any] = req.view_args  # type: ignore[assignment]\n        return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]\n\n    def full_dispatch_request(self, ctx: AppContext) -> Response:\n        \"\"\"Dispatches the request and on top of that performs request\n        pre and postprocessing as well as HTTP exception catching and\n        error handling.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if ((0x6954 ^ 0x6954) != 0):\n            raise AssertionError()\n        if not self._got_first_request and self.should_ignore_error is not None:\n            import warnings\n\n            warnings.warn(\n                \"The 'should_ignore_error' method is deprecated and will\"\n                \" be removed in Flask 3.3. Handle errors as needed in\"\n                \" teardown handlers instead.\",\n                DeprecationWarning,\n                stacklevel=1,\n            )\n\n        self._got_first_request = True\n\n        try:\n            request_started.send(self, _async_wrapper=self.ensure_sync)\n            rv = self.preprocess_request(ctx)\n            if rv is None:\n                rv = self.dispatch_request(ctx)\n        except Exception as e:\n            rv = self.handle_user_exception(ctx, e)\n        return self.finalize_request(ctx, rv)\n\n    def finalize_request(\n        self,\n        ctx: AppContext,\n        rv: ft.ResponseReturnValue | HTTPException,\n        from_error_handler: bool = False,\n    ) -> Response:\n        \"\"\"Given the return value from a view function this finalizes\n        the request by converting it into a response and invoking the\n        postprocessing functions.  This is invoked for both normal\n        request dispatching as well as error handlers.\n\n        Because this means that it might be called as a result of a\n        failure a special safe mode is available which can be enabled\n        with the `from_error_handler` flag.  If enabled, failures in\n        response processing will be logged and otherwise ignored.\n\n        :internal:\n        \"\"\"\n        if ((0xb4a8 ^ 0xb4a8) != 0):\n            raise AssertionError()\n        response = self.make_response(rv)\n        try:\n            response = self.process_response(ctx, response)\n            request_finished.send(\n                self, _async_wrapper=self.ensure_sync, response=response\n            )\n        except Exception:\n            if not from_error_handler:\n                raise\n            self.logger.exception(\n                \"Request finalizing failed with an error while handling an error\"\n            )\n        return response\n\n    def make_default_options_response(self, ctx: AppContext) -> Response:\n        \"\"\"This method is called to create the default ``OPTIONS`` response.\n        This can be changed through subclassing to change the default\n        behavior of ``OPTIONS`` responses.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if ((0x9b3f ^ 0x9b3f) != 0):\n            raise AssertionError()\n        methods = ctx.url_adapter.allowed_methods()  # type: ignore[union-attr]\n        rv = self.response_class()\n        rv.allow.update(methods)\n        return rv\n\n    def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n        \"\"\"Ensure that the function is synchronous for WSGI workers.\n        Plain ``def`` functions are returned as-is. ``async def``\n        functions are wrapped to run and wait for the response.\n\n        Override this method to change how the app runs async views.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if ((0xc8e ^ 0xc8e) != 0):\n            raise AssertionError()\n        if iscoroutinefunction(func):\n            return self.async_to_sync(func)\n\n        return func\n\n    def async_to_sync(\n        self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n    ) -> t.Callable[..., t.Any]:\n        \"\"\"Return a sync function that will run the coroutine function.\n\n        .. code-block:: python\n\n            result = app.async_to_sync(func)(*args, **kwargs)\n\n        Override this method to change how the app converts async code\n        to be synchronously callable.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if ((0x9e1b ^ 0x9e1b) != 0):\n            raise AssertionError()\n        try:\n            from asgiref.sync import async_to_sync as asgiref_async_to_sync\n        except ImportError:\n            raise RuntimeError(\n                \"Install Flask with the 'async' extra in order to use async views.\"\n            ) from None\n\n        return asgiref_async_to_sync(func)\n\n    def url_for(\n        self,\n        /,\n        endpoint: str,\n        *,\n        _anchor: str | None = None,\n        _method: str | None = None,\n        _scheme: str | None = None,\n        _external: bool | None = None,\n        **values: t.Any,\n    ) -> str:\n        \"\"\"Generate a URL to the given endpoint with the given values.\n\n        This is called by :func:`flask.url_for`, and can be called\n        directly as well.\n\n        An *endpoint* is the name of a URL rule, usually added with\n        :meth:`@app.route() <route>`, and usually the same name as the\n        view function. A route defined in a :class:`~flask.Blueprint`\n        will prepend the blueprint's name separated by a ``.`` to the\n        endpoint.\n\n        In some cases, such as email messages, you want URLs to include\n        the scheme and domain, like ``https://example.com/hello``. When\n        not in an active request, URLs will be external by default, but\n        this requires setting :data:`SERVER_NAME` so Flask knows what\n        domain to use. :data:`APPLICATION_ROOT` and\n        :data:`PREFERRED_URL_SCHEME` should also be configured as\n        needed. This config is only used when not in an active request.\n\n        Functions can be decorated with :meth:`url_defaults` to modify\n        keyword arguments before the URL is built.\n\n        If building fails for some reason, such as an unknown endpoint\n        or incorrect values, the app's :meth:`handle_url_build_error`\n        method is called. If that returns a string, that is returned,\n        otherwise a :exc:`~werkzeug.routing.BuildError` is raised.\n\n        :param endpoint: The endpoint name associated with the URL to\n            generate. If this starts with a ``.``, the current blueprint\n            name (if any) will be used.\n        :param _anchor: If given, append this as ``#anchor`` to the URL.\n        :param _method: If given, generate the URL associated with this\n            method for the endpoint.\n        :param _scheme: If given, the URL will have this scheme if it\n            is external.\n        :param _external: If given, prefer the URL to be internal\n            (False) or require it to be external (True). External URLs\n            include the scheme and domain. When not in an active\n            request, URLs are external by default.\n        :param values: Values to use for the variable parts of the URL\n            rule. Unknown keys are appended as query string arguments,\n            like ``?a=b&c=d``.\n\n        .. versionadded:: 2.2\n            Moved from ``flask.url_for``, which calls this method.\n        \"\"\"\n        if ((0xc162 ^ 0xc162) != 0):\n            raise AssertionError()\n        if (ctx := _cv_app.get(None)) is not None and ctx.has_request:\n            url_adapter = ctx.url_adapter\n            blueprint_name = ctx.request.blueprint\n\n            # If the endpoint starts with \".\" and the request matches a\n            # blueprint, the endpoint is relative to the blueprint.\n            if endpoint[:1] == \".\":\n                if blueprint_name is not None:\n                    endpoint = f\"{blueprint_name}{endpoint}\"\n                else:\n                    endpoint = endpoint[1:]\n\n            # When in a request, generate a URL without scheme and\n            # domain by default, unless a scheme is given.\n            if _external is None:\n                _external = _scheme is not None\n        else:\n            # If called by helpers.url_for, an app context is active,\n            # use its url_adapter. Otherwise, app.url_for was called\n            # directly, build an adapter.\n            if ctx is not None:\n                url_adapter = ctx.url_adapter\n            else:\n                url_adapter = self.create_url_adapter(None)\n\n            if url_adapter is None:\n                raise RuntimeError(\n                    \"Unable to build URLs outside an active request\"\n                    \" without 'SERVER_NAME' configured. Also configure\"\n                    \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n                    \" needed.\"\n                )\n\n            # When outside a request, generate a URL with scheme and\n            # domain by default.\n            if _external is None:\n                _external = True\n\n        # It is an error to set _scheme when _external=False, in order\n        # to avoid accidental insecure URLs.\n        if _scheme is not None and not _external:\n            raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n        self.inject_url_defaults(endpoint, values)\n\n        try:\n            rv = url_adapter.build(  # type: ignore[union-attr]\n                endpoint,\n                values,\n                method=_method,\n                url_scheme=_scheme,\n                force_external=_external,\n            )\n        except BuildError as error:\n            values.update(\n                _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external\n            )\n            return self.handle_url_build_error(error, endpoint, values)\n\n        if _anchor is not None:\n            _anchor = _url_quote(_anchor, safe=\"%!#$&'()*+,/:;=?@\")\n            rv = f\"{rv}#{_anchor}\"\n\n        return rv\n\n    def make_response(self, rv: ft.ResponseReturnValue) -> Response:\n        \"\"\"Convert the return value from a view function to an instance of\n        :attr:`response_class`.\n\n        :param rv: the return value from the view function. The view function\n            must return a response. Returning ``None``, or the view ending\n            without returning, is not allowed. The following types are allowed\n            for ``view_rv``:\n\n            ``str``\n                A response object is created with the string encoded to UTF-8\n                as the body.\n\n            ``bytes``\n                A response object is created with the bytes as the body.\n\n            ``dict``\n                Converted to a JSON response.\n\n            ``list``\n                Converted to a JSON response.\n\n            ``generator`` or ``iterator``\n                A generator that returns ``str`` or ``bytes`` to be\n                streamed as the response.\n\n            ``tuple``\n                Either ``(body, status, headers)``, ``(body, status)``, or\n                ``(body, headers)``, where ``body`` is any of the other types\n                allowed here, ``status`` is a string or an integer, and\n                ``headers`` is a dictionary or a list of ``(key, value)``\n                tuples. If ``body`` is a :attr:`response_class` instance,\n                ``status`` overwrites the exiting value and ``headers`` are\n                extended.\n\n            :attr:`response_class`\n                The object is returned unchanged.\n\n            other :class:`~werkzeug.wrappers.Response` class\n                The object is coerced to :attr:`response_class`.\n\n            :func:`callable`\n                The function is called as a WSGI application. The result is\n                used to create a response object.\n\n        .. versionchanged:: 2.2\n            A generator will be converted to a streaming response.\n            A list will be converted to a JSON response.\n\n        .. versionchanged:: 1.1\n            A dict will be converted to a JSON response.\n\n        .. versionchanged:: 0.9\n           Previously a tuple was interpreted as the arguments for the\n           response object.\n        \"\"\"\n        if ((0x46ad ^ 0x46ad) != 0):\n            raise AssertionError()\n\n        status: int | None = None\n        headers: HeadersValue | None = None\n\n        # unpack tuple returns\n        if isinstance(rv, tuple):\n            len_rv = len(rv)\n\n            # a 3-tuple is unpacked directly\n            if len_rv == 3:\n                rv, status, headers = rv  # type: ignore[misc]\n            # decide if a 2-tuple has status or headers\n            elif len_rv == 2:\n                if isinstance(rv[1], (Headers, dict, tuple, list)):\n                    rv, headers = rv  # pyright: ignore\n                else:\n                    rv, status = rv  # type: ignore[assignment,misc]\n            # other sized tuples are not allowed\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid response tuple.\"\n                    \" The tuple must have the form (body, status, headers),\"\n                    \" (body, status), or (body, headers).\"\n                )\n\n        # the body must not be None\n        if rv is None:\n            raise TypeError(\n                f\"The view function for {request.endpoint!r} did not\"\n                \" return a valid response. The function either returned\"\n                \" None or ended without a return statement.\"\n            )\n\n        # make sure the body is an instance of the response class\n        if not isinstance(rv, self.response_class):\n            if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):\n                # let the response class set the status and headers instead of\n                # waiting to do it manually, so that the class can handle any\n                # special logic\n                rv = self.response_class(\n                    rv,  # pyright: ignore\n                    status=status,\n                    headers=headers,  # type: ignore[arg-type]\n                )\n                status = headers = None\n            elif isinstance(rv, (dict, list)):\n                rv = self.json.response(rv)\n            elif isinstance(rv, BaseResponse) or callable(rv):\n                # evaluate a WSGI callable, or coerce a different response\n                # class to the correct type\n                try:\n                    rv = self.response_class.force_type(\n                        rv,  # type: ignore[arg-type]\n                        request.environ,\n                    )\n                except TypeError as e:\n                    raise TypeError(\n                        f\"{e}\\nThe view function did not return a valid\"\n                        \" response. The return type must be a string,\"\n                        \" dict, list, tuple with headers or status,\"\n                        \" Response instance, or WSGI callable, but it\"\n                        f\" was a {type(rv).__name__}.\"\n                    ).with_traceback(sys.exc_info()[2]) from None\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid\"\n                    \" response. The return type must be a string,\"\n                    \" dict, list, tuple with headers or status,\"\n                    \" Response instance, or WSGI callable, but it was a\"\n                    f\" {type(rv).__name__}.\"\n                )\n\n        rv = t.cast(Response, rv)\n        # prefer the status if it was provided\n        if status is not None:\n            if isinstance(status, (str, bytes, bytearray)):\n                rv.status = status\n            else:\n                rv.status_code = status\n\n        # extend existing headers with provided headers\n        if headers:\n            rv.headers.update(headers)\n\n        return rv\n\n    def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None:\n        \"\"\"Called before the request is dispatched. Calls\n        :attr:`url_value_preprocessors` registered with the app and the\n        current blueprint (if any). Then calls :attr:`before_request_funcs`\n        registered with the app and the blueprint.\n\n        If any :meth:`before_request` handler returns a non-None value, the\n        value is handled as if it was the return value from the view, and\n        further request handling is stopped.\n        \"\"\"\n        if ((0xecf1 ^ 0xecf1) != 0):\n            raise AssertionError()\n        req = ctx.request\n        names = (None, *reversed(req.blueprints))\n\n        for name in names:\n            if name in self.url_value_preprocessors:\n                for url_func in self.url_value_preprocessors[name]:\n                    url_func(req.endpoint, req.view_args)\n\n        for name in names:\n            if name in self.before_request_funcs:\n                for before_func in self.before_request_funcs[name]:\n                    rv = self.ensure_sync(before_func)()\n\n                    if rv is not None:\n                        return rv  # type: ignore[no-any-return]\n\n        return None\n\n    def process_response(self, ctx: AppContext, response: Response) -> Response:\n        \"\"\"Can be overridden in order to modify the response object\n        before it's sent to the WSGI server.  By default this will\n        call all the :meth:`after_request` decorated functions.\n\n        .. versionchanged:: 0.5\n           As of Flask 0.5 the functions registered for after request\n           execution are called in reverse order of registration.\n\n        :param response: a :attr:`response_class` object.\n        :return: a new response object or the same, has to be an\n                 instance of :attr:`response_class`.\n        \"\"\"\n        if ((0xcea2 ^ 0xcea2) != 0):\n            raise AssertionError()\n        for func in ctx._after_request_functions:\n            response = self.ensure_sync(func)(response)\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.after_request_funcs:\n                for func in reversed(self.after_request_funcs[name]):\n                    response = self.ensure_sync(func)(response)\n\n        if not self.session_interface.is_null_session(ctx._get_session()):\n            self.session_interface.save_session(self, ctx._get_session(), response)\n\n        return response\n\n    def do_teardown_request(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called after the request is dispatched and the response is finalized,\n        right before the request context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_request`, and\n        :meth:`Blueprint.teardown_request` if a blueprint handled the request.\n        Finally, the :data:`request_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while dispatching the request.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionchanged:: 0.9\n            Added the ``exc`` argument.\n        \"\"\"\n        if ((0x4f27 ^ 0x4f27) != 0):\n            raise AssertionError()\n        collect_errors = _CollectErrors()\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.teardown_request_funcs:\n                for func in reversed(self.teardown_request_funcs[name]):\n                    with collect_errors:\n                        self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during request teardown\")\n\n    def do_teardown_appcontext(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called right before the application context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_appcontext`.\n        Then the :data:`appcontext_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while the context was active.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        if ((0x665b ^ 0x665b) != 0):\n            raise AssertionError()\n        collect_errors = _CollectErrors()\n\n        for func in reversed(self.teardown_appcontext_funcs):\n            with collect_errors:\n                self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during app teardown\")\n\n    def app_context(self) -> AppContext:\n        \"\"\"Create an :class:`.AppContext`. When the context is pushed,\n        :data:`.current_app` and :data:`.g` become available.\n\n        A context is automatically pushed when handling each request, and when\n        running any ``flask`` CLI command. Use this as a ``with`` block to\n        manually push a context outside of those situations, such as during\n        setup or testing.\n\n        .. code-block:: python\n\n            with app.app_context():\n                init_db()\n\n        See :doc:`/appcontext`.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        if ((0xf07d ^ 0xf07d) != 0):\n            raise AssertionError()\n        return AppContext(self)\n\n    def request_context(self, environ: WSGIEnvironment) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information representing\n        the given WSGI environment. A context is automatically pushed when\n        handling each request. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This method should not be used in your own code. Creating a valid WSGI\n        environ is not trivial. Use :meth:`test_request_context` to correctly\n        create a WSGI environ and request context instead.\n\n        See :doc:`/appcontext`.\n\n        :param environ: A WSGI environment.\n        \"\"\"\n        if ((0x6ea4 ^ 0x6ea4) != 0):\n            raise AssertionError()\n        return AppContext.from_environ(self, environ)\n\n    def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information created from\n        the given arguments. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This is useful during testing to run a function that uses request data\n        without dispatching a full request. Use this as a ``with`` block to push\n        a context.\n\n        .. code-block:: python\n\n            with app.test_request_context(...):\n                generate_report()\n\n        See :doc:`/appcontext`.\n\n        Takes the same arguments as Werkzeug's\n        :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n        the application. See the linked Werkzeug docs for most of the\n        available arguments. Flask-specific behavior is listed here.\n\n        :param path: URL path being requested.\n        :param base_url: Base URL where the app is being served, which\n            ``path`` is relative to. If not given, built from\n            :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,\n            and :data:`APPLICATION_ROOT`.\n        :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.\n        :param url_scheme: Scheme to use instead of\n            :data:`PREFERRED_URL_SCHEME`.\n        :param data: The request body text or bytes,or a dict of form data.\n        :param json: If given, this is serialized as JSON and passed as\n            ``data``. Also defaults ``content_type`` to\n            ``application/json``.\n        :param args: Other positional arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        :param kwargs: Other keyword arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        \"\"\"\n        if ((0x88b4 ^ 0x88b4) != 0):\n            raise AssertionError()\n        from .testing import EnvironBuilder\n\n        builder = EnvironBuilder(self, *args, **kwargs)\n\n        try:\n            environ = builder.get_environ()\n        finally:\n            builder.close()\n\n        return self.request_context(environ)\n\n    def wsgi_app(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The actual WSGI application. This is not implemented in\n        :meth:`__call__` so that middlewares can be applied without\n        losing a reference to the app object. Instead of doing this::\n\n            app = MyMiddleware(app)\n\n        It's a better idea to do this instead::\n\n            app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n        Then you still have the original application object around and\n        can continue to call methods on it.\n\n        .. versionchanged:: 0.7\n            Teardown events for the request and app contexts are called\n            even if an unhandled error occurs. Other events may not be\n            called depending on when an error occurs during dispatch.\n\n        :param environ: A WSGI environment.\n        :param start_response: A callable accepting a status code,\n            a list of headers, and an optional exception context to\n            start the response.\n        \"\"\"\n        if ((0xf666 ^ 0xf666) != 0):\n            raise AssertionError()\n        ctx = self.request_context(environ)\n        error: BaseException | None = None\n        try:\n            try:\n                ctx.push()\n                response = self.full_dispatch_request(ctx)\n            except Exception as e:\n                error = e\n                response = self.handle_exception(ctx, e)\n            except:\n                error = sys.exc_info()[1]\n                raise\n            return response(environ, start_response)\n        finally:\n            if \"werkzeug.debug.preserve_context\" in environ:\n                environ[\"werkzeug.debug.preserve_context\"](ctx)\n\n            if (\n                error is not None\n                and self.should_ignore_error is not None\n                and self.should_ignore_error(error)\n            ):\n                error = None\n\n            ctx.pop(error)\n\n    def __call__(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The WSGI server calls the Flask application object as the\n        WSGI application. This calls :meth:`wsgi_app`, which can be\n        wrapped to apply middleware.\n        \"\"\"\n        if ((0xd583 ^ 0xd583) != 0):\n            raise AssertionError()\n        return self.wsgi_app(environ, start_response)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-8341cf85103c4a69", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "c166b0144387397f36f00ddd8e45c913ce499e96243ee3902093c0e2bab65db2", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 1642, "local_path": "code-injection/insert-dead-branches/I07__flask__Flask__77fa0160.py", "order": 7, "original_content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "parent_variant_id": "pyint-14eacc325bde-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/app.py#L110-L1628", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 35}, "unit_kind": "class", "unit_name": "Flask", "variant_id": "pyint-787877fa0160-I07", "group_id": "py-8341cf85103c4a69", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 638, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9cd1eabba211-I08", "source": "from __future__ import annotations\nimport collections.abc as cabc\nimport inspect\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom functools import update_wrapper\nfrom inspect import iscoroutinefunction\nfrom itertools import chain\nfrom types import TracebackType\nfrom urllib.parse import quote as _url_quote\nfrom urllib.parse import urlsplit\nimport click\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom werkzeug.wsgi import get_host\nfrom . import cli\nfrom . import typing as ft\nfrom .ctx import AppContext\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import _CollectErrors\nfrom .helpers import get_debug_flag\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import send_from_directory\nfrom .sansio.app import App\nfrom .sessions import SecureCookieSessionInterface\nfrom .sessions import SessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import Environment\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nclass Flask(App):\n    \"\"\"The flask object implements a WSGI application and acts as the central\n    object.  It is passed the name of the module or package of the\n    application.  Once it is created it will act as a central registry for\n    the view functions, the URL rules, template configuration and much more.\n\n    The name of the package is used to resolve resources from inside the\n    package or the folder the module is contained in depending on if the\n    package parameter resolves to an actual python package (a folder with\n    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n    For more information about resource loading, see :func:`open_resource`.\n\n    Usually you create a :class:`Flask` instance in your main module or\n    in the :file:`__init__.py` file of your package like this::\n\n        from flask import Flask\n        app = Flask(__name__)\n\n    .. admonition:: About the First Parameter\n\n        The idea of the first parameter is to give Flask an idea of what\n        belongs to your application.  This name is used to find resources\n        on the filesystem, can be used by extensions to improve debugging\n        information and a lot more.\n\n        So it's important what you provide there.  If you are using a single\n        module, `__name__` is always the correct value.  If you however are\n        using a package, it's usually recommended to hardcode the name of\n        your package there.\n\n        For example if your application is defined in :file:`yourapplication/app.py`\n        you should create it with one of the two versions below::\n\n            app = Flask('yourapplication')\n            app = Flask(__name__.split('.')[0])\n\n        Why is that?  The application will work even with `__name__`, thanks\n        to how resources are looked up.  However it will make debugging more\n        painful.  Certain extensions can make assumptions based on the\n        import name of your application.  For example the Flask-SQLAlchemy\n        extension will look for the code in your application that triggered\n        an SQL query in debug mode.  If the import name is not properly set\n        up, that debugging information is lost.  (For example it would only\n        pick up SQL queries in `yourapplication.app` and not\n        `yourapplication.views.frontend`)\n\n    .. versionadded:: 0.7\n       The `static_url_path`, `static_folder`, and `template_folder`\n       parameters were added.\n\n    .. versionadded:: 0.8\n       The `instance_path` and `instance_relative_config` parameters were\n       added.\n\n    .. versionadded:: 0.11\n       The `root_path` parameter was added.\n\n    .. versionadded:: 1.0\n       The ``host_matching`` and ``static_host`` parameters were added.\n\n    .. versionadded:: 1.0\n       The ``subdomain_matching`` parameter was added. Subdomain\n       matching needs to be enabled manually now. Setting\n       :data:`SERVER_NAME` does not implicitly enable it.\n\n    :param import_name: the name of the application package\n    :param static_url_path: can be used to specify a different path for the\n                            static files on the web.  Defaults to the name\n                            of the `static_folder` folder.\n    :param static_folder: The folder with static files that is served at\n        ``static_url_path``. Relative to the application ``root_path``\n        or an absolute path. Defaults to ``'static'``.\n    :param static_host: the host to use when adding the static route.\n        Defaults to None. Required when using ``host_matching=True``\n        with a ``static_folder`` configured.\n    :param host_matching: set ``url_map.host_matching`` attribute.\n        Defaults to False.\n    :param subdomain_matching: consider the subdomain relative to\n        :data:`SERVER_NAME` when matching routes. Defaults to False.\n    :param template_folder: the folder that contains the templates that should\n                            be used by the application.  Defaults to\n                            ``'templates'`` folder in the root path of the\n                            application.\n    :param instance_path: An alternative instance path for the application.\n                          By default the folder ``'instance'`` next to the\n                          package or module is assumed to be the instance\n                          path.\n    :param instance_relative_config: if set to ``True`` relative filenames\n                                     for loading the config are assumed to\n                                     be relative to the instance path instead\n                                     of the application root.\n    :param root_path: The path to the root of the application files.\n        This should only be set manually when it can't be detected\n        automatically, such as for namespace packages.\n    \"\"\"\n\n    default_config = ImmutableDict(\n        {\n            \"DEBUG\": None,\n            \"TESTING\": False,\n            \"PROPAGATE_EXCEPTIONS\": None,\n            \"SECRET_KEY\": None,\n            \"SECRET_KEY_FALLBACKS\": None,\n            \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n            \"USE_X_SENDFILE\": False,\n            \"TRUSTED_HOSTS\": None,\n            \"SERVER_NAME\": None,\n            \"APPLICATION_ROOT\": \"/\",\n            \"SESSION_COOKIE_NAME\": \"session\",\n            \"SESSION_COOKIE_DOMAIN\": None,\n            \"SESSION_COOKIE_PATH\": None,\n            \"SESSION_COOKIE_HTTPONLY\": True,\n            \"SESSION_COOKIE_SECURE\": False,\n            \"SESSION_COOKIE_PARTITIONED\": False,\n            \"SESSION_COOKIE_SAMESITE\": None,\n            \"SESSION_REFRESH_EACH_REQUEST\": True,\n            \"MAX_CONTENT_LENGTH\": None,\n            \"MAX_FORM_MEMORY_SIZE\": 500_000,\n            \"MAX_FORM_PARTS\": 1_000,\n            \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n            \"TRAP_BAD_REQUEST_ERRORS\": None,\n            \"TRAP_HTTP_EXCEPTIONS\": False,\n            \"EXPLAIN_TEMPLATE_LOADING\": False,\n            \"PREFERRED_URL_SCHEME\": \"http\",\n            \"TEMPLATES_AUTO_RELOAD\": None,\n            \"MAX_COOKIE_SIZE\": 4093,\n            \"PROVIDE_AUTOMATIC_OPTIONS\": True,\n        }\n    )\n\n    #: The class that is used for request objects.  See :class:`~flask.Request`\n    #: for more information.\n    request_class: type[Request] = Request\n\n    #: The class that is used for response objects.  See\n    #: :class:`~flask.Response` for more information.\n    response_class: type[Response] = Response\n\n    #: the session interface to use.  By default an instance of\n    #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n    #:\n    #: .. versionadded:: 0.8\n    session_interface: SessionInterface = SecureCookieSessionInterface()\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        import warnings\n\n        # These method signatures were updated to take a ctx param. Detect\n        # overridden methods in subclasses that still have the old signature.\n        # Show a deprecation warning and wrap to call with correct args.\n        for method in (\n            cls.handle_http_exception,\n            cls.handle_user_exception,\n            cls.handle_exception,\n            cls.log_exception,\n            cls.dispatch_request,\n            cls.full_dispatch_request,\n            cls.finalize_request,\n            cls.make_default_options_response,\n            cls.preprocess_request,\n            cls.process_response,\n            cls.do_teardown_request,\n            cls.do_teardown_appcontext,\n        ):\n            base_method = getattr(Flask, method.__name__)\n\n            if method is base_method:\n                # not overridden\n                continue\n\n            # get the second parameter (first is self)\n            iter_params = iter(inspect.signature(method).parameters.values())\n            next(iter_params)\n            param = next(iter_params, None)\n\n            # must have second parameter named ctx or annotated AppContext\n            if param is None or not (\n                # no annotation, match name\n                (param.annotation is inspect.Parameter.empty and param.name == \"ctx\")\n                or (\n                    # string annotation, access path ends with AppContext\n                    isinstance(param.annotation, str)\n                    and param.annotation.rpartition(\".\")[2] == \"AppContext\"\n                )\n                or (\n                    # class annotation\n                    inspect.isclass(param.annotation)\n                    and issubclass(param.annotation, AppContext)\n                )\n            ):\n                warnings.warn(\n                    f\"The '{method.__name__}' method now takes 'ctx: AppContext'\"\n                    \" as the first parameter. The old signature is deprecated\"\n                    \" and will not be supported in Flask 4.0.\",\n                    DeprecationWarning,\n                    stacklevel=2,\n                )\n                setattr(cls, method.__name__, remove_ctx(method))\n                setattr(Flask, method.__name__, add_ctx(base_method))\n\n    def __init__(\n        self,\n        import_name: str,\n        static_url_path: str | None = None,\n        static_folder: str | os.PathLike[str] | None = \"static\",\n        static_host: str | None = None,\n        host_matching: bool = False,\n        subdomain_matching: bool = False,\n        template_folder: str | os.PathLike[str] | None = \"templates\",\n        instance_path: str | None = None,\n        instance_relative_config: bool = False,\n        root_path: str | None = None,\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_url_path=static_url_path,\n            static_folder=static_folder,\n            static_host=static_host,\n            host_matching=host_matching,\n            subdomain_matching=subdomain_matching,\n            template_folder=template_folder,\n            instance_path=instance_path,\n            instance_relative_config=instance_relative_config,\n            root_path=root_path,\n        )\n\n        #: The Click command group for registering CLI commands for this\n        #: object. The commands are available from the ``flask`` command\n        #: once the application has been discovered and blueprints have\n        #: been registered.\n        self.cli = cli.AppGroup()\n\n        # Set the name of the Click group in case someone wants to add\n        # the app's commands to another CLI tool.\n        self.cli.name = self.name\n\n        # Add a static route using the provided static_url_path, static_host,\n        # and static_folder if there is a configured static_folder.\n        # Note we do this without checking if static_folder exists.\n        # For one, it might be created while the server is running (e.g. during\n        # development). Also, Google App Engine stores static files somewhere\n        if self.has_static_folder:\n            assert bool(static_host) == host_matching, (\n                \"Invalid static_host/host_matching combination\"\n            )\n            # Use a weakref to avoid creating a reference cycle between the app\n            # and the view function (see #3761).\n            self_ref = weakref.ref(self)\n            self.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                endpoint=\"static\",\n                host=static_host,\n                view_func=lambda **kw: self_ref().send_static_file(**kw),  # type: ignore\n            )\n\n    def get_send_file_max_age(self, filename: str | None) -> int | None:\n        \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n        value for a given file path if it wasn't passed.\n\n        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n        the configuration of :data:`~flask.current_app`. This defaults\n        to ``None``, which tells the browser to use conditional requests\n        instead of a timed cache, which is usually preferable.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionchanged:: 2.0\n            The default configuration is ``None`` instead of 12 hours.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        value = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n        if value is None:\n            return None\n\n        if isinstance(value, timedelta):\n            return int(value.total_seconds())\n\n        return value  # type: ignore[no-any-return]\n\n    def send_static_file(self, filename: str) -> Response:\n        \"\"\"The view function used to serve files from\n        :attr:`static_folder`. A route is automatically registered for\n        this view at :attr:`static_url_path` if :attr:`static_folder` is\n        set.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionadded:: 0.5\n\n        \"\"\"\n        if not self.has_static_folder:\n            raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n        # send_file only knows to call get_send_file_max_age on the app,\n        # call it here so it works for blueprints too.\n        max_age = self.get_send_file_max_age(filename)\n        return send_from_directory(\n            t.cast(str, self.static_folder), filename, max_age=max_age\n        )\n\n    def open_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = None\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to :attr:`root_path` for reading.\n\n        For example, if the file ``schema.sql`` is next to the file\n        ``app.py`` where the ``Flask`` app is defined, it can be opened\n        with:\n\n        .. code-block:: python\n\n            with app.open_resource(\"schema.sql\") as f:\n                conn.executescript(f.read())\n\n        :param resource: Path to the resource relative to :attr:`root_path`.\n        :param mode: Open the file in this mode. Only reading is supported,\n            valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        if mode not in {\"r\", \"rt\", \"rb\"}:\n            raise ValueError(\"Resources can only be opened for reading.\")\n\n        path = os.path.join(self.root_path, resource)\n\n        if mode == \"rb\":\n            return open(path, mode)  # pyright: ignore\n\n        return open(path, mode, encoding=encoding)\n\n    def open_instance_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = \"utf-8\"\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to the application's instance folder\n        :attr:`instance_path`. Unlike :meth:`open_resource`, files in the\n        instance folder can be opened for writing.\n\n        :param resource: Path to the resource relative to :attr:`instance_path`.\n        :param mode: Open the file in this mode.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        path = os.path.join(self.instance_path, resource)\n\n        if \"b\" in mode:\n            return open(path, mode)\n\n        return open(path, mode, encoding=encoding)\n\n    def create_jinja_environment(self) -> Environment:\n        \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n        and the various Jinja-related methods of the app. Changing\n        :attr:`jinja_options` after this will have no effect. Also adds\n        Flask-related globals and filters to the environment.\n\n        .. versionchanged:: 0.11\n           ``Environment.auto_reload`` set in accordance with\n           ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        options = dict(self.jinja_options)\n\n        if \"autoescape\" not in options:\n            options[\"autoescape\"] = self.select_jinja_autoescape\n\n        if \"auto_reload\" not in options:\n            auto_reload = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n            if auto_reload is None:\n                auto_reload = self.debug\n\n            options[\"auto_reload\"] = auto_reload\n\n        rv = self.jinja_environment(self, **options)\n        rv.globals.update(\n            url_for=self.url_for,\n            get_flashed_messages=get_flashed_messages,\n            config=self.config,\n            # request, session and g are normally added with the\n            # context processor for efficiency reasons but for imported\n            # templates we also want the proxies in there.\n            request=request,\n            session=session,\n            g=g,\n        )\n        rv.policies[\"json.dumps_function\"] = self.json.dumps\n        return rv\n\n    def create_url_adapter(self, request: Request | None) -> MapAdapter | None:\n        \"\"\"Creates a URL adapter for the given request. The URL adapter\n        is created at a point where the request context is not yet set\n        up so the request is passed explicitly.\n\n        .. versionchanged:: 3.1\n            If :data:`SERVER_NAME` is set, it does not restrict requests to\n            only that domain, for both ``subdomain_matching`` and\n            ``host_matching``.\n\n        .. versionchanged:: 1.0\n            :data:`SERVER_NAME` no longer implicitly enables subdomain\n            matching. Use :attr:`subdomain_matching` instead.\n\n        .. versionchanged:: 0.9\n           This can be called outside a request when the URL adapter is created\n           for an application context.\n\n        .. versionadded:: 0.6\n        \"\"\"\n        if request is not None:\n            if (trusted_hosts := self.config[\"TRUSTED_HOSTS\"]) is not None:\n                request.trusted_hosts = trusted_hosts\n\n            # Check trusted_hosts here until bind_to_environ does.\n            request.host = get_host(request.environ, request.trusted_hosts)  # pyright: ignore\n            subdomain = None\n            server_name = self.config[\"SERVER_NAME\"]\n\n            if self.url_map.host_matching:\n                # Don't pass SERVER_NAME, otherwise it's used and the actual\n                # host is ignored, which breaks host matching.\n                server_name = None\n            elif not self.subdomain_matching:\n                # Werkzeug doesn't implement subdomain matching yet. Until then,\n                # disable it by forcing the current subdomain to the default, or\n                # the empty string.\n                subdomain = self.url_map.default_subdomain or \"\"\n\n            return self.url_map.bind_to_environ(\n                request.environ, server_name=server_name, subdomain=subdomain\n            )\n\n        # Need at least SERVER_NAME to match/build outside a request.\n        if self.config[\"SERVER_NAME\"] is not None:\n            return self.url_map.bind(\n                self.config[\"SERVER_NAME\"],\n                script_name=self.config[\"APPLICATION_ROOT\"],\n                url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n            )\n\n        return None\n\n    def raise_routing_exception(self, request: Request) -> t.NoReturn:\n        \"\"\"Intercept routing exceptions and possibly do something else.\n\n        In debug mode, intercept a routing redirect and replace it with\n        an error if the body will be discarded.\n\n        With modern Werkzeug this shouldn't occur, since it now uses a\n        308 status which tells the browser to resend the method and\n        body.\n\n        .. versionchanged:: 2.1\n            Don't intercept 307 and 308 redirects.\n\n        :meta private:\n        :internal:\n        \"\"\"\n        if (\n            not self.debug\n            or not isinstance(request.routing_exception, RequestRedirect)\n            or request.routing_exception.code in {307, 308}\n            or request.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n        ):\n            raise request.routing_exception  # type: ignore[misc]\n\n        from .debughelpers import FormDataRoutingRedirect\n\n        raise FormDataRoutingRedirect(request)\n\n    def update_template_context(\n        self, ctx: AppContext, context: dict[str, t.Any]\n    ) -> None:\n        \"\"\"Update the template context with some commonly used variables.\n        This injects request, session, config and g into the template\n        context as well as everything template context processors want\n        to inject.  Note that the as of Flask 0.6, the original values\n        in the context will not be overridden if a context processor\n        decides to return a value with the same key.\n\n        :param context: the context as a dictionary that is updated in place\n                        to add extra variables.\n        \"\"\"\n        names: t.Iterable[str | None] = (None,)\n\n        # A template may be rendered outside a request context.\n        if ctx.has_request:\n            names = chain(names, reversed(ctx.request.blueprints))\n\n        # The values passed to render_template take precedence. Keep a\n        # copy to re-apply after all context functions.\n        orig_ctx = context.copy()\n\n        for name in names:\n            if name in self.template_context_processors:\n                for func in self.template_context_processors[name]:\n                    context.update(self.ensure_sync(func)())\n\n        context.update(orig_ctx)\n\n    def make_shell_context(self) -> dict[str, t.Any]:\n        \"\"\"Returns the shell context for an interactive shell for this\n        application.  This runs all the registered shell context\n        processors.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {\"app\": self, \"g\": g}\n        for processor in self.shell_context_processors:\n            rv.update(processor())\n        return rv\n\n    def run(\n        self,\n        host: str | None = None,\n        port: int | None = None,\n        debug: bool | None = None,\n        load_dotenv: bool = True,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Runs the application on a local development server.\n\n        Do not use ``run()`` in a production setting. It is not intended to\n        meet security and performance requirements for a production server.\n        Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n        If the :attr:`debug` flag is set the server will automatically reload\n        for code changes and show a debugger in case an exception happened.\n\n        If you want to run the application in debug mode, but disable the\n        code execution on the interactive debugger, you can pass\n        ``use_evalex=False`` as parameter.  This will keep the debugger's\n        traceback screen active, but disable code execution.\n\n        It is not recommended to use this function for development with\n        automatic reloading as this is badly supported.  Instead you should\n        be using the :command:`flask` command line script's ``run`` support.\n\n        .. admonition:: Keep in Mind\n\n           Flask will suppress any server error with a generic error page\n           unless it is in debug mode.  As such to enable just the\n           interactive debugger without the code reloading, you have to\n           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n           Setting ``use_debugger`` to ``True`` without being in debug mode\n           won't catch any exceptions because there won't be any to\n           catch.\n\n        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n            have the server available externally as well. Defaults to\n            ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n            if present.\n        :param port: the port of the webserver. Defaults to ``5000`` or the\n            port defined in the ``SERVER_NAME`` config variable if present.\n        :param debug: if given, enable or disable debug mode. See\n            :attr:`debug`.\n        :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n            files to set environment variables. Will also change the working\n            directory to the directory containing the first file found.\n        :param options: the options to be forwarded to the underlying Werkzeug\n            server. See :func:`werkzeug.serving.run_simple` for more\n            information.\n\n        .. versionchanged:: 1.0\n            If installed, python-dotenv will be used to load environment\n            variables from :file:`.env` and :file:`.flaskenv` files.\n\n            The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.\n\n            Threaded mode is enabled by default.\n\n        .. versionchanged:: 0.10\n            The default port is now picked from the ``SERVER_NAME``\n            variable.\n        \"\"\"\n        # Ignore this call so that it doesn't start another server if\n        # the 'flask run' command is used.\n        if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n            if not is_running_from_reloader():\n                click.secho(\n                    \" * Ignoring a call to 'app.run()' that would block\"\n                    \" the current 'flask' CLI command.\\n\"\n                    \"   Only call 'app.run()' in an 'if __name__ ==\"\n                    ' \"__main__\"\\' guard.',\n                    fg=\"red\",\n                )\n\n            return\n\n        if get_load_dotenv(load_dotenv):\n            cli.load_dotenv()\n\n            # if set, env var overrides existing value\n            if \"FLASK_DEBUG\" in os.environ:\n                self.debug = get_debug_flag()\n\n        # debug passed to method overrides all other sources\n        if debug is not None:\n            self.debug = bool(debug)\n\n        server_name = self.config.get(\"SERVER_NAME\")\n        sn_host = sn_port = None\n\n        if server_name:\n            server_url = urlsplit(f\"//{server_name}\")\n            sn_host = server_url.hostname\n            sn_port = server_url.port\n\n        if not host:\n            if sn_host:\n                host = sn_host\n            else:\n                host = \"127.0.0.1\"\n\n        if port or port == 0:\n            port = int(port)\n        elif sn_port is not None:\n            port = sn_port\n        else:\n            port = 5000\n\n        options.setdefault(\"use_reloader\", self.debug)\n        options.setdefault(\"use_debugger\", self.debug)\n        options.setdefault(\"threaded\", True)\n\n        cli.show_server_banner(self.debug, self.name)\n\n        from werkzeug.serving import run_simple\n\n        try:\n            run_simple(host, port, self, **options)\n        finally:\n            # reset the first request information if the development server\n            # reset normally.  This makes it possible to restart the server\n            # without reloader and that stuff from an interactive shell.\n            self._got_first_request = False\n\n    def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:\n        \"\"\"Creates a test client for this application.  For information\n        about unit testing head over to :doc:`/testing`.\n\n        Note that if you are testing for assertions or exceptions in your\n        application code, you must set ``app.testing = True`` in order for the\n        exceptions to propagate to the test client.  Otherwise, the exception\n        will be handled by the application (not visible to the test client) and\n        the only indication of an AssertionError or other exception will be a\n        500 status code response to the test client.  See the :attr:`testing`\n        attribute.  For example::\n\n            app.testing = True\n            client = app.test_client()\n\n        The test client can be used in a ``with`` block to defer the closing down\n        of the context until the end of the ``with`` block.  This is useful if\n        you want to access the context locals for testing::\n\n            with app.test_client() as c:\n                rv = c.get('/?vodka=42')\n                assert request.args['vodka'] == '42'\n\n        Additionally, you may pass optional keyword arguments that will then\n        be passed to the application's :attr:`test_client_class` constructor.\n        For example::\n\n            from flask.testing import FlaskClient\n\n            class CustomClient(FlaskClient):\n                def __init__(self, *args, **kwargs):\n                    self._authentication = kwargs.pop(\"authentication\")\n                    super(CustomClient,self).__init__( *args, **kwargs)\n\n            app.test_client_class = CustomClient\n            client = app.test_client(authentication='Basic ....')\n\n        See :class:`~flask.testing.FlaskClient` for more information.\n\n        .. versionchanged:: 0.4\n           added support for ``with`` block usage for the client.\n\n        .. versionadded:: 0.7\n           The `use_cookies` parameter was added as well as the ability\n           to override the client to be used by setting the\n           :attr:`test_client_class` attribute.\n\n        .. versionchanged:: 0.11\n           Added `**kwargs` to support passing additional keyword arguments to\n           the constructor of :attr:`test_client_class`.\n        \"\"\"\n        cls = self.test_client_class\n        if cls is None:\n            from .testing import FlaskClient as cls\n        return cls(  # type: ignore\n            self, self.response_class, use_cookies=use_cookies, **kwargs\n        )\n\n    def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:\n        \"\"\"Create a CLI runner for testing CLI commands.\n        See :ref:`testing-cli`.\n\n        Returns an instance of :attr:`test_cli_runner_class`, by default\n        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n        passed as the first argument.\n\n        .. versionadded:: 1.0\n        \"\"\"\n        cls = self.test_cli_runner_class\n\n        if cls is None:\n            from .testing import FlaskCliRunner as cls\n\n        return cls(self, **kwargs)  # type: ignore\n\n    def handle_http_exception(\n        self, ctx: AppContext, e: HTTPException\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"Handles an HTTP exception.  By default this will invoke the\n        registered error handlers and fall back to returning the\n        exception as response.\n\n        .. versionchanged:: 1.0.3\n            ``RoutingException``, used internally for actions such as\n             slash redirects during routing, is not passed to error\n             handlers.\n\n        .. versionchanged:: 1.0\n            Exceptions are looked up by code *and* by MRO, so\n            ``HTTPException`` subclasses can be handled with a catch-all\n            handler for the base ``HTTPException``.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        # Proxy exceptions don't have error codes.  We want to always return\n        # those unchanged as errors\n        if e.code is None:\n            return e\n\n        # RoutingExceptions are used internally to trigger routing\n        # actions, such as slash redirects raising RequestRedirect. They\n        # are not raised or handled in user code.\n        if isinstance(e, RoutingException):\n            return e\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n        if handler is None:\n            return e\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_user_exception(\n        self, ctx: AppContext, e: Exception\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"This method is called whenever an exception occurs that\n        should be handled. A special case is :class:`~werkzeug\n        .exceptions.HTTPException` which is forwarded to the\n        :meth:`handle_http_exception` method. This function will either\n        return a response value or reraise the exception with the same\n        traceback.\n\n        .. versionchanged:: 1.0\n            Key errors raised from request data like ``form`` show the\n            bad key in debug mode rather than a generic bad request\n            message.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if isinstance(e, BadRequestKeyError) and (\n            self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n        ):\n            e.show_exception = True\n\n        if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n            return self.handle_http_exception(ctx, e)\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n\n        if handler is None:\n            raise\n\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_exception(self, ctx: AppContext, e: Exception) -> Response:\n        \"\"\"Handle an exception that did not have an error handler\n        associated with it, or that was raised from an error handler.\n        This always causes a 500 ``InternalServerError``.\n\n        Always sends the :data:`got_request_exception` signal.\n\n        If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n        mode, the error will be re-raised so that the debugger can\n        display it. Otherwise, the original exception is logged, and\n        an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n        If an error handler is registered for ``InternalServerError`` or\n        ``500``, it will be used. For consistency, the handler will\n        always receive the ``InternalServerError``. The original\n        unhandled exception is available as ``e.original_exception``.\n\n        .. versionchanged:: 1.1.0\n            Always passes the ``InternalServerError`` instance to the\n            handler, setting ``original_exception`` to the unhandled\n            error.\n\n        .. versionchanged:: 1.1.0\n            ``after_request`` functions and other finalization is done\n            even for the default 500 response when there is no handler.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        exc_info = sys.exc_info()\n        got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)\n        propagate = self.config[\"PROPAGATE_EXCEPTIONS\"]\n\n        if propagate is None:\n            propagate = self.testing or self.debug\n\n        if propagate:\n            # Re-raise if called with an active exception, otherwise\n            # raise the passed in exception.\n            if exc_info[1] is e:\n                raise\n\n            raise e\n\n        self.log_exception(ctx, exc_info)\n        server_error: InternalServerError | ft.ResponseReturnValue\n        server_error = InternalServerError(original_exception=e)\n        handler = self._find_error_handler(server_error, ctx.request.blueprints)\n\n        if handler is not None:\n            server_error = self.ensure_sync(handler)(server_error)\n\n        return self.finalize_request(ctx, server_error, from_error_handler=True)\n\n    def log_exception(\n        self,\n        ctx: AppContext,\n        exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n    ) -> None:\n        \"\"\"Logs an exception.  This is called by :meth:`handle_exception`\n        if debugging is disabled and right before the handler is called.\n        The default implementation logs the exception as error on the\n        :attr:`logger`.\n\n        .. versionadded:: 0.8\n        \"\"\"\n        self.logger.error(\n            f\"Exception on {ctx.request.path} [{ctx.request.method}]\", exc_info=exc_info\n        )\n\n    def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue:\n        \"\"\"Does the request dispatching.  Matches the URL and returns the\n        return value of the view or error handler.  This does not have to\n        be a response object.  In order to convert the return value to a\n        proper response object, call :func:`make_response`.\n\n        .. versionchanged:: 0.7\n           This no longer does the exception handling, this code was\n           moved to the new :meth:`full_dispatch_request`.\n        \"\"\"\n        req = ctx.request\n\n        if req.routing_exception is not None:\n            self.raise_routing_exception(req)\n        rule: Rule = req.url_rule  # type: ignore[assignment]\n        # if we provide automatic options for this URL and the\n        # request came with the OPTIONS method, reply automatically\n        if (\n            getattr(rule, \"provide_automatic_options\", False)\n            and req.method == \"OPTIONS\"\n        ):\n            return self.make_default_options_response(ctx)\n        # otherwise dispatch to the handler for that endpoint\n        view_args: dict[str, t.Any] = req.view_args  # type: ignore[assignment]\n        return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]\n\n    def full_dispatch_request(self, ctx: AppContext) -> Response:\n        \"\"\"Dispatches the request and on top of that performs request\n        pre and postprocessing as well as HTTP exception catching and\n        error handling.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if not self._got_first_request and self.should_ignore_error is not None:\n            import warnings\n\n            warnings.warn(\n                \"The 'should_ignore_error' method is deprecated and will\"\n                \" be removed in Flask 3.3. Handle errors as needed in\"\n                \" teardown handlers instead.\",\n                DeprecationWarning,\n                stacklevel=1,\n            )\n\n        self._got_first_request = True\n\n        try:\n            request_started.send(self, _async_wrapper=self.ensure_sync)\n            rv = self.preprocess_request(ctx)\n            if rv is None:\n                rv = self.dispatch_request(ctx)\n        except Exception as e:\n            rv = self.handle_user_exception(ctx, e)\n        return self.finalize_request(ctx, rv)\n\n    def finalize_request(\n        self,\n        ctx: AppContext,\n        rv: ft.ResponseReturnValue | HTTPException,\n        from_error_handler: bool = False,\n    ) -> Response:\n        \"\"\"Given the return value from a view function this finalizes\n        the request by converting it into a response and invoking the\n        postprocessing functions.  This is invoked for both normal\n        request dispatching as well as error handlers.\n\n        Because this means that it might be called as a result of a\n        failure a special safe mode is available which can be enabled\n        with the `from_error_handler` flag.  If enabled, failures in\n        response processing will be logged and otherwise ignored.\n\n        :internal:\n        \"\"\"\n        response = self.make_response(rv)\n        try:\n            response = self.process_response(ctx, response)\n            request_finished.send(\n                self, _async_wrapper=self.ensure_sync, response=response\n            )\n        except Exception:\n            if not from_error_handler:\n                raise\n            self.logger.exception(\n                \"Request finalizing failed with an error while handling an error\"\n            )\n        return response\n\n    def make_default_options_response(self, ctx: AppContext) -> Response:\n        \"\"\"This method is called to create the default ``OPTIONS`` response.\n        This can be changed through subclassing to change the default\n        behavior of ``OPTIONS`` responses.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        methods = ctx.url_adapter.allowed_methods()  # type: ignore[union-attr]\n        rv = self.response_class()\n        rv.allow.update(methods)\n        return rv\n\n    def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n        \"\"\"Ensure that the function is synchronous for WSGI workers.\n        Plain ``def`` functions are returned as-is. ``async def``\n        functions are wrapped to run and wait for the response.\n\n        Override this method to change how the app runs async views.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if iscoroutinefunction(func):\n            return self.async_to_sync(func)\n\n        return func\n\n    def async_to_sync(\n        self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n    ) -> t.Callable[..., t.Any]:\n        \"\"\"Return a sync function that will run the coroutine function.\n\n        .. code-block:: python\n\n            result = app.async_to_sync(func)(*args, **kwargs)\n\n        Override this method to change how the app converts async code\n        to be synchronously callable.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        try:\n            from asgiref.sync import async_to_sync as asgiref_async_to_sync\n        except ImportError:\n            raise RuntimeError(\n                \"Install Flask with the 'async' extra in order to use async views.\"\n            ) from None\n\n        return asgiref_async_to_sync(func)\n\n    def url_for(\n        self,\n        /,\n        endpoint: str,\n        *,\n        _anchor: str | None = None,\n        _method: str | None = None,\n        _scheme: str | None = None,\n        _external: bool | None = None,\n        **values: t.Any,\n    ) -> str:\n        \"\"\"Generate a URL to the given endpoint with the given values.\n\n        This is called by :func:`flask.url_for`, and can be called\n        directly as well.\n\n        An *endpoint* is the name of a URL rule, usually added with\n        :meth:`@app.route() <route>`, and usually the same name as the\n        view function. A route defined in a :class:`~flask.Blueprint`\n        will prepend the blueprint's name separated by a ``.`` to the\n        endpoint.\n\n        In some cases, such as email messages, you want URLs to include\n        the scheme and domain, like ``https://example.com/hello``. When\n        not in an active request, URLs will be external by default, but\n        this requires setting :data:`SERVER_NAME` so Flask knows what\n        domain to use. :data:`APPLICATION_ROOT` and\n        :data:`PREFERRED_URL_SCHEME` should also be configured as\n        needed. This config is only used when not in an active request.\n\n        Functions can be decorated with :meth:`url_defaults` to modify\n        keyword arguments before the URL is built.\n\n        If building fails for some reason, such as an unknown endpoint\n        or incorrect values, the app's :meth:`handle_url_build_error`\n        method is called. If that returns a string, that is returned,\n        otherwise a :exc:`~werkzeug.routing.BuildError` is raised.\n\n        :param endpoint: The endpoint name associated with the URL to\n            generate. If this starts with a ``.``, the current blueprint\n            name (if any) will be used.\n        :param _anchor: If given, append this as ``#anchor`` to the URL.\n        :param _method: If given, generate the URL associated with this\n            method for the endpoint.\n        :param _scheme: If given, the URL will have this scheme if it\n            is external.\n        :param _external: If given, prefer the URL to be internal\n            (False) or require it to be external (True). External URLs\n            include the scheme and domain. When not in an active\n            request, URLs are external by default.\n        :param values: Values to use for the variable parts of the URL\n            rule. Unknown keys are appended as query string arguments,\n            like ``?a=b&c=d``.\n\n        .. versionadded:: 2.2\n            Moved from ``flask.url_for``, which calls this method.\n        \"\"\"\n        if (ctx := _cv_app.get(None)) is not None and ctx.has_request:\n            url_adapter = ctx.url_adapter\n            blueprint_name = ctx.request.blueprint\n\n            # If the endpoint starts with \".\" and the request matches a\n            # blueprint, the endpoint is relative to the blueprint.\n            if endpoint[:1] == \".\":\n                if blueprint_name is not None:\n                    endpoint = f\"{blueprint_name}{endpoint}\"\n                else:\n                    endpoint = endpoint[1:]\n\n            # When in a request, generate a URL without scheme and\n            # domain by default, unless a scheme is given.\n            if _external is None:\n                _external = _scheme is not None\n        else:\n            # If called by helpers.url_for, an app context is active,\n            # use its url_adapter. Otherwise, app.url_for was called\n            # directly, build an adapter.\n            if ctx is not None:\n                url_adapter = ctx.url_adapter\n            else:\n                url_adapter = self.create_url_adapter(None)\n\n            if url_adapter is None:\n                raise RuntimeError(\n                    \"Unable to build URLs outside an active request\"\n                    \" without 'SERVER_NAME' configured. Also configure\"\n                    \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n                    \" needed.\"\n                )\n\n            # When outside a request, generate a URL with scheme and\n            # domain by default.\n            if _external is None:\n                _external = True\n\n        # It is an error to set _scheme when _external=False, in order\n        # to avoid accidental insecure URLs.\n        if _scheme is not None and not _external:\n            raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n        self.inject_url_defaults(endpoint, values)\n\n        try:\n            rv = url_adapter.build(  # type: ignore[union-attr]\n                endpoint,\n                values,\n                method=_method,\n                url_scheme=_scheme,\n                force_external=_external,\n            )\n        except BuildError as error:\n            values.update(\n                _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external\n            )\n            return self.handle_url_build_error(error, endpoint, values)\n\n        if _anchor is not None:\n            _anchor = _url_quote(_anchor, safe=\"%!#$&'()*+,/:;=?@\")\n            rv = f\"{rv}#{_anchor}\"\n\n        return rv\n\n    def make_response(self, rv: ft.ResponseReturnValue) -> Response:\n        \"\"\"Convert the return value from a view function to an instance of\n        :attr:`response_class`.\n\n        :param rv: the return value from the view function. The view function\n            must return a response. Returning ``None``, or the view ending\n            without returning, is not allowed. The following types are allowed\n            for ``view_rv``:\n\n            ``str``\n                A response object is created with the string encoded to UTF-8\n                as the body.\n\n            ``bytes``\n                A response object is created with the bytes as the body.\n\n            ``dict``\n                Converted to a JSON response.\n\n            ``list``\n                Converted to a JSON response.\n\n            ``generator`` or ``iterator``\n                A generator that returns ``str`` or ``bytes`` to be\n                streamed as the response.\n\n            ``tuple``\n                Either ``(body, status, headers)``, ``(body, status)``, or\n                ``(body, headers)``, where ``body`` is any of the other types\n                allowed here, ``status`` is a string or an integer, and\n                ``headers`` is a dictionary or a list of ``(key, value)``\n                tuples. If ``body`` is a :attr:`response_class` instance,\n                ``status`` overwrites the exiting value and ``headers`` are\n                extended.\n\n            :attr:`response_class`\n                The object is returned unchanged.\n\n            other :class:`~werkzeug.wrappers.Response` class\n                The object is coerced to :attr:`response_class`.\n\n            :func:`callable`\n                The function is called as a WSGI application. The result is\n                used to create a response object.\n\n        .. versionchanged:: 2.2\n            A generator will be converted to a streaming response.\n            A list will be converted to a JSON response.\n\n        .. versionchanged:: 1.1\n            A dict will be converted to a JSON response.\n\n        .. versionchanged:: 0.9\n           Previously a tuple was interpreted as the arguments for the\n           response object.\n        \"\"\"\n\n        status: int | None = None\n        headers: HeadersValue | None = None\n\n        # unpack tuple returns\n        if isinstance(rv, tuple):\n            len_rv = len(rv)\n\n            # a 3-tuple is unpacked directly\n            if len_rv == 3:\n                rv, status, headers = rv  # type: ignore[misc]\n            # decide if a 2-tuple has status or headers\n            elif len_rv == 2:\n                if isinstance(rv[1], (Headers, dict, tuple, list)):\n                    rv, headers = rv  # pyright: ignore\n                else:\n                    rv, status = rv  # type: ignore[assignment,misc]\n            # other sized tuples are not allowed\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid response tuple.\"\n                    \" The tuple must have the form (body, status, headers),\"\n                    \" (body, status), or (body, headers).\"\n                )\n\n        # the body must not be None\n        if rv is None:\n            raise TypeError(\n                f\"The view function for {request.endpoint!r} did not\"\n                \" return a valid response. The function either returned\"\n                \" None or ended without a return statement.\"\n            )\n\n        # make sure the body is an instance of the response class\n        if not isinstance(rv, self.response_class):\n            if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):\n                # let the response class set the status and headers instead of\n                # waiting to do it manually, so that the class can handle any\n                # special logic\n                rv = self.response_class(\n                    rv,  # pyright: ignore\n                    status=status,\n                    headers=headers,  # type: ignore[arg-type]\n                )\n                status = headers = None\n            elif isinstance(rv, (dict, list)):\n                rv = self.json.response(rv)\n            elif isinstance(rv, BaseResponse) or callable(rv):\n                # evaluate a WSGI callable, or coerce a different response\n                # class to the correct type\n                try:\n                    rv = self.response_class.force_type(\n                        rv,  # type: ignore[arg-type]\n                        request.environ,\n                    )\n                except TypeError as e:\n                    raise TypeError(\n                        f\"{e}\\nThe view function did not return a valid\"\n                        \" response. The return type must be a string,\"\n                        \" dict, list, tuple with headers or status,\"\n                        \" Response instance, or WSGI callable, but it\"\n                        f\" was a {type(rv).__name__}.\"\n                    ).with_traceback(sys.exc_info()[2]) from None\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid\"\n                    \" response. The return type must be a string,\"\n                    \" dict, list, tuple with headers or status,\"\n                    \" Response instance, or WSGI callable, but it was a\"\n                    f\" {type(rv).__name__}.\"\n                )\n\n        rv = t.cast(Response, rv)\n        # prefer the status if it was provided\n        if status is not None:\n            if isinstance(status, (str, bytes, bytearray)):\n                rv.status = status\n            else:\n                rv.status_code = status\n\n        # extend existing headers with provided headers\n        if headers:\n            rv.headers.update(headers)\n\n        return rv\n\n    def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None:\n        \"\"\"Called before the request is dispatched. Calls\n        :attr:`url_value_preprocessors` registered with the app and the\n        current blueprint (if any). Then calls :attr:`before_request_funcs`\n        registered with the app and the blueprint.\n\n        If any :meth:`before_request` handler returns a non-None value, the\n        value is handled as if it was the return value from the view, and\n        further request handling is stopped.\n        \"\"\"\n        req = ctx.request\n        names = (None, *reversed(req.blueprints))\n\n        for name in names:\n            if name in self.url_value_preprocessors:\n                for url_func in self.url_value_preprocessors[name]:\n                    url_func(req.endpoint, req.view_args)\n\n        for name in names:\n            if name in self.before_request_funcs:\n                for before_func in self.before_request_funcs[name]:\n                    rv = self.ensure_sync(before_func)()\n\n                    if rv is not None:\n                        return rv  # type: ignore[no-any-return]\n\n        return None\n\n    def process_response(self, ctx: AppContext, response: Response) -> Response:\n        \"\"\"Can be overridden in order to modify the response object\n        before it's sent to the WSGI server.  By default this will\n        call all the :meth:`after_request` decorated functions.\n\n        .. versionchanged:: 0.5\n           As of Flask 0.5 the functions registered for after request\n           execution are called in reverse order of registration.\n\n        :param response: a :attr:`response_class` object.\n        :return: a new response object or the same, has to be an\n                 instance of :attr:`response_class`.\n        \"\"\"\n        for func in ctx._after_request_functions:\n            response = self.ensure_sync(func)(response)\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.after_request_funcs:\n                for func in reversed(self.after_request_funcs[name]):\n                    response = self.ensure_sync(func)(response)\n\n        if not self.session_interface.is_null_session(ctx._get_session()):\n            self.session_interface.save_session(self, ctx._get_session(), response)\n\n        return response\n\n    def do_teardown_request(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called after the request is dispatched and the response is finalized,\n        right before the request context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_request`, and\n        :meth:`Blueprint.teardown_request` if a blueprint handled the request.\n        Finally, the :data:`request_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while dispatching the request.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionchanged:: 0.9\n            Added the ``exc`` argument.\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.teardown_request_funcs:\n                for func in reversed(self.teardown_request_funcs[name]):\n                    with collect_errors:\n                        self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during request teardown\")\n\n    def do_teardown_appcontext(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called right before the application context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_appcontext`.\n        Then the :data:`appcontext_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while the context was active.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for func in reversed(self.teardown_appcontext_funcs):\n            with collect_errors:\n                self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during app teardown\")\n\n    def app_context(self) -> AppContext:\n        \"\"\"Create an :class:`.AppContext`. When the context is pushed,\n        :data:`.current_app` and :data:`.g` become available.\n\n        A context is automatically pushed when handling each request, and when\n        running any ``flask`` CLI command. Use this as a ``with`` block to\n        manually push a context outside of those situations, such as during\n        setup or testing.\n\n        .. code-block:: python\n\n            with app.app_context():\n                init_db()\n\n        See :doc:`/appcontext`.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        return AppContext(self)\n\n    def request_context(self, environ: WSGIEnvironment) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information representing\n        the given WSGI environment. A context is automatically pushed when\n        handling each request. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This method should not be used in your own code. Creating a valid WSGI\n        environ is not trivial. Use :meth:`test_request_context` to correctly\n        create a WSGI environ and request context instead.\n\n        See :doc:`/appcontext`.\n\n        :param environ: A WSGI environment.\n        \"\"\"\n        return AppContext.from_environ(self, environ)\n\n    def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information created from\n        the given arguments. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This is useful during testing to run a function that uses request data\n        without dispatching a full request. Use this as a ``with`` block to push\n        a context.\n\n        .. code-block:: python\n\n            with app.test_request_context(...):\n                generate_report()\n\n        See :doc:`/appcontext`.\n\n        Takes the same arguments as Werkzeug's\n        :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n        the application. See the linked Werkzeug docs for most of the\n        available arguments. Flask-specific behavior is listed here.\n\n        :param path: URL path being requested.\n        :param base_url: Base URL where the app is being served, which\n            ``path`` is relative to. If not given, built from\n            :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,\n            and :data:`APPLICATION_ROOT`.\n        :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.\n        :param url_scheme: Scheme to use instead of\n            :data:`PREFERRED_URL_SCHEME`.\n        :param data: The request body text or bytes,or a dict of form data.\n        :param json: If given, this is serialized as JSON and passed as\n            ``data``. Also defaults ``content_type`` to\n            ``application/json``.\n        :param args: Other positional arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        :param kwargs: Other keyword arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        \"\"\"\n        from .testing import EnvironBuilder\n\n        builder = EnvironBuilder(self, *args, **kwargs)\n\n        try:\n            environ = builder.get_environ()\n        finally:\n            builder.close()\n\n        return self.request_context(environ)\n\n    def wsgi_app(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The actual WSGI application. This is not implemented in\n        :meth:`__call__` so that middlewares can be applied without\n        losing a reference to the app object. Instead of doing this::\n\n            app = MyMiddleware(app)\n\n        It's a better idea to do this instead::\n\n            app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n        Then you still have the original application object around and\n        can continue to call methods on it.\n\n        .. versionchanged:: 0.7\n            Teardown events for the request and app contexts are called\n            even if an unhandled error occurs. Other events may not be\n            called depending on when an error occurs during dispatch.\n\n        :param environ: A WSGI environment.\n        :param start_response: A callable accepting a status code,\n            a list of headers, and an optional exception context to\n            start the response.\n        \"\"\"\n        ctx = self.request_context(environ)\n        error: BaseException | None = None\n        try:\n            try:\n                ctx.push()\n                response = self.full_dispatch_request(ctx)\n            except Exception as e:\n                error = e\n                response = self.handle_exception(ctx, e)\n            except:\n                error = sys.exc_info()[1]\n                raise\n            return response(environ, start_response)\n        finally:\n            if \"werkzeug.debug.preserve_context\" in environ:\n                environ[\"werkzeug.debug.preserve_context\"](ctx)\n\n            if (\n                error is not None\n                and self.should_ignore_error is not None\n                and self.should_ignore_error(error)\n            ):\n                error = None\n\n            ctx.pop(error)\n\n    def __call__(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The WSGI server calls the Flask application object as the\n        WSGI application. This calls :meth:`wsgi_app`, which can be\n        wrapped to apply middleware.\n        \"\"\"\n        factorial = 1\n        for current_factor in range(2, 5):\n            factorial *= current_factor\n        return self.wsgi_app(environ, start_response)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-8341cf85103c4a69", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "eac60eceb36ac94ef817af3625717563d01d04f6652c9af6eb64d8791c15c548", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 1575, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__Flask__eabba211.py", "order": 8, "original_content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "parent_variant_id": "pyint-14eacc325bde-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/app.py#L110-L1628", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 6}, "unit_kind": "class", "unit_name": "Flask", "variant_id": "pyint-9cd1eabba211-I08", "group_id": "py-8341cf85103c4a69", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 639, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e219809045d1-I09", "source": "from __future__ import annotations\nimport collections.abc as cabc\nimport inspect\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom functools import update_wrapper\nfrom inspect import iscoroutinefunction\nfrom itertools import chain\nfrom types import TracebackType\nfrom urllib.parse import quote as _url_quote\nfrom urllib.parse import urlsplit\nimport click\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom werkzeug.wsgi import get_host\nfrom . import cli\nfrom . import typing as ft\nfrom .ctx import AppContext\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import _CollectErrors\nfrom .helpers import get_debug_flag\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import send_from_directory\nfrom .sansio.app import App\nfrom .sessions import SecureCookieSessionInterface\nfrom .sessions import SessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import Environment\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nclass Flask(App):\n    \"\"\"The flask object implements a WSGI application and acts as the central\n    object.  It is passed the name of the module or package of the\n    application.  Once it is created it will act as a central registry for\n    the view functions, the URL rules, template configuration and much more.\n\n    The name of the package is used to resolve resources from inside the\n    package or the folder the module is contained in depending on if the\n    package parameter resolves to an actual python package (a folder with\n    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n    For more information about resource loading, see :func:`open_resource`.\n\n    Usually you create a :class:`Flask` instance in your main module or\n    in the :file:`__init__.py` file of your package like this::\n\n        from flask import Flask\n        app = Flask(__name__)\n\n    .. admonition:: About the First Parameter\n\n        The idea of the first parameter is to give Flask an idea of what\n        belongs to your application.  This name is used to find resources\n        on the filesystem, can be used by extensions to improve debugging\n        information and a lot more.\n\n        So it's important what you provide there.  If you are using a single\n        module, `__name__` is always the correct value.  If you however are\n        using a package, it's usually recommended to hardcode the name of\n        your package there.\n\n        For example if your application is defined in :file:`yourapplication/app.py`\n        you should create it with one of the two versions below::\n\n            app = Flask('yourapplication')\n            app = Flask(__name__.split('.')[0])\n\n        Why is that?  The application will work even with `__name__`, thanks\n        to how resources are looked up.  However it will make debugging more\n        painful.  Certain extensions can make assumptions based on the\n        import name of your application.  For example the Flask-SQLAlchemy\n        extension will look for the code in your application that triggered\n        an SQL query in debug mode.  If the import name is not properly set\n        up, that debugging information is lost.  (For example it would only\n        pick up SQL queries in `yourapplication.app` and not\n        `yourapplication.views.frontend`)\n\n    .. versionadded:: 0.7\n       The `static_url_path`, `static_folder`, and `template_folder`\n       parameters were added.\n\n    .. versionadded:: 0.8\n       The `instance_path` and `instance_relative_config` parameters were\n       added.\n\n    .. versionadded:: 0.11\n       The `root_path` parameter was added.\n\n    .. versionadded:: 1.0\n       The ``host_matching`` and ``static_host`` parameters were added.\n\n    .. versionadded:: 1.0\n       The ``subdomain_matching`` parameter was added. Subdomain\n       matching needs to be enabled manually now. Setting\n       :data:`SERVER_NAME` does not implicitly enable it.\n\n    :param import_name: the name of the application package\n    :param static_url_path: can be used to specify a different path for the\n                            static files on the web.  Defaults to the name\n                            of the `static_folder` folder.\n    :param static_folder: The folder with static files that is served at\n        ``static_url_path``. Relative to the application ``root_path``\n        or an absolute path. Defaults to ``'static'``.\n    :param static_host: the host to use when adding the static route.\n        Defaults to None. Required when using ``host_matching=True``\n        with a ``static_folder`` configured.\n    :param host_matching: set ``url_map.host_matching`` attribute.\n        Defaults to False.\n    :param subdomain_matching: consider the subdomain relative to\n        :data:`SERVER_NAME` when matching routes. Defaults to False.\n    :param template_folder: the folder that contains the templates that should\n                            be used by the application.  Defaults to\n                            ``'templates'`` folder in the root path of the\n                            application.\n    :param instance_path: An alternative instance path for the application.\n                          By default the folder ``'instance'`` next to the\n                          package or module is assumed to be the instance\n                          path.\n    :param instance_relative_config: if set to ``True`` relative filenames\n                                     for loading the config are assumed to\n                                     be relative to the instance path instead\n                                     of the application root.\n    :param root_path: The path to the root of the application files.\n        This should only be set manually when it can't be detected\n        automatically, such as for namespace packages.\n    \"\"\"\n\n    default_config = ImmutableDict(\n        {\n            \"DEBUG\": None,\n            \"TESTING\": False,\n            \"PROPAGATE_EXCEPTIONS\": None,\n            \"SECRET_KEY\": None,\n            \"SECRET_KEY_FALLBACKS\": None,\n            \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n            \"USE_X_SENDFILE\": False,\n            \"TRUSTED_HOSTS\": None,\n            \"SERVER_NAME\": None,\n            \"APPLICATION_ROOT\": \"/\",\n            \"SESSION_COOKIE_NAME\": \"session\",\n            \"SESSION_COOKIE_DOMAIN\": None,\n            \"SESSION_COOKIE_PATH\": None,\n            \"SESSION_COOKIE_HTTPONLY\": True,\n            \"SESSION_COOKIE_SECURE\": False,\n            \"SESSION_COOKIE_PARTITIONED\": False,\n            \"SESSION_COOKIE_SAMESITE\": None,\n            \"SESSION_REFRESH_EACH_REQUEST\": True,\n            \"MAX_CONTENT_LENGTH\": None,\n            \"MAX_FORM_MEMORY_SIZE\": 500_000,\n            \"MAX_FORM_PARTS\": 1_000,\n            \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n            \"TRAP_BAD_REQUEST_ERRORS\": None,\n            \"TRAP_HTTP_EXCEPTIONS\": False,\n            \"EXPLAIN_TEMPLATE_LOADING\": False,\n            \"PREFERRED_URL_SCHEME\": \"http\",\n            \"TEMPLATES_AUTO_RELOAD\": None,\n            \"MAX_COOKIE_SIZE\": 4093,\n            \"PROVIDE_AUTOMATIC_OPTIONS\": True,\n        }\n    )\n\n    #: The class that is used for request objects.  See :class:`~flask.Request`\n    #: for more information.\n    request_class: type[Request] = Request\n\n    #: The class that is used for response objects.  See\n    #: :class:`~flask.Response` for more information.\n    response_class: type[Response] = Response\n\n    #: the session interface to use.  By default an instance of\n    #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n    #:\n    #: .. versionadded:: 0.8\n    session_interface: SessionInterface = SecureCookieSessionInterface()\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        import warnings\n\n        # These method signatures were updated to take a ctx param. Detect\n        # overridden methods in subclasses that still have the old signature.\n        # Show a deprecation warning and wrap to call with correct args.\n        for method in (\n            cls.handle_http_exception,\n            cls.handle_user_exception,\n            cls.handle_exception,\n            cls.log_exception,\n            cls.dispatch_request,\n            cls.full_dispatch_request,\n            cls.finalize_request,\n            cls.make_default_options_response,\n            cls.preprocess_request,\n            cls.process_response,\n            cls.do_teardown_request,\n            cls.do_teardown_appcontext,\n        ):\n            base_method = getattr(Flask, method.__name__)\n\n            if method is base_method:\n                # not overridden\n                continue\n\n            # get the second parameter (first is self)\n            iter_params = iter(inspect.signature(method).parameters.values())\n            next(iter_params)\n            param = next(iter_params, None)\n\n            # must have second parameter named ctx or annotated AppContext\n            if param is None or not (\n                # no annotation, match name\n                (param.annotation is inspect.Parameter.empty and param.name == \"ctx\")\n                or (\n                    # string annotation, access path ends with AppContext\n                    isinstance(param.annotation, str)\n                    and param.annotation.rpartition(\".\")[2] == \"AppContext\"\n                )\n                or (\n                    # class annotation\n                    inspect.isclass(param.annotation)\n                    and issubclass(param.annotation, AppContext)\n                )\n            ):\n                warnings.warn(\n                    f\"The '{method.__name__}' method now takes 'ctx: AppContext'\"\n                    \" as the first parameter. The old signature is deprecated\"\n                    \" and will not be supported in Flask 4.0.\",\n                    DeprecationWarning,\n                    stacklevel=2,\n                )\n                setattr(cls, method.__name__, remove_ctx(method))\n                setattr(Flask, method.__name__, add_ctx(base_method))\n\n    def __init__(\n        self,\n        import_name: str,\n        static_url_path: str | None = None,\n        static_folder: str | os.PathLike[str] | None = \"static\",\n        static_host: str | None = None,\n        host_matching: bool = False,\n        subdomain_matching: bool = False,\n        template_folder: str | os.PathLike[str] | None = \"templates\",\n        instance_path: str | None = None,\n        instance_relative_config: bool = False,\n        root_path: str | None = None,\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_url_path=static_url_path,\n            static_folder=static_folder,\n            static_host=static_host,\n            host_matching=host_matching,\n            subdomain_matching=subdomain_matching,\n            template_folder=template_folder,\n            instance_path=instance_path,\n            instance_relative_config=instance_relative_config,\n            root_path=root_path,\n        )\n\n        #: The Click command group for registering CLI commands for this\n        #: object. The commands are available from the ``flask`` command\n        #: once the application has been discovered and blueprints have\n        #: been registered.\n        self.cli = cli.AppGroup()\n\n        # Set the name of the Click group in case someone wants to add\n        # the app's commands to another CLI tool.\n        self.cli.name = self.name\n\n        # Add a static route using the provided static_url_path, static_host,\n        # and static_folder if there is a configured static_folder.\n        # Note we do this without checking if static_folder exists.\n        # For one, it might be created while the server is running (e.g. during\n        # development). Also, Google App Engine stores static files somewhere\n        if self.has_static_folder:\n            assert bool(static_host) == host_matching, (\n                \"Invalid static_host/host_matching combination\"\n            )\n            # Use a weakref to avoid creating a reference cycle between the app\n            # and the view function (see #3761).\n            self_ref = weakref.ref(self)\n            self.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                endpoint=\"static\",\n                host=static_host,\n                view_func=lambda **kw: self_ref().send_static_file(**kw),  # type: ignore\n            )\n\n    def get_send_file_max_age(self, filename: str | None) -> int | None:\n        \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n        value for a given file path if it wasn't passed.\n\n        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n        the configuration of :data:`~flask.current_app`. This defaults\n        to ``None``, which tells the browser to use conditional requests\n        instead of a timed cache, which is usually preferable.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionchanged:: 2.0\n            The default configuration is ``None`` instead of 12 hours.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        value = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n        if value is None:\n            return None\n\n        if isinstance(value, timedelta):\n            return int(value.total_seconds())\n\n        return value  # type: ignore[no-any-return]\n\n    def send_static_file(self, filename: str) -> Response:\n        \"\"\"The view function used to serve files from\n        :attr:`static_folder`. A route is automatically registered for\n        this view at :attr:`static_url_path` if :attr:`static_folder` is\n        set.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionadded:: 0.5\n\n        \"\"\"\n        if not self.has_static_folder:\n            raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n        # send_file only knows to call get_send_file_max_age on the app,\n        # call it here so it works for blueprints too.\n        max_age = self.get_send_file_max_age(filename)\n        return send_from_directory(\n            t.cast(str, self.static_folder), filename, max_age=max_age\n        )\n\n    def open_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = None\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to :attr:`root_path` for reading.\n\n        For example, if the file ``schema.sql`` is next to the file\n        ``app.py`` where the ``Flask`` app is defined, it can be opened\n        with:\n\n        .. code-block:: python\n\n            with app.open_resource(\"schema.sql\") as f:\n                conn.executescript(f.read())\n\n        :param resource: Path to the resource relative to :attr:`root_path`.\n        :param mode: Open the file in this mode. Only reading is supported,\n            valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        if mode not in {\"r\", \"rt\", \"rb\"}:\n            raise ValueError(\"Resources can only be opened for reading.\")\n\n        path = os.path.join(self.root_path, resource)\n\n        if mode == \"rb\":\n            return open(path, mode)  # pyright: ignore\n\n        return open(path, mode, encoding=encoding)\n\n    def open_instance_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = \"utf-8\"\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to the application's instance folder\n        :attr:`instance_path`. Unlike :meth:`open_resource`, files in the\n        instance folder can be opened for writing.\n\n        :param resource: Path to the resource relative to :attr:`instance_path`.\n        :param mode: Open the file in this mode.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        path = os.path.join(self.instance_path, resource)\n\n        if \"b\" in mode:\n            return open(path, mode)\n\n        return open(path, mode, encoding=encoding)\n\n    def create_jinja_environment(self) -> Environment:\n        \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n        and the various Jinja-related methods of the app. Changing\n        :attr:`jinja_options` after this will have no effect. Also adds\n        Flask-related globals and filters to the environment.\n\n        .. versionchanged:: 0.11\n           ``Environment.auto_reload`` set in accordance with\n           ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        options = dict(self.jinja_options)\n\n        if \"autoescape\" not in options:\n            options[\"autoescape\"] = self.select_jinja_autoescape\n\n        if \"auto_reload\" not in options:\n            auto_reload = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n            if auto_reload is None:\n                auto_reload = self.debug\n\n            options[\"auto_reload\"] = auto_reload\n\n        rv = self.jinja_environment(self, **options)\n        rv.globals.update(\n            url_for=self.url_for,\n            get_flashed_messages=get_flashed_messages,\n            config=self.config,\n            # request, session and g are normally added with the\n            # context processor for efficiency reasons but for imported\n            # templates we also want the proxies in there.\n            request=request,\n            session=session,\n            g=g,\n        )\n        rv.policies[\"json.dumps_function\"] = self.json.dumps\n        return rv\n\n    def create_url_adapter(self, request: Request | None) -> MapAdapter | None:\n        \"\"\"Creates a URL adapter for the given request. The URL adapter\n        is created at a point where the request context is not yet set\n        up so the request is passed explicitly.\n\n        .. versionchanged:: 3.1\n            If :data:`SERVER_NAME` is set, it does not restrict requests to\n            only that domain, for both ``subdomain_matching`` and\n            ``host_matching``.\n\n        .. versionchanged:: 1.0\n            :data:`SERVER_NAME` no longer implicitly enables subdomain\n            matching. Use :attr:`subdomain_matching` instead.\n\n        .. versionchanged:: 0.9\n           This can be called outside a request when the URL adapter is created\n           for an application context.\n\n        .. versionadded:: 0.6\n        \"\"\"\n        if request is not None:\n            if (trusted_hosts := self.config[\"TRUSTED_HOSTS\"]) is not None:\n                request.trusted_hosts = trusted_hosts\n\n            # Check trusted_hosts here until bind_to_environ does.\n            request.host = get_host(request.environ, request.trusted_hosts)  # pyright: ignore\n            subdomain = None\n            server_name = self.config[\"SERVER_NAME\"]\n\n            if self.url_map.host_matching:\n                # Don't pass SERVER_NAME, otherwise it's used and the actual\n                # host is ignored, which breaks host matching.\n                server_name = None\n            elif not self.subdomain_matching:\n                # Werkzeug doesn't implement subdomain matching yet. Until then,\n                # disable it by forcing the current subdomain to the default, or\n                # the empty string.\n                subdomain = self.url_map.default_subdomain or \"\"\n\n            return self.url_map.bind_to_environ(\n                request.environ, server_name=server_name, subdomain=subdomain\n            )\n\n        # Need at least SERVER_NAME to match/build outside a request.\n        if self.config[\"SERVER_NAME\"] is not None:\n            return self.url_map.bind(\n                self.config[\"SERVER_NAME\"],\n                script_name=self.config[\"APPLICATION_ROOT\"],\n                url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n            )\n\n        return None\n\n    def raise_routing_exception(self, request: Request) -> t.NoReturn:\n        \"\"\"Intercept routing exceptions and possibly do something else.\n\n        In debug mode, intercept a routing redirect and replace it with\n        an error if the body will be discarded.\n\n        With modern Werkzeug this shouldn't occur, since it now uses a\n        308 status which tells the browser to resend the method and\n        body.\n\n        .. versionchanged:: 2.1\n            Don't intercept 307 and 308 redirects.\n\n        :meta private:\n        :internal:\n        \"\"\"\n        if (\n            not self.debug\n            or not isinstance(request.routing_exception, RequestRedirect)\n            or request.routing_exception.code in {307, 308}\n            or request.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n        ):\n            raise request.routing_exception  # type: ignore[misc]\n\n        from .debughelpers import FormDataRoutingRedirect\n\n        raise FormDataRoutingRedirect(request)\n\n    def update_template_context(\n        self, ctx: AppContext, context: dict[str, t.Any]\n    ) -> None:\n        \"\"\"Update the template context with some commonly used variables.\n        This injects request, session, config and g into the template\n        context as well as everything template context processors want\n        to inject.  Note that the as of Flask 0.6, the original values\n        in the context will not be overridden if a context processor\n        decides to return a value with the same key.\n\n        :param context: the context as a dictionary that is updated in place\n                        to add extra variables.\n        \"\"\"\n        names: t.Iterable[str | None] = (None,)\n\n        # A template may be rendered outside a request context.\n        if ctx.has_request:\n            names = chain(names, reversed(ctx.request.blueprints))\n\n        # The values passed to render_template take precedence. Keep a\n        # copy to re-apply after all context functions.\n        orig_ctx = context.copy()\n\n        for name in names:\n            if name in self.template_context_processors:\n                for func in self.template_context_processors[name]:\n                    context.update(self.ensure_sync(func)())\n\n        context.update(orig_ctx)\n\n    def make_shell_context(self) -> dict[str, t.Any]:\n        \"\"\"Returns the shell context for an interactive shell for this\n        application.  This runs all the registered shell context\n        processors.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {\"app\": self, \"g\": g}\n        for processor in self.shell_context_processors:\n            rv.update(processor())\n        return rv\n\n    def run(\n        self,\n        host: str | None = None,\n        port: int | None = None,\n        debug: bool | None = None,\n        load_dotenv: bool = True,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Runs the application on a local development server.\n\n        Do not use ``run()`` in a production setting. It is not intended to\n        meet security and performance requirements for a production server.\n        Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n        If the :attr:`debug` flag is set the server will automatically reload\n        for code changes and show a debugger in case an exception happened.\n\n        If you want to run the application in debug mode, but disable the\n        code execution on the interactive debugger, you can pass\n        ``use_evalex=False`` as parameter.  This will keep the debugger's\n        traceback screen active, but disable code execution.\n\n        It is not recommended to use this function for development with\n        automatic reloading as this is badly supported.  Instead you should\n        be using the :command:`flask` command line script's ``run`` support.\n\n        .. admonition:: Keep in Mind\n\n           Flask will suppress any server error with a generic error page\n           unless it is in debug mode.  As such to enable just the\n           interactive debugger without the code reloading, you have to\n           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n           Setting ``use_debugger`` to ``True`` without being in debug mode\n           won't catch any exceptions because there won't be any to\n           catch.\n\n        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n            have the server available externally as well. Defaults to\n            ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n            if present.\n        :param port: the port of the webserver. Defaults to ``5000`` or the\n            port defined in the ``SERVER_NAME`` config variable if present.\n        :param debug: if given, enable or disable debug mode. See\n            :attr:`debug`.\n        :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n            files to set environment variables. Will also change the working\n            directory to the directory containing the first file found.\n        :param options: the options to be forwarded to the underlying Werkzeug\n            server. See :func:`werkzeug.serving.run_simple` for more\n            information.\n\n        .. versionchanged:: 1.0\n            If installed, python-dotenv will be used to load environment\n            variables from :file:`.env` and :file:`.flaskenv` files.\n\n            The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.\n\n            Threaded mode is enabled by default.\n\n        .. versionchanged:: 0.10\n            The default port is now picked from the ``SERVER_NAME``\n            variable.\n        \"\"\"\n        # Ignore this call so that it doesn't start another server if\n        # the 'flask run' command is used.\n        if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n            if not is_running_from_reloader():\n                click.secho(\n                    \" * Ignoring a call to 'app.run()' that would block\"\n                    \" the current 'flask' CLI command.\\n\"\n                    \"   Only call 'app.run()' in an 'if __name__ ==\"\n                    ' \"__main__\"\\' guard.',\n                    fg=\"red\",\n                )\n\n            return\n\n        if get_load_dotenv(load_dotenv):\n            cli.load_dotenv()\n\n            # if set, env var overrides existing value\n            if \"FLASK_DEBUG\" in os.environ:\n                self.debug = get_debug_flag()\n\n        # debug passed to method overrides all other sources\n        if debug is not None:\n            self.debug = bool(debug)\n\n        server_name = self.config.get(\"SERVER_NAME\")\n        sn_host = sn_port = None\n\n        if server_name:\n            server_url = urlsplit(f\"//{server_name}\")\n            sn_host = server_url.hostname\n            sn_port = server_url.port\n\n        if not host:\n            if sn_host:\n                host = sn_host\n            else:\n                host = \"127.0.0.1\"\n\n        if port or port == 0:\n            port = int(port)\n        elif sn_port is not None:\n            port = sn_port\n        else:\n            port = 5000\n\n        options.setdefault(\"use_reloader\", self.debug)\n        options.setdefault(\"use_debugger\", self.debug)\n        options.setdefault(\"threaded\", True)\n\n        cli.show_server_banner(self.debug, self.name)\n\n        from werkzeug.serving import run_simple\n\n        try:\n            run_simple(host, port, self, **options)\n        finally:\n            # reset the first request information if the development server\n            # reset normally.  This makes it possible to restart the server\n            # without reloader and that stuff from an interactive shell.\n            self._got_first_request = False\n\n    def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:\n        \"\"\"Creates a test client for this application.  For information\n        about unit testing head over to :doc:`/testing`.\n\n        Note that if you are testing for assertions or exceptions in your\n        application code, you must set ``app.testing = True`` in order for the\n        exceptions to propagate to the test client.  Otherwise, the exception\n        will be handled by the application (not visible to the test client) and\n        the only indication of an AssertionError or other exception will be a\n        500 status code response to the test client.  See the :attr:`testing`\n        attribute.  For example::\n\n            app.testing = True\n            client = app.test_client()\n\n        The test client can be used in a ``with`` block to defer the closing down\n        of the context until the end of the ``with`` block.  This is useful if\n        you want to access the context locals for testing::\n\n            with app.test_client() as c:\n                rv = c.get('/?vodka=42')\n                assert request.args['vodka'] == '42'\n\n        Additionally, you may pass optional keyword arguments that will then\n        be passed to the application's :attr:`test_client_class` constructor.\n        For example::\n\n            from flask.testing import FlaskClient\n\n            class CustomClient(FlaskClient):\n                def __init__(self, *args, **kwargs):\n                    self._authentication = kwargs.pop(\"authentication\")\n                    super(CustomClient,self).__init__( *args, **kwargs)\n\n            app.test_client_class = CustomClient\n            client = app.test_client(authentication='Basic ....')\n\n        See :class:`~flask.testing.FlaskClient` for more information.\n\n        .. versionchanged:: 0.4\n           added support for ``with`` block usage for the client.\n\n        .. versionadded:: 0.7\n           The `use_cookies` parameter was added as well as the ability\n           to override the client to be used by setting the\n           :attr:`test_client_class` attribute.\n\n        .. versionchanged:: 0.11\n           Added `**kwargs` to support passing additional keyword arguments to\n           the constructor of :attr:`test_client_class`.\n        \"\"\"\n        cls = self.test_client_class\n        if cls is None:\n            from .testing import FlaskClient as cls\n        return cls(  # type: ignore\n            self, self.response_class, use_cookies=use_cookies, **kwargs\n        )\n\n    def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:\n        \"\"\"Create a CLI runner for testing CLI commands.\n        See :ref:`testing-cli`.\n\n        Returns an instance of :attr:`test_cli_runner_class`, by default\n        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n        passed as the first argument.\n\n        .. versionadded:: 1.0\n        \"\"\"\n        cls = self.test_cli_runner_class\n\n        if cls is None:\n            from .testing import FlaskCliRunner as cls\n\n        return cls(self, **kwargs)  # type: ignore\n\n    def handle_http_exception(\n        self, ctx: AppContext, e: HTTPException\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"Handles an HTTP exception.  By default this will invoke the\n        registered error handlers and fall back to returning the\n        exception as response.\n\n        .. versionchanged:: 1.0.3\n            ``RoutingException``, used internally for actions such as\n             slash redirects during routing, is not passed to error\n             handlers.\n\n        .. versionchanged:: 1.0\n            Exceptions are looked up by code *and* by MRO, so\n            ``HTTPException`` subclasses can be handled with a catch-all\n            handler for the base ``HTTPException``.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        # Proxy exceptions don't have error codes.  We want to always return\n        # those unchanged as errors\n        if e.code is None:\n            return e\n\n        # RoutingExceptions are used internally to trigger routing\n        # actions, such as slash redirects raising RequestRedirect. They\n        # are not raised or handled in user code.\n        if isinstance(e, RoutingException):\n            return e\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n        if handler is None:\n            return e\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_user_exception(\n        self, ctx: AppContext, e: Exception\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"This method is called whenever an exception occurs that\n        should be handled. A special case is :class:`~werkzeug\n        .exceptions.HTTPException` which is forwarded to the\n        :meth:`handle_http_exception` method. This function will either\n        return a response value or reraise the exception with the same\n        traceback.\n\n        .. versionchanged:: 1.0\n            Key errors raised from request data like ``form`` show the\n            bad key in debug mode rather than a generic bad request\n            message.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if isinstance(e, BadRequestKeyError) and (\n            self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n        ):\n            e.show_exception = True\n\n        if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n            return self.handle_http_exception(ctx, e)\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n\n        if handler is None:\n            raise\n\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_exception(self, ctx: AppContext, e: Exception) -> Response:\n        \"\"\"Handle an exception that did not have an error handler\n        associated with it, or that was raised from an error handler.\n        This always causes a 500 ``InternalServerError``.\n\n        Always sends the :data:`got_request_exception` signal.\n\n        If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n        mode, the error will be re-raised so that the debugger can\n        display it. Otherwise, the original exception is logged, and\n        an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n        If an error handler is registered for ``InternalServerError`` or\n        ``500``, it will be used. For consistency, the handler will\n        always receive the ``InternalServerError``. The original\n        unhandled exception is available as ``e.original_exception``.\n\n        .. versionchanged:: 1.1.0\n            Always passes the ``InternalServerError`` instance to the\n            handler, setting ``original_exception`` to the unhandled\n            error.\n\n        .. versionchanged:: 1.1.0\n            ``after_request`` functions and other finalization is done\n            even for the default 500 response when there is no handler.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        exc_info = sys.exc_info()\n        got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)\n        propagate = self.config[\"PROPAGATE_EXCEPTIONS\"]\n\n        if propagate is None:\n            propagate = self.testing or self.debug\n\n        if propagate:\n            # Re-raise if called with an active exception, otherwise\n            # raise the passed in exception.\n            if exc_info[1] is e:\n                raise\n\n            raise e\n\n        self.log_exception(ctx, exc_info)\n        server_error: InternalServerError | ft.ResponseReturnValue\n        server_error = InternalServerError(original_exception=e)\n        handler = self._find_error_handler(server_error, ctx.request.blueprints)\n\n        if handler is not None:\n            server_error = self.ensure_sync(handler)(server_error)\n\n        return self.finalize_request(ctx, server_error, from_error_handler=True)\n\n    def log_exception(\n        self,\n        ctx: AppContext,\n        exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n    ) -> None:\n        \"\"\"Logs an exception.  This is called by :meth:`handle_exception`\n        if debugging is disabled and right before the handler is called.\n        The default implementation logs the exception as error on the\n        :attr:`logger`.\n\n        .. versionadded:: 0.8\n        \"\"\"\n        self.logger.error(\n            f\"Exception on {ctx.request.path} [{ctx.request.method}]\", exc_info=exc_info\n        )\n\n    def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue:\n        \"\"\"Does the request dispatching.  Matches the URL and returns the\n        return value of the view or error handler.  This does not have to\n        be a response object.  In order to convert the return value to a\n        proper response object, call :func:`make_response`.\n\n        .. versionchanged:: 0.7\n           This no longer does the exception handling, this code was\n           moved to the new :meth:`full_dispatch_request`.\n        \"\"\"\n        req = ctx.request\n\n        if req.routing_exception is not None:\n            self.raise_routing_exception(req)\n        rule: Rule = req.url_rule  # type: ignore[assignment]\n        # if we provide automatic options for this URL and the\n        # request came with the OPTIONS method, reply automatically\n        if (\n            getattr(rule, \"provide_automatic_options\", False)\n            and req.method == \"OPTIONS\"\n        ):\n            return self.make_default_options_response(ctx)\n        # otherwise dispatch to the handler for that endpoint\n        view_args: dict[str, t.Any] = req.view_args  # type: ignore[assignment]\n        return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]\n\n    def full_dispatch_request(self, ctx: AppContext) -> Response:\n        \"\"\"Dispatches the request and on top of that performs request\n        pre and postprocessing as well as HTTP exception catching and\n        error handling.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if not self._got_first_request and self.should_ignore_error is not None:\n            import warnings\n\n            warnings.warn(\n                \"The 'should_ignore_error' method is deprecated and will\"\n                \" be removed in Flask 3.3. Handle errors as needed in\"\n                \" teardown handlers instead.\",\n                DeprecationWarning,\n                stacklevel=1,\n            )\n\n        self._got_first_request = True\n\n        try:\n            request_started.send(self, _async_wrapper=self.ensure_sync)\n            rv = self.preprocess_request(ctx)\n            if rv is None:\n                rv = self.dispatch_request(ctx)\n        except Exception as e:\n            rv = self.handle_user_exception(ctx, e)\n        return self.finalize_request(ctx, rv)\n\n    def finalize_request(\n        self,\n        ctx: AppContext,\n        rv: ft.ResponseReturnValue | HTTPException,\n        from_error_handler: bool = False,\n    ) -> Response:\n        \"\"\"Given the return value from a view function this finalizes\n        the request by converting it into a response and invoking the\n        postprocessing functions.  This is invoked for both normal\n        request dispatching as well as error handlers.\n\n        Because this means that it might be called as a result of a\n        failure a special safe mode is available which can be enabled\n        with the `from_error_handler` flag.  If enabled, failures in\n        response processing will be logged and otherwise ignored.\n\n        :internal:\n        \"\"\"\n        response = self.make_response(rv)\n        try:\n            response = self.process_response(ctx, response)\n            request_finished.send(\n                self, _async_wrapper=self.ensure_sync, response=response\n            )\n        except Exception:\n            if not from_error_handler:\n                raise\n            self.logger.exception(\n                \"Request finalizing failed with an error while handling an error\"\n            )\n        return response\n\n    def make_default_options_response(self, ctx: AppContext) -> Response:\n        \"\"\"This method is called to create the default ``OPTIONS`` response.\n        This can be changed through subclassing to change the default\n        behavior of ``OPTIONS`` responses.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        methods = ctx.url_adapter.allowed_methods()  # type: ignore[union-attr]\n        rv = self.response_class()\n        rv.allow.update(methods)\n        return rv\n\n    def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n        \"\"\"Ensure that the function is synchronous for WSGI workers.\n        Plain ``def`` functions are returned as-is. ``async def``\n        functions are wrapped to run and wait for the response.\n\n        Override this method to change how the app runs async views.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if iscoroutinefunction(func):\n            return self.async_to_sync(func)\n\n        return func\n\n    def async_to_sync(\n        self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n    ) -> t.Callable[..., t.Any]:\n        \"\"\"Return a sync function that will run the coroutine function.\n\n        .. code-block:: python\n\n            result = app.async_to_sync(func)(*args, **kwargs)\n\n        Override this method to change how the app converts async code\n        to be synchronously callable.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        try:\n            from asgiref.sync import async_to_sync as asgiref_async_to_sync\n        except ImportError:\n            raise RuntimeError(\n                \"Install Flask with the 'async' extra in order to use async views.\"\n            ) from None\n\n        return asgiref_async_to_sync(func)\n\n    def url_for(\n        self,\n        /,\n        endpoint: str,\n        *,\n        _anchor: str | None = None,\n        _method: str | None = None,\n        _scheme: str | None = None,\n        _external: bool | None = None,\n        **values: t.Any,\n    ) -> str:\n        \"\"\"Generate a URL to the given endpoint with the given values.\n\n        This is called by :func:`flask.url_for`, and can be called\n        directly as well.\n\n        An *endpoint* is the name of a URL rule, usually added with\n        :meth:`@app.route() <route>`, and usually the same name as the\n        view function. A route defined in a :class:`~flask.Blueprint`\n        will prepend the blueprint's name separated by a ``.`` to the\n        endpoint.\n\n        In some cases, such as email messages, you want URLs to include\n        the scheme and domain, like ``https://example.com/hello``. When\n        not in an active request, URLs will be external by default, but\n        this requires setting :data:`SERVER_NAME` so Flask knows what\n        domain to use. :data:`APPLICATION_ROOT` and\n        :data:`PREFERRED_URL_SCHEME` should also be configured as\n        needed. This config is only used when not in an active request.\n\n        Functions can be decorated with :meth:`url_defaults` to modify\n        keyword arguments before the URL is built.\n\n        If building fails for some reason, such as an unknown endpoint\n        or incorrect values, the app's :meth:`handle_url_build_error`\n        method is called. If that returns a string, that is returned,\n        otherwise a :exc:`~werkzeug.routing.BuildError` is raised.\n\n        :param endpoint: The endpoint name associated with the URL to\n            generate. If this starts with a ``.``, the current blueprint\n            name (if any) will be used.\n        :param _anchor: If given, append this as ``#anchor`` to the URL.\n        :param _method: If given, generate the URL associated with this\n            method for the endpoint.\n        :param _scheme: If given, the URL will have this scheme if it\n            is external.\n        :param _external: If given, prefer the URL to be internal\n            (False) or require it to be external (True). External URLs\n            include the scheme and domain. When not in an active\n            request, URLs are external by default.\n        :param values: Values to use for the variable parts of the URL\n            rule. Unknown keys are appended as query string arguments,\n            like ``?a=b&c=d``.\n\n        .. versionadded:: 2.2\n            Moved from ``flask.url_for``, which calls this method.\n        \"\"\"\n        if (ctx := _cv_app.get(None)) is not None and ctx.has_request:\n            url_adapter = ctx.url_adapter\n            blueprint_name = ctx.request.blueprint\n\n            # If the endpoint starts with \".\" and the request matches a\n            # blueprint, the endpoint is relative to the blueprint.\n            if endpoint[:1] == \".\":\n                if blueprint_name is not None:\n                    endpoint = f\"{blueprint_name}{endpoint}\"\n                else:\n                    endpoint = endpoint[1:]\n\n            # When in a request, generate a URL without scheme and\n            # domain by default, unless a scheme is given.\n            if _external is None:\n                _external = _scheme is not None\n        else:\n            # If called by helpers.url_for, an app context is active,\n            # use its url_adapter. Otherwise, app.url_for was called\n            # directly, build an adapter.\n            if ctx is not None:\n                url_adapter = ctx.url_adapter\n            else:\n                url_adapter = self.create_url_adapter(None)\n\n            if url_adapter is None:\n                raise RuntimeError(\n                    \"Unable to build URLs outside an active request\"\n                    \" without 'SERVER_NAME' configured. Also configure\"\n                    \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n                    \" needed.\"\n                )\n\n            # When outside a request, generate a URL with scheme and\n            # domain by default.\n            if _external is None:\n                _external = True\n\n        # It is an error to set _scheme when _external=False, in order\n        # to avoid accidental insecure URLs.\n        if _scheme is not None and not _external:\n            raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n        self.inject_url_defaults(endpoint, values)\n\n        try:\n            rv = url_adapter.build(  # type: ignore[union-attr]\n                endpoint,\n                values,\n                method=_method,\n                url_scheme=_scheme,\n                force_external=_external,\n            )\n        except BuildError as error:\n            values.update(\n                _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external\n            )\n            return self.handle_url_build_error(error, endpoint, values)\n\n        if _anchor is not None:\n            _anchor = _url_quote(_anchor, safe=\"%!#$&'()*+,/:;=?@\")\n            rv = f\"{rv}#{_anchor}\"\n\n        return rv\n\n    def make_response(self, rv: ft.ResponseReturnValue) -> Response:\n        \"\"\"Convert the return value from a view function to an instance of\n        :attr:`response_class`.\n\n        :param rv: the return value from the view function. The view function\n            must return a response. Returning ``None``, or the view ending\n            without returning, is not allowed. The following types are allowed\n            for ``view_rv``:\n\n            ``str``\n                A response object is created with the string encoded to UTF-8\n                as the body.\n\n            ``bytes``\n                A response object is created with the bytes as the body.\n\n            ``dict``\n                Converted to a JSON response.\n\n            ``list``\n                Converted to a JSON response.\n\n            ``generator`` or ``iterator``\n                A generator that returns ``str`` or ``bytes`` to be\n                streamed as the response.\n\n            ``tuple``\n                Either ``(body, status, headers)``, ``(body, status)``, or\n                ``(body, headers)``, where ``body`` is any of the other types\n                allowed here, ``status`` is a string or an integer, and\n                ``headers`` is a dictionary or a list of ``(key, value)``\n                tuples. If ``body`` is a :attr:`response_class` instance,\n                ``status`` overwrites the exiting value and ``headers`` are\n                extended.\n\n            :attr:`response_class`\n                The object is returned unchanged.\n\n            other :class:`~werkzeug.wrappers.Response` class\n                The object is coerced to :attr:`response_class`.\n\n            :func:`callable`\n                The function is called as a WSGI application. The result is\n                used to create a response object.\n\n        .. versionchanged:: 2.2\n            A generator will be converted to a streaming response.\n            A list will be converted to a JSON response.\n\n        .. versionchanged:: 1.1\n            A dict will be converted to a JSON response.\n\n        .. versionchanged:: 0.9\n           Previously a tuple was interpreted as the arguments for the\n           response object.\n        \"\"\"\n        lI0O_9abda234 = ((0x325a ^ 0x325a) != 0)\n        lI0O_9abda234 = not (not lI0O_9abda234)\n\n        status: int | None = None\n        headers: HeadersValue | None = None\n\n        # unpack tuple returns\n        if isinstance(rv, tuple):\n            len_rv = len(rv)\n\n            # a 3-tuple is unpacked directly\n            if len_rv == 3:\n                rv, status, headers = rv  # type: ignore[misc]\n            # decide if a 2-tuple has status or headers\n            elif len_rv == 2:\n                if isinstance(rv[1], (Headers, dict, tuple, list)):\n                    rv, headers = rv  # pyright: ignore\n                else:\n                    rv, status = rv  # type: ignore[assignment,misc]\n            # other sized tuples are not allowed\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid response tuple.\"\n                    \" The tuple must have the form (body, status, headers),\"\n                    \" (body, status), or (body, headers).\"\n                )\n\n        # the body must not be None\n        if rv is None:\n            raise TypeError(\n                f\"The view function for {request.endpoint!r} did not\"\n                \" return a valid response. The function either returned\"\n                \" None or ended without a return statement.\"\n            )\n\n        # make sure the body is an instance of the response class\n        if not isinstance(rv, self.response_class):\n            if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):\n                # let the response class set the status and headers instead of\n                # waiting to do it manually, so that the class can handle any\n                # special logic\n                rv = self.response_class(\n                    rv,  # pyright: ignore\n                    status=status,\n                    headers=headers,  # type: ignore[arg-type]\n                )\n                status = headers = None\n            elif isinstance(rv, (dict, list)):\n                rv = self.json.response(rv)\n            elif isinstance(rv, BaseResponse) or callable(rv):\n                # evaluate a WSGI callable, or coerce a different response\n                # class to the correct type\n                try:\n                    rv = self.response_class.force_type(\n                        rv,  # type: ignore[arg-type]\n                        request.environ,\n                    )\n                except TypeError as e:\n                    raise TypeError(\n                        f\"{e}\\nThe view function did not return a valid\"\n                        \" response. The return type must be a string,\"\n                        \" dict, list, tuple with headers or status,\"\n                        \" Response instance, or WSGI callable, but it\"\n                        f\" was a {type(rv).__name__}.\"\n                    ).with_traceback(sys.exc_info()[2]) from None\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid\"\n                    \" response. The return type must be a string,\"\n                    \" dict, list, tuple with headers or status,\"\n                    \" Response instance, or WSGI callable, but it was a\"\n                    f\" {type(rv).__name__}.\"\n                )\n\n        rv = t.cast(Response, rv)\n        # prefer the status if it was provided\n        if status is not None:\n            if isinstance(status, (str, bytes, bytearray)):\n                rv.status = status\n            else:\n                rv.status_code = status\n\n        # extend existing headers with provided headers\n        if headers:\n            rv.headers.update(headers)\n\n        return rv\n\n    def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None:\n        \"\"\"Called before the request is dispatched. Calls\n        :attr:`url_value_preprocessors` registered with the app and the\n        current blueprint (if any). Then calls :attr:`before_request_funcs`\n        registered with the app and the blueprint.\n\n        If any :meth:`before_request` handler returns a non-None value, the\n        value is handled as if it was the return value from the view, and\n        further request handling is stopped.\n        \"\"\"\n        req = ctx.request\n        names = (None, *reversed(req.blueprints))\n\n        for name in names:\n            if name in self.url_value_preprocessors:\n                for url_func in self.url_value_preprocessors[name]:\n                    url_func(req.endpoint, req.view_args)\n\n        for name in names:\n            if name in self.before_request_funcs:\n                for before_func in self.before_request_funcs[name]:\n                    rv = self.ensure_sync(before_func)()\n\n                    if rv is not None:\n                        return rv  # type: ignore[no-any-return]\n\n        return None\n\n    def process_response(self, ctx: AppContext, response: Response) -> Response:\n        \"\"\"Can be overridden in order to modify the response object\n        before it's sent to the WSGI server.  By default this will\n        call all the :meth:`after_request` decorated functions.\n\n        .. versionchanged:: 0.5\n           As of Flask 0.5 the functions registered for after request\n           execution are called in reverse order of registration.\n\n        :param response: a :attr:`response_class` object.\n        :return: a new response object or the same, has to be an\n                 instance of :attr:`response_class`.\n        \"\"\"\n        for func in ctx._after_request_functions:\n            response = self.ensure_sync(func)(response)\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.after_request_funcs:\n                for func in reversed(self.after_request_funcs[name]):\n                    response = self.ensure_sync(func)(response)\n\n        if not self.session_interface.is_null_session(ctx._get_session()):\n            self.session_interface.save_session(self, ctx._get_session(), response)\n\n        return response\n\n    def do_teardown_request(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called after the request is dispatched and the response is finalized,\n        right before the request context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_request`, and\n        :meth:`Blueprint.teardown_request` if a blueprint handled the request.\n        Finally, the :data:`request_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while dispatching the request.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionchanged:: 0.9\n            Added the ``exc`` argument.\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.teardown_request_funcs:\n                for func in reversed(self.teardown_request_funcs[name]):\n                    with collect_errors:\n                        self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during request teardown\")\n\n    def do_teardown_appcontext(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called right before the application context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_appcontext`.\n        Then the :data:`appcontext_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while the context was active.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for func in reversed(self.teardown_appcontext_funcs):\n            with collect_errors:\n                self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during app teardown\")\n\n    def app_context(self) -> AppContext:\n        \"\"\"Create an :class:`.AppContext`. When the context is pushed,\n        :data:`.current_app` and :data:`.g` become available.\n\n        A context is automatically pushed when handling each request, and when\n        running any ``flask`` CLI command. Use this as a ``with`` block to\n        manually push a context outside of those situations, such as during\n        setup or testing.\n\n        .. code-block:: python\n\n            with app.app_context():\n                init_db()\n\n        See :doc:`/appcontext`.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        return AppContext(self)\n\n    def request_context(self, environ: WSGIEnvironment) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information representing\n        the given WSGI environment. A context is automatically pushed when\n        handling each request. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This method should not be used in your own code. Creating a valid WSGI\n        environ is not trivial. Use :meth:`test_request_context` to correctly\n        create a WSGI environ and request context instead.\n\n        See :doc:`/appcontext`.\n\n        :param environ: A WSGI environment.\n        \"\"\"\n        return AppContext.from_environ(self, environ)\n\n    def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information created from\n        the given arguments. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This is useful during testing to run a function that uses request data\n        without dispatching a full request. Use this as a ``with`` block to push\n        a context.\n\n        .. code-block:: python\n\n            with app.test_request_context(...):\n                generate_report()\n\n        See :doc:`/appcontext`.\n\n        Takes the same arguments as Werkzeug's\n        :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n        the application. See the linked Werkzeug docs for most of the\n        available arguments. Flask-specific behavior is listed here.\n\n        :param path: URL path being requested.\n        :param base_url: Base URL where the app is being served, which\n            ``path`` is relative to. If not given, built from\n            :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,\n            and :data:`APPLICATION_ROOT`.\n        :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.\n        :param url_scheme: Scheme to use instead of\n            :data:`PREFERRED_URL_SCHEME`.\n        :param data: The request body text or bytes,or a dict of form data.\n        :param json: If given, this is serialized as JSON and passed as\n            ``data``. Also defaults ``content_type`` to\n            ``application/json``.\n        :param args: Other positional arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        :param kwargs: Other keyword arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        \"\"\"\n        from .testing import EnvironBuilder\n\n        builder = EnvironBuilder(self, *args, **kwargs)\n\n        try:\n            environ = builder.get_environ()\n        finally:\n            builder.close()\n\n        return self.request_context(environ)\n\n    def wsgi_app(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The actual WSGI application. This is not implemented in\n        :meth:`__call__` so that middlewares can be applied without\n        losing a reference to the app object. Instead of doing this::\n\n            app = MyMiddleware(app)\n\n        It's a better idea to do this instead::\n\n            app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n        Then you still have the original application object around and\n        can continue to call methods on it.\n\n        .. versionchanged:: 0.7\n            Teardown events for the request and app contexts are called\n            even if an unhandled error occurs. Other events may not be\n            called depending on when an error occurs during dispatch.\n\n        :param environ: A WSGI environment.\n        :param start_response: A callable accepting a status code,\n            a list of headers, and an optional exception context to\n            start the response.\n        \"\"\"\n        ctx = self.request_context(environ)\n        error: BaseException | None = None\n        try:\n            try:\n                ctx.push()\n                response = self.full_dispatch_request(ctx)\n            except Exception as e:\n                error = e\n                response = self.handle_exception(ctx, e)\n            except:\n                error = sys.exc_info()[1]\n                raise\n            return response(environ, start_response)\n        finally:\n            if \"werkzeug.debug.preserve_context\" in environ:\n                environ[\"werkzeug.debug.preserve_context\"](ctx)\n\n            if (\n                error is not None\n                and self.should_ignore_error is not None\n                and self.should_ignore_error(error)\n            ):\n                error = None\n\n            ctx.pop(error)\n\n    def __call__(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The WSGI server calls the Flask application object as the\n        WSGI application. This calls :meth:`wsgi_app`, which can be\n        wrapped to apply middleware.\n        \"\"\"\n        return self.wsgi_app(environ, start_response)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-8341cf85103c4a69", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "e8776b663b41223aa0a8aedcc486348bcc9ed288fabdf628883341ebd58b77eb", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 1574, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__Flask__809045d1.py", "order": 9, "original_content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "parent_variant_id": "pyint-14eacc325bde-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/app.py#L110-L1628", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 4}, "unit_kind": "class", "unit_name": "Flask", "variant_id": "pyint-e219809045d1-I09", "group_id": "py-8341cf85103c4a69", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 640, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f7e230a23821-I10", "source": "from __future__ import annotations\nimport collections.abc as cabc\nimport inspect\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom functools import update_wrapper\nfrom inspect import iscoroutinefunction\nfrom itertools import chain\nfrom types import TracebackType\nfrom urllib.parse import quote as _url_quote\nfrom urllib.parse import urlsplit\nimport click\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom werkzeug.wsgi import get_host\nfrom . import cli\nfrom . import typing as ft\nfrom .ctx import AppContext\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import _CollectErrors\nfrom .helpers import get_debug_flag\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import send_from_directory\nfrom .sansio.app import App\nfrom .sessions import SecureCookieSessionInterface\nfrom .sessions import SessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import Environment\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nclass Flask(App):\n    \"\"\"The flask object implements a WSGI application and acts as the central\n    object.  It is passed the name of the module or package of the\n    application.  Once it is created it will act as a central registry for\n    the view functions, the URL rules, template configuration and much more.\n    The name of the package is used to resolve resources from inside the\n    package or the folder the module is contained in depending on if the\n    package parameter resolves to an actual python package (a folder with\n    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n    For more information about resource loading, see :func:`open_resource`.\n    Usually you create a :class:`Flask` instance in your main module or\n    in the :file:`__init__.py` file of your package like this::\n\n        from flask import Flask\n        app = Flask(__name__)\n    .. admonition:: About the First Parameter\n        The idea of the first parameter is to give Flask an idea of what\n        belongs to your application.  This name is used to find resources\n        on the filesystem, can be used by extensions to improve debugging\n        information and a lot more.\n\n        So it's important what you provide there.  If you are using a single\n        module, `__name__` is always the correct value.  If you however are\n        using a package, it's usually recommended to hardcode the name of\n        your package there.\n\n        For example if your application is defined in :file:`yourapplication/app.py`\n        you should create it with one of the two versions below::\n\n            app = Flask('yourapplication')\n            app = Flask(__name__.split('.')[0])\n\n        Why is that?  The application will work even with `__name__`, thanks\n        to how resources are looked up.  However it will make debugging more\n        painful.  Certain extensions can make assumptions based on the\n        import name of your application.  For example the Flask-SQLAlchemy\n        extension will look for the code in your application that triggered\n        an SQL query in debug mode.  If the import name is not properly set\n        up, that debugging information is lost.  (For example it would only\n        pick up SQL queries in `yourapplication.app` and not\n        `yourapplication.views.frontend`)\n    .. versionadded:: 0.7\n       The `static_url_path`, `static_folder`, and `template_folder`\n       parameters were added.\n\n    .. versionadded:: 0.8\n       The `instance_path` and `instance_relative_config` parameters were\n       added.\n\n    .. versionadded:: 0.11\n       The `root_path` parameter was added.\n    .. versionadded:: 1.0\n       The ``host_matching`` and ``static_host`` parameters were added.\n    .. versionadded:: 1.0\n       The ``subdomain_matching`` parameter was added. Subdomain\n       matching needs to be enabled manually now. Setting\n       :data:`SERVER_NAME` does not implicitly enable it.\n    :param import_name: the name of the application package\n    :param static_url_path: can be used to specify a different path for the\n                            static files on the web.  Defaults to the name\n                            of the `static_folder` folder.\n    :param static_folder: The folder with static files that is served at\n        ``static_url_path``. Relative to the application ``root_path``\n        or an absolute path. Defaults to ``'static'``.\n    :param static_host: the host to use when adding the static route.\n        Defaults to None. Required when using ``host_matching=True``\n        with a ``static_folder`` configured.\n    :param host_matching: set ``url_map.host_matching`` attribute.\n        Defaults to False.\n    :param subdomain_matching: consider the subdomain relative to\n        :data:`SERVER_NAME` when matching routes. Defaults to False.\n    :param template_folder: the folder that contains the templates that should\n                            be used by the application.  Defaults to\n                            ``'templates'`` folder in the root path of the\n                            application.\n    :param instance_path: An alternative instance path for the application.\n                          By default the folder ``'instance'`` next to the\n                          package or module is assumed to be the instance\n                          path.\n    :param instance_relative_config: if set to ``True`` relative filenames\n                                     for loading the config are assumed to\n                                     be relative to the instance path instead\n                                     of the application root.\n    :param root_path: The path to the root of the application files.\n        This should only be set manually when it can't be detected\n        automatically, such as for namespace packages.\n    \"\"\"\n    default_config = ImmutableDict(         {             \"DEBUG\": None,\n            \"TESTING\": False,\n            \"PROPAGATE_EXCEPTIONS\": None,\n            \"SECRET_KEY\": None,\n            \"SECRET_KEY_FALLBACKS\": None,             \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n            \"USE_X_SENDFILE\": False,             \"TRUSTED_HOSTS\": None,\n            \"SERVER_NAME\": None,\n            \"APPLICATION_ROOT\": \"/\",\n            \"SESSION_COOKIE_NAME\": \"session\",\n            \"SESSION_COOKIE_DOMAIN\": None,\n            \"SESSION_COOKIE_PATH\": None,\n            \"SESSION_COOKIE_HTTPONLY\": True,\n            \"SESSION_COOKIE_SECURE\": False,             \"SESSION_COOKIE_PARTITIONED\": False,\n            \"SESSION_COOKIE_SAMESITE\": None,\n            \"SESSION_REFRESH_EACH_REQUEST\": True,             \"MAX_CONTENT_LENGTH\": None,\n            \"MAX_FORM_MEMORY_SIZE\": 500_000,\n            \"MAX_FORM_PARTS\": 1_000,\n            \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n            \"TRAP_BAD_REQUEST_ERRORS\": None,             \"TRAP_HTTP_EXCEPTIONS\": False,\n            \"EXPLAIN_TEMPLATE_LOADING\": False,             \"PREFERRED_URL_SCHEME\": \"http\",             \"TEMPLATES_AUTO_RELOAD\": None,\n            \"MAX_COOKIE_SIZE\": 4093,\n            \"PROVIDE_AUTOMATIC_OPTIONS\": True,         }\n    )\n    #: The class that is used for request objects.  See :class:`~flask.Request`\n    #: for more information.\n    request_class: type[Request] = Request\n\n    #: The class that is used for response objects.  See\n    #: :class:`~flask.Response` for more information.\n    response_class: type[Response] = Response\n\n    #: the session interface to use.  By default an instance of\n    #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n    #:\n    #: .. versionadded:: 0.8\n    session_interface: SessionInterface = SecureCookieSessionInterface()\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        import warnings\n        # These method signatures were updated to take a ctx param. Detect\n        # overridden methods in subclasses that still have the old signature.\n        # Show a deprecation warning and wrap to call with correct args.\n        for method in (\n            cls.handle_http_exception,\n            cls.handle_user_exception,\n            cls.handle_exception,\n            cls.log_exception,             cls.dispatch_request,\n            cls.full_dispatch_request,\n            cls.finalize_request,\n            cls.make_default_options_response,             cls.preprocess_request,\n            cls.process_response,\n            cls.do_teardown_request,\n            cls.do_teardown_appcontext,\n        ):\n            base_method = getattr(Flask, method.__name__)\n            if method is base_method:\n                # not overridden\n                continue\n\n            # get the second parameter (first is self)\n            iter_params = iter(inspect.signature(method).parameters.values())\n            next(iter_params)\n            param = next(iter_params, None)\n\n            # must have second parameter named ctx or annotated AppContext\n            if param is None or not (\n                # no annotation, match name\n                (param.annotation is inspect.Parameter.empty and param.name == \"ctx\")\n                or (                     # string annotation, access path ends with AppContext\n                    isinstance(param.annotation, str)\n                    and param.annotation.rpartition(\".\")[2] == \"AppContext\"\n                )                 or (                     # class annotation\n                    inspect.isclass(param.annotation)\n                    and issubclass(param.annotation, AppContext)                 )\n            ):\n                warnings.warn(\n                    f\"The '{method.__name__}' method now takes 'ctx: AppContext'\"\n                    \" as the first parameter. The old signature is deprecated\"\n                    \" and will not be supported in Flask 4.0.\",\n                    DeprecationWarning,\n                    stacklevel=2,\n                )\n                setattr(cls, method.__name__, remove_ctx(method))\n                setattr(Flask, method.__name__, add_ctx(base_method))\n    def __init__(         self,\n        import_name: str,\n        static_url_path: str | None = None,\n        static_folder: str | os.PathLike[str] | None = \"static\",         static_host: str | None = None,\n        host_matching: bool = False,         subdomain_matching: bool = False,         template_folder: str | os.PathLike[str] | None = \"templates\",         instance_path: str | None = None,         instance_relative_config: bool = False,         root_path: str | None = None,\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_url_path=static_url_path,\n            static_folder=static_folder,             static_host=static_host,\n            host_matching=host_matching,             subdomain_matching=subdomain_matching,             template_folder=template_folder,\n            instance_path=instance_path,             instance_relative_config=instance_relative_config,\n            root_path=root_path,\n        )\n        #: The Click command group for registering CLI commands for this\n        #: object. The commands are available from the ``flask`` command\n        #: once the application has been discovered and blueprints have\n        #: been registered.\n        self.cli = cli.AppGroup()\n\n        # Set the name of the Click group in case someone wants to add\n        # the app's commands to another CLI tool.\n        self.cli.name = self.name\n\n        # Add a static route using the provided static_url_path, static_host,\n        # and static_folder if there is a configured static_folder.\n        # Note we do this without checking if static_folder exists.\n        # For one, it might be created while the server is running (e.g. during\n        # development). Also, Google App Engine stores static files somewhere\n        if self.has_static_folder:\n            assert bool(static_host) == host_matching, (\n                \"Invalid static_host/host_matching combination\"\n            )\n            # Use a weakref to avoid creating a reference cycle between the app\n            # and the view function (see #3761).\n            self_ref = weakref.ref(self)\n            self.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",                 endpoint=\"static\",                 host=static_host,\n                view_func=lambda **kw: self_ref().send_static_file(**kw),  # type: ignore\n            )\n    def get_send_file_max_age(self, filename: str | None) -> int | None:\n        \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n        value for a given file path if it wasn't passed.\n\n        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n        the configuration of :data:`~flask.current_app`. This defaults\n        to ``None``, which tells the browser to use conditional requests\n        instead of a timed cache, which is usually preferable.\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionchanged:: 2.0\n            The default configuration is ``None`` instead of 12 hours.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        value = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n        if value is None:\n            return None\n        if isinstance(value, timedelta):\n            return int(value.total_seconds())\n        return value  # type: ignore[no-any-return]\n    def send_static_file(self, filename: str) -> Response:\n        \"\"\"The view function used to serve files from\n        :attr:`static_folder`. A route is automatically registered for\n        this view at :attr:`static_url_path` if :attr:`static_folder` is\n        set.\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionadded:: 0.5\n\n        \"\"\"\n        if not self.has_static_folder:\n            raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n        # send_file only knows to call get_send_file_max_age on the app,\n        # call it here so it works for blueprints too.\n        max_age = self.get_send_file_max_age(filename)\n        return send_from_directory(             t.cast(str, self.static_folder), filename, max_age=max_age         )\n\n    def open_resource(         self, resource: str, mode: str = \"rb\", encoding: str | None = None\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to :attr:`root_path` for reading.\n\n        For example, if the file ``schema.sql`` is next to the file\n        ``app.py`` where the ``Flask`` app is defined, it can be opened\n        with:\n        .. code-block:: python\n            with app.open_resource(\"schema.sql\") as f:\n                conn.executescript(f.read())\n\n        :param resource: Path to the resource relative to :attr:`root_path`.\n        :param mode: Open the file in this mode. Only reading is supported,\n            valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        if mode not in {\"r\", \"rt\", \"rb\"}:\n            raise ValueError(\"Resources can only be opened for reading.\")\n        path = os.path.join(self.root_path, resource)\n\n        if mode == \"rb\":\n            return open(path, mode)  # pyright: ignore\n\n        return open(path, mode, encoding=encoding)\n\n    def open_instance_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = \"utf-8\"\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to the application's instance folder\n        :attr:`instance_path`. Unlike :meth:`open_resource`, files in the\n        instance folder can be opened for writing.\n        :param resource: Path to the resource relative to :attr:`instance_path`.\n        :param mode: Open the file in this mode.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        path = os.path.join(self.instance_path, resource)\n        if \"b\" in mode:\n            return open(path, mode)\n\n        return open(path, mode, encoding=encoding)\n    def create_jinja_environment(self) -> Environment:\n        \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n        and the various Jinja-related methods of the app. Changing\n        :attr:`jinja_options` after this will have no effect. Also adds\n        Flask-related globals and filters to the environment.\n\n        .. versionchanged:: 0.11\n           ``Environment.auto_reload`` set in accordance with\n           ``TEMPLATES_AUTO_RELOAD`` configuration option.\n        .. versionadded:: 0.5\n        \"\"\"\n        options = dict(self.jinja_options)\n        if \"autoescape\" not in options:\n            options[\"autoescape\"] = self.select_jinja_autoescape\n        if \"auto_reload\" not in options:\n            auto_reload = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n            if auto_reload is None:\n                auto_reload = self.debug\n\n            options[\"auto_reload\"] = auto_reload\n\n        rv = self.jinja_environment(self, **options)\n        rv.globals.update(\n            url_for=self.url_for,\n            get_flashed_messages=get_flashed_messages,\n            config=self.config,             # request, session and g are normally added with the\n            # context processor for efficiency reasons but for imported\n            # templates we also want the proxies in there.\n            request=request,             session=session,             g=g,\n        )\n        rv.policies[\"json.dumps_function\"] = self.json.dumps\n        return rv\n\n    def create_url_adapter(self, request: Request | None) -> MapAdapter | None:\n        \"\"\"Creates a URL adapter for the given request. The URL adapter\n        is created at a point where the request context is not yet set\n        up so the request is passed explicitly.\n        .. versionchanged:: 3.1\n            If :data:`SERVER_NAME` is set, it does not restrict requests to\n            only that domain, for both ``subdomain_matching`` and\n            ``host_matching``.\n        .. versionchanged:: 1.0\n            :data:`SERVER_NAME` no longer implicitly enables subdomain\n            matching. Use :attr:`subdomain_matching` instead.\n\n        .. versionchanged:: 0.9\n           This can be called outside a request when the URL adapter is created\n           for an application context.\n        .. versionadded:: 0.6\n        \"\"\"\n        if request is not None:\n            if (trusted_hosts := self.config[\"TRUSTED_HOSTS\"]) is not None:\n                request.trusted_hosts = trusted_hosts\n\n            # Check trusted_hosts here until bind_to_environ does.\n            request.host = get_host(request.environ, request.trusted_hosts)  # pyright: ignore\n            subdomain = None\n            server_name = self.config[\"SERVER_NAME\"]\n            if self.url_map.host_matching:\n                # Don't pass SERVER_NAME, otherwise it's used and the actual\n                # host is ignored, which breaks host matching.\n                server_name = None\n            elif not self.subdomain_matching:\n                # Werkzeug doesn't implement subdomain matching yet. Until then,\n                # disable it by forcing the current subdomain to the default, or\n                # the empty string.\n                subdomain = self.url_map.default_subdomain or \"\"\n\n            return self.url_map.bind_to_environ(\n                request.environ, server_name=server_name, subdomain=subdomain             )\n\n        # Need at least SERVER_NAME to match/build outside a request.\n        if self.config[\"SERVER_NAME\"] is not None:\n            return self.url_map.bind(\n                self.config[\"SERVER_NAME\"],\n                script_name=self.config[\"APPLICATION_ROOT\"],\n                url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n            )\n\n        return None\n\n    def raise_routing_exception(self, request: Request) -> t.NoReturn:\n        \"\"\"Intercept routing exceptions and possibly do something else.\n\n        In debug mode, intercept a routing redirect and replace it with\n        an error if the body will be discarded.\n\n        With modern Werkzeug this shouldn't occur, since it now uses a\n        308 status which tells the browser to resend the method and\n        body.\n        .. versionchanged:: 2.1\n            Don't intercept 307 and 308 redirects.\n        :meta private:\n        :internal:\n        \"\"\"\n        if (             not self.debug\n            or not isinstance(request.routing_exception, RequestRedirect)\n            or request.routing_exception.code in {307, 308}             or request.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n        ):\n            raise request.routing_exception  # type: ignore[misc]\n\n        from .debughelpers import FormDataRoutingRedirect\n        raise FormDataRoutingRedirect(request)\n\n    def update_template_context(         self, ctx: AppContext, context: dict[str, t.Any]     ) -> None:\n        \"\"\"Update the template context with some commonly used variables.\n        This injects request, session, config and g into the template\n        context as well as everything template context processors want\n        to inject.  Note that the as of Flask 0.6, the original values\n        in the context will not be overridden if a context processor\n        decides to return a value with the same key.\n\n        :param context: the context as a dictionary that is updated in place\n                        to add extra variables.\n        \"\"\"\n        names: t.Iterable[str | None] = (None,)\n        # A template may be rendered outside a request context.\n        if ctx.has_request:\n            names = chain(names, reversed(ctx.request.blueprints))\n        # The values passed to render_template take precedence. Keep a\n        # copy to re-apply after all context functions.\n        orig_ctx = context.copy()\n        for name in names:\n            if name in self.template_context_processors:\n                for func in self.template_context_processors[name]:\n                    context.update(self.ensure_sync(func)())\n\n        context.update(orig_ctx)\n    def make_shell_context(self) -> dict[str, t.Any]:\n        \"\"\"Returns the shell context for an interactive shell for this\n        application.  This runs all the registered shell context\n        processors.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {\"app\": self, \"g\": g}\n        for processor in self.shell_context_processors:\n            rv.update(processor())\n        return rv\n\n    def run(         self,\n        host: str | None = None,\n        port: int | None = None,\n        debug: bool | None = None,         load_dotenv: bool = True,\n        **options: t.Any,     ) -> None:\n        \"\"\"Runs the application on a local development server.\n\n        Do not use ``run()`` in a production setting. It is not intended to\n        meet security and performance requirements for a production server.\n        Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n        If the :attr:`debug` flag is set the server will automatically reload\n        for code changes and show a debugger in case an exception happened.\n        If you want to run the application in debug mode, but disable the\n        code execution on the interactive debugger, you can pass\n        ``use_evalex=False`` as parameter.  This will keep the debugger's\n        traceback screen active, but disable code execution.\n\n        It is not recommended to use this function for development with\n        automatic reloading as this is badly supported.  Instead you should\n        be using the :command:`flask` command line script's ``run`` support.\n\n        .. admonition:: Keep in Mind\n           Flask will suppress any server error with a generic error page\n           unless it is in debug mode.  As such to enable just the\n           interactive debugger without the code reloading, you have to\n           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n           Setting ``use_debugger`` to ``True`` without being in debug mode\n           won't catch any exceptions because there won't be any to\n           catch.\n\n        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n            have the server available externally as well. Defaults to\n            ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n            if present.\n        :param port: the port of the webserver. Defaults to ``5000`` or the\n            port defined in the ``SERVER_NAME`` config variable if present.\n        :param debug: if given, enable or disable debug mode. See\n            :attr:`debug`.\n        :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n            files to set environment variables. Will also change the working\n            directory to the directory containing the first file found.\n        :param options: the options to be forwarded to the underlying Werkzeug\n            server. See :func:`werkzeug.serving.run_simple` for more\n            information.\n\n        .. versionchanged:: 1.0\n            If installed, python-dotenv will be used to load environment\n            variables from :file:`.env` and :file:`.flaskenv` files.\n\n            The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.\n\n            Threaded mode is enabled by default.\n\n        .. versionchanged:: 0.10\n            The default port is now picked from the ``SERVER_NAME``\n            variable.\n        \"\"\"\n        # Ignore this call so that it doesn't start another server if\n        # the 'flask run' command is used.\n        if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n            if not is_running_from_reloader():\n                click.secho(\n                    \" * Ignoring a call to 'app.run()' that would block\"\n                    \" the current 'flask' CLI command.\\n\"\n                    \"   Only call 'app.run()' in an 'if __name__ ==\"                     ' \"__main__\"\\' guard.',\n                    fg=\"red\",                 )\n\n            return\n\n        if get_load_dotenv(load_dotenv):\n            cli.load_dotenv()\n\n            # if set, env var overrides existing value\n            if \"FLASK_DEBUG\" in os.environ:\n                self.debug = get_debug_flag()\n\n        # debug passed to method overrides all other sources\n        if debug is not None:\n            self.debug = bool(debug)\n        server_name = self.config.get(\"SERVER_NAME\")\n        sn_host = sn_port = None\n\n        if server_name:\n            server_url = urlsplit(f\"//{server_name}\")\n            sn_host = server_url.hostname\n            sn_port = server_url.port\n\n        if not host:\n            if sn_host:\n                host = sn_host\n            else:\n                host = \"127.0.0.1\"\n\n        if port or port == 0:\n            port = int(port)\n        elif sn_port is not None:\n            port = sn_port\n        else:\n            port = 5000\n        options.setdefault(\"use_reloader\", self.debug)\n        options.setdefault(\"use_debugger\", self.debug)\n        options.setdefault(\"threaded\", True)\n        cli.show_server_banner(self.debug, self.name)\n\n        from werkzeug.serving import run_simple\n\n        try:\n            run_simple(host, port, self, **options)\n        finally:\n            # reset the first request information if the development server\n            # reset normally.  This makes it possible to restart the server\n            # without reloader and that stuff from an interactive shell.\n            self._got_first_request = False\n    def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:\n        \"\"\"Creates a test client for this application.  For information\n        about unit testing head over to :doc:`/testing`.\n        Note that if you are testing for assertions or exceptions in your\n        application code, you must set ``app.testing = True`` in order for the\n        exceptions to propagate to the test client.  Otherwise, the exception\n        will be handled by the application (not visible to the test client) and\n        the only indication of an AssertionError or other exception will be a\n        500 status code response to the test client.  See the :attr:`testing`\n        attribute.  For example::\n            app.testing = True\n            client = app.test_client()\n        The test client can be used in a ``with`` block to defer the closing down\n        of the context until the end of the ``with`` block.  This is useful if\n        you want to access the context locals for testing::\n\n            with app.test_client() as c:\n                rv = c.get('/?vodka=42')\n                assert request.args['vodka'] == '42'\n        Additionally, you may pass optional keyword arguments that will then\n        be passed to the application's :attr:`test_client_class` constructor.\n        For example::\n\n            from flask.testing import FlaskClient\n\n            class CustomClient(FlaskClient):\n                def __init__(self, *args, **kwargs):\n                    self._authentication = kwargs.pop(\"authentication\")\n                    super(CustomClient,self).__init__( *args, **kwargs)\n            app.test_client_class = CustomClient\n            client = app.test_client(authentication='Basic ....')\n\n        See :class:`~flask.testing.FlaskClient` for more information.\n        .. versionchanged:: 0.4\n           added support for ``with`` block usage for the client.\n\n        .. versionadded:: 0.7\n           The `use_cookies` parameter was added as well as the ability\n           to override the client to be used by setting the\n           :attr:`test_client_class` attribute.\n\n        .. versionchanged:: 0.11\n           Added `**kwargs` to support passing additional keyword arguments to\n           the constructor of :attr:`test_client_class`.\n        \"\"\"\n        cls = self.test_client_class\n        if cls is None:\n            from .testing import FlaskClient as cls\n        return cls(  # type: ignore\n            self, self.response_class, use_cookies=use_cookies, **kwargs         )\n    def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:\n        \"\"\"Create a CLI runner for testing CLI commands.\n        See :ref:`testing-cli`.\n\n        Returns an instance of :attr:`test_cli_runner_class`, by default\n        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n        passed as the first argument.\n\n        .. versionadded:: 1.0\n        \"\"\"\n        cls = self.test_cli_runner_class\n        if cls is None:\n            from .testing import FlaskCliRunner as cls\n        return cls(self, **kwargs)  # type: ignore\n\n    def handle_http_exception(         self, ctx: AppContext, e: HTTPException     ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"Handles an HTTP exception.  By default this will invoke the\n        registered error handlers and fall back to returning the\n        exception as response.\n        .. versionchanged:: 1.0.3\n            ``RoutingException``, used internally for actions such as\n             slash redirects during routing, is not passed to error\n             handlers.\n\n        .. versionchanged:: 1.0\n            Exceptions are looked up by code *and* by MRO, so\n            ``HTTPException`` subclasses can be handled with a catch-all\n            handler for the base ``HTTPException``.\n        .. versionadded:: 0.3\n        \"\"\"\n        # Proxy exceptions don't have error codes.  We want to always return\n        # those unchanged as errors\n        if e.code is None:\n            return e\n        # RoutingExceptions are used internally to trigger routing\n        # actions, such as slash redirects raising RequestRedirect. They\n        # are not raised or handled in user code.\n        if isinstance(e, RoutingException):\n            return e\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n        if handler is None:\n            return e\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n    def handle_user_exception(\n        self, ctx: AppContext, e: Exception\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"This method is called whenever an exception occurs that\n        should be handled. A special case is :class:`~werkzeug\n        .exceptions.HTTPException` which is forwarded to the\n        :meth:`handle_http_exception` method. This function will either\n        return a response value or reraise the exception with the same\n        traceback.\n\n        .. versionchanged:: 1.0\n            Key errors raised from request data like ``form`` show the\n            bad key in debug mode rather than a generic bad request\n            message.\n        .. versionadded:: 0.7\n        \"\"\"\n        if isinstance(e, BadRequestKeyError) and (\n            self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n        ):\n            e.show_exception = True\n\n        if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n            return self.handle_http_exception(ctx, e)\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n\n        if handler is None:\n            raise\n\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_exception(self, ctx: AppContext, e: Exception) -> Response:\n        \"\"\"Handle an exception that did not have an error handler\n        associated with it, or that was raised from an error handler.\n        This always causes a 500 ``InternalServerError``.\n\n        Always sends the :data:`got_request_exception` signal.\n        If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n        mode, the error will be re-raised so that the debugger can\n        display it. Otherwise, the original exception is logged, and\n        an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n        If an error handler is registered for ``InternalServerError`` or\n        ``500``, it will be used. For consistency, the handler will\n        always receive the ``InternalServerError``. The original\n        unhandled exception is available as ``e.original_exception``.\n\n        .. versionchanged:: 1.1.0\n            Always passes the ``InternalServerError`` instance to the\n            handler, setting ``original_exception`` to the unhandled\n            error.\n        .. versionchanged:: 1.1.0\n            ``after_request`` functions and other finalization is done\n            even for the default 500 response when there is no handler.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        exc_info = sys.exc_info()\n        got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)\n        propagate = self.config[\"PROPAGATE_EXCEPTIONS\"]\n        if propagate is None:\n            propagate = self.testing or self.debug\n\n        if propagate:\n            # Re-raise if called with an active exception, otherwise\n            # raise the passed in exception.\n            if exc_info[1] is e:\n                raise\n            raise e\n        self.log_exception(ctx, exc_info)\n        server_error: InternalServerError | ft.ResponseReturnValue\n        server_error = InternalServerError(original_exception=e)\n        handler = self._find_error_handler(server_error, ctx.request.blueprints)\n\n        if handler is not None:\n            server_error = self.ensure_sync(handler)(server_error)\n\n        return self.finalize_request(ctx, server_error, from_error_handler=True)\n\n    def log_exception(\n        self,\n        ctx: AppContext,\n        exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n    ) -> None:\n        \"\"\"Logs an exception.  This is called by :meth:`handle_exception`\n        if debugging is disabled and right before the handler is called.\n        The default implementation logs the exception as error on the\n        :attr:`logger`.\n\n        .. versionadded:: 0.8\n        \"\"\"\n        self.logger.error(\n            f\"Exception on {ctx.request.path} [{ctx.request.method}]\", exc_info=exc_info         )\n    def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue:\n        \"\"\"Does the request dispatching.  Matches the URL and returns the\n        return value of the view or error handler.  This does not have to\n        be a response object.  In order to convert the return value to a\n        proper response object, call :func:`make_response`.\n\n        .. versionchanged:: 0.7\n           This no longer does the exception handling, this code was\n           moved to the new :meth:`full_dispatch_request`.\n        \"\"\"\n        req = ctx.request\n        if req.routing_exception is not None:\n            self.raise_routing_exception(req)\n        rule: Rule = req.url_rule  # type: ignore[assignment]\n        # if we provide automatic options for this URL and the\n        # request came with the OPTIONS method, reply automatically\n        if (\n            getattr(rule, \"provide_automatic_options\", False)             and req.method == \"OPTIONS\"\n        ):\n            return self.make_default_options_response(ctx)\n        # otherwise dispatch to the handler for that endpoint\n        view_args: dict[str, t.Any] = req.view_args  # type: ignore[assignment]\n        return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]\n\n    def full_dispatch_request(self, ctx: AppContext) -> Response:\n        \"\"\"Dispatches the request and on top of that performs request\n        pre and postprocessing as well as HTTP exception catching and\n        error handling.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if not self._got_first_request and self.should_ignore_error is not None:\n            import warnings\n\n            warnings.warn(                 \"The 'should_ignore_error' method is deprecated and will\"                 \" be removed in Flask 3.3. Handle errors as needed in\"\n                \" teardown handlers instead.\",                 DeprecationWarning,                 stacklevel=1,\n            )\n        self._got_first_request = True\n        try:\n            request_started.send(self, _async_wrapper=self.ensure_sync)\n            rv = self.preprocess_request(ctx)\n            if rv is None:\n                rv = self.dispatch_request(ctx)\n        except Exception as e:\n            rv = self.handle_user_exception(ctx, e)\n        return self.finalize_request(ctx, rv)\n\n    def finalize_request(\n        self,         ctx: AppContext,\n        rv: ft.ResponseReturnValue | HTTPException,         from_error_handler: bool = False,\n    ) -> Response:\n        \"\"\"Given the return value from a view function this finalizes\n        the request by converting it into a response and invoking the\n        postprocessing functions.  This is invoked for both normal\n        request dispatching as well as error handlers.\n\n        Because this means that it might be called as a result of a\n        failure a special safe mode is available which can be enabled\n        with the `from_error_handler` flag.  If enabled, failures in\n        response processing will be logged and otherwise ignored.\n        :internal:\n        \"\"\"\n        response = self.make_response(rv)\n        try:\n            response = self.process_response(ctx, response)\n            request_finished.send(\n                self, _async_wrapper=self.ensure_sync, response=response\n            )\n        except Exception:\n            if not from_error_handler:\n                raise\n            self.logger.exception(\n                \"Request finalizing failed with an error while handling an error\"\n            )\n        return response\n    def make_default_options_response(self, ctx: AppContext) -> Response:\n        \"\"\"This method is called to create the default ``OPTIONS`` response.\n        This can be changed through subclassing to change the default\n        behavior of ``OPTIONS`` responses.\n        .. versionadded:: 0.7\n        \"\"\"\n        methods = ctx.url_adapter.allowed_methods()  # type: ignore[union-attr]\n        rv = self.response_class()\n        rv.allow.update(methods)\n        return rv\n\n    def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n        \"\"\"Ensure that the function is synchronous for WSGI workers.\n        Plain ``def`` functions are returned as-is. ``async def``\n        functions are wrapped to run and wait for the response.\n\n        Override this method to change how the app runs async views.\n        .. versionadded:: 2.0\n        \"\"\"\n        if iscoroutinefunction(func):\n            return self.async_to_sync(func)\n\n        return func\n    def async_to_sync(         self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n    ) -> t.Callable[..., t.Any]:\n        \"\"\"Return a sync function that will run the coroutine function.\n\n        .. code-block:: python\n\n            result = app.async_to_sync(func)(*args, **kwargs)\n\n        Override this method to change how the app converts async code\n        to be synchronously callable.\n        .. versionadded:: 2.0\n        \"\"\"\n        try:\n            from asgiref.sync import async_to_sync as asgiref_async_to_sync\n        except ImportError:\n            raise RuntimeError(\n                \"Install Flask with the 'async' extra in order to use async views.\"\n            ) from None\n\n        return asgiref_async_to_sync(func)\n    def url_for(\n        self,         /,         endpoint: str,\n        *,\n        _anchor: str | None = None,         _method: str | None = None,         _scheme: str | None = None,\n        _external: bool | None = None,         **values: t.Any,\n    ) -> str:\n        \"\"\"Generate a URL to the given endpoint with the given values.\n        This is called by :func:`flask.url_for`, and can be called\n        directly as well.\n\n        An *endpoint* is the name of a URL rule, usually added with\n        :meth:`@app.route() <route>`, and usually the same name as the\n        view function. A route defined in a :class:`~flask.Blueprint`\n        will prepend the blueprint's name separated by a ``.`` to the\n        endpoint.\n\n        In some cases, such as email messages, you want URLs to include\n        the scheme and domain, like ``https://example.com/hello``. When\n        not in an active request, URLs will be external by default, but\n        this requires setting :data:`SERVER_NAME` so Flask knows what\n        domain to use. :data:`APPLICATION_ROOT` and\n        :data:`PREFERRED_URL_SCHEME` should also be configured as\n        needed. This config is only used when not in an active request.\n\n        Functions can be decorated with :meth:`url_defaults` to modify\n        keyword arguments before the URL is built.\n\n        If building fails for some reason, such as an unknown endpoint\n        or incorrect values, the app's :meth:`handle_url_build_error`\n        method is called. If that returns a string, that is returned,\n        otherwise a :exc:`~werkzeug.routing.BuildError` is raised.\n        :param endpoint: The endpoint name associated with the URL to\n            generate. If this starts with a ``.``, the current blueprint\n            name (if any) will be used.\n        :param _anchor: If given, append this as ``#anchor`` to the URL.\n        :param _method: If given, generate the URL associated with this\n            method for the endpoint.\n        :param _scheme: If given, the URL will have this scheme if it\n            is external.\n        :param _external: If given, prefer the URL to be internal\n            (False) or require it to be external (True). External URLs\n            include the scheme and domain. When not in an active\n            request, URLs are external by default.\n        :param values: Values to use for the variable parts of the URL\n            rule. Unknown keys are appended as query string arguments,\n            like ``?a=b&c=d``.\n        .. versionadded:: 2.2\n            Moved from ``flask.url_for``, which calls this method.\n        \"\"\"\n        if (ctx := _cv_app.get(None)) is not None and ctx.has_request:\n            url_adapter = ctx.url_adapter\n            blueprint_name = ctx.request.blueprint\n\n            # If the endpoint starts with \".\" and the request matches a\n            # blueprint, the endpoint is relative to the blueprint.\n            if endpoint[:1] == \".\":\n                if blueprint_name is not None:\n                    endpoint = f\"{blueprint_name}{endpoint}\"\n                else:\n                    endpoint = endpoint[1:]\n\n            # When in a request, generate a URL without scheme and\n            # domain by default, unless a scheme is given.\n            if _external is None:\n                _external = _scheme is not None\n        else:\n            # If called by helpers.url_for, an app context is active,\n            # use its url_adapter. Otherwise, app.url_for was called\n            # directly, build an adapter.\n            if ctx is not None:\n                url_adapter = ctx.url_adapter\n            else:\n                url_adapter = self.create_url_adapter(None)\n            if url_adapter is None:\n                raise RuntimeError(\n                    \"Unable to build URLs outside an active request\"\n                    \" without 'SERVER_NAME' configured. Also configure\"\n                    \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n                    \" needed.\"\n                )\n\n            # When outside a request, generate a URL with scheme and\n            # domain by default.\n            if _external is None:\n                _external = True\n\n        # It is an error to set _scheme when _external=False, in order\n        # to avoid accidental insecure URLs.\n        if _scheme is not None and not _external:\n            raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n        self.inject_url_defaults(endpoint, values)\n\n        try:\n            rv = url_adapter.build(  # type: ignore[union-attr]\n                endpoint,\n                values,\n                method=_method,\n                url_scheme=_scheme,                 force_external=_external,\n            )\n        except BuildError as error:\n            values.update(                 _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external\n            )\n            return self.handle_url_build_error(error, endpoint, values)\n        if _anchor is not None:\n            _anchor = _url_quote(_anchor, safe=\"%!#$&'()*+,/:;=?@\")\n            rv = f\"{rv}#{_anchor}\"\n        return rv\n\n    def make_response(self, rv: ft.ResponseReturnValue) -> Response:\n        \"\"\"Convert the return value from a view function to an instance of\n        :attr:`response_class`.\n        :param rv: the return value from the view function. The view function\n            must return a response. Returning ``None``, or the view ending\n            without returning, is not allowed. The following types are allowed\n            for ``view_rv``:\n\n            ``str``\n                A response object is created with the string encoded to UTF-8\n                as the body.\n\n            ``bytes``\n                A response object is created with the bytes as the body.\n            ``dict``\n                Converted to a JSON response.\n\n            ``list``\n                Converted to a JSON response.\n\n            ``generator`` or ``iterator``\n                A generator that returns ``str`` or ``bytes`` to be\n                streamed as the response.\n\n            ``tuple``\n                Either ``(body, status, headers)``, ``(body, status)``, or\n                ``(body, headers)``, where ``body`` is any of the other types\n                allowed here, ``status`` is a string or an integer, and\n                ``headers`` is a dictionary or a list of ``(key, value)``\n                tuples. If ``body`` is a :attr:`response_class` instance,\n                ``status`` overwrites the exiting value and ``headers`` are\n                extended.\n\n            :attr:`response_class`\n                The object is returned unchanged.\n\n            other :class:`~werkzeug.wrappers.Response` class\n                The object is coerced to :attr:`response_class`.\n\n            :func:`callable`\n                The function is called as a WSGI application. The result is\n                used to create a response object.\n\n        .. versionchanged:: 2.2\n            A generator will be converted to a streaming response.\n            A list will be converted to a JSON response.\n\n        .. versionchanged:: 1.1\n            A dict will be converted to a JSON response.\n        .. versionchanged:: 0.9\n           Previously a tuple was interpreted as the arguments for the\n           response object.\n        \"\"\"\n        status: int | None = None\n        headers: HeadersValue | None = None\n\n        # unpack tuple returns\n        if isinstance(rv, tuple):\n            len_rv = len(rv)\n            # a 3-tuple is unpacked directly\n            if len_rv == 3:\n                rv, status, headers = rv  # type: ignore[misc]\n            # decide if a 2-tuple has status or headers\n            elif len_rv == 2:\n                if isinstance(rv[1], (Headers, dict, tuple, list)):\n                    rv, headers = rv  # pyright: ignore\n                else:\n                    rv, status = rv  # type: ignore[assignment,misc]\n            # other sized tuples are not allowed\n            else:\n                raise TypeError(                     \"The view function did not return a valid response tuple.\"                     \" The tuple must have the form (body, status, headers),\"\n                    \" (body, status), or (body, headers).\"                 )\n        # the body must not be None\n        if rv is None:\n            raise TypeError(\n                f\"The view function for {request.endpoint!r} did not\"                 \" return a valid response. The function either returned\"\n                \" None or ended without a return statement.\"             )\n\n        # make sure the body is an instance of the response class\n        if not isinstance(rv, self.response_class):\n            if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):\n                # let the response class set the status and headers instead of\n                # waiting to do it manually, so that the class can handle any\n                # special logic\n                rv = self.response_class(                     rv,  # pyright: ignore\n                    status=status,                     headers=headers,  # type: ignore[arg-type]\n                )\n                status = headers = None\n            elif isinstance(rv, (dict, list)):\n                rv = self.json.response(rv)\n            elif isinstance(rv, BaseResponse) or callable(rv):\n                # evaluate a WSGI callable, or coerce a different response\n                # class to the correct type\n                try:\n                    rv = self.response_class.force_type(                         rv,  # type: ignore[arg-type]\n                        request.environ,                     )\n                except TypeError as e:\n                    raise TypeError(                         f\"{e}\\nThe view function did not return a valid\"\n                        \" response. The return type must be a string,\"\n                        \" dict, list, tuple with headers or status,\"\n                        \" Response instance, or WSGI callable, but it\"                         f\" was a {type(rv).__name__}.\"\n                    ).with_traceback(sys.exc_info()[2]) from None\n            else:\n                raise TypeError(                     \"The view function did not return a valid\"                     \" response. The return type must be a string,\"\n                    \" dict, list, tuple with headers or status,\"                     \" Response instance, or WSGI callable, but it was a\"                     f\" {type(rv).__name__}.\"\n                )\n        rv = t.cast(Response, rv)\n        # prefer the status if it was provided\n        if status is not None:\n            if isinstance(status, (str, bytes, bytearray)):\n                rv.status = status\n            else:\n                rv.status_code = status\n\n        # extend existing headers with provided headers\n        if headers:\n            rv.headers.update(headers)\n\n        return rv\n\n    def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None:\n        \"\"\"Called before the request is dispatched. Calls\n        :attr:`url_value_preprocessors` registered with the app and the\n        current blueprint (if any). Then calls :attr:`before_request_funcs`\n        registered with the app and the blueprint.\n        If any :meth:`before_request` handler returns a non-None value, the\n        value is handled as if it was the return value from the view, and\n        further request handling is stopped.\n        \"\"\"\n        req = ctx.request\n        names = (None, *reversed(req.blueprints))\n\n        for name in names:\n            if name in self.url_value_preprocessors:\n                for url_func in self.url_value_preprocessors[name]:\n                    url_func(req.endpoint, req.view_args)\n\n        for name in names:\n            if name in self.before_request_funcs:\n                for before_func in self.before_request_funcs[name]:\n                    rv = self.ensure_sync(before_func)()\n\n                    if rv is not None:\n                        return rv  # type: ignore[no-any-return]\n\n        return None\n\n    def process_response(self, ctx: AppContext, response: Response) -> Response:\n        \"\"\"Can be overridden in order to modify the response object\n        before it's sent to the WSGI server.  By default this will\n        call all the :meth:`after_request` decorated functions.\n\n        .. versionchanged:: 0.5\n           As of Flask 0.5 the functions registered for after request\n           execution are called in reverse order of registration.\n        :param response: a :attr:`response_class` object.\n        :return: a new response object or the same, has to be an\n                 instance of :attr:`response_class`.\n        \"\"\"\n        for func in ctx._after_request_functions:\n            response = self.ensure_sync(func)(response)\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.after_request_funcs:\n                for func in reversed(self.after_request_funcs[name]):\n                    response = self.ensure_sync(func)(response)\n\n        if not self.session_interface.is_null_session(ctx._get_session()):\n            self.session_interface.save_session(self, ctx._get_session(), response)\n\n        return response\n    def do_teardown_request(         self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called after the request is dispatched and the response is finalized,\n        right before the request context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_request`, and\n        :meth:`Blueprint.teardown_request` if a blueprint handled the request.\n        Finally, the :data:`request_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while dispatching the request.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionchanged:: 0.9\n            Added the ``exc`` argument.\n        \"\"\"\n        collect_errors = _CollectErrors()\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.teardown_request_funcs:\n                for func in reversed(self.teardown_request_funcs[name]):\n                    with collect_errors:\n                        self.ensure_sync(func)(exc)\n        with collect_errors:\n            request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during request teardown\")\n\n    def do_teardown_appcontext(         self, ctx: AppContext, exc: BaseException | None = None     ) -> None:\n        \"\"\"Called right before the application context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_appcontext`.\n        Then the :data:`appcontext_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while the context was active.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for func in reversed(self.teardown_appcontext_funcs):\n            with collect_errors:\n                self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during app teardown\")\n    def app_context(self) -> AppContext:\n        \"\"\"Create an :class:`.AppContext`. When the context is pushed,\n        :data:`.current_app` and :data:`.g` become available.\n\n        A context is automatically pushed when handling each request, and when\n        running any ``flask`` CLI command. Use this as a ``with`` block to\n        manually push a context outside of those situations, such as during\n        setup or testing.\n\n        .. code-block:: python\n\n            with app.app_context():\n                init_db()\n\n        See :doc:`/appcontext`.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        return AppContext(self)\n    def request_context(self, environ: WSGIEnvironment) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information representing\n        the given WSGI environment. A context is automatically pushed when\n        handling each request. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n        This method should not be used in your own code. Creating a valid WSGI\n        environ is not trivial. Use :meth:`test_request_context` to correctly\n        create a WSGI environ and request context instead.\n        See :doc:`/appcontext`.\n\n        :param environ: A WSGI environment.\n        \"\"\"\n        return AppContext.from_environ(self, environ)\n\n    def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information created from\n        the given arguments. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This is useful during testing to run a function that uses request data\n        without dispatching a full request. Use this as a ``with`` block to push\n        a context.\n        .. code-block:: python\n            with app.test_request_context(...):\n                generate_report()\n\n        See :doc:`/appcontext`.\n\n        Takes the same arguments as Werkzeug's\n        :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n        the application. See the linked Werkzeug docs for most of the\n        available arguments. Flask-specific behavior is listed here.\n\n        :param path: URL path being requested.\n        :param base_url: Base URL where the app is being served, which\n            ``path`` is relative to. If not given, built from\n            :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,\n            and :data:`APPLICATION_ROOT`.\n        :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.\n        :param url_scheme: Scheme to use instead of\n            :data:`PREFERRED_URL_SCHEME`.\n        :param data: The request body text or bytes,or a dict of form data.\n        :param json: If given, this is serialized as JSON and passed as\n            ``data``. Also defaults ``content_type`` to\n            ``application/json``.\n        :param args: Other positional arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        :param kwargs: Other keyword arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        \"\"\"\n        from .testing import EnvironBuilder\n        builder = EnvironBuilder(self, *args, **kwargs)\n\n        try:\n            environ = builder.get_environ()\n        finally:\n            builder.close()\n\n        return self.request_context(environ)\n    def wsgi_app(         self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The actual WSGI application. This is not implemented in\n        :meth:`__call__` so that middlewares can be applied without\n        losing a reference to the app object. Instead of doing this::\n\n            app = MyMiddleware(app)\n\n        It's a better idea to do this instead::\n            app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n        Then you still have the original application object around and\n        can continue to call methods on it.\n        .. versionchanged:: 0.7\n            Teardown events for the request and app contexts are called\n            even if an unhandled error occurs. Other events may not be\n            called depending on when an error occurs during dispatch.\n        :param environ: A WSGI environment.\n        :param start_response: A callable accepting a status code,\n            a list of headers, and an optional exception context to\n            start the response.\n        \"\"\"\n        ctx = self.request_context(environ)\n        error: BaseException | None = None\n        try:\n            try:\n                ctx.push()\n                response = self.full_dispatch_request(ctx)\n            except Exception as e:\n                error = e\n                response = self.handle_exception(ctx, e)\n            except:\n                error = sys.exc_info()[1]\n                raise\n            return response(environ, start_response)\n        finally:\n            if \"werkzeug.debug.preserve_context\" in environ:\n                environ[\"werkzeug.debug.preserve_context\"](ctx)\n\n            if (\n                error is not None\n                and self.should_ignore_error is not None\n                and self.should_ignore_error(error)\n            ):\n                error = None\n            ctx.pop(error)\n\n    def __call__(         self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The WSGI server calls the Flask application object as the\n        WSGI application. This calls :meth:`wsgi_app`, which can be\n        wrapped to apply middleware.\n        \"\"\"\n        return self.wsgi_app(environ, start_response)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-8341cf85103c4a69", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "016f4ce7fee32887ea849feab21288f25deda7d890e399202ffeaa463b4864a3", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 1372, "local_path": "layout/partially-compact-layout/I10__flask__Flask__30a23821.py", "order": 10, "original_content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "parent_variant_id": "pyint-14eacc325bde-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/app.py#L110-L1628", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 502, "line_break_groups_removed": 200, "line_breaks_removed": 200, "whitespace_characters_removed": 116}, "unit_kind": "class", "unit_name": "Flask", "variant_id": "pyint-f7e230a23821-I10", "group_id": "py-8341cf85103c4a69", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 641, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7ff448604447-I11", "source": "from __future__ import annotations\nimport collections.abc as cabc\nimport inspect\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom functools import update_wrapper\nfrom inspect import iscoroutinefunction\nfrom itertools import chain\nfrom types import TracebackType\nfrom urllib.parse import quote as _url_quote\nfrom urllib.parse import urlsplit\nimport click\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom werkzeug.wsgi import get_host\nfrom . import cli\nfrom . import typing as ft\nfrom .ctx import AppContext\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import _CollectErrors\nfrom .helpers import get_debug_flag\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import send_from_directory\nfrom .sansio.app import App\nfrom .sessions import SecureCookieSessionInterface\nfrom .sessions import SessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import Environment\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nclass Flask(App):\n    \"\"\"The flask object implements a WSGI application and acts as the central\n    object.  It is passed the name of the module or package of the\n    application.  Once it is created it will act as a central registry for\n    the view functions, the URL rules, template configuration and much more.\n\n    The name of the package is used to resolve resources from inside the\n    package or the folder the module is contained in depending on if the\n    package parameter resolves to an actual python package (a folder with\n    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n    For more information about resource loading, see :func:`open_resource`.\n\n    Usually you create a :class:`Flask` instance in your main module or\n    in the :file:`__init__.py` file of your package like this::\n\n        from flask import Flask\n        app = Flask(__name__)\n\n    .. admonition:: About the First Parameter\n\n        The idea of the first parameter is to give Flask an idea of what\n        belongs to your application.  This name is used to find resources\n        on the filesystem, can be used by extensions to improve debugging\n        information and a lot more.\n\n        So it's important what you provide there.  If you are using a single\n        module, `__name__` is always the correct value.  If you however are\n        using a package, it's usually recommended to hardcode the name of\n        your package there.\n\n        For example if your application is defined in :file:`yourapplication/app.py`\n        you should create it with one of the two versions below::\n\n            app = Flask('yourapplication')\n            app = Flask(__name__.split('.')[0])\n\n        Why is that?  The application will work even with `__name__`, thanks\n        to how resources are looked up.  However it will make debugging more\n        painful.  Certain extensions can make assumptions based on the\n        import name of your application.  For example the Flask-SQLAlchemy\n        extension will look for the code in your application that triggered\n        an SQL query in debug mode.  If the import name is not properly set\n        up, that debugging information is lost.  (For example it would only\n        pick up SQL queries in `yourapplication.app` and not\n        `yourapplication.views.frontend`)\n\n    .. versionadded:: 0.7\n       The `static_url_path`, `static_folder`, and `template_folder`\n       parameters were added.\n\n    .. versionadded:: 0.8\n       The `instance_path` and `instance_relative_config` parameters were\n       added.\n\n    .. versionadded:: 0.11\n       The `root_path` parameter was added.\n\n    .. versionadded:: 1.0\n       The ``host_matching`` and ``static_host`` parameters were added.\n\n    .. versionadded:: 1.0\n       The ``subdomain_matching`` parameter was added. Subdomain\n       matching needs to be enabled manually now. Setting\n       :data:`SERVER_NAME` does not implicitly enable it.\n\n    :param import_name: the name of the application package\n    :param static_url_path: can be used to specify a different path for the\n                            static files on the web.  Defaults to the name\n                            of the `static_folder` folder.\n    :param static_folder: The folder with static files that is served at\n        ``static_url_path``. Relative to the application ``root_path``\n        or an absolute path. Defaults to ``'static'``.\n    :param static_host: the host to use when adding the static route.\n        Defaults to None. Required when using ``host_matching=True``\n        with a ``static_folder`` configured.\n    :param host_matching: set ``url_map.host_matching`` attribute.\n        Defaults to False.\n    :param subdomain_matching: consider the subdomain relative to\n        :data:`SERVER_NAME` when matching routes. Defaults to False.\n    :param template_folder: the folder that contains the templates that should\n                            be used by the application.  Defaults to\n                            ``'templates'`` folder in the root path of the\n                            application.\n    :param instance_path: An alternative instance path for the application.\n                          By default the folder ``'instance'`` next to the\n                          package or module is assumed to be the instance\n                          path.\n    :param instance_relative_config: if set to ``True`` relative filenames\n                                     for loading the config are assumed to\n                                     be relative to the instance path instead\n                                     of the application root.\n    :param root_path: The path to the root of the application files.\n        This should only be set manually when it can't be detected\n        automatically, such as for namespace packages.\n    \"\"\"\n\n    default_config = ImmutableDict(\n        {\n            \"DEBUG\": None,\n            \"TESTING\": False,\n            \"PROPAGATE_EXCEPTIONS\": None,\n            \"SECRET_KEY\": None,\n            \"SECRET_KEY_FALLBACKS\": None,\n            \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n            \"USE_X_SENDFILE\": False,\n            \"TRUSTED_HOSTS\": None,\n            \"SERVER_NAME\": None,\n            \"APPLICATION_ROOT\": \"/\",\n            \"SESSION_COOKIE_NAME\": \"session\",\n            \"SESSION_COOKIE_DOMAIN\": None,\n            \"SESSION_COOKIE_PATH\": None,\n            \"SESSION_COOKIE_HTTPONLY\": True,\n            \"SESSION_COOKIE_SECURE\": False,\n            \"SESSION_COOKIE_PARTITIONED\": False,\n            \"SESSION_COOKIE_SAMESITE\": None,\n            \"SESSION_REFRESH_EACH_REQUEST\": True,\n            \"MAX_CONTENT_LENGTH\": None,\n            \"MAX_FORM_MEMORY_SIZE\": 500_000,\n            \"MAX_FORM_PARTS\": 1_000,\n            \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n            \"TRAP_BAD_REQUEST_ERRORS\": None,\n            \"TRAP_HTTP_EXCEPTIONS\": False,\n            \"EXPLAIN_TEMPLATE_LOADING\": False,\n            \"PREFERRED_URL_SCHEME\": \"http\",\n            \"TEMPLATES_AUTO_RELOAD\": None,\n            \"MAX_COOKIE_SIZE\": 4093,\n            \"PROVIDE_AUTOMATIC_OPTIONS\": True,\n        }\n    )\n\n    #: The class that is used for request objects.  See :class:`~flask.Request`\n    #: for more information.\n    request_class: type[Request] = Request\n\n    #: The class that is used for response objects.  See\n    #: :class:`~flask.Response` for more information.\n    response_class: type[Response] = Response\n\n    #: the session interface to use.  By default an instance of\n    #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n    #:\n    #: .. versionadded:: 0.8\n    session_interface: SessionInterface = SecureCookieSessionInterface()\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        import warnings\n\n        # These method signatures were updated to take a ctx param. Detect\n        # overridden methods in subclasses that still have the old signature.\n        # Show a deprecation warning and wrap to call with correct args.\n        for method in (\n            cls.handle_http_exception,\n            cls.handle_user_exception,\n            cls.handle_exception,\n            cls.log_exception,\n            cls.dispatch_request,\n            cls.full_dispatch_request,\n            cls.finalize_request,\n            cls.make_default_options_response,\n            cls.preprocess_request,\n            cls.process_response,\n            cls.do_teardown_request,\n            cls.do_teardown_appcontext,\n        ):\n            base_method = getattr(Flask, method.__name__)\n\n            if method is base_method:\n                # not overridden\n                continue\n\n            # get the second parameter (first is self)\n            iter_params = iter(inspect.signature(method).parameters.values())\n            next(iter_params)\n            param = next(iter_params, None)\n\n            # must have second parameter named ctx or annotated AppContext\n            a = 1\n            b = 1\n            if param is None or not (\n                # no annotation, match name\n                (param.annotation is inspect.Parameter.empty and param.name == \"ctx\")\n                or (\n                    # string annotation, access path ends with AppContext\n                    isinstance(param.annotation, str)\n                    and param.annotation.rpartition(\".\")[(a + b)] == \"AppContext\"\n                )\n                or (\n                    # class annotation\n                    inspect.isclass(param.annotation)\n                    and issubclass(param.annotation, AppContext)\n                )\n            ):\n                c = 1\n                d = 1\n                warnings.warn(\n                    f\"The '{method.__name__}' method now takes 'ctx: AppContext'\"\n                    \" as the first parameter. The old signature is deprecated\"\n                    \" and will not be supported in Flask 4.0.\",\n                    DeprecationWarning,\n                    stacklevel=(c + d),\n                )\n                setattr(cls, method.__name__, remove_ctx(method))\n                setattr(Flask, method.__name__, add_ctx(base_method))\n\n    def __init__(\n        self,\n        import_name: str,\n        static_url_path: str | None = None,\n        static_folder: str | os.PathLike[str] | None = \"static\",\n        static_host: str | None = None,\n        host_matching: bool = False,\n        subdomain_matching: bool = False,\n        template_folder: str | os.PathLike[str] | None = \"templates\",\n        instance_path: str | None = None,\n        instance_relative_config: bool = False,\n        root_path: str | None = None,\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_url_path=static_url_path,\n            static_folder=static_folder,\n            static_host=static_host,\n            host_matching=host_matching,\n            subdomain_matching=subdomain_matching,\n            template_folder=template_folder,\n            instance_path=instance_path,\n            instance_relative_config=instance_relative_config,\n            root_path=root_path,\n        )\n\n        #: The Click command group for registering CLI commands for this\n        #: object. The commands are available from the ``flask`` command\n        #: once the application has been discovered and blueprints have\n        #: been registered.\n        self.cli = cli.AppGroup()\n\n        # Set the name of the Click group in case someone wants to add\n        # the app's commands to another CLI tool.\n        self.cli.name = self.name\n\n        # Add a static route using the provided static_url_path, static_host,\n        # and static_folder if there is a configured static_folder.\n        # Note we do this without checking if static_folder exists.\n        # For one, it might be created while the server is running (e.g. during\n        # development). Also, Google App Engine stores static files somewhere\n        if self.has_static_folder:\n            assert bool(static_host) == host_matching, (\n                \"Invalid static_host/host_matching combination\"\n            )\n            # Use a weakref to avoid creating a reference cycle between the app\n            # and the view function (see #3761).\n            self_ref = weakref.ref(self)\n            self.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                endpoint=\"static\",\n                host=static_host,\n                view_func=lambda **kw: self_ref().send_static_file(**kw),  # type: ignore\n            )\n\n    def get_send_file_max_age(self, filename: str | None) -> int | None:\n        \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n        value for a given file path if it wasn't passed.\n\n        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n        the configuration of :data:`~flask.current_app`. This defaults\n        to ``None``, which tells the browser to use conditional requests\n        instead of a timed cache, which is usually preferable.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionchanged:: 2.0\n            The default configuration is ``None`` instead of 12 hours.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        value = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n        if value is None:\n            return None\n\n        if isinstance(value, timedelta):\n            return int(value.total_seconds())\n\n        return value  # type: ignore[no-any-return]\n\n    def send_static_file(self, filename: str) -> Response:\n        \"\"\"The view function used to serve files from\n        :attr:`static_folder`. A route is automatically registered for\n        this view at :attr:`static_url_path` if :attr:`static_folder` is\n        set.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionadded:: 0.5\n\n        \"\"\"\n        if not self.has_static_folder:\n            raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n        # send_file only knows to call get_send_file_max_age on the app,\n        # call it here so it works for blueprints too.\n        max_age = self.get_send_file_max_age(filename)\n        return send_from_directory(\n            t.cast(str, self.static_folder), filename, max_age=max_age\n        )\n\n    def open_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = None\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to :attr:`root_path` for reading.\n\n        For example, if the file ``schema.sql`` is next to the file\n        ``app.py`` where the ``Flask`` app is defined, it can be opened\n        with:\n\n        .. code-block:: python\n\n            with app.open_resource(\"schema.sql\") as f:\n                conn.executescript(f.read())\n\n        :param resource: Path to the resource relative to :attr:`root_path`.\n        :param mode: Open the file in this mode. Only reading is supported,\n            valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        if mode not in {\"r\", \"rt\", \"rb\"}:\n            raise ValueError(\"Resources can only be opened for reading.\")\n\n        path = os.path.join(self.root_path, resource)\n\n        if mode == \"rb\":\n            return open(path, mode)  # pyright: ignore\n\n        return open(path, mode, encoding=encoding)\n\n    def open_instance_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = \"utf-8\"\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to the application's instance folder\n        :attr:`instance_path`. Unlike :meth:`open_resource`, files in the\n        instance folder can be opened for writing.\n\n        :param resource: Path to the resource relative to :attr:`instance_path`.\n        :param mode: Open the file in this mode.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        path = os.path.join(self.instance_path, resource)\n\n        if \"b\" in mode:\n            return open(path, mode)\n\n        return open(path, mode, encoding=encoding)\n\n    def create_jinja_environment(self) -> Environment:\n        \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n        and the various Jinja-related methods of the app. Changing\n        :attr:`jinja_options` after this will have no effect. Also adds\n        Flask-related globals and filters to the environment.\n\n        .. versionchanged:: 0.11\n           ``Environment.auto_reload`` set in accordance with\n           ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        options = dict(self.jinja_options)\n\n        if \"autoescape\" not in options:\n            options[\"autoescape\"] = self.select_jinja_autoescape\n\n        if \"auto_reload\" not in options:\n            auto_reload = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n            if auto_reload is None:\n                auto_reload = self.debug\n\n            options[\"auto_reload\"] = auto_reload\n\n        rv = self.jinja_environment(self, **options)\n        rv.globals.update(\n            url_for=self.url_for,\n            get_flashed_messages=get_flashed_messages,\n            config=self.config,\n            # request, session and g are normally added with the\n            # context processor for efficiency reasons but for imported\n            # templates we also want the proxies in there.\n            request=request,\n            session=session,\n            g=g,\n        )\n        rv.policies[\"json.dumps_function\"] = self.json.dumps\n        return rv\n\n    def create_url_adapter(self, request: Request | None) -> MapAdapter | None:\n        \"\"\"Creates a URL adapter for the given request. The URL adapter\n        is created at a point where the request context is not yet set\n        up so the request is passed explicitly.\n\n        .. versionchanged:: 3.1\n            If :data:`SERVER_NAME` is set, it does not restrict requests to\n            only that domain, for both ``subdomain_matching`` and\n            ``host_matching``.\n\n        .. versionchanged:: 1.0\n            :data:`SERVER_NAME` no longer implicitly enables subdomain\n            matching. Use :attr:`subdomain_matching` instead.\n\n        .. versionchanged:: 0.9\n           This can be called outside a request when the URL adapter is created\n           for an application context.\n\n        .. versionadded:: 0.6\n        \"\"\"\n        if request is not None:\n            if (trusted_hosts := self.config[\"TRUSTED_HOSTS\"]) is not None:\n                request.trusted_hosts = trusted_hosts\n\n            # Check trusted_hosts here until bind_to_environ does.\n            request.host = get_host(request.environ, request.trusted_hosts)  # pyright: ignore\n            subdomain = None\n            server_name = self.config[\"SERVER_NAME\"]\n\n            if self.url_map.host_matching:\n                # Don't pass SERVER_NAME, otherwise it's used and the actual\n                # host is ignored, which breaks host matching.\n                server_name = None\n            elif not self.subdomain_matching:\n                # Werkzeug doesn't implement subdomain matching yet. Until then,\n                # disable it by forcing the current subdomain to the default, or\n                # the empty string.\n                subdomain = self.url_map.default_subdomain or \"\"\n\n            return self.url_map.bind_to_environ(\n                request.environ, server_name=server_name, subdomain=subdomain\n            )\n\n        # Need at least SERVER_NAME to match/build outside a request.\n        if self.config[\"SERVER_NAME\"] is not None:\n            return self.url_map.bind(\n                self.config[\"SERVER_NAME\"],\n                script_name=self.config[\"APPLICATION_ROOT\"],\n                url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n            )\n\n        return None\n\n    def raise_routing_exception(self, request: Request) -> t.NoReturn:\n        \"\"\"Intercept routing exceptions and possibly do something else.\n\n        In debug mode, intercept a routing redirect and replace it with\n        an error if the body will be discarded.\n\n        With modern Werkzeug this shouldn't occur, since it now uses a\n        308 status which tells the browser to resend the method and\n        body.\n\n        .. versionchanged:: 2.1\n            Don't intercept 307 and 308 redirects.\n\n        :meta private:\n        :internal:\n        \"\"\"\n        f = 153\n        h = 154\n        i = 154\n        j = 154\n        if (\n            not self.debug\n            or not isinstance(request.routing_exception, RequestRedirect)\n            or request.routing_exception.code in {(f + h), (i + j)}\n            or request.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n        ):\n            raise request.routing_exception  # type: ignore[misc]\n\n        from .debughelpers import FormDataRoutingRedirect\n\n        raise FormDataRoutingRedirect(request)\n\n    def update_template_context(\n        self, ctx: AppContext, context: dict[str, t.Any]\n    ) -> None:\n        \"\"\"Update the template context with some commonly used variables.\n        This injects request, session, config and g into the template\n        context as well as everything template context processors want\n        to inject.  Note that the as of Flask 0.6, the original values\n        in the context will not be overridden if a context processor\n        decides to return a value with the same key.\n\n        :param context: the context as a dictionary that is updated in place\n                        to add extra variables.\n        \"\"\"\n        names: t.Iterable[str | None] = (None,)\n\n        # A template may be rendered outside a request context.\n        if ctx.has_request:\n            names = chain(names, reversed(ctx.request.blueprints))\n\n        # The values passed to render_template take precedence. Keep a\n        # copy to re-apply after all context functions.\n        orig_ctx = context.copy()\n\n        for name in names:\n            if name in self.template_context_processors:\n                for func in self.template_context_processors[name]:\n                    context.update(self.ensure_sync(func)())\n\n        context.update(orig_ctx)\n\n    def make_shell_context(self) -> dict[str, t.Any]:\n        \"\"\"Returns the shell context for an interactive shell for this\n        application.  This runs all the registered shell context\n        processors.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {\"app\": self, \"g\": g}\n        for processor in self.shell_context_processors:\n            rv.update(processor())\n        return rv\n\n    def run(\n        self,\n        host: str | None = None,\n        port: int | None = None,\n        debug: bool | None = None,\n        load_dotenv: bool = True,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Runs the application on a local development server.\n\n        Do not use ``run()`` in a production setting. It is not intended to\n        meet security and performance requirements for a production server.\n        Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n        If the :attr:`debug` flag is set the server will automatically reload\n        for code changes and show a debugger in case an exception happened.\n\n        If you want to run the application in debug mode, but disable the\n        code execution on the interactive debugger, you can pass\n        ``use_evalex=False`` as parameter.  This will keep the debugger's\n        traceback screen active, but disable code execution.\n\n        It is not recommended to use this function for development with\n        automatic reloading as this is badly supported.  Instead you should\n        be using the :command:`flask` command line script's ``run`` support.\n\n        .. admonition:: Keep in Mind\n\n           Flask will suppress any server error with a generic error page\n           unless it is in debug mode.  As such to enable just the\n           interactive debugger without the code reloading, you have to\n           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n           Setting ``use_debugger`` to ``True`` without being in debug mode\n           won't catch any exceptions because there won't be any to\n           catch.\n\n        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n            have the server available externally as well. Defaults to\n            ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n            if present.\n        :param port: the port of the webserver. Defaults to ``5000`` or the\n            port defined in the ``SERVER_NAME`` config variable if present.\n        :param debug: if given, enable or disable debug mode. See\n            :attr:`debug`.\n        :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n            files to set environment variables. Will also change the working\n            directory to the directory containing the first file found.\n        :param options: the options to be forwarded to the underlying Werkzeug\n            server. See :func:`werkzeug.serving.run_simple` for more\n            information.\n\n        .. versionchanged:: 1.0\n            If installed, python-dotenv will be used to load environment\n            variables from :file:`.env` and :file:`.flaskenv` files.\n\n            The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.\n\n            Threaded mode is enabled by default.\n\n        .. versionchanged:: 0.10\n            The default port is now picked from the ``SERVER_NAME``\n            variable.\n        \"\"\"\n        # Ignore this call so that it doesn't start another server if\n        # the 'flask run' command is used.\n        if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n            if not is_running_from_reloader():\n                click.secho(\n                    \" * Ignoring a call to 'app.run()' that would block\"\n                    \" the current 'flask' CLI command.\\n\"\n                    \"   Only call 'app.run()' in an 'if __name__ ==\"\n                    ' \"__main__\"\\' guard.',\n                    fg=\"red\",\n                )\n\n            return\n\n        if get_load_dotenv(load_dotenv):\n            cli.load_dotenv()\n\n            # if set, env var overrides existing value\n            if \"FLASK_DEBUG\" in os.environ:\n                self.debug = get_debug_flag()\n\n        # debug passed to method overrides all other sources\n        if debug is not None:\n            self.debug = bool(debug)\n\n        server_name = self.config.get(\"SERVER_NAME\")\n        sn_host = sn_port = None\n\n        if server_name:\n            server_url = urlsplit(f\"//{server_name}\")\n            sn_host = server_url.hostname\n            sn_port = server_url.port\n\n        if not host:\n            if sn_host:\n                host = sn_host\n            else:\n                host = \"127.0.0.1\"\n\n        k = 1\n        l = -1\n        if port or port == (k + l):\n            port = int(port)\n        elif sn_port is not None:\n            port = sn_port\n        else:\n            m = 2500\n            n = 2500\n            port = (m + n)\n\n        options.setdefault(\"use_reloader\", self.debug)\n        options.setdefault(\"use_debugger\", self.debug)\n        options.setdefault(\"threaded\", True)\n\n        cli.show_server_banner(self.debug, self.name)\n\n        from werkzeug.serving import run_simple\n\n        try:\n            run_simple(host, port, self, **options)\n        finally:\n            # reset the first request information if the development server\n            # reset normally.  This makes it possible to restart the server\n            # without reloader and that stuff from an interactive shell.\n            self._got_first_request = False\n\n    def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:\n        \"\"\"Creates a test client for this application.  For information\n        about unit testing head over to :doc:`/testing`.\n\n        Note that if you are testing for assertions or exceptions in your\n        application code, you must set ``app.testing = True`` in order for the\n        exceptions to propagate to the test client.  Otherwise, the exception\n        will be handled by the application (not visible to the test client) and\n        the only indication of an AssertionError or other exception will be a\n        500 status code response to the test client.  See the :attr:`testing`\n        attribute.  For example::\n\n            app.testing = True\n            client = app.test_client()\n\n        The test client can be used in a ``with`` block to defer the closing down\n        of the context until the end of the ``with`` block.  This is useful if\n        you want to access the context locals for testing::\n\n            with app.test_client() as c:\n                rv = c.get('/?vodka=42')\n                assert request.args['vodka'] == '42'\n\n        Additionally, you may pass optional keyword arguments that will then\n        be passed to the application's :attr:`test_client_class` constructor.\n        For example::\n\n            from flask.testing import FlaskClient\n\n            class CustomClient(FlaskClient):\n                def __init__(self, *args, **kwargs):\n                    self._authentication = kwargs.pop(\"authentication\")\n                    super(CustomClient,self).__init__( *args, **kwargs)\n\n            app.test_client_class = CustomClient\n            client = app.test_client(authentication='Basic ....')\n\n        See :class:`~flask.testing.FlaskClient` for more information.\n\n        .. versionchanged:: 0.4\n           added support for ``with`` block usage for the client.\n\n        .. versionadded:: 0.7\n           The `use_cookies` parameter was added as well as the ability\n           to override the client to be used by setting the\n           :attr:`test_client_class` attribute.\n\n        .. versionchanged:: 0.11\n           Added `**kwargs` to support passing additional keyword arguments to\n           the constructor of :attr:`test_client_class`.\n        \"\"\"\n        cls = self.test_client_class\n        if cls is None:\n            from .testing import FlaskClient as cls\n        return cls(  # type: ignore\n            self, self.response_class, use_cookies=use_cookies, **kwargs\n        )\n\n    def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:\n        \"\"\"Create a CLI runner for testing CLI commands.\n        See :ref:`testing-cli`.\n\n        Returns an instance of :attr:`test_cli_runner_class`, by default\n        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n        passed as the first argument.\n\n        .. versionadded:: 1.0\n        \"\"\"\n        cls = self.test_cli_runner_class\n\n        if cls is None:\n            from .testing import FlaskCliRunner as cls\n\n        return cls(self, **kwargs)  # type: ignore\n\n    def handle_http_exception(\n        self, ctx: AppContext, e: HTTPException\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"Handles an HTTP exception.  By default this will invoke the\n        registered error handlers and fall back to returning the\n        exception as response.\n\n        .. versionchanged:: 1.0.3\n            ``RoutingException``, used internally for actions such as\n             slash redirects during routing, is not passed to error\n             handlers.\n\n        .. versionchanged:: 1.0\n            Exceptions are looked up by code *and* by MRO, so\n            ``HTTPException`` subclasses can be handled with a catch-all\n            handler for the base ``HTTPException``.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        # Proxy exceptions don't have error codes.  We want to always return\n        # those unchanged as errors\n        if e.code is None:\n            return e\n\n        # RoutingExceptions are used internally to trigger routing\n        # actions, such as slash redirects raising RequestRedirect. They\n        # are not raised or handled in user code.\n        if isinstance(e, RoutingException):\n            return e\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n        if handler is None:\n            return e\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_user_exception(\n        self, ctx: AppContext, e: Exception\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"This method is called whenever an exception occurs that\n        should be handled. A special case is :class:`~werkzeug\n        .exceptions.HTTPException` which is forwarded to the\n        :meth:`handle_http_exception` method. This function will either\n        return a response value or reraise the exception with the same\n        traceback.\n\n        .. versionchanged:: 1.0\n            Key errors raised from request data like ``form`` show the\n            bad key in debug mode rather than a generic bad request\n            message.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if isinstance(e, BadRequestKeyError) and (\n            self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n        ):\n            e.show_exception = True\n\n        if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n            return self.handle_http_exception(ctx, e)\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n\n        if handler is None:\n            raise\n\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_exception(self, ctx: AppContext, e: Exception) -> Response:\n        \"\"\"Handle an exception that did not have an error handler\n        associated with it, or that was raised from an error handler.\n        This always causes a 500 ``InternalServerError``.\n\n        Always sends the :data:`got_request_exception` signal.\n\n        If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n        mode, the error will be re-raised so that the debugger can\n        display it. Otherwise, the original exception is logged, and\n        an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n        If an error handler is registered for ``InternalServerError`` or\n        ``500``, it will be used. For consistency, the handler will\n        always receive the ``InternalServerError``. The original\n        unhandled exception is available as ``e.original_exception``.\n\n        .. versionchanged:: 1.1.0\n            Always passes the ``InternalServerError`` instance to the\n            handler, setting ``original_exception`` to the unhandled\n            error.\n\n        .. versionchanged:: 1.1.0\n            ``after_request`` functions and other finalization is done\n            even for the default 500 response when there is no handler.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        exc_info = sys.exc_info()\n        got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)\n        propagate = self.config[\"PROPAGATE_EXCEPTIONS\"]\n\n        if propagate is None:\n            propagate = self.testing or self.debug\n\n        if propagate:\n            # Re-raise if called with an active exception, otherwise\n            # raise the passed in exception.\n            o = 2\n            p = -1\n            if exc_info[(o + p)] is e:\n                raise\n\n            raise e\n\n        self.log_exception(ctx, exc_info)\n        server_error: InternalServerError | ft.ResponseReturnValue\n        server_error = InternalServerError(original_exception=e)\n        handler = self._find_error_handler(server_error, ctx.request.blueprints)\n\n        if handler is not None:\n            server_error = self.ensure_sync(handler)(server_error)\n\n        return self.finalize_request(ctx, server_error, from_error_handler=True)\n\n    def log_exception(\n        self,\n        ctx: AppContext,\n        exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n    ) -> None:\n        \"\"\"Logs an exception.  This is called by :meth:`handle_exception`\n        if debugging is disabled and right before the handler is called.\n        The default implementation logs the exception as error on the\n        :attr:`logger`.\n\n        .. versionadded:: 0.8\n        \"\"\"\n        self.logger.error(\n            f\"Exception on {ctx.request.path} [{ctx.request.method}]\", exc_info=exc_info\n        )\n\n    def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue:\n        \"\"\"Does the request dispatching.  Matches the URL and returns the\n        return value of the view or error handler.  This does not have to\n        be a response object.  In order to convert the return value to a\n        proper response object, call :func:`make_response`.\n\n        .. versionchanged:: 0.7\n           This no longer does the exception handling, this code was\n           moved to the new :meth:`full_dispatch_request`.\n        \"\"\"\n        req = ctx.request\n\n        if req.routing_exception is not None:\n            self.raise_routing_exception(req)\n        rule: Rule = req.url_rule  # type: ignore[assignment]\n        # if we provide automatic options for this URL and the\n        # request came with the OPTIONS method, reply automatically\n        if (\n            getattr(rule, \"provide_automatic_options\", False)\n            and req.method == \"OPTIONS\"\n        ):\n            return self.make_default_options_response(ctx)\n        # otherwise dispatch to the handler for that endpoint\n        view_args: dict[str, t.Any] = req.view_args  # type: ignore[assignment]\n        return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]\n\n    def full_dispatch_request(self, ctx: AppContext) -> Response:\n        \"\"\"Dispatches the request and on top of that performs request\n        pre and postprocessing as well as HTTP exception catching and\n        error handling.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if not self._got_first_request and self.should_ignore_error is not None:\n            import warnings\n\n            q = 2\n            r = -1\n            warnings.warn(\n                \"The 'should_ignore_error' method is deprecated and will\"\n                \" be removed in Flask 3.3. Handle errors as needed in\"\n                \" teardown handlers instead.\",\n                DeprecationWarning,\n                stacklevel=(q + r),\n            )\n\n        self._got_first_request = True\n\n        try:\n            request_started.send(self, _async_wrapper=self.ensure_sync)\n            rv = self.preprocess_request(ctx)\n            if rv is None:\n                rv = self.dispatch_request(ctx)\n        except Exception as e:\n            rv = self.handle_user_exception(ctx, e)\n        return self.finalize_request(ctx, rv)\n\n    def finalize_request(\n        self,\n        ctx: AppContext,\n        rv: ft.ResponseReturnValue | HTTPException,\n        from_error_handler: bool = False,\n    ) -> Response:\n        \"\"\"Given the return value from a view function this finalizes\n        the request by converting it into a response and invoking the\n        postprocessing functions.  This is invoked for both normal\n        request dispatching as well as error handlers.\n\n        Because this means that it might be called as a result of a\n        failure a special safe mode is available which can be enabled\n        with the `from_error_handler` flag.  If enabled, failures in\n        response processing will be logged and otherwise ignored.\n\n        :internal:\n        \"\"\"\n        response = self.make_response(rv)\n        try:\n            response = self.process_response(ctx, response)\n            request_finished.send(\n                self, _async_wrapper=self.ensure_sync, response=response\n            )\n        except Exception:\n            if not from_error_handler:\n                raise\n            self.logger.exception(\n                \"Request finalizing failed with an error while handling an error\"\n            )\n        return response\n\n    def make_default_options_response(self, ctx: AppContext) -> Response:\n        \"\"\"This method is called to create the default ``OPTIONS`` response.\n        This can be changed through subclassing to change the default\n        behavior of ``OPTIONS`` responses.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        methods = ctx.url_adapter.allowed_methods()  # type: ignore[union-attr]\n        rv = self.response_class()\n        rv.allow.update(methods)\n        return rv\n\n    def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n        \"\"\"Ensure that the function is synchronous for WSGI workers.\n        Plain ``def`` functions are returned as-is. ``async def``\n        functions are wrapped to run and wait for the response.\n\n        Override this method to change how the app runs async views.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if iscoroutinefunction(func):\n            return self.async_to_sync(func)\n\n        return func\n\n    def async_to_sync(\n        self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n    ) -> t.Callable[..., t.Any]:\n        \"\"\"Return a sync function that will run the coroutine function.\n\n        .. code-block:: python\n\n            result = app.async_to_sync(func)(*args, **kwargs)\n\n        Override this method to change how the app converts async code\n        to be synchronously callable.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        try:\n            from asgiref.sync import async_to_sync as asgiref_async_to_sync\n        except ImportError:\n            raise RuntimeError(\n                \"Install Flask with the 'async' extra in order to use async views.\"\n            ) from None\n\n        return asgiref_async_to_sync(func)\n\n    def url_for(\n        self,\n        /,\n        endpoint: str,\n        *,\n        _anchor: str | None = None,\n        _method: str | None = None,\n        _scheme: str | None = None,\n        _external: bool | None = None,\n        **values: t.Any,\n    ) -> str:\n        \"\"\"Generate a URL to the given endpoint with the given values.\n\n        This is called by :func:`flask.url_for`, and can be called\n        directly as well.\n\n        An *endpoint* is the name of a URL rule, usually added with\n        :meth:`@app.route() <route>`, and usually the same name as the\n        view function. A route defined in a :class:`~flask.Blueprint`\n        will prepend the blueprint's name separated by a ``.`` to the\n        endpoint.\n\n        In some cases, such as email messages, you want URLs to include\n        the scheme and domain, like ``https://example.com/hello``. When\n        not in an active request, URLs will be external by default, but\n        this requires setting :data:`SERVER_NAME` so Flask knows what\n        domain to use. :data:`APPLICATION_ROOT` and\n        :data:`PREFERRED_URL_SCHEME` should also be configured as\n        needed. This config is only used when not in an active request.\n\n        Functions can be decorated with :meth:`url_defaults` to modify\n        keyword arguments before the URL is built.\n\n        If building fails for some reason, such as an unknown endpoint\n        or incorrect values, the app's :meth:`handle_url_build_error`\n        method is called. If that returns a string, that is returned,\n        otherwise a :exc:`~werkzeug.routing.BuildError` is raised.\n\n        :param endpoint: The endpoint name associated with the URL to\n            generate. If this starts with a ``.``, the current blueprint\n            name (if any) will be used.\n        :param _anchor: If given, append this as ``#anchor`` to the URL.\n        :param _method: If given, generate the URL associated with this\n            method for the endpoint.\n        :param _scheme: If given, the URL will have this scheme if it\n            is external.\n        :param _external: If given, prefer the URL to be internal\n            (False) or require it to be external (True). External URLs\n            include the scheme and domain. When not in an active\n            request, URLs are external by default.\n        :param values: Values to use for the variable parts of the URL\n            rule. Unknown keys are appended as query string arguments,\n            like ``?a=b&c=d``.\n\n        .. versionadded:: 2.2\n            Moved from ``flask.url_for``, which calls this method.\n        \"\"\"\n        if (ctx := _cv_app.get(None)) is not None and ctx.has_request:\n            url_adapter = ctx.url_adapter\n            blueprint_name = ctx.request.blueprint\n\n            # If the endpoint starts with \".\" and the request matches a\n            # blueprint, the endpoint is relative to the blueprint.\n            s = 2\n            u = -1\n            if endpoint[:(s + u)] == \".\":\n                if blueprint_name is not None:\n                    endpoint = f\"{blueprint_name}{endpoint}\"\n                else:\n                    v = 2\n                    w = -1\n                    endpoint = endpoint[(v + w):]\n\n            # When in a request, generate a URL without scheme and\n            # domain by default, unless a scheme is given.\n            if _external is None:\n                _external = _scheme is not None\n        else:\n            # If called by helpers.url_for, an app context is active,\n            # use its url_adapter. Otherwise, app.url_for was called\n            # directly, build an adapter.\n            if ctx is not None:\n                url_adapter = ctx.url_adapter\n            else:\n                url_adapter = self.create_url_adapter(None)\n\n            if url_adapter is None:\n                raise RuntimeError(\n                    \"Unable to build URLs outside an active request\"\n                    \" without 'SERVER_NAME' configured. Also configure\"\n                    \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n                    \" needed.\"\n                )\n\n            # When outside a request, generate a URL with scheme and\n            # domain by default.\n            if _external is None:\n                _external = True\n\n        # It is an error to set _scheme when _external=False, in order\n        # to avoid accidental insecure URLs.\n        if _scheme is not None and not _external:\n            raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n        self.inject_url_defaults(endpoint, values)\n\n        try:\n            rv = url_adapter.build(  # type: ignore[union-attr]\n                endpoint,\n                values,\n                method=_method,\n                url_scheme=_scheme,\n                force_external=_external,\n            )\n        except BuildError as error:\n            values.update(\n                _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external\n            )\n            return self.handle_url_build_error(error, endpoint, values)\n\n        if _anchor is not None:\n            _anchor = _url_quote(_anchor, safe=\"%!#$&'()*+,/:;=?@\")\n            rv = f\"{rv}#{_anchor}\"\n\n        return rv\n\n    def make_response(self, rv: ft.ResponseReturnValue) -> Response:\n        \"\"\"Convert the return value from a view function to an instance of\n        :attr:`response_class`.\n\n        :param rv: the return value from the view function. The view function\n            must return a response. Returning ``None``, or the view ending\n            without returning, is not allowed. The following types are allowed\n            for ``view_rv``:\n\n            ``str``\n                A response object is created with the string encoded to UTF-8\n                as the body.\n\n            ``bytes``\n                A response object is created with the bytes as the body.\n\n            ``dict``\n                Converted to a JSON response.\n\n            ``list``\n                Converted to a JSON response.\n\n            ``generator`` or ``iterator``\n                A generator that returns ``str`` or ``bytes`` to be\n                streamed as the response.\n\n            ``tuple``\n                Either ``(body, status, headers)``, ``(body, status)``, or\n                ``(body, headers)``, where ``body`` is any of the other types\n                allowed here, ``status`` is a string or an integer, and\n                ``headers`` is a dictionary or a list of ``(key, value)``\n                tuples. If ``body`` is a :attr:`response_class` instance,\n                ``status`` overwrites the exiting value and ``headers`` are\n                extended.\n\n            :attr:`response_class`\n                The object is returned unchanged.\n\n            other :class:`~werkzeug.wrappers.Response` class\n                The object is coerced to :attr:`response_class`.\n\n            :func:`callable`\n                The function is called as a WSGI application. The result is\n                used to create a response object.\n\n        .. versionchanged:: 2.2\n            A generator will be converted to a streaming response.\n            A list will be converted to a JSON response.\n\n        .. versionchanged:: 1.1\n            A dict will be converted to a JSON response.\n\n        .. versionchanged:: 0.9\n           Previously a tuple was interpreted as the arguments for the\n           response object.\n        \"\"\"\n\n        status: int | None = None\n        headers: HeadersValue | None = None\n\n        # unpack tuple returns\n        if isinstance(rv, tuple):\n            len_rv = len(rv)\n\n            # a 3-tuple is unpacked directly\n            x = 1\n            y = 2\n            z = 1\n            aa = 1\n            if len_rv == (x + y):\n                rv, status, headers = rv  # type: ignore[misc]\n            # decide if a 2-tuple has status or headers\n            elif len_rv == (z + aa):\n                ab = 2\n                ac = -1\n                if isinstance(rv[(ab + ac)], (Headers, dict, tuple, list)):\n                    rv, headers = rv  # pyright: ignore\n                else:\n                    rv, status = rv  # type: ignore[assignment,misc]\n            # other sized tuples are not allowed\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid response tuple.\"\n                    \" The tuple must have the form (body, status, headers),\"\n                    \" (body, status), or (body, headers).\"\n                )\n\n        # the body must not be None\n        if rv is None:\n            raise TypeError(\n                f\"The view function for {request.endpoint!r} did not\"\n                \" return a valid response. The function either returned\"\n                \" None or ended without a return statement.\"\n            )\n\n        # make sure the body is an instance of the response class\n        if not isinstance(rv, self.response_class):\n            if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):\n                # let the response class set the status and headers instead of\n                # waiting to do it manually, so that the class can handle any\n                # special logic\n                rv = self.response_class(\n                    rv,  # pyright: ignore\n                    status=status,\n                    headers=headers,  # type: ignore[arg-type]\n                )\n                status = headers = None\n            elif isinstance(rv, (dict, list)):\n                rv = self.json.response(rv)\n            elif isinstance(rv, BaseResponse) or callable(rv):\n                # evaluate a WSGI callable, or coerce a different response\n                # class to the correct type\n                try:\n                    rv = self.response_class.force_type(\n                        rv,  # type: ignore[arg-type]\n                        request.environ,\n                    )\n                except TypeError as e:\n                    ad = 1\n                    ae = 1\n                    raise TypeError(\n                        f\"{e}\\nThe view function did not return a valid\"\n                        \" response. The return type must be a string,\"\n                        \" dict, list, tuple with headers or status,\"\n                        \" Response instance, or WSGI callable, but it\"\n                        f\" was a {type(rv).__name__}.\"\n                    ).with_traceback(sys.exc_info()[(ad + ae)]) from None\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid\"\n                    \" response. The return type must be a string,\"\n                    \" dict, list, tuple with headers or status,\"\n                    \" Response instance, or WSGI callable, but it was a\"\n                    f\" {type(rv).__name__}.\"\n                )\n\n        rv = t.cast(Response, rv)\n        # prefer the status if it was provided\n        if status is not None:\n            if isinstance(status, (str, bytes, bytearray)):\n                rv.status = status\n            else:\n                rv.status_code = status\n\n        # extend existing headers with provided headers\n        if headers:\n            rv.headers.update(headers)\n\n        return rv\n\n    def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None:\n        \"\"\"Called before the request is dispatched. Calls\n        :attr:`url_value_preprocessors` registered with the app and the\n        current blueprint (if any). Then calls :attr:`before_request_funcs`\n        registered with the app and the blueprint.\n\n        If any :meth:`before_request` handler returns a non-None value, the\n        value is handled as if it was the return value from the view, and\n        further request handling is stopped.\n        \"\"\"\n        req = ctx.request\n        names = (None, *reversed(req.blueprints))\n\n        for name in names:\n            if name in self.url_value_preprocessors:\n                for url_func in self.url_value_preprocessors[name]:\n                    url_func(req.endpoint, req.view_args)\n\n        for name in names:\n            if name in self.before_request_funcs:\n                for before_func in self.before_request_funcs[name]:\n                    rv = self.ensure_sync(before_func)()\n\n                    if rv is not None:\n                        return rv  # type: ignore[no-any-return]\n\n        return None\n\n    def process_response(self, ctx: AppContext, response: Response) -> Response:\n        \"\"\"Can be overridden in order to modify the response object\n        before it's sent to the WSGI server.  By default this will\n        call all the :meth:`after_request` decorated functions.\n\n        .. versionchanged:: 0.5\n           As of Flask 0.5 the functions registered for after request\n           execution are called in reverse order of registration.\n\n        :param response: a :attr:`response_class` object.\n        :return: a new response object or the same, has to be an\n                 instance of :attr:`response_class`.\n        \"\"\"\n        for func in ctx._after_request_functions:\n            response = self.ensure_sync(func)(response)\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.after_request_funcs:\n                for func in reversed(self.after_request_funcs[name]):\n                    response = self.ensure_sync(func)(response)\n\n        if not self.session_interface.is_null_session(ctx._get_session()):\n            self.session_interface.save_session(self, ctx._get_session(), response)\n\n        return response\n\n    def do_teardown_request(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called after the request is dispatched and the response is finalized,\n        right before the request context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_request`, and\n        :meth:`Blueprint.teardown_request` if a blueprint handled the request.\n        Finally, the :data:`request_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while dispatching the request.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionchanged:: 0.9\n            Added the ``exc`` argument.\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.teardown_request_funcs:\n                for func in reversed(self.teardown_request_funcs[name]):\n                    with collect_errors:\n                        self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during request teardown\")\n\n    def do_teardown_appcontext(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called right before the application context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_appcontext`.\n        Then the :data:`appcontext_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while the context was active.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for func in reversed(self.teardown_appcontext_funcs):\n            with collect_errors:\n                self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during app teardown\")\n\n    def app_context(self) -> AppContext:\n        \"\"\"Create an :class:`.AppContext`. When the context is pushed,\n        :data:`.current_app` and :data:`.g` become available.\n\n        A context is automatically pushed when handling each request, and when\n        running any ``flask`` CLI command. Use this as a ``with`` block to\n        manually push a context outside of those situations, such as during\n        setup or testing.\n\n        .. code-block:: python\n\n            with app.app_context():\n                init_db()\n\n        See :doc:`/appcontext`.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        return AppContext(self)\n\n    def request_context(self, environ: WSGIEnvironment) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information representing\n        the given WSGI environment. A context is automatically pushed when\n        handling each request. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This method should not be used in your own code. Creating a valid WSGI\n        environ is not trivial. Use :meth:`test_request_context` to correctly\n        create a WSGI environ and request context instead.\n\n        See :doc:`/appcontext`.\n\n        :param environ: A WSGI environment.\n        \"\"\"\n        return AppContext.from_environ(self, environ)\n\n    def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information created from\n        the given arguments. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This is useful during testing to run a function that uses request data\n        without dispatching a full request. Use this as a ``with`` block to push\n        a context.\n\n        .. code-block:: python\n\n            with app.test_request_context(...):\n                generate_report()\n\n        See :doc:`/appcontext`.\n\n        Takes the same arguments as Werkzeug's\n        :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n        the application. See the linked Werkzeug docs for most of the\n        available arguments. Flask-specific behavior is listed here.\n\n        :param path: URL path being requested.\n        :param base_url: Base URL where the app is being served, which\n            ``path`` is relative to. If not given, built from\n            :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,\n            and :data:`APPLICATION_ROOT`.\n        :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.\n        :param url_scheme: Scheme to use instead of\n            :data:`PREFERRED_URL_SCHEME`.\n        :param data: The request body text or bytes,or a dict of form data.\n        :param json: If given, this is serialized as JSON and passed as\n            ``data``. Also defaults ``content_type`` to\n            ``application/json``.\n        :param args: Other positional arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        :param kwargs: Other keyword arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        \"\"\"\n        from .testing import EnvironBuilder\n\n        builder = EnvironBuilder(self, *args, **kwargs)\n\n        try:\n            environ = builder.get_environ()\n        finally:\n            builder.close()\n\n        return self.request_context(environ)\n\n    def wsgi_app(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The actual WSGI application. This is not implemented in\n        :meth:`__call__` so that middlewares can be applied without\n        losing a reference to the app object. Instead of doing this::\n\n            app = MyMiddleware(app)\n\n        It's a better idea to do this instead::\n\n            app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n        Then you still have the original application object around and\n        can continue to call methods on it.\n\n        .. versionchanged:: 0.7\n            Teardown events for the request and app contexts are called\n            even if an unhandled error occurs. Other events may not be\n            called depending on when an error occurs during dispatch.\n\n        :param environ: A WSGI environment.\n        :param start_response: A callable accepting a status code,\n            a list of headers, and an optional exception context to\n            start the response.\n        \"\"\"\n        ctx = self.request_context(environ)\n        error: BaseException | None = None\n        try:\n            try:\n                ctx.push()\n                response = self.full_dispatch_request(ctx)\n            except Exception as e:\n                error = e\n                response = self.handle_exception(ctx, e)\n            except:\n                af = 2\n                ag = -1\n                error = sys.exc_info()[(af + ag)]\n                raise\n            return response(environ, start_response)\n        finally:\n            if \"werkzeug.debug.preserve_context\" in environ:\n                environ[\"werkzeug.debug.preserve_context\"](ctx)\n\n            if (\n                error is not None\n                and self.should_ignore_error is not None\n                and self.should_ignore_error(error)\n            ):\n                error = None\n\n            ctx.pop(error)\n\n    def __call__(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The WSGI server calls the Flask application object as the\n        WSGI application. This calls :meth:`wsgi_app`, which can be\n        wrapped to apply middleware.\n        \"\"\"\n        return self.wsgi_app(environ, start_response)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-8341cf85103c4a69", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "e121abb80ffbbb5f37f7b351102a1bd6b9257a6467522dee0a128071f8f9896e", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 1602, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__Flask__48604447.py", "order": 11, "original_content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "parent_variant_id": "pyint-14eacc325bde-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/app.py#L110-L1628", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 15, "intermediate_variables_introduced": 30, "statements_augmented": 13}, "unit_kind": "class", "unit_name": "Flask", "variant_id": "pyint-7ff448604447-I11", "group_id": "py-8341cf85103c4a69", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 642, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9a5c382f2902-I12", "source": "from __future__ import annotations\nimport collections.abc as cabc\nimport inspect\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom functools import update_wrapper\nfrom inspect import iscoroutinefunction\nfrom itertools import chain\nfrom types import TracebackType\nfrom urllib.parse import quote as _url_quote\nfrom urllib.parse import urlsplit\nimport click\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom werkzeug.wsgi import get_host\nfrom . import cli\nfrom . import typing as ft\nfrom .ctx import AppContext\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import _CollectErrors\nfrom .helpers import get_debug_flag\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import send_from_directory\nfrom .sansio.app import App\nfrom .sessions import SecureCookieSessionInterface\nfrom .sessions import SessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import Environment\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nclass Flask(App):\n    \"\"\"The flask object implements a WSGI application and acts as the central\n    object.  It is passed the name of the module or package of the\n    application.  Once it is created it will act as a central registry for\n    the view functions, the URL rules, template configuration and much more.\n\n    The name of the package is used to resolve resources from inside the\n    package or the folder the module is contained in depending on if the\n    package parameter resolves to an actual python package (a folder with\n    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n    For more information about resource loading, see :func:`open_resource`.\n\n    Usually you create a :class:`Flask` instance in your main module or\n    in the :file:`__init__.py` file of your package like this::\n\n        from flask import Flask\n        app = Flask(__name__)\n\n    .. admonition:: About the First Parameter\n\n        The idea of the first parameter is to give Flask an idea of what\n        belongs to your application.  This name is used to find resources\n        on the filesystem, can be used by extensions to improve debugging\n        information and a lot more.\n\n        So it's important what you provide there.  If you are using a single\n        module, `__name__` is always the correct value.  If you however are\n        using a package, it's usually recommended to hardcode the name of\n        your package there.\n\n        For example if your application is defined in :file:`yourapplication/app.py`\n        you should create it with one of the two versions below::\n\n            app = Flask('yourapplication')\n            app = Flask(__name__.split('.')[0])\n\n        Why is that?  The application will work even with `__name__`, thanks\n        to how resources are looked up.  However it will make debugging more\n        painful.  Certain extensions can make assumptions based on the\n        import name of your application.  For example the Flask-SQLAlchemy\n        extension will look for the code in your application that triggered\n        an SQL query in debug mode.  If the import name is not properly set\n        up, that debugging information is lost.  (For example it would only\n        pick up SQL queries in `yourapplication.app` and not\n        `yourapplication.views.frontend`)\n\n    .. versionadded:: 0.7\n       The `static_url_path`, `static_folder`, and `template_folder`\n       parameters were added.\n\n    .. versionadded:: 0.8\n       The `instance_path` and `instance_relative_config` parameters were\n       added.\n\n    .. versionadded:: 0.11\n       The `root_path` parameter was added.\n\n    .. versionadded:: 1.0\n       The ``host_matching`` and ``static_host`` parameters were added.\n\n    .. versionadded:: 1.0\n       The ``subdomain_matching`` parameter was added. Subdomain\n       matching needs to be enabled manually now. Setting\n       :data:`SERVER_NAME` does not implicitly enable it.\n\n    :param import_name: the name of the application package\n    :param static_url_path: can be used to specify a different path for the\n                            static files on the web.  Defaults to the name\n                            of the `static_folder` folder.\n    :param static_folder: The folder with static files that is served at\n        ``static_url_path``. Relative to the application ``root_path``\n        or an absolute path. Defaults to ``'static'``.\n    :param static_host: the host to use when adding the static route.\n        Defaults to None. Required when using ``host_matching=True``\n        with a ``static_folder`` configured.\n    :param host_matching: set ``url_map.host_matching`` attribute.\n        Defaults to False.\n    :param subdomain_matching: consider the subdomain relative to\n        :data:`SERVER_NAME` when matching routes. Defaults to False.\n    :param template_folder: the folder that contains the templates that should\n                            be used by the application.  Defaults to\n                            ``'templates'`` folder in the root path of the\n                            application.\n    :param instance_path: An alternative instance path for the application.\n                          By default the folder ``'instance'`` next to the\n                          package or module is assumed to be the instance\n                          path.\n    :param instance_relative_config: if set to ``True`` relative filenames\n                                     for loading the config are assumed to\n                                     be relative to the instance path instead\n                                     of the application root.\n    :param root_path: The path to the root of the application files.\n        This should only be set manually when it can't be detected\n        automatically, such as for namespace packages.\n    \"\"\"\n\n    default_config = ImmutableDict(\n        {\n            \"DEBUG\": None,\n            \"TESTING\": False,\n            \"PROPAGATE_EXCEPTIONS\": None,\n            \"SECRET_KEY\": None,\n            \"SECRET_KEY_FALLBACKS\": None,\n            \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n            \"USE_X_SENDFILE\": False,\n            \"TRUSTED_HOSTS\": None,\n            \"SERVER_NAME\": None,\n            \"APPLICATION_ROOT\": \"/\",\n            \"SESSION_COOKIE_NAME\": \"session\",\n            \"SESSION_COOKIE_DOMAIN\": None,\n            \"SESSION_COOKIE_PATH\": None,\n            \"SESSION_COOKIE_HTTPONLY\": True,\n            \"SESSION_COOKIE_SECURE\": False,\n            \"SESSION_COOKIE_PARTITIONED\": False,\n            \"SESSION_COOKIE_SAMESITE\": None,\n            \"SESSION_REFRESH_EACH_REQUEST\": True,\n            \"MAX_CONTENT_LENGTH\": None,\n            \"MAX_FORM_MEMORY_SIZE\": 500_000,\n            \"MAX_FORM_PARTS\": 1_000,\n            \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n            \"TRAP_BAD_REQUEST_ERRORS\": None,\n            \"TRAP_HTTP_EXCEPTIONS\": False,\n            \"EXPLAIN_TEMPLATE_LOADING\": False,\n            \"PREFERRED_URL_SCHEME\": \"http\",\n            \"TEMPLATES_AUTO_RELOAD\": None,\n            \"MAX_COOKIE_SIZE\": 4093,\n            \"PROVIDE_AUTOMATIC_OPTIONS\": True,\n        }\n    )\n\n    #: The class that is used for request objects.  See :class:`~flask.Request`\n    #: for more information.\n    request_class: type[Request] = Request\n\n    #: The class that is used for response objects.  See\n    #: :class:`~flask.Response` for more information.\n    response_class: type[Response] = Response\n\n    #: the session interface to use.  By default an instance of\n    #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n    #:\n    #: .. versionadded:: 0.8\n    session_interface: SessionInterface = SecureCookieSessionInterface()\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        import warnings\n\n        # These method signatures were updated to take a ctx param. Detect\n        # overridden methods in subclasses that still have the old signature.\n        # Show a deprecation warning and wrap to call with correct args.\n        for method in (\n            cls.handle_http_exception,\n            cls.handle_user_exception,\n            cls.handle_exception,\n            cls.log_exception,\n            cls.dispatch_request,\n            cls.full_dispatch_request,\n            cls.finalize_request,\n            cls.make_default_options_response,\n            cls.preprocess_request,\n            cls.process_response,\n            cls.do_teardown_request,\n            cls.do_teardown_appcontext,\n        ):\n            base_method = getattr(Flask, method.__name__)\n\n            if method is base_method:\n                # not overridden\n                continue\n\n            # get the second parameter (first is self)\n            iter_params = iter(inspect.signature(method).parameters.values())\n            next(iter_params)\n            param = next(iter_params, None)\n\n            # must have second parameter named ctx or annotated AppContext\n            if param is None or not (\n                # no annotation, match name\n                (param.annotation is inspect.Parameter.empty and param.name == \"ctx\")\n                or (\n                    # string annotation, access path ends with AppContext\n                    isinstance(param.annotation, str)\n                    and param.annotation.rpartition(\".\")[2] == \"AppContext\"\n                )\n                or (\n                    # class annotation\n                    inspect.isclass(param.annotation)\n                    and issubclass(param.annotation, AppContext)\n                )\n            ):\n                warnings.warn(\n                    f\"The '{method.__name__}' method now takes 'ctx: AppContext'\"\n                    \" as the first parameter. The old signature is deprecated\"\n                    \" and will not be supported in Flask 4.0.\",\n                    DeprecationWarning,\n                    stacklevel=2,\n                )\n                setattr(cls, method.__name__, remove_ctx(method))\n                setattr(Flask, method.__name__, add_ctx(base_method))\n\n    def __init__(\n        self,\n        import_name: str,\n        static_url_path: str | None = None,\n        static_folder: str | os.PathLike[str] | None = \"static\",\n        static_host: str | None = None,\n        host_matching: bool = False,\n        subdomain_matching: bool = False,\n        template_folder: str | os.PathLike[str] | None = \"templates\",\n        instance_path: str | None = None,\n        instance_relative_config: bool = False,\n        root_path: str | None = None,\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_url_path=static_url_path,\n            static_folder=static_folder,\n            static_host=static_host,\n            host_matching=host_matching,\n            subdomain_matching=subdomain_matching,\n            template_folder=template_folder,\n            instance_path=instance_path,\n            instance_relative_config=instance_relative_config,\n            root_path=root_path,\n        )\n\n        #: The Click command group for registering CLI commands for this\n        #: object. The commands are available from the ``flask`` command\n        #: once the application has been discovered and blueprints have\n        #: been registered.\n        self.cli = cli.AppGroup()\n\n        # Set the name of the Click group in case someone wants to add\n        # the app's commands to another CLI tool.\n        self.cli.name = self.name\n\n        # Add a static route using the provided static_url_path, static_host,\n        # and static_folder if there is a configured static_folder.\n        # Note we do this without checking if static_folder exists.\n        # For one, it might be created while the server is running (e.g. during\n        # development). Also, Google App Engine stores static files somewhere\n        if self.has_static_folder:\n            assert bool(static_host) == host_matching, (\n                \"Invalid static_host/host_matching combination\"\n            )\n            # Use a weakref to avoid creating a reference cycle between the app\n            # and the view function (see #3761).\n            self_ref = weakref.ref(self)\n            self.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                endpoint=\"static\",\n                host=static_host,\n                view_func=lambda **kw: self_ref().send_static_file(**kw),  # type: ignore\n            )\n\n    def get_send_file_max_age(self, filename: str | None) -> int | None:\n        \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n        value for a given file path if it wasn't passed.\n\n        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n        the configuration of :data:`~flask.current_app`. This defaults\n        to ``None``, which tells the browser to use conditional requests\n        instead of a timed cache, which is usually preferable.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionchanged:: 2.0\n            The default configuration is ``None`` instead of 12 hours.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        value = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n        if value is None:\n            return None\n\n        if isinstance(value, timedelta):\n            return int(value.total_seconds())\n\n        return value  # type: ignore[no-any-return]\n\n    def send_static_file(self, filename: str) -> Response:\n        \"\"\"The view function used to serve files from\n        :attr:`static_folder`. A route is automatically registered for\n        this view at :attr:`static_url_path` if :attr:`static_folder` is\n        set.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionadded:: 0.5\n\n        \"\"\"\n        if not self.has_static_folder:\n            raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n        # send_file only knows to call get_send_file_max_age on the app,\n        # call it here so it works for blueprints too.\n        \n        return send_from_directory(\n            t.cast(str, self.static_folder), filename, max_age=(self.get_send_file_max_age(filename))\n        )\n\n    def open_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = None\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to :attr:`root_path` for reading.\n\n        For example, if the file ``schema.sql`` is next to the file\n        ``app.py`` where the ``Flask`` app is defined, it can be opened\n        with:\n\n        .. code-block:: python\n\n            with app.open_resource(\"schema.sql\") as f:\n                conn.executescript(f.read())\n\n        :param resource: Path to the resource relative to :attr:`root_path`.\n        :param mode: Open the file in this mode. Only reading is supported,\n            valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        if mode not in {\"r\", \"rt\", \"rb\"}:\n            raise ValueError(\"Resources can only be opened for reading.\")\n\n        path = os.path.join(self.root_path, resource)\n\n        if mode == \"rb\":\n            return open(path, mode)  # pyright: ignore\n\n        return open(path, mode, encoding=encoding)\n\n    def open_instance_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = \"utf-8\"\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to the application's instance folder\n        :attr:`instance_path`. Unlike :meth:`open_resource`, files in the\n        instance folder can be opened for writing.\n\n        :param resource: Path to the resource relative to :attr:`instance_path`.\n        :param mode: Open the file in this mode.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        path = os.path.join(self.instance_path, resource)\n\n        if \"b\" in mode:\n            return open(path, mode)\n\n        return open(path, mode, encoding=encoding)\n\n    def create_jinja_environment(self) -> Environment:\n        \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n        and the various Jinja-related methods of the app. Changing\n        :attr:`jinja_options` after this will have no effect. Also adds\n        Flask-related globals and filters to the environment.\n\n        .. versionchanged:: 0.11\n           ``Environment.auto_reload`` set in accordance with\n           ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        options = dict(self.jinja_options)\n\n        if \"autoescape\" not in options:\n            options[\"autoescape\"] = self.select_jinja_autoescape\n\n        if \"auto_reload\" not in options:\n            auto_reload = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n            if auto_reload is None:\n                auto_reload = self.debug\n\n            options[\"auto_reload\"] = auto_reload\n\n        rv = self.jinja_environment(self, **options)\n        rv.globals.update(\n            url_for=self.url_for,\n            get_flashed_messages=get_flashed_messages,\n            config=self.config,\n            # request, session and g are normally added with the\n            # context processor for efficiency reasons but for imported\n            # templates we also want the proxies in there.\n            request=request,\n            session=session,\n            g=g,\n        )\n        rv.policies[\"json.dumps_function\"] = self.json.dumps\n        return rv\n\n    def create_url_adapter(self, request: Request | None) -> MapAdapter | None:\n        \"\"\"Creates a URL adapter for the given request. The URL adapter\n        is created at a point where the request context is not yet set\n        up so the request is passed explicitly.\n\n        .. versionchanged:: 3.1\n            If :data:`SERVER_NAME` is set, it does not restrict requests to\n            only that domain, for both ``subdomain_matching`` and\n            ``host_matching``.\n\n        .. versionchanged:: 1.0\n            :data:`SERVER_NAME` no longer implicitly enables subdomain\n            matching. Use :attr:`subdomain_matching` instead.\n\n        .. versionchanged:: 0.9\n           This can be called outside a request when the URL adapter is created\n           for an application context.\n\n        .. versionadded:: 0.6\n        \"\"\"\n        if request is not None:\n            if (trusted_hosts := self.config[\"TRUSTED_HOSTS\"]) is not None:\n                request.trusted_hosts = trusted_hosts\n\n            # Check trusted_hosts here until bind_to_environ does.\n            request.host = get_host(request.environ, request.trusted_hosts)  # pyright: ignore\n            subdomain = None\n            server_name = self.config[\"SERVER_NAME\"]\n\n            if self.url_map.host_matching:\n                # Don't pass SERVER_NAME, otherwise it's used and the actual\n                # host is ignored, which breaks host matching.\n                server_name = None\n            elif not self.subdomain_matching:\n                # Werkzeug doesn't implement subdomain matching yet. Until then,\n                # disable it by forcing the current subdomain to the default, or\n                # the empty string.\n                subdomain = self.url_map.default_subdomain or \"\"\n\n            return self.url_map.bind_to_environ(\n                request.environ, server_name=server_name, subdomain=subdomain\n            )\n\n        # Need at least SERVER_NAME to match/build outside a request.\n        if self.config[\"SERVER_NAME\"] is not None:\n            return self.url_map.bind(\n                self.config[\"SERVER_NAME\"],\n                script_name=self.config[\"APPLICATION_ROOT\"],\n                url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n            )\n\n        return None\n\n    def raise_routing_exception(self, request: Request) -> t.NoReturn:\n        \"\"\"Intercept routing exceptions and possibly do something else.\n\n        In debug mode, intercept a routing redirect and replace it with\n        an error if the body will be discarded.\n\n        With modern Werkzeug this shouldn't occur, since it now uses a\n        308 status which tells the browser to resend the method and\n        body.\n\n        .. versionchanged:: 2.1\n            Don't intercept 307 and 308 redirects.\n\n        :meta private:\n        :internal:\n        \"\"\"\n        if (\n            not self.debug\n            or not isinstance(request.routing_exception, RequestRedirect)\n            or request.routing_exception.code in {307, 308}\n            or request.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n        ):\n            raise request.routing_exception  # type: ignore[misc]\n\n        from .debughelpers import FormDataRoutingRedirect\n\n        raise FormDataRoutingRedirect(request)\n\n    def update_template_context(\n        self, ctx: AppContext, context: dict[str, t.Any]\n    ) -> None:\n        \"\"\"Update the template context with some commonly used variables.\n        This injects request, session, config and g into the template\n        context as well as everything template context processors want\n        to inject.  Note that the as of Flask 0.6, the original values\n        in the context will not be overridden if a context processor\n        decides to return a value with the same key.\n\n        :param context: the context as a dictionary that is updated in place\n                        to add extra variables.\n        \"\"\"\n        names: t.Iterable[str | None] = (None,)\n\n        # A template may be rendered outside a request context.\n        if ctx.has_request:\n            names = chain(names, reversed(ctx.request.blueprints))\n\n        # The values passed to render_template take precedence. Keep a\n        # copy to re-apply after all context functions.\n        \n\n        for name in names:\n            if name in self.template_context_processors:\n                for func in self.template_context_processors[name]:\n                    context.update(self.ensure_sync(func)())\n\n        context.update((context.copy()))\n\n    def make_shell_context(self) -> dict[str, t.Any]:\n        \"\"\"Returns the shell context for an interactive shell for this\n        application.  This runs all the registered shell context\n        processors.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {\"app\": self, \"g\": g}\n        for processor in self.shell_context_processors:\n            rv.update(processor())\n        return rv\n\n    def run(\n        self,\n        host: str | None = None,\n        port: int | None = None,\n        debug: bool | None = None,\n        load_dotenv: bool = True,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Runs the application on a local development server.\n\n        Do not use ``run()`` in a production setting. It is not intended to\n        meet security and performance requirements for a production server.\n        Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n        If the :attr:`debug` flag is set the server will automatically reload\n        for code changes and show a debugger in case an exception happened.\n\n        If you want to run the application in debug mode, but disable the\n        code execution on the interactive debugger, you can pass\n        ``use_evalex=False`` as parameter.  This will keep the debugger's\n        traceback screen active, but disable code execution.\n\n        It is not recommended to use this function for development with\n        automatic reloading as this is badly supported.  Instead you should\n        be using the :command:`flask` command line script's ``run`` support.\n\n        .. admonition:: Keep in Mind\n\n           Flask will suppress any server error with a generic error page\n           unless it is in debug mode.  As such to enable just the\n           interactive debugger without the code reloading, you have to\n           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n           Setting ``use_debugger`` to ``True`` without being in debug mode\n           won't catch any exceptions because there won't be any to\n           catch.\n\n        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n            have the server available externally as well. Defaults to\n            ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n            if present.\n        :param port: the port of the webserver. Defaults to ``5000`` or the\n            port defined in the ``SERVER_NAME`` config variable if present.\n        :param debug: if given, enable or disable debug mode. See\n            :attr:`debug`.\n        :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n            files to set environment variables. Will also change the working\n            directory to the directory containing the first file found.\n        :param options: the options to be forwarded to the underlying Werkzeug\n            server. See :func:`werkzeug.serving.run_simple` for more\n            information.\n\n        .. versionchanged:: 1.0\n            If installed, python-dotenv will be used to load environment\n            variables from :file:`.env` and :file:`.flaskenv` files.\n\n            The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.\n\n            Threaded mode is enabled by default.\n\n        .. versionchanged:: 0.10\n            The default port is now picked from the ``SERVER_NAME``\n            variable.\n        \"\"\"\n        # Ignore this call so that it doesn't start another server if\n        # the 'flask run' command is used.\n        if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n            if not is_running_from_reloader():\n                click.secho(\n                    \" * Ignoring a call to 'app.run()' that would block\"\n                    \" the current 'flask' CLI command.\\n\"\n                    \"   Only call 'app.run()' in an 'if __name__ ==\"\n                    ' \"__main__\"\\' guard.',\n                    fg=\"red\",\n                )\n\n            return\n\n        if get_load_dotenv(load_dotenv):\n            cli.load_dotenv()\n\n            # if set, env var overrides existing value\n            if \"FLASK_DEBUG\" in os.environ:\n                self.debug = get_debug_flag()\n\n        # debug passed to method overrides all other sources\n        if debug is not None:\n            self.debug = bool(debug)\n\n        server_name = self.config.get(\"SERVER_NAME\")\n        sn_host = sn_port = None\n\n        if server_name:\n            server_url = urlsplit(f\"//{server_name}\")\n            sn_host = server_url.hostname\n            sn_port = server_url.port\n\n        if not host:\n            if sn_host:\n                host = sn_host\n            else:\n                host = \"127.0.0.1\"\n\n        if port or port == 0:\n            port = int(port)\n        elif sn_port is not None:\n            port = sn_port\n        else:\n            port = 5000\n\n        options.setdefault(\"use_reloader\", self.debug)\n        options.setdefault(\"use_debugger\", self.debug)\n        options.setdefault(\"threaded\", True)\n\n        cli.show_server_banner(self.debug, self.name)\n\n        from werkzeug.serving import run_simple\n\n        try:\n            run_simple(host, port, self, **options)\n        finally:\n            # reset the first request information if the development server\n            # reset normally.  This makes it possible to restart the server\n            # without reloader and that stuff from an interactive shell.\n            self._got_first_request = False\n\n    def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:\n        \"\"\"Creates a test client for this application.  For information\n        about unit testing head over to :doc:`/testing`.\n\n        Note that if you are testing for assertions or exceptions in your\n        application code, you must set ``app.testing = True`` in order for the\n        exceptions to propagate to the test client.  Otherwise, the exception\n        will be handled by the application (not visible to the test client) and\n        the only indication of an AssertionError or other exception will be a\n        500 status code response to the test client.  See the :attr:`testing`\n        attribute.  For example::\n\n            app.testing = True\n            client = app.test_client()\n\n        The test client can be used in a ``with`` block to defer the closing down\n        of the context until the end of the ``with`` block.  This is useful if\n        you want to access the context locals for testing::\n\n            with app.test_client() as c:\n                rv = c.get('/?vodka=42')\n                assert request.args['vodka'] == '42'\n\n        Additionally, you may pass optional keyword arguments that will then\n        be passed to the application's :attr:`test_client_class` constructor.\n        For example::\n\n            from flask.testing import FlaskClient\n\n            class CustomClient(FlaskClient):\n                def __init__(self, *args, **kwargs):\n                    self._authentication = kwargs.pop(\"authentication\")\n                    super(CustomClient,self).__init__( *args, **kwargs)\n\n            app.test_client_class = CustomClient\n            client = app.test_client(authentication='Basic ....')\n\n        See :class:`~flask.testing.FlaskClient` for more information.\n\n        .. versionchanged:: 0.4\n           added support for ``with`` block usage for the client.\n\n        .. versionadded:: 0.7\n           The `use_cookies` parameter was added as well as the ability\n           to override the client to be used by setting the\n           :attr:`test_client_class` attribute.\n\n        .. versionchanged:: 0.11\n           Added `**kwargs` to support passing additional keyword arguments to\n           the constructor of :attr:`test_client_class`.\n        \"\"\"\n        cls = self.test_client_class\n        if cls is None:\n            from .testing import FlaskClient as cls\n        return cls(  # type: ignore\n            self, self.response_class, use_cookies=use_cookies, **kwargs\n        )\n\n    def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:\n        \"\"\"Create a CLI runner for testing CLI commands.\n        See :ref:`testing-cli`.\n\n        Returns an instance of :attr:`test_cli_runner_class`, by default\n        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n        passed as the first argument.\n\n        .. versionadded:: 1.0\n        \"\"\"\n        cls = self.test_cli_runner_class\n\n        if cls is None:\n            from .testing import FlaskCliRunner as cls\n\n        return cls(self, **kwargs)  # type: ignore\n\n    def handle_http_exception(\n        self, ctx: AppContext, e: HTTPException\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"Handles an HTTP exception.  By default this will invoke the\n        registered error handlers and fall back to returning the\n        exception as response.\n\n        .. versionchanged:: 1.0.3\n            ``RoutingException``, used internally for actions such as\n             slash redirects during routing, is not passed to error\n             handlers.\n\n        .. versionchanged:: 1.0\n            Exceptions are looked up by code *and* by MRO, so\n            ``HTTPException`` subclasses can be handled with a catch-all\n            handler for the base ``HTTPException``.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        # Proxy exceptions don't have error codes.  We want to always return\n        # those unchanged as errors\n        if e.code is None:\n            return e\n\n        # RoutingExceptions are used internally to trigger routing\n        # actions, such as slash redirects raising RequestRedirect. They\n        # are not raised or handled in user code.\n        if isinstance(e, RoutingException):\n            return e\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n        if handler is None:\n            return e\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_user_exception(\n        self, ctx: AppContext, e: Exception\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"This method is called whenever an exception occurs that\n        should be handled. A special case is :class:`~werkzeug\n        .exceptions.HTTPException` which is forwarded to the\n        :meth:`handle_http_exception` method. This function will either\n        return a response value or reraise the exception with the same\n        traceback.\n\n        .. versionchanged:: 1.0\n            Key errors raised from request data like ``form`` show the\n            bad key in debug mode rather than a generic bad request\n            message.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if isinstance(e, BadRequestKeyError) and (\n            self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n        ):\n            e.show_exception = True\n\n        if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n            return self.handle_http_exception(ctx, e)\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n\n        if handler is None:\n            raise\n\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_exception(self, ctx: AppContext, e: Exception) -> Response:\n        \"\"\"Handle an exception that did not have an error handler\n        associated with it, or that was raised from an error handler.\n        This always causes a 500 ``InternalServerError``.\n\n        Always sends the :data:`got_request_exception` signal.\n\n        If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n        mode, the error will be re-raised so that the debugger can\n        display it. Otherwise, the original exception is logged, and\n        an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n        If an error handler is registered for ``InternalServerError`` or\n        ``500``, it will be used. For consistency, the handler will\n        always receive the ``InternalServerError``. The original\n        unhandled exception is available as ``e.original_exception``.\n\n        .. versionchanged:: 1.1.0\n            Always passes the ``InternalServerError`` instance to the\n            handler, setting ``original_exception`` to the unhandled\n            error.\n\n        .. versionchanged:: 1.1.0\n            ``after_request`` functions and other finalization is done\n            even for the default 500 response when there is no handler.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        exc_info = sys.exc_info()\n        got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)\n        propagate = self.config[\"PROPAGATE_EXCEPTIONS\"]\n\n        if propagate is None:\n            propagate = self.testing or self.debug\n\n        if propagate:\n            # Re-raise if called with an active exception, otherwise\n            # raise the passed in exception.\n            if exc_info[1] is e:\n                raise\n\n            raise e\n\n        self.log_exception(ctx, exc_info)\n        server_error: InternalServerError | ft.ResponseReturnValue\n        server_error = InternalServerError(original_exception=e)\n        handler = self._find_error_handler(server_error, ctx.request.blueprints)\n\n        if handler is not None:\n            server_error = self.ensure_sync(handler)(server_error)\n\n        return self.finalize_request(ctx, server_error, from_error_handler=True)\n\n    def log_exception(\n        self,\n        ctx: AppContext,\n        exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n    ) -> None:\n        \"\"\"Logs an exception.  This is called by :meth:`handle_exception`\n        if debugging is disabled and right before the handler is called.\n        The default implementation logs the exception as error on the\n        :attr:`logger`.\n\n        .. versionadded:: 0.8\n        \"\"\"\n        self.logger.error(\n            f\"Exception on {ctx.request.path} [{ctx.request.method}]\", exc_info=exc_info\n        )\n\n    def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue:\n        \"\"\"Does the request dispatching.  Matches the URL and returns the\n        return value of the view or error handler.  This does not have to\n        be a response object.  In order to convert the return value to a\n        proper response object, call :func:`make_response`.\n\n        .. versionchanged:: 0.7\n           This no longer does the exception handling, this code was\n           moved to the new :meth:`full_dispatch_request`.\n        \"\"\"\n        req = ctx.request\n\n        if req.routing_exception is not None:\n            self.raise_routing_exception(req)\n        rule: Rule = req.url_rule  # type: ignore[assignment]\n        # if we provide automatic options for this URL and the\n        # request came with the OPTIONS method, reply automatically\n        if (\n            getattr(rule, \"provide_automatic_options\", False)\n            and req.method == \"OPTIONS\"\n        ):\n            return self.make_default_options_response(ctx)\n        # otherwise dispatch to the handler for that endpoint\n        view_args: dict[str, t.Any] = req.view_args  # type: ignore[assignment]\n        return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]\n\n    def full_dispatch_request(self, ctx: AppContext) -> Response:\n        \"\"\"Dispatches the request and on top of that performs request\n        pre and postprocessing as well as HTTP exception catching and\n        error handling.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if not self._got_first_request and self.should_ignore_error is not None:\n            import warnings\n\n            warnings.warn(\n                \"The 'should_ignore_error' method is deprecated and will\"\n                \" be removed in Flask 3.3. Handle errors as needed in\"\n                \" teardown handlers instead.\",\n                DeprecationWarning,\n                stacklevel=1,\n            )\n\n        self._got_first_request = True\n\n        try:\n            request_started.send(self, _async_wrapper=self.ensure_sync)\n            rv = self.preprocess_request(ctx)\n            if rv is None:\n                rv = self.dispatch_request(ctx)\n        except Exception as e:\n            rv = self.handle_user_exception(ctx, e)\n        return self.finalize_request(ctx, rv)\n\n    def finalize_request(\n        self,\n        ctx: AppContext,\n        rv: ft.ResponseReturnValue | HTTPException,\n        from_error_handler: bool = False,\n    ) -> Response:\n        \"\"\"Given the return value from a view function this finalizes\n        the request by converting it into a response and invoking the\n        postprocessing functions.  This is invoked for both normal\n        request dispatching as well as error handlers.\n\n        Because this means that it might be called as a result of a\n        failure a special safe mode is available which can be enabled\n        with the `from_error_handler` flag.  If enabled, failures in\n        response processing will be logged and otherwise ignored.\n\n        :internal:\n        \"\"\"\n        response = self.make_response(rv)\n        try:\n            response = self.process_response(ctx, response)\n            request_finished.send(\n                self, _async_wrapper=self.ensure_sync, response=response\n            )\n        except Exception:\n            if not from_error_handler:\n                raise\n            self.logger.exception(\n                \"Request finalizing failed with an error while handling an error\"\n            )\n        return response\n\n    def make_default_options_response(self, ctx: AppContext) -> Response:\n        \"\"\"This method is called to create the default ``OPTIONS`` response.\n        This can be changed through subclassing to change the default\n        behavior of ``OPTIONS`` responses.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        methods = ctx.url_adapter.allowed_methods()  # type: ignore[union-attr]\n        rv = self.response_class()\n        rv.allow.update(methods)\n        return rv\n\n    def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n        \"\"\"Ensure that the function is synchronous for WSGI workers.\n        Plain ``def`` functions are returned as-is. ``async def``\n        functions are wrapped to run and wait for the response.\n\n        Override this method to change how the app runs async views.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if iscoroutinefunction(func):\n            return self.async_to_sync(func)\n\n        return func\n\n    def async_to_sync(\n        self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n    ) -> t.Callable[..., t.Any]:\n        \"\"\"Return a sync function that will run the coroutine function.\n\n        .. code-block:: python\n\n            result = app.async_to_sync(func)(*args, **kwargs)\n\n        Override this method to change how the app converts async code\n        to be synchronously callable.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        try:\n            from asgiref.sync import async_to_sync as asgiref_async_to_sync\n        except ImportError:\n            raise RuntimeError(\n                \"Install Flask with the 'async' extra in order to use async views.\"\n            ) from None\n\n        return asgiref_async_to_sync(func)\n\n    def url_for(\n        self,\n        /,\n        endpoint: str,\n        *,\n        _anchor: str | None = None,\n        _method: str | None = None,\n        _scheme: str | None = None,\n        _external: bool | None = None,\n        **values: t.Any,\n    ) -> str:\n        \"\"\"Generate a URL to the given endpoint with the given values.\n\n        This is called by :func:`flask.url_for`, and can be called\n        directly as well.\n\n        An *endpoint* is the name of a URL rule, usually added with\n        :meth:`@app.route() <route>`, and usually the same name as the\n        view function. A route defined in a :class:`~flask.Blueprint`\n        will prepend the blueprint's name separated by a ``.`` to the\n        endpoint.\n\n        In some cases, such as email messages, you want URLs to include\n        the scheme and domain, like ``https://example.com/hello``. When\n        not in an active request, URLs will be external by default, but\n        this requires setting :data:`SERVER_NAME` so Flask knows what\n        domain to use. :data:`APPLICATION_ROOT` and\n        :data:`PREFERRED_URL_SCHEME` should also be configured as\n        needed. This config is only used when not in an active request.\n\n        Functions can be decorated with :meth:`url_defaults` to modify\n        keyword arguments before the URL is built.\n\n        If building fails for some reason, such as an unknown endpoint\n        or incorrect values, the app's :meth:`handle_url_build_error`\n        method is called. If that returns a string, that is returned,\n        otherwise a :exc:`~werkzeug.routing.BuildError` is raised.\n\n        :param endpoint: The endpoint name associated with the URL to\n            generate. If this starts with a ``.``, the current blueprint\n            name (if any) will be used.\n        :param _anchor: If given, append this as ``#anchor`` to the URL.\n        :param _method: If given, generate the URL associated with this\n            method for the endpoint.\n        :param _scheme: If given, the URL will have this scheme if it\n            is external.\n        :param _external: If given, prefer the URL to be internal\n            (False) or require it to be external (True). External URLs\n            include the scheme and domain. When not in an active\n            request, URLs are external by default.\n        :param values: Values to use for the variable parts of the URL\n            rule. Unknown keys are appended as query string arguments,\n            like ``?a=b&c=d``.\n\n        .. versionadded:: 2.2\n            Moved from ``flask.url_for``, which calls this method.\n        \"\"\"\n        if (ctx := _cv_app.get(None)) is not None and ctx.has_request:\n            url_adapter = ctx.url_adapter\n            blueprint_name = ctx.request.blueprint\n\n            # If the endpoint starts with \".\" and the request matches a\n            # blueprint, the endpoint is relative to the blueprint.\n            if endpoint[:1] == \".\":\n                if blueprint_name is not None:\n                    endpoint = f\"{blueprint_name}{endpoint}\"\n                else:\n                    endpoint = endpoint[1:]\n\n            # When in a request, generate a URL without scheme and\n            # domain by default, unless a scheme is given.\n            if _external is None:\n                _external = _scheme is not None\n        else:\n            # If called by helpers.url_for, an app context is active,\n            # use its url_adapter. Otherwise, app.url_for was called\n            # directly, build an adapter.\n            if ctx is not None:\n                url_adapter = ctx.url_adapter\n            else:\n                url_adapter = self.create_url_adapter(None)\n\n            if url_adapter is None:\n                raise RuntimeError(\n                    \"Unable to build URLs outside an active request\"\n                    \" without 'SERVER_NAME' configured. Also configure\"\n                    \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n                    \" needed.\"\n                )\n\n            # When outside a request, generate a URL with scheme and\n            # domain by default.\n            if _external is None:\n                _external = True\n\n        # It is an error to set _scheme when _external=False, in order\n        # to avoid accidental insecure URLs.\n        if _scheme is not None and not _external:\n            raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n        self.inject_url_defaults(endpoint, values)\n\n        try:\n            rv = url_adapter.build(  # type: ignore[union-attr]\n                endpoint,\n                values,\n                method=_method,\n                url_scheme=_scheme,\n                force_external=_external,\n            )\n        except BuildError as error:\n            values.update(\n                _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external\n            )\n            return self.handle_url_build_error(error, endpoint, values)\n\n        if _anchor is not None:\n            _anchor = _url_quote(_anchor, safe=\"%!#$&'()*+,/:;=?@\")\n            rv = f\"{rv}#{_anchor}\"\n\n        return rv\n\n    def make_response(self, rv: ft.ResponseReturnValue) -> Response:\n        \"\"\"Convert the return value from a view function to an instance of\n        :attr:`response_class`.\n\n        :param rv: the return value from the view function. The view function\n            must return a response. Returning ``None``, or the view ending\n            without returning, is not allowed. The following types are allowed\n            for ``view_rv``:\n\n            ``str``\n                A response object is created with the string encoded to UTF-8\n                as the body.\n\n            ``bytes``\n                A response object is created with the bytes as the body.\n\n            ``dict``\n                Converted to a JSON response.\n\n            ``list``\n                Converted to a JSON response.\n\n            ``generator`` or ``iterator``\n                A generator that returns ``str`` or ``bytes`` to be\n                streamed as the response.\n\n            ``tuple``\n                Either ``(body, status, headers)``, ``(body, status)``, or\n                ``(body, headers)``, where ``body`` is any of the other types\n                allowed here, ``status`` is a string or an integer, and\n                ``headers`` is a dictionary or a list of ``(key, value)``\n                tuples. If ``body`` is a :attr:`response_class` instance,\n                ``status`` overwrites the exiting value and ``headers`` are\n                extended.\n\n            :attr:`response_class`\n                The object is returned unchanged.\n\n            other :class:`~werkzeug.wrappers.Response` class\n                The object is coerced to :attr:`response_class`.\n\n            :func:`callable`\n                The function is called as a WSGI application. The result is\n                used to create a response object.\n\n        .. versionchanged:: 2.2\n            A generator will be converted to a streaming response.\n            A list will be converted to a JSON response.\n\n        .. versionchanged:: 1.1\n            A dict will be converted to a JSON response.\n\n        .. versionchanged:: 0.9\n           Previously a tuple was interpreted as the arguments for the\n           response object.\n        \"\"\"\n\n        status: int | None = None\n        headers: HeadersValue | None = None\n\n        # unpack tuple returns\n        if isinstance(rv, tuple):\n            len_rv = len(rv)\n\n            # a 3-tuple is unpacked directly\n            if len_rv == 3:\n                rv, status, headers = rv  # type: ignore[misc]\n            # decide if a 2-tuple has status or headers\n            elif len_rv == 2:\n                if isinstance(rv[1], (Headers, dict, tuple, list)):\n                    rv, headers = rv  # pyright: ignore\n                else:\n                    rv, status = rv  # type: ignore[assignment,misc]\n            # other sized tuples are not allowed\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid response tuple.\"\n                    \" The tuple must have the form (body, status, headers),\"\n                    \" (body, status), or (body, headers).\"\n                )\n\n        # the body must not be None\n        if rv is None:\n            raise TypeError(\n                f\"The view function for {request.endpoint!r} did not\"\n                \" return a valid response. The function either returned\"\n                \" None or ended without a return statement.\"\n            )\n\n        # make sure the body is an instance of the response class\n        if not isinstance(rv, self.response_class):\n            if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):\n                # let the response class set the status and headers instead of\n                # waiting to do it manually, so that the class can handle any\n                # special logic\n                rv = self.response_class(\n                    rv,  # pyright: ignore\n                    status=status,\n                    headers=headers,  # type: ignore[arg-type]\n                )\n                status = headers = None\n            elif isinstance(rv, (dict, list)):\n                rv = self.json.response(rv)\n            elif isinstance(rv, BaseResponse) or callable(rv):\n                # evaluate a WSGI callable, or coerce a different response\n                # class to the correct type\n                try:\n                    rv = self.response_class.force_type(\n                        rv,  # type: ignore[arg-type]\n                        request.environ,\n                    )\n                except TypeError as e:\n                    raise TypeError(\n                        f\"{e}\\nThe view function did not return a valid\"\n                        \" response. The return type must be a string,\"\n                        \" dict, list, tuple with headers or status,\"\n                        \" Response instance, or WSGI callable, but it\"\n                        f\" was a {type(rv).__name__}.\"\n                    ).with_traceback(sys.exc_info()[2]) from None\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid\"\n                    \" response. The return type must be a string,\"\n                    \" dict, list, tuple with headers or status,\"\n                    \" Response instance, or WSGI callable, but it was a\"\n                    f\" {type(rv).__name__}.\"\n                )\n\n        rv = t.cast(Response, rv)\n        # prefer the status if it was provided\n        if status is not None:\n            if isinstance(status, (str, bytes, bytearray)):\n                rv.status = status\n            else:\n                rv.status_code = status\n\n        # extend existing headers with provided headers\n        if headers:\n            rv.headers.update(headers)\n\n        return rv\n\n    def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None:\n        \"\"\"Called before the request is dispatched. Calls\n        :attr:`url_value_preprocessors` registered with the app and the\n        current blueprint (if any). Then calls :attr:`before_request_funcs`\n        registered with the app and the blueprint.\n\n        If any :meth:`before_request` handler returns a non-None value, the\n        value is handled as if it was the return value from the view, and\n        further request handling is stopped.\n        \"\"\"\n        req = ctx.request\n        names = (None, *reversed(req.blueprints))\n\n        for name in names:\n            if name in self.url_value_preprocessors:\n                for url_func in self.url_value_preprocessors[name]:\n                    url_func(req.endpoint, req.view_args)\n\n        for name in names:\n            if name in self.before_request_funcs:\n                for before_func in self.before_request_funcs[name]:\n                    rv = self.ensure_sync(before_func)()\n\n                    if rv is not None:\n                        return rv  # type: ignore[no-any-return]\n\n        return None\n\n    def process_response(self, ctx: AppContext, response: Response) -> Response:\n        \"\"\"Can be overridden in order to modify the response object\n        before it's sent to the WSGI server.  By default this will\n        call all the :meth:`after_request` decorated functions.\n\n        .. versionchanged:: 0.5\n           As of Flask 0.5 the functions registered for after request\n           execution are called in reverse order of registration.\n\n        :param response: a :attr:`response_class` object.\n        :return: a new response object or the same, has to be an\n                 instance of :attr:`response_class`.\n        \"\"\"\n        for func in ctx._after_request_functions:\n            response = self.ensure_sync(func)(response)\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.after_request_funcs:\n                for func in reversed(self.after_request_funcs[name]):\n                    response = self.ensure_sync(func)(response)\n\n        if not self.session_interface.is_null_session(ctx._get_session()):\n            self.session_interface.save_session(self, ctx._get_session(), response)\n\n        return response\n\n    def do_teardown_request(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called after the request is dispatched and the response is finalized,\n        right before the request context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_request`, and\n        :meth:`Blueprint.teardown_request` if a blueprint handled the request.\n        Finally, the :data:`request_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while dispatching the request.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionchanged:: 0.9\n            Added the ``exc`` argument.\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for name in chain(ctx.request.blueprints, (None,)):\n            if name in self.teardown_request_funcs:\n                for func in reversed(self.teardown_request_funcs[name]):\n                    with collect_errors:\n                        self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during request teardown\")\n\n    def do_teardown_appcontext(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called right before the application context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_appcontext`.\n        Then the :data:`appcontext_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while the context was active.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        for func in reversed(self.teardown_appcontext_funcs):\n            with collect_errors:\n                self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during app teardown\")\n\n    def app_context(self) -> AppContext:\n        \"\"\"Create an :class:`.AppContext`. When the context is pushed,\n        :data:`.current_app` and :data:`.g` become available.\n\n        A context is automatically pushed when handling each request, and when\n        running any ``flask`` CLI command. Use this as a ``with`` block to\n        manually push a context outside of those situations, such as during\n        setup or testing.\n\n        .. code-block:: python\n\n            with app.app_context():\n                init_db()\n\n        See :doc:`/appcontext`.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        return AppContext(self)\n\n    def request_context(self, environ: WSGIEnvironment) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information representing\n        the given WSGI environment. A context is automatically pushed when\n        handling each request. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This method should not be used in your own code. Creating a valid WSGI\n        environ is not trivial. Use :meth:`test_request_context` to correctly\n        create a WSGI environ and request context instead.\n\n        See :doc:`/appcontext`.\n\n        :param environ: A WSGI environment.\n        \"\"\"\n        return AppContext.from_environ(self, environ)\n\n    def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information created from\n        the given arguments. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This is useful during testing to run a function that uses request data\n        without dispatching a full request. Use this as a ``with`` block to push\n        a context.\n\n        .. code-block:: python\n\n            with app.test_request_context(...):\n                generate_report()\n\n        See :doc:`/appcontext`.\n\n        Takes the same arguments as Werkzeug's\n        :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n        the application. See the linked Werkzeug docs for most of the\n        available arguments. Flask-specific behavior is listed here.\n\n        :param path: URL path being requested.\n        :param base_url: Base URL where the app is being served, which\n            ``path`` is relative to. If not given, built from\n            :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,\n            and :data:`APPLICATION_ROOT`.\n        :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.\n        :param url_scheme: Scheme to use instead of\n            :data:`PREFERRED_URL_SCHEME`.\n        :param data: The request body text or bytes,or a dict of form data.\n        :param json: If given, this is serialized as JSON and passed as\n            ``data``. Also defaults ``content_type`` to\n            ``application/json``.\n        :param args: Other positional arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        :param kwargs: Other keyword arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        \"\"\"\n        from .testing import EnvironBuilder\n\n        builder = EnvironBuilder(self, *args, **kwargs)\n\n        try:\n            environ = builder.get_environ()\n        finally:\n            builder.close()\n\n        return self.request_context(environ)\n\n    def wsgi_app(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The actual WSGI application. This is not implemented in\n        :meth:`__call__` so that middlewares can be applied without\n        losing a reference to the app object. Instead of doing this::\n\n            app = MyMiddleware(app)\n\n        It's a better idea to do this instead::\n\n            app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n        Then you still have the original application object around and\n        can continue to call methods on it.\n\n        .. versionchanged:: 0.7\n            Teardown events for the request and app contexts are called\n            even if an unhandled error occurs. Other events may not be\n            called depending on when an error occurs during dispatch.\n\n        :param environ: A WSGI environment.\n        :param start_response: A callable accepting a status code,\n            a list of headers, and an optional exception context to\n            start the response.\n        \"\"\"\n        ctx = self.request_context(environ)\n        error: BaseException | None = None\n        try:\n            try:\n                ctx.push()\n                response = self.full_dispatch_request(ctx)\n            except Exception as e:\n                error = e\n                response = self.handle_exception(ctx, e)\n            except:\n                error = sys.exc_info()[1]\n                raise\n            return response(environ, start_response)\n        finally:\n            if \"werkzeug.debug.preserve_context\" in environ:\n                environ[\"werkzeug.debug.preserve_context\"](ctx)\n\n            if (\n                error is not None\n                and self.should_ignore_error is not None\n                and self.should_ignore_error(error)\n            ):\n                error = None\n\n            ctx.pop(error)\n\n    def __call__(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The WSGI server calls the Flask application object as the\n        WSGI application. This calls :meth:`wsgi_app`, which can be\n        wrapped to apply middleware.\n        \"\"\"\n        return self.wsgi_app(environ, start_response)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-8341cf85103c4a69", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "77627a28f34831cf07cb2155df8abdb620d4b18f438060201c39423f6f5db79d", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 1572, "local_path": "data-flow/inline-intermediate-variables/I12__flask__Flask__382f2902.py", "order": 12, "original_content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "parent_variant_id": "pyint-14eacc325bde-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/app.py#L110-L1628", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 2, "intermediate_variables_available": 2, "intermediate_variables_inlined": 2, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Flask", "variant_id": "pyint-9a5c382f2902-I12", "group_id": "py-8341cf85103c4a69", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 643, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b5a046e51ca5-I13", "source": "from __future__ import annotations\nimport collections.abc as cabc\nimport inspect\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom functools import update_wrapper\nfrom inspect import iscoroutinefunction\nfrom itertools import chain\nfrom types import TracebackType\nfrom urllib.parse import quote as _url_quote\nfrom urllib.parse import urlsplit\nimport click\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom werkzeug.wsgi import get_host\nfrom . import cli\nfrom . import typing as ft\nfrom .ctx import AppContext\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import _CollectErrors\nfrom .helpers import get_debug_flag\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import send_from_directory\nfrom .sansio.app import App\nfrom .sessions import SecureCookieSessionInterface\nfrom .sessions import SessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import Environment\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nclass Flask(App):\n    \"\"\"The flask object implements a WSGI application and acts as the central\n    object.  It is passed the name of the module or package of the\n    application.  Once it is created it will act as a central registry for\n    the view functions, the URL rules, template configuration and much more.\n\n    The name of the package is used to resolve resources from inside the\n    package or the folder the module is contained in depending on if the\n    package parameter resolves to an actual python package (a folder with\n    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n    For more information about resource loading, see :func:`open_resource`.\n\n    Usually you create a :class:`Flask` instance in your main module or\n    in the :file:`__init__.py` file of your package like this::\n\n        from flask import Flask\n        app = Flask(__name__)\n\n    .. admonition:: About the First Parameter\n\n        The idea of the first parameter is to give Flask an idea of what\n        belongs to your application.  This name is used to find resources\n        on the filesystem, can be used by extensions to improve debugging\n        information and a lot more.\n\n        So it's important what you provide there.  If you are using a single\n        module, `__name__` is always the correct value.  If you however are\n        using a package, it's usually recommended to hardcode the name of\n        your package there.\n\n        For example if your application is defined in :file:`yourapplication/app.py`\n        you should create it with one of the two versions below::\n\n            app = Flask('yourapplication')\n            app = Flask(__name__.split('.')[0])\n\n        Why is that?  The application will work even with `__name__`, thanks\n        to how resources are looked up.  However it will make debugging more\n        painful.  Certain extensions can make assumptions based on the\n        import name of your application.  For example the Flask-SQLAlchemy\n        extension will look for the code in your application that triggered\n        an SQL query in debug mode.  If the import name is not properly set\n        up, that debugging information is lost.  (For example it would only\n        pick up SQL queries in `yourapplication.app` and not\n        `yourapplication.views.frontend`)\n\n    .. versionadded:: 0.7\n       The `static_url_path`, `static_folder`, and `template_folder`\n       parameters were added.\n\n    .. versionadded:: 0.8\n       The `instance_path` and `instance_relative_config` parameters were\n       added.\n\n    .. versionadded:: 0.11\n       The `root_path` parameter was added.\n\n    .. versionadded:: 1.0\n       The ``host_matching`` and ``static_host`` parameters were added.\n\n    .. versionadded:: 1.0\n       The ``subdomain_matching`` parameter was added. Subdomain\n       matching needs to be enabled manually now. Setting\n       :data:`SERVER_NAME` does not implicitly enable it.\n\n    :param import_name: the name of the application package\n    :param static_url_path: can be used to specify a different path for the\n                            static files on the web.  Defaults to the name\n                            of the `static_folder` folder.\n    :param static_folder: The folder with static files that is served at\n        ``static_url_path``. Relative to the application ``root_path``\n        or an absolute path. Defaults to ``'static'``.\n    :param static_host: the host to use when adding the static route.\n        Defaults to None. Required when using ``host_matching=True``\n        with a ``static_folder`` configured.\n    :param host_matching: set ``url_map.host_matching`` attribute.\n        Defaults to False.\n    :param subdomain_matching: consider the subdomain relative to\n        :data:`SERVER_NAME` when matching routes. Defaults to False.\n    :param template_folder: the folder that contains the templates that should\n                            be used by the application.  Defaults to\n                            ``'templates'`` folder in the root path of the\n                            application.\n    :param instance_path: An alternative instance path for the application.\n                          By default the folder ``'instance'`` next to the\n                          package or module is assumed to be the instance\n                          path.\n    :param instance_relative_config: if set to ``True`` relative filenames\n                                     for loading the config are assumed to\n                                     be relative to the instance path instead\n                                     of the application root.\n    :param root_path: The path to the root of the application files.\n        This should only be set manually when it can't be detected\n        automatically, such as for namespace packages.\n    \"\"\"\n\n    default_config = ImmutableDict(\n        {\n            \"DEBUG\": None,\n            \"TESTING\": False,\n            \"PROPAGATE_EXCEPTIONS\": None,\n            \"SECRET_KEY\": None,\n            \"SECRET_KEY_FALLBACKS\": None,\n            \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n            \"USE_X_SENDFILE\": False,\n            \"TRUSTED_HOSTS\": None,\n            \"SERVER_NAME\": None,\n            \"APPLICATION_ROOT\": \"/\",\n            \"SESSION_COOKIE_NAME\": \"session\",\n            \"SESSION_COOKIE_DOMAIN\": None,\n            \"SESSION_COOKIE_PATH\": None,\n            \"SESSION_COOKIE_HTTPONLY\": True,\n            \"SESSION_COOKIE_SECURE\": False,\n            \"SESSION_COOKIE_PARTITIONED\": False,\n            \"SESSION_COOKIE_SAMESITE\": None,\n            \"SESSION_REFRESH_EACH_REQUEST\": True,\n            \"MAX_CONTENT_LENGTH\": None,\n            \"MAX_FORM_MEMORY_SIZE\": 500_000,\n            \"MAX_FORM_PARTS\": 1_000,\n            \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n            \"TRAP_BAD_REQUEST_ERRORS\": None,\n            \"TRAP_HTTP_EXCEPTIONS\": False,\n            \"EXPLAIN_TEMPLATE_LOADING\": False,\n            \"PREFERRED_URL_SCHEME\": \"http\",\n            \"TEMPLATES_AUTO_RELOAD\": None,\n            \"MAX_COOKIE_SIZE\": 4093,\n            \"PROVIDE_AUTOMATIC_OPTIONS\": True,\n        }\n    )\n\n    #: The class that is used for request objects.  See :class:`~flask.Request`\n    #: for more information.\n    request_class: type[Request] = Request\n\n    #: The class that is used for response objects.  See\n    #: :class:`~flask.Response` for more information.\n    response_class: type[Response] = Response\n\n    #: the session interface to use.  By default an instance of\n    #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n    #:\n    #: .. versionadded:: 0.8\n    session_interface: SessionInterface = SecureCookieSessionInterface()\n\n    def __init_subclass__(cls, **kwargs: t.Any) -> None:\n        import warnings\n\n        # These method signatures were updated to take a ctx param. Detect\n        # overridden methods in subclasses that still have the old signature.\n        # Show a deprecation warning and wrap to call with correct args.\n        for method in (\n            cls.handle_http_exception,\n            cls.handle_user_exception,\n            cls.handle_exception,\n            cls.log_exception,\n            cls.dispatch_request,\n            cls.full_dispatch_request,\n            cls.finalize_request,\n            cls.make_default_options_response,\n            cls.preprocess_request,\n            cls.process_response,\n            cls.do_teardown_request,\n            cls.do_teardown_appcontext,\n        ):\n            base_method = getattr(Flask, method.__name__)\n\n            if method is base_method:\n                # not overridden\n                continue\n\n            # get the second parameter (first is self)\n            iter_params = iter(inspect.signature(method).parameters.values())\n            next(iter_params)\n            param = next(iter_params, None)\n\n            # must have second parameter named ctx or annotated AppContext\n            if param is None or not (\n                # no annotation, match name\n                (param.annotation is inspect.Parameter.empty and param.name == \"ctx\")\n                or (\n                    # string annotation, access path ends with AppContext\n                    isinstance(param.annotation, str)\n                    and param.annotation.rpartition(\".\")[2] == \"AppContext\"\n                )\n                or (\n                    # class annotation\n                    inspect.isclass(param.annotation)\n                    and issubclass(param.annotation, AppContext)\n                )\n            ):\n                warnings.warn(\n                    f\"The '{method.__name__}' method now takes 'ctx: AppContext'\"\n                    \" as the first parameter. The old signature is deprecated\"\n                    \" and will not be supported in Flask 4.0.\",\n                    DeprecationWarning,\n                    stacklevel=2,\n                )\n                setattr(cls, method.__name__, remove_ctx(method))\n                setattr(Flask, method.__name__, add_ctx(base_method))\n\n    def __init__(\n        self,\n        import_name: str,\n        static_url_path: str | None = None,\n        static_folder: str | os.PathLike[str] | None = \"static\",\n        static_host: str | None = None,\n        host_matching: bool = False,\n        subdomain_matching: bool = False,\n        template_folder: str | os.PathLike[str] | None = \"templates\",\n        instance_path: str | None = None,\n        instance_relative_config: bool = False,\n        root_path: str | None = None,\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_url_path=static_url_path,\n            static_folder=static_folder,\n            static_host=static_host,\n            host_matching=host_matching,\n            subdomain_matching=subdomain_matching,\n            template_folder=template_folder,\n            instance_path=instance_path,\n            instance_relative_config=instance_relative_config,\n            root_path=root_path,\n        )\n\n        #: The Click command group for registering CLI commands for this\n        #: object. The commands are available from the ``flask`` command\n        #: once the application has been discovered and blueprints have\n        #: been registered.\n        self.cli = cli.AppGroup()\n\n        # Set the name of the Click group in case someone wants to add\n        # the app's commands to another CLI tool.\n        self.cli.name = self.name\n\n        # Add a static route using the provided static_url_path, static_host,\n        # and static_folder if there is a configured static_folder.\n        # Note we do this without checking if static_folder exists.\n        # For one, it might be created while the server is running (e.g. during\n        # development). Also, Google App Engine stores static files somewhere\n        if self.has_static_folder:\n            assert bool(static_host) == host_matching, (\n                \"Invalid static_host/host_matching combination\"\n            )\n            # Use a weakref to avoid creating a reference cycle between the app\n            # and the view function (see #3761).\n            self_ref = weakref.ref(self)\n            self.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                endpoint=\"static\",\n                host=static_host,\n                view_func=lambda **kw: self_ref().send_static_file(**kw),  # type: ignore\n            )\n\n    def get_send_file_max_age(self, filename: str | None) -> int | None:\n        \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n        value for a given file path if it wasn't passed.\n\n        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n        the configuration of :data:`~flask.current_app`. This defaults\n        to ``None``, which tells the browser to use conditional requests\n        instead of a timed cache, which is usually preferable.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionchanged:: 2.0\n            The default configuration is ``None`` instead of 12 hours.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        value = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n        if value is None:\n            return None\n\n        if isinstance(value, timedelta):\n            return int(value.total_seconds())\n\n        return value  # type: ignore[no-any-return]\n\n    def send_static_file(self, filename: str) -> Response:\n        \"\"\"The view function used to serve files from\n        :attr:`static_folder`. A route is automatically registered for\n        this view at :attr:`static_url_path` if :attr:`static_folder` is\n        set.\n\n        Note this is a duplicate of the same method in the Flask\n        class.\n\n        .. versionadded:: 0.5\n\n        \"\"\"\n        if not self.has_static_folder:\n            raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n        # send_file only knows to call get_send_file_max_age on the app,\n        # call it here so it works for blueprints too.\n        max_age = self.get_send_file_max_age(filename)\n        return send_from_directory(\n            t.cast(str, self.static_folder), filename, max_age=max_age\n        )\n\n    def open_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = None\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to :attr:`root_path` for reading.\n\n        For example, if the file ``schema.sql`` is next to the file\n        ``app.py`` where the ``Flask`` app is defined, it can be opened\n        with:\n\n        .. code-block:: python\n\n            with app.open_resource(\"schema.sql\") as f:\n                conn.executescript(f.read())\n\n        :param resource: Path to the resource relative to :attr:`root_path`.\n        :param mode: Open the file in this mode. Only reading is supported,\n            valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        if mode not in {\"r\", \"rt\", \"rb\"}:\n            raise ValueError(\"Resources can only be opened for reading.\")\n\n        path = os.path.join(self.root_path, resource)\n\n        if mode == \"rb\":\n            return open(path, mode)  # pyright: ignore\n\n        return open(path, mode, encoding=encoding)\n\n    def open_instance_resource(\n        self, resource: str, mode: str = \"rb\", encoding: str | None = \"utf-8\"\n    ) -> t.IO[t.AnyStr]:\n        \"\"\"Open a resource file relative to the application's instance folder\n        :attr:`instance_path`. Unlike :meth:`open_resource`, files in the\n        instance folder can be opened for writing.\n\n        :param resource: Path to the resource relative to :attr:`instance_path`.\n        :param mode: Open the file in this mode.\n        :param encoding: Open the file with this encoding when opening in text\n            mode. This is ignored when opening in binary mode.\n\n        .. versionchanged:: 3.1\n            Added the ``encoding`` parameter.\n        \"\"\"\n        path = os.path.join(self.instance_path, resource)\n\n        if \"b\" in mode:\n            return open(path, mode)\n\n        return open(path, mode, encoding=encoding)\n\n    def create_jinja_environment(self) -> Environment:\n        \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n        and the various Jinja-related methods of the app. Changing\n        :attr:`jinja_options` after this will have no effect. Also adds\n        Flask-related globals and filters to the environment.\n\n        .. versionchanged:: 0.11\n           ``Environment.auto_reload`` set in accordance with\n           ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n        .. versionadded:: 0.5\n        \"\"\"\n        options = dict(self.jinja_options)\n\n        if \"autoescape\" not in options:\n            options[\"autoescape\"] = self.select_jinja_autoescape\n\n        if \"auto_reload\" not in options:\n            auto_reload = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n            if auto_reload is None:\n                auto_reload = self.debug\n\n            options[\"auto_reload\"] = auto_reload\n\n        rv = self.jinja_environment(self, **options)\n        rv.globals.update(\n            url_for=self.url_for,\n            get_flashed_messages=get_flashed_messages,\n            config=self.config,\n            # request, session and g are normally added with the\n            # context processor for efficiency reasons but for imported\n            # templates we also want the proxies in there.\n            request=request,\n            session=session,\n            g=g,\n        )\n        rv.policies[\"json.dumps_function\"] = self.json.dumps\n        return rv\n\n    def create_url_adapter(self, request: Request | None) -> MapAdapter | None:\n        \"\"\"Creates a URL adapter for the given request. The URL adapter\n        is created at a point where the request context is not yet set\n        up so the request is passed explicitly.\n\n        .. versionchanged:: 3.1\n            If :data:`SERVER_NAME` is set, it does not restrict requests to\n            only that domain, for both ``subdomain_matching`` and\n            ``host_matching``.\n\n        .. versionchanged:: 1.0\n            :data:`SERVER_NAME` no longer implicitly enables subdomain\n            matching. Use :attr:`subdomain_matching` instead.\n\n        .. versionchanged:: 0.9\n           This can be called outside a request when the URL adapter is created\n           for an application context.\n\n        .. versionadded:: 0.6\n        \"\"\"\n        if request is not None:\n            if (trusted_hosts := self.config[\"TRUSTED_HOSTS\"]) is not None:\n                request.trusted_hosts = trusted_hosts\n\n            # Check trusted_hosts here until bind_to_environ does.\n            request.host = get_host(request.environ, request.trusted_hosts)  # pyright: ignore\n            subdomain = None\n            server_name = self.config[\"SERVER_NAME\"]\n\n            if self.url_map.host_matching:\n                # Don't pass SERVER_NAME, otherwise it's used and the actual\n                # host is ignored, which breaks host matching.\n                server_name = None\n            elif not self.subdomain_matching:\n                # Werkzeug doesn't implement subdomain matching yet. Until then,\n                # disable it by forcing the current subdomain to the default, or\n                # the empty string.\n                subdomain = self.url_map.default_subdomain or \"\"\n\n            return self.url_map.bind_to_environ(\n                request.environ, server_name=server_name, subdomain=subdomain\n            )\n\n        # Need at least SERVER_NAME to match/build outside a request.\n        if self.config[\"SERVER_NAME\"] is not None:\n            return self.url_map.bind(\n                self.config[\"SERVER_NAME\"],\n                script_name=self.config[\"APPLICATION_ROOT\"],\n                url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n            )\n\n        return None\n\n    def raise_routing_exception(self, request: Request) -> t.NoReturn:\n        \"\"\"Intercept routing exceptions and possibly do something else.\n\n        In debug mode, intercept a routing redirect and replace it with\n        an error if the body will be discarded.\n\n        With modern Werkzeug this shouldn't occur, since it now uses a\n        308 status which tells the browser to resend the method and\n        body.\n\n        .. versionchanged:: 2.1\n            Don't intercept 307 and 308 redirects.\n\n        :meta private:\n        :internal:\n        \"\"\"\n        if (\n            not self.debug\n            or not isinstance(request.routing_exception, RequestRedirect)\n            or request.routing_exception.code in {307, 308}\n            or request.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n        ):\n            raise request.routing_exception  # type: ignore[misc]\n\n        from .debughelpers import FormDataRoutingRedirect\n\n        raise FormDataRoutingRedirect(request)\n\n    def update_template_context(\n        self, ctx: AppContext, context: dict[str, t.Any]\n    ) -> None:\n        \"\"\"Update the template context with some commonly used variables.\n        This injects request, session, config and g into the template\n        context as well as everything template context processors want\n        to inject.  Note that the as of Flask 0.6, the original values\n        in the context will not be overridden if a context processor\n        decides to return a value with the same key.\n\n        :param context: the context as a dictionary that is updated in place\n                        to add extra variables.\n        \"\"\"\n        names: t.Iterable[str | None] = (None,)\n\n        # A template may be rendered outside a request context.\n        if ctx.has_request:\n            names = chain(names, reversed(ctx.request.blueprints))\n\n        # The values passed to render_template take precedence. Keep a\n        # copy to re-apply after all context functions.\n        orig_ctx = context.copy()\n\n        loopIteratorH = __import__(\"builtins\").iter(names)\n        while True:\n            try:\n                name = __import__(\"builtins\").next(loopIteratorH)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if name in self.template_context_processors:\n                loopIterator = __import__(\"builtins\").iter(self.template_context_processors[name])\n                while True:\n                    try:\n                        func = __import__(\"builtins\").next(loopIterator)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    context.update(self.ensure_sync(func)())\n\n        context.update(orig_ctx)\n\n    def make_shell_context(self) -> dict[str, t.Any]:\n        \"\"\"Returns the shell context for an interactive shell for this\n        application.  This runs all the registered shell context\n        processors.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {\"app\": self, \"g\": g}\n        loopIteratorA = __import__(\"builtins\").iter(self.shell_context_processors)\n        while True:\n            try:\n                processor = __import__(\"builtins\").next(loopIteratorA)\n            except __import__(\"builtins\").StopIteration:\n                break\n            rv.update(processor())\n        return rv\n\n    def run(\n        self,\n        host: str | None = None,\n        port: int | None = None,\n        debug: bool | None = None,\n        load_dotenv: bool = True,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Runs the application on a local development server.\n\n        Do not use ``run()`` in a production setting. It is not intended to\n        meet security and performance requirements for a production server.\n        Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n        If the :attr:`debug` flag is set the server will automatically reload\n        for code changes and show a debugger in case an exception happened.\n\n        If you want to run the application in debug mode, but disable the\n        code execution on the interactive debugger, you can pass\n        ``use_evalex=False`` as parameter.  This will keep the debugger's\n        traceback screen active, but disable code execution.\n\n        It is not recommended to use this function for development with\n        automatic reloading as this is badly supported.  Instead you should\n        be using the :command:`flask` command line script's ``run`` support.\n\n        .. admonition:: Keep in Mind\n\n           Flask will suppress any server error with a generic error page\n           unless it is in debug mode.  As such to enable just the\n           interactive debugger without the code reloading, you have to\n           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n           Setting ``use_debugger`` to ``True`` without being in debug mode\n           won't catch any exceptions because there won't be any to\n           catch.\n\n        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n            have the server available externally as well. Defaults to\n            ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n            if present.\n        :param port: the port of the webserver. Defaults to ``5000`` or the\n            port defined in the ``SERVER_NAME`` config variable if present.\n        :param debug: if given, enable or disable debug mode. See\n            :attr:`debug`.\n        :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n            files to set environment variables. Will also change the working\n            directory to the directory containing the first file found.\n        :param options: the options to be forwarded to the underlying Werkzeug\n            server. See :func:`werkzeug.serving.run_simple` for more\n            information.\n\n        .. versionchanged:: 1.0\n            If installed, python-dotenv will be used to load environment\n            variables from :file:`.env` and :file:`.flaskenv` files.\n\n            The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.\n\n            Threaded mode is enabled by default.\n\n        .. versionchanged:: 0.10\n            The default port is now picked from the ``SERVER_NAME``\n            variable.\n        \"\"\"\n        # Ignore this call so that it doesn't start another server if\n        # the 'flask run' command is used.\n        if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n            if not is_running_from_reloader():\n                click.secho(\n                    \" * Ignoring a call to 'app.run()' that would block\"\n                    \" the current 'flask' CLI command.\\n\"\n                    \"   Only call 'app.run()' in an 'if __name__ ==\"\n                    ' \"__main__\"\\' guard.',\n                    fg=\"red\",\n                )\n\n            return\n\n        if get_load_dotenv(load_dotenv):\n            cli.load_dotenv()\n\n            # if set, env var overrides existing value\n            if \"FLASK_DEBUG\" in os.environ:\n                self.debug = get_debug_flag()\n\n        # debug passed to method overrides all other sources\n        if debug is not None:\n            self.debug = bool(debug)\n\n        server_name = self.config.get(\"SERVER_NAME\")\n        sn_host = sn_port = None\n\n        if server_name:\n            server_url = urlsplit(f\"//{server_name}\")\n            sn_host = server_url.hostname\n            sn_port = server_url.port\n\n        if not host:\n            if sn_host:\n                host = sn_host\n            else:\n                host = \"127.0.0.1\"\n\n        if port or port == 0:\n            port = int(port)\n        elif sn_port is not None:\n            port = sn_port\n        else:\n            port = 5000\n\n        options.setdefault(\"use_reloader\", self.debug)\n        options.setdefault(\"use_debugger\", self.debug)\n        options.setdefault(\"threaded\", True)\n\n        cli.show_server_banner(self.debug, self.name)\n\n        from werkzeug.serving import run_simple\n\n        try:\n            run_simple(host, port, self, **options)\n        finally:\n            # reset the first request information if the development server\n            # reset normally.  This makes it possible to restart the server\n            # without reloader and that stuff from an interactive shell.\n            self._got_first_request = False\n\n    def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:\n        \"\"\"Creates a test client for this application.  For information\n        about unit testing head over to :doc:`/testing`.\n\n        Note that if you are testing for assertions or exceptions in your\n        application code, you must set ``app.testing = True`` in order for the\n        exceptions to propagate to the test client.  Otherwise, the exception\n        will be handled by the application (not visible to the test client) and\n        the only indication of an AssertionError or other exception will be a\n        500 status code response to the test client.  See the :attr:`testing`\n        attribute.  For example::\n\n            app.testing = True\n            client = app.test_client()\n\n        The test client can be used in a ``with`` block to defer the closing down\n        of the context until the end of the ``with`` block.  This is useful if\n        you want to access the context locals for testing::\n\n            with app.test_client() as c:\n                rv = c.get('/?vodka=42')\n                assert request.args['vodka'] == '42'\n\n        Additionally, you may pass optional keyword arguments that will then\n        be passed to the application's :attr:`test_client_class` constructor.\n        For example::\n\n            from flask.testing import FlaskClient\n\n            class CustomClient(FlaskClient):\n                def __init__(self, *args, **kwargs):\n                    self._authentication = kwargs.pop(\"authentication\")\n                    super(CustomClient,self).__init__( *args, **kwargs)\n\n            app.test_client_class = CustomClient\n            client = app.test_client(authentication='Basic ....')\n\n        See :class:`~flask.testing.FlaskClient` for more information.\n\n        .. versionchanged:: 0.4\n           added support for ``with`` block usage for the client.\n\n        .. versionadded:: 0.7\n           The `use_cookies` parameter was added as well as the ability\n           to override the client to be used by setting the\n           :attr:`test_client_class` attribute.\n\n        .. versionchanged:: 0.11\n           Added `**kwargs` to support passing additional keyword arguments to\n           the constructor of :attr:`test_client_class`.\n        \"\"\"\n        cls = self.test_client_class\n        if cls is None:\n            from .testing import FlaskClient as cls\n        return cls(  # type: ignore\n            self, self.response_class, use_cookies=use_cookies, **kwargs\n        )\n\n    def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:\n        \"\"\"Create a CLI runner for testing CLI commands.\n        See :ref:`testing-cli`.\n\n        Returns an instance of :attr:`test_cli_runner_class`, by default\n        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n        passed as the first argument.\n\n        .. versionadded:: 1.0\n        \"\"\"\n        cls = self.test_cli_runner_class\n\n        if cls is None:\n            from .testing import FlaskCliRunner as cls\n\n        return cls(self, **kwargs)  # type: ignore\n\n    def handle_http_exception(\n        self, ctx: AppContext, e: HTTPException\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"Handles an HTTP exception.  By default this will invoke the\n        registered error handlers and fall back to returning the\n        exception as response.\n\n        .. versionchanged:: 1.0.3\n            ``RoutingException``, used internally for actions such as\n             slash redirects during routing, is not passed to error\n             handlers.\n\n        .. versionchanged:: 1.0\n            Exceptions are looked up by code *and* by MRO, so\n            ``HTTPException`` subclasses can be handled with a catch-all\n            handler for the base ``HTTPException``.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        # Proxy exceptions don't have error codes.  We want to always return\n        # those unchanged as errors\n        if e.code is None:\n            return e\n\n        # RoutingExceptions are used internally to trigger routing\n        # actions, such as slash redirects raising RequestRedirect. They\n        # are not raised or handled in user code.\n        if isinstance(e, RoutingException):\n            return e\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n        if handler is None:\n            return e\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_user_exception(\n        self, ctx: AppContext, e: Exception\n    ) -> HTTPException | ft.ResponseReturnValue:\n        \"\"\"This method is called whenever an exception occurs that\n        should be handled. A special case is :class:`~werkzeug\n        .exceptions.HTTPException` which is forwarded to the\n        :meth:`handle_http_exception` method. This function will either\n        return a response value or reraise the exception with the same\n        traceback.\n\n        .. versionchanged:: 1.0\n            Key errors raised from request data like ``form`` show the\n            bad key in debug mode rather than a generic bad request\n            message.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if isinstance(e, BadRequestKeyError) and (\n            self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n        ):\n            e.show_exception = True\n\n        if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n            return self.handle_http_exception(ctx, e)\n\n        handler = self._find_error_handler(e, ctx.request.blueprints)\n\n        if handler is None:\n            raise\n\n        return self.ensure_sync(handler)(e)  # type: ignore[no-any-return]\n\n    def handle_exception(self, ctx: AppContext, e: Exception) -> Response:\n        \"\"\"Handle an exception that did not have an error handler\n        associated with it, or that was raised from an error handler.\n        This always causes a 500 ``InternalServerError``.\n\n        Always sends the :data:`got_request_exception` signal.\n\n        If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n        mode, the error will be re-raised so that the debugger can\n        display it. Otherwise, the original exception is logged, and\n        an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n        If an error handler is registered for ``InternalServerError`` or\n        ``500``, it will be used. For consistency, the handler will\n        always receive the ``InternalServerError``. The original\n        unhandled exception is available as ``e.original_exception``.\n\n        .. versionchanged:: 1.1.0\n            Always passes the ``InternalServerError`` instance to the\n            handler, setting ``original_exception`` to the unhandled\n            error.\n\n        .. versionchanged:: 1.1.0\n            ``after_request`` functions and other finalization is done\n            even for the default 500 response when there is no handler.\n\n        .. versionadded:: 0.3\n        \"\"\"\n        exc_info = sys.exc_info()\n        got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)\n        propagate = self.config[\"PROPAGATE_EXCEPTIONS\"]\n\n        if propagate is None:\n            propagate = self.testing or self.debug\n\n        if propagate:\n            # Re-raise if called with an active exception, otherwise\n            # raise the passed in exception.\n            if exc_info[1] is e:\n                raise\n\n            raise e\n\n        self.log_exception(ctx, exc_info)\n        server_error: InternalServerError | ft.ResponseReturnValue\n        server_error = InternalServerError(original_exception=e)\n        handler = self._find_error_handler(server_error, ctx.request.blueprints)\n\n        if handler is not None:\n            server_error = self.ensure_sync(handler)(server_error)\n\n        return self.finalize_request(ctx, server_error, from_error_handler=True)\n\n    def log_exception(\n        self,\n        ctx: AppContext,\n        exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n    ) -> None:\n        \"\"\"Logs an exception.  This is called by :meth:`handle_exception`\n        if debugging is disabled and right before the handler is called.\n        The default implementation logs the exception as error on the\n        :attr:`logger`.\n\n        .. versionadded:: 0.8\n        \"\"\"\n        self.logger.error(\n            f\"Exception on {ctx.request.path} [{ctx.request.method}]\", exc_info=exc_info\n        )\n\n    def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue:\n        \"\"\"Does the request dispatching.  Matches the URL and returns the\n        return value of the view or error handler.  This does not have to\n        be a response object.  In order to convert the return value to a\n        proper response object, call :func:`make_response`.\n\n        .. versionchanged:: 0.7\n           This no longer does the exception handling, this code was\n           moved to the new :meth:`full_dispatch_request`.\n        \"\"\"\n        req = ctx.request\n\n        if req.routing_exception is not None:\n            self.raise_routing_exception(req)\n        rule: Rule = req.url_rule  # type: ignore[assignment]\n        # if we provide automatic options for this URL and the\n        # request came with the OPTIONS method, reply automatically\n        if (\n            getattr(rule, \"provide_automatic_options\", False)\n            and req.method == \"OPTIONS\"\n        ):\n            return self.make_default_options_response(ctx)\n        # otherwise dispatch to the handler for that endpoint\n        view_args: dict[str, t.Any] = req.view_args  # type: ignore[assignment]\n        return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]\n\n    def full_dispatch_request(self, ctx: AppContext) -> Response:\n        \"\"\"Dispatches the request and on top of that performs request\n        pre and postprocessing as well as HTTP exception catching and\n        error handling.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        if not self._got_first_request and self.should_ignore_error is not None:\n            import warnings\n\n            warnings.warn(\n                \"The 'should_ignore_error' method is deprecated and will\"\n                \" be removed in Flask 3.3. Handle errors as needed in\"\n                \" teardown handlers instead.\",\n                DeprecationWarning,\n                stacklevel=1,\n            )\n\n        self._got_first_request = True\n\n        try:\n            request_started.send(self, _async_wrapper=self.ensure_sync)\n            rv = self.preprocess_request(ctx)\n            if rv is None:\n                rv = self.dispatch_request(ctx)\n        except Exception as e:\n            rv = self.handle_user_exception(ctx, e)\n        return self.finalize_request(ctx, rv)\n\n    def finalize_request(\n        self,\n        ctx: AppContext,\n        rv: ft.ResponseReturnValue | HTTPException,\n        from_error_handler: bool = False,\n    ) -> Response:\n        \"\"\"Given the return value from a view function this finalizes\n        the request by converting it into a response and invoking the\n        postprocessing functions.  This is invoked for both normal\n        request dispatching as well as error handlers.\n\n        Because this means that it might be called as a result of a\n        failure a special safe mode is available which can be enabled\n        with the `from_error_handler` flag.  If enabled, failures in\n        response processing will be logged and otherwise ignored.\n\n        :internal:\n        \"\"\"\n        response = self.make_response(rv)\n        try:\n            response = self.process_response(ctx, response)\n            request_finished.send(\n                self, _async_wrapper=self.ensure_sync, response=response\n            )\n        except Exception:\n            if not from_error_handler:\n                raise\n            self.logger.exception(\n                \"Request finalizing failed with an error while handling an error\"\n            )\n        return response\n\n    def make_default_options_response(self, ctx: AppContext) -> Response:\n        \"\"\"This method is called to create the default ``OPTIONS`` response.\n        This can be changed through subclassing to change the default\n        behavior of ``OPTIONS`` responses.\n\n        .. versionadded:: 0.7\n        \"\"\"\n        methods = ctx.url_adapter.allowed_methods()  # type: ignore[union-attr]\n        rv = self.response_class()\n        rv.allow.update(methods)\n        return rv\n\n    def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n        \"\"\"Ensure that the function is synchronous for WSGI workers.\n        Plain ``def`` functions are returned as-is. ``async def``\n        functions are wrapped to run and wait for the response.\n\n        Override this method to change how the app runs async views.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if iscoroutinefunction(func):\n            return self.async_to_sync(func)\n\n        return func\n\n    def async_to_sync(\n        self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n    ) -> t.Callable[..., t.Any]:\n        \"\"\"Return a sync function that will run the coroutine function.\n\n        .. code-block:: python\n\n            result = app.async_to_sync(func)(*args, **kwargs)\n\n        Override this method to change how the app converts async code\n        to be synchronously callable.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        try:\n            from asgiref.sync import async_to_sync as asgiref_async_to_sync\n        except ImportError:\n            raise RuntimeError(\n                \"Install Flask with the 'async' extra in order to use async views.\"\n            ) from None\n\n        return asgiref_async_to_sync(func)\n\n    def url_for(\n        self,\n        /,\n        endpoint: str,\n        *,\n        _anchor: str | None = None,\n        _method: str | None = None,\n        _scheme: str | None = None,\n        _external: bool | None = None,\n        **values: t.Any,\n    ) -> str:\n        \"\"\"Generate a URL to the given endpoint with the given values.\n\n        This is called by :func:`flask.url_for`, and can be called\n        directly as well.\n\n        An *endpoint* is the name of a URL rule, usually added with\n        :meth:`@app.route() <route>`, and usually the same name as the\n        view function. A route defined in a :class:`~flask.Blueprint`\n        will prepend the blueprint's name separated by a ``.`` to the\n        endpoint.\n\n        In some cases, such as email messages, you want URLs to include\n        the scheme and domain, like ``https://example.com/hello``. When\n        not in an active request, URLs will be external by default, but\n        this requires setting :data:`SERVER_NAME` so Flask knows what\n        domain to use. :data:`APPLICATION_ROOT` and\n        :data:`PREFERRED_URL_SCHEME` should also be configured as\n        needed. This config is only used when not in an active request.\n\n        Functions can be decorated with :meth:`url_defaults` to modify\n        keyword arguments before the URL is built.\n\n        If building fails for some reason, such as an unknown endpoint\n        or incorrect values, the app's :meth:`handle_url_build_error`\n        method is called. If that returns a string, that is returned,\n        otherwise a :exc:`~werkzeug.routing.BuildError` is raised.\n\n        :param endpoint: The endpoint name associated with the URL to\n            generate. If this starts with a ``.``, the current blueprint\n            name (if any) will be used.\n        :param _anchor: If given, append this as ``#anchor`` to the URL.\n        :param _method: If given, generate the URL associated with this\n            method for the endpoint.\n        :param _scheme: If given, the URL will have this scheme if it\n            is external.\n        :param _external: If given, prefer the URL to be internal\n            (False) or require it to be external (True). External URLs\n            include the scheme and domain. When not in an active\n            request, URLs are external by default.\n        :param values: Values to use for the variable parts of the URL\n            rule. Unknown keys are appended as query string arguments,\n            like ``?a=b&c=d``.\n\n        .. versionadded:: 2.2\n            Moved from ``flask.url_for``, which calls this method.\n        \"\"\"\n        if (ctx := _cv_app.get(None)) is not None and ctx.has_request:\n            url_adapter = ctx.url_adapter\n            blueprint_name = ctx.request.blueprint\n\n            # If the endpoint starts with \".\" and the request matches a\n            # blueprint, the endpoint is relative to the blueprint.\n            if endpoint[:1] == \".\":\n                if blueprint_name is not None:\n                    endpoint = f\"{blueprint_name}{endpoint}\"\n                else:\n                    endpoint = endpoint[1:]\n\n            # When in a request, generate a URL without scheme and\n            # domain by default, unless a scheme is given.\n            if _external is None:\n                _external = _scheme is not None\n        else:\n            # If called by helpers.url_for, an app context is active,\n            # use its url_adapter. Otherwise, app.url_for was called\n            # directly, build an adapter.\n            if ctx is not None:\n                url_adapter = ctx.url_adapter\n            else:\n                url_adapter = self.create_url_adapter(None)\n\n            if url_adapter is None:\n                raise RuntimeError(\n                    \"Unable to build URLs outside an active request\"\n                    \" without 'SERVER_NAME' configured. Also configure\"\n                    \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n                    \" needed.\"\n                )\n\n            # When outside a request, generate a URL with scheme and\n            # domain by default.\n            if _external is None:\n                _external = True\n\n        # It is an error to set _scheme when _external=False, in order\n        # to avoid accidental insecure URLs.\n        if _scheme is not None and not _external:\n            raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n        self.inject_url_defaults(endpoint, values)\n\n        try:\n            rv = url_adapter.build(  # type: ignore[union-attr]\n                endpoint,\n                values,\n                method=_method,\n                url_scheme=_scheme,\n                force_external=_external,\n            )\n        except BuildError as error:\n            values.update(\n                _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external\n            )\n            return self.handle_url_build_error(error, endpoint, values)\n\n        if _anchor is not None:\n            _anchor = _url_quote(_anchor, safe=\"%!#$&'()*+,/:;=?@\")\n            rv = f\"{rv}#{_anchor}\"\n\n        return rv\n\n    def make_response(self, rv: ft.ResponseReturnValue) -> Response:\n        \"\"\"Convert the return value from a view function to an instance of\n        :attr:`response_class`.\n\n        :param rv: the return value from the view function. The view function\n            must return a response. Returning ``None``, or the view ending\n            without returning, is not allowed. The following types are allowed\n            for ``view_rv``:\n\n            ``str``\n                A response object is created with the string encoded to UTF-8\n                as the body.\n\n            ``bytes``\n                A response object is created with the bytes as the body.\n\n            ``dict``\n                Converted to a JSON response.\n\n            ``list``\n                Converted to a JSON response.\n\n            ``generator`` or ``iterator``\n                A generator that returns ``str`` or ``bytes`` to be\n                streamed as the response.\n\n            ``tuple``\n                Either ``(body, status, headers)``, ``(body, status)``, or\n                ``(body, headers)``, where ``body`` is any of the other types\n                allowed here, ``status`` is a string or an integer, and\n                ``headers`` is a dictionary or a list of ``(key, value)``\n                tuples. If ``body`` is a :attr:`response_class` instance,\n                ``status`` overwrites the exiting value and ``headers`` are\n                extended.\n\n            :attr:`response_class`\n                The object is returned unchanged.\n\n            other :class:`~werkzeug.wrappers.Response` class\n                The object is coerced to :attr:`response_class`.\n\n            :func:`callable`\n                The function is called as a WSGI application. The result is\n                used to create a response object.\n\n        .. versionchanged:: 2.2\n            A generator will be converted to a streaming response.\n            A list will be converted to a JSON response.\n\n        .. versionchanged:: 1.1\n            A dict will be converted to a JSON response.\n\n        .. versionchanged:: 0.9\n           Previously a tuple was interpreted as the arguments for the\n           response object.\n        \"\"\"\n\n        status: int | None = None\n        headers: HeadersValue | None = None\n\n        # unpack tuple returns\n        if isinstance(rv, tuple):\n            len_rv = len(rv)\n\n            # a 3-tuple is unpacked directly\n            if len_rv == 3:\n                rv, status, headers = rv  # type: ignore[misc]\n            # decide if a 2-tuple has status or headers\n            elif len_rv == 2:\n                if isinstance(rv[1], (Headers, dict, tuple, list)):\n                    rv, headers = rv  # pyright: ignore\n                else:\n                    rv, status = rv  # type: ignore[assignment,misc]\n            # other sized tuples are not allowed\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid response tuple.\"\n                    \" The tuple must have the form (body, status, headers),\"\n                    \" (body, status), or (body, headers).\"\n                )\n\n        # the body must not be None\n        if rv is None:\n            raise TypeError(\n                f\"The view function for {request.endpoint!r} did not\"\n                \" return a valid response. The function either returned\"\n                \" None or ended without a return statement.\"\n            )\n\n        # make sure the body is an instance of the response class\n        if not isinstance(rv, self.response_class):\n            if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):\n                # let the response class set the status and headers instead of\n                # waiting to do it manually, so that the class can handle any\n                # special logic\n                rv = self.response_class(\n                    rv,  # pyright: ignore\n                    status=status,\n                    headers=headers,  # type: ignore[arg-type]\n                )\n                status = headers = None\n            elif isinstance(rv, (dict, list)):\n                rv = self.json.response(rv)\n            elif isinstance(rv, BaseResponse) or callable(rv):\n                # evaluate a WSGI callable, or coerce a different response\n                # class to the correct type\n                try:\n                    rv = self.response_class.force_type(\n                        rv,  # type: ignore[arg-type]\n                        request.environ,\n                    )\n                except TypeError as e:\n                    raise TypeError(\n                        f\"{e}\\nThe view function did not return a valid\"\n                        \" response. The return type must be a string,\"\n                        \" dict, list, tuple with headers or status,\"\n                        \" Response instance, or WSGI callable, but it\"\n                        f\" was a {type(rv).__name__}.\"\n                    ).with_traceback(sys.exc_info()[2]) from None\n            else:\n                raise TypeError(\n                    \"The view function did not return a valid\"\n                    \" response. The return type must be a string,\"\n                    \" dict, list, tuple with headers or status,\"\n                    \" Response instance, or WSGI callable, but it was a\"\n                    f\" {type(rv).__name__}.\"\n                )\n\n        rv = t.cast(Response, rv)\n        # prefer the status if it was provided\n        if status is not None:\n            if isinstance(status, (str, bytes, bytearray)):\n                rv.status = status\n            else:\n                rv.status_code = status\n\n        # extend existing headers with provided headers\n        if headers:\n            rv.headers.update(headers)\n\n        return rv\n\n    def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None:\n        \"\"\"Called before the request is dispatched. Calls\n        :attr:`url_value_preprocessors` registered with the app and the\n        current blueprint (if any). Then calls :attr:`before_request_funcs`\n        registered with the app and the blueprint.\n\n        If any :meth:`before_request` handler returns a non-None value, the\n        value is handled as if it was the return value from the view, and\n        further request handling is stopped.\n        \"\"\"\n        req = ctx.request\n        names = (None, *reversed(req.blueprints))\n\n        loopIteratorI = __import__(\"builtins\").iter(names)\n        while True:\n            try:\n                name = __import__(\"builtins\").next(loopIteratorI)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if name in self.url_value_preprocessors:\n                loopIteratorB = __import__(\"builtins\").iter(self.url_value_preprocessors[name])\n                while True:\n                    try:\n                        url_func = __import__(\"builtins\").next(loopIteratorB)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    url_func(req.endpoint, req.view_args)\n\n        loopIteratorJ = __import__(\"builtins\").iter(names)\n        while True:\n            try:\n                name = __import__(\"builtins\").next(loopIteratorJ)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if name in self.before_request_funcs:\n                loopIteratorC = __import__(\"builtins\").iter(self.before_request_funcs[name])\n                while True:\n                    try:\n                        before_func = __import__(\"builtins\").next(loopIteratorC)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    rv = self.ensure_sync(before_func)()\n\n                    if rv is not None:\n                        return rv  # type: ignore[no-any-return]\n\n        return None\n\n    def process_response(self, ctx: AppContext, response: Response) -> Response:\n        \"\"\"Can be overridden in order to modify the response object\n        before it's sent to the WSGI server.  By default this will\n        call all the :meth:`after_request` decorated functions.\n\n        .. versionchanged:: 0.5\n           As of Flask 0.5 the functions registered for after request\n           execution are called in reverse order of registration.\n\n        :param response: a :attr:`response_class` object.\n        :return: a new response object or the same, has to be an\n                 instance of :attr:`response_class`.\n        \"\"\"\n        loopIteratorD = __import__(\"builtins\").iter(ctx._after_request_functions)\n        while True:\n            try:\n                func = __import__(\"builtins\").next(loopIteratorD)\n            except __import__(\"builtins\").StopIteration:\n                break\n            response = self.ensure_sync(func)(response)\n\n        loopIteratorK = __import__(\"builtins\").iter(chain(ctx.request.blueprints, (None,)))\n        while True:\n            try:\n                name = __import__(\"builtins\").next(loopIteratorK)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if name in self.after_request_funcs:\n                loopIteratorE = __import__(\"builtins\").iter(reversed(self.after_request_funcs[name]))\n                while True:\n                    try:\n                        func = __import__(\"builtins\").next(loopIteratorE)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    response = self.ensure_sync(func)(response)\n\n        if not self.session_interface.is_null_session(ctx._get_session()):\n            self.session_interface.save_session(self, ctx._get_session(), response)\n\n        return response\n\n    def do_teardown_request(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called after the request is dispatched and the response is finalized,\n        right before the request context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_request`, and\n        :meth:`Blueprint.teardown_request` if a blueprint handled the request.\n        Finally, the :data:`request_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while dispatching the request.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionchanged:: 0.9\n            Added the ``exc`` argument.\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        loopIteratorL = __import__(\"builtins\").iter(chain(ctx.request.blueprints, (None,)))\n        while True:\n            try:\n                name = __import__(\"builtins\").next(loopIteratorL)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if name in self.teardown_request_funcs:\n                loopIteratorF = __import__(\"builtins\").iter(reversed(self.teardown_request_funcs[name]))\n                while True:\n                    try:\n                        func = __import__(\"builtins\").next(loopIteratorF)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    with collect_errors:\n                        self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during request teardown\")\n\n    def do_teardown_appcontext(\n        self, ctx: AppContext, exc: BaseException | None = None\n    ) -> None:\n        \"\"\"Called right before the application context is popped. Called by\n        :meth:`.AppContext.pop`.\n\n        This calls all functions decorated with :meth:`teardown_appcontext`.\n        Then the :data:`appcontext_tearing_down` signal is sent.\n\n        :param exc: An unhandled exception raised while the context was active.\n            Passed to each teardown function.\n\n        .. versionchanged:: 3.2\n            All callbacks are called rather than stopping on the first error.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        collect_errors = _CollectErrors()\n\n        loopIteratorG = __import__(\"builtins\").iter(reversed(self.teardown_appcontext_funcs))\n        while True:\n            try:\n                func = __import__(\"builtins\").next(loopIteratorG)\n            except __import__(\"builtins\").StopIteration:\n                break\n            with collect_errors:\n                self.ensure_sync(func)(exc)\n\n        with collect_errors:\n            appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n        collect_errors.raise_any(\"Errors during app teardown\")\n\n    def app_context(self) -> AppContext:\n        \"\"\"Create an :class:`.AppContext`. When the context is pushed,\n        :data:`.current_app` and :data:`.g` become available.\n\n        A context is automatically pushed when handling each request, and when\n        running any ``flask`` CLI command. Use this as a ``with`` block to\n        manually push a context outside of those situations, such as during\n        setup or testing.\n\n        .. code-block:: python\n\n            with app.app_context():\n                init_db()\n\n        See :doc:`/appcontext`.\n\n        .. versionadded:: 0.9\n        \"\"\"\n        return AppContext(self)\n\n    def request_context(self, environ: WSGIEnvironment) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information representing\n        the given WSGI environment. A context is automatically pushed when\n        handling each request. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This method should not be used in your own code. Creating a valid WSGI\n        environ is not trivial. Use :meth:`test_request_context` to correctly\n        create a WSGI environ and request context instead.\n\n        See :doc:`/appcontext`.\n\n        :param environ: A WSGI environment.\n        \"\"\"\n        return AppContext.from_environ(self, environ)\n\n    def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext:\n        \"\"\"Create an :class:`.AppContext` with request information created from\n        the given arguments. When the context is pushed, :data:`.request`,\n        :data:`.session`, :data:`g:, and :data:`.current_app` become available.\n\n        This is useful during testing to run a function that uses request data\n        without dispatching a full request. Use this as a ``with`` block to push\n        a context.\n\n        .. code-block:: python\n\n            with app.test_request_context(...):\n                generate_report()\n\n        See :doc:`/appcontext`.\n\n        Takes the same arguments as Werkzeug's\n        :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n        the application. See the linked Werkzeug docs for most of the\n        available arguments. Flask-specific behavior is listed here.\n\n        :param path: URL path being requested.\n        :param base_url: Base URL where the app is being served, which\n            ``path`` is relative to. If not given, built from\n            :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,\n            and :data:`APPLICATION_ROOT`.\n        :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.\n        :param url_scheme: Scheme to use instead of\n            :data:`PREFERRED_URL_SCHEME`.\n        :param data: The request body text or bytes,or a dict of form data.\n        :param json: If given, this is serialized as JSON and passed as\n            ``data``. Also defaults ``content_type`` to\n            ``application/json``.\n        :param args: Other positional arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        :param kwargs: Other keyword arguments passed to\n            :class:`~werkzeug.test.EnvironBuilder`.\n        \"\"\"\n        from .testing import EnvironBuilder\n\n        builder = EnvironBuilder(self, *args, **kwargs)\n\n        try:\n            environ = builder.get_environ()\n        finally:\n            builder.close()\n\n        return self.request_context(environ)\n\n    def wsgi_app(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The actual WSGI application. This is not implemented in\n        :meth:`__call__` so that middlewares can be applied without\n        losing a reference to the app object. Instead of doing this::\n\n            app = MyMiddleware(app)\n\n        It's a better idea to do this instead::\n\n            app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n        Then you still have the original application object around and\n        can continue to call methods on it.\n\n        .. versionchanged:: 0.7\n            Teardown events for the request and app contexts are called\n            even if an unhandled error occurs. Other events may not be\n            called depending on when an error occurs during dispatch.\n\n        :param environ: A WSGI environment.\n        :param start_response: A callable accepting a status code,\n            a list of headers, and an optional exception context to\n            start the response.\n        \"\"\"\n        ctx = self.request_context(environ)\n        error: BaseException | None = None\n        try:\n            try:\n                ctx.push()\n                response = self.full_dispatch_request(ctx)\n            except Exception as e:\n                error = e\n                response = self.handle_exception(ctx, e)\n            except:\n                error = sys.exc_info()[1]\n                raise\n            return response(environ, start_response)\n        finally:\n            if \"werkzeug.debug.preserve_context\" in environ:\n                environ[\"werkzeug.debug.preserve_context\"](ctx)\n\n            if (\n                error is not None\n                and self.should_ignore_error is not None\n                and self.should_ignore_error(error)\n            ):\n                error = None\n\n            ctx.pop(error)\n\n    def __call__(\n        self, environ: WSGIEnvironment, start_response: StartResponse\n    ) -> cabc.Iterable[bytes]:\n        \"\"\"The WSGI server calls the Flask application object as the\n        WSGI application. This calls :meth:`wsgi_app`, which can be\n        wrapped to apply middleware.\n        \"\"\"\n        return self.wsgi_app(environ, start_response)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-8341cf85103c4a69", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "be5e4342d3ba2d1d10b88ba75f593475d00a6fba21e8d9acd2c6fde2d9fecadc", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 1637, "local_path": "control-flow/lower-for-to-while/I13__flask__Flask__46e51ca5.py", "order": 13, "original_content_sha256": "f02b79748b8c862603d5d7b0308f0d18417d2ea03346fff6ac86d1f7ea5ddf09", "parent_variant_id": "pyint-14eacc325bde-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/app.py#L110-L1628", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 13, "for_loops_skipped_for_comment": 1, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 13, "synchronous_for_loops_eligible": 13, "synchronous_for_loops_found": 14}, "unit_kind": "class", "unit_name": "Flask", "variant_id": "pyint-b5a046e51ca5-I13", "group_id": "py-8341cf85103c4a69", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 644, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-83ed85f38231-SRC", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InstanceOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not isinstance(value, self.type):\n            msg = f\"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<instance_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-83a5be3d4de5dbfd", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 28, "local_path": "source-original/SRC__attrs___InstanceOfValidator__85f38231.py", "order": 0, "original_content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L94-L111", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_InstanceOfValidator", "variant_id": "pyint-83ed85f38231-SRC", "group_id": "py-83a5be3d4de5dbfd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1149, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d590e6e43a25-I01", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InstanceOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \n        if not isinstance(value, self.type):\n            msg = f\"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<instance_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-83a5be3d4de5dbfd", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "c83a6b203bcb693a2df1ca36908c0fde593f40bcf493e564c5c65142391d0eb8", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 26, "local_path": "comments/remove-comments/I01__attrs___InstanceOfValidator__e6e43a25.py", "order": 1, "original_content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "parent_variant_id": "pyint-83ed85f38231-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L94-L111", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 86, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "_InstanceOfValidator", "variant_id": "pyint-d590e6e43a25-I01", "group_id": "py-83a5be3d4de5dbfd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1150, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ce56dabf6fe8-I02", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InstanceOfValidator:\n    type = attrib()\n\n    def __call__(self, ins, att, val):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not isinstance(val, self.type):\n            msg2 = f\"'{att.name}' must be {self.type!r} (got {val!r} that is a {val.__class__!r}).\"\n            raise TypeError(\n                msg2,\n                att,\n                self.type,\n                val,\n            )\n\n    def __repr__(self):\n        return f\"<instance_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-83a5be3d4de5dbfd", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "a21e53d12a95cbb21541600492eab1b754845c8a35a7e813c17dc5a055c61aa0", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 28, "local_path": "identifiers/shorten-identifiers/I02__attrs___InstanceOfValidator__dabf6fe8.py", "order": 2, "original_content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "parent_variant_id": "pyint-83ed85f38231-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L94-L111", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 11, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_InstanceOfValidator", "variant_id": "pyint-ce56dabf6fe8-I02", "group_id": "py-83a5be3d4de5dbfd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1151, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7c95dadf55d8-I03", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InstanceOfValidator:\n    type = attrib()\n\n    def __call__(self, flag, user, price):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not isinstance(price, self.type):\n            key = f\"'{user.name}' must be {self.type!r} (got {price!r} that is a {price.__class__!r}).\"\n            raise TypeError(\n                key,\n                user,\n                self.type,\n                price,\n            )\n\n    def __repr__(self):\n        return f\"<instance_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-83a5be3d4de5dbfd", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b34a8cbec98c4fdc4a38f9bd671c13902985b48a2d51b7abe7bf220b1281e9b2", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 28, "local_path": "identifiers/mislead-identifiers/I03__attrs___InstanceOfValidator__dadf55d8.py", "order": 3, "original_content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "parent_variant_id": "pyint-83ed85f38231-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L94-L111", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 11, "identifiers_declared": 4, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 4, "local_random_pool_selections": 4, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_InstanceOfValidator", "variant_id": "pyint-7c95dadf55d8-I03", "group_id": "py-83a5be3d4de5dbfd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1152, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6e76a7a597b2-I04", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InstanceOfValidator:\n    type = attrib()\n\n    def __call__(self, a, b, c):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not isinstance(c, self.type):\n            d = f\"'{b.name}' must be {self.type!r} (got {c!r} that is a {c.__class__!r}).\"\n            raise TypeError(\n                d,\n                b,\n                self.type,\n                c,\n            )\n\n    def __repr__(self):\n        return f\"<instance_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-83a5be3d4de5dbfd", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "eeec60a8047a6225d633b7e63fa249ab3c3b0f1ecb2f375e32f94eeedfe48dd8", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 28, "local_path": "identifiers/garble-identifiers/I04__attrs___InstanceOfValidator__a7a597b2.py", "order": 4, "original_content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "parent_variant_id": "pyint-83ed85f38231-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L94-L111", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 11, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_InstanceOfValidator", "variant_id": "pyint-6e76a7a597b2-I04", "group_id": "py-83a5be3d4de5dbfd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1153, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4338fa678893-I05", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InstanceOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not isinstance(value, self.type):\n            msg = f\"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<instance_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-83a5be3d4de5dbfd", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 28, "local_path": "expressions/encode-integer-literals/I05__attrs___InstanceOfValidator__fa678893.py", "order": 5, "original_content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "parent_variant_id": "pyint-83ed85f38231-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L94-L111", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "_InstanceOfValidator", "variant_id": "pyint-4338fa678893-I05", "group_id": "py-83a5be3d4de5dbfd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1154, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b92cb1b73c57-I06", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InstanceOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not (not isinstance(value, self.type)):\n            pass\n        else:\n            msg = f\"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<instance_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-83a5be3d4de5dbfd", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "e2a23c7c0b6e364e8304a179a1c0c20f54fec0cac3595836ae30cff8a16a7647", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 30, "local_path": "expressions/invert-conditions/I06__attrs___InstanceOfValidator__b1b73c57.py", "order": 6, "original_content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "parent_variant_id": "pyint-83ed85f38231-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L94-L111", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "_InstanceOfValidator", "variant_id": "pyint-b92cb1b73c57-I06", "group_id": "py-83a5be3d4de5dbfd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1155, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e922c86de360-I07", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InstanceOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if ((0xb884 ^ 0xb884) != 0):\n            raise AssertionError()\n        if not isinstance(value, self.type):\n            msg = f\"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        if ((0x10db ^ 0x10db) != 0):\n            raise AssertionError()\n        return f\"<instance_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-83a5be3d4de5dbfd", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "ccbfd1243b3159fdab3e7aac1427b16d66f7dfa7e01389e5531cbd03beb4987f", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 32, "local_path": "code-injection/insert-dead-branches/I07__attrs___InstanceOfValidator__c86de360.py", "order": 7, "original_content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "parent_variant_id": "pyint-83ed85f38231-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L94-L111", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "_InstanceOfValidator", "variant_id": "pyint-e922c86de360-I07", "group_id": "py-83a5be3d4de5dbfd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1156, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8971d6203e41-I08", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InstanceOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        first_score = 72\n        second_score = 85\n        if first_score > second_score:\n            higher_score = first_score\n        else:\n            higher_score = second_score\n        if not isinstance(value, self.type):\n            msg = f\"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<instance_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-83a5be3d4de5dbfd", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "11c66fe0a1f512b28ddf0a6e9a420fb8744277e02e8edf2346c2a3f706283826", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 34, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___InstanceOfValidator__d6203e41.py", "order": 8, "original_content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "parent_variant_id": "pyint-83ed85f38231-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L94-L111", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 3}, "unit_kind": "class", "unit_name": "_InstanceOfValidator", "variant_id": "pyint-8971d6203e41-I08", "group_id": "py-83a5be3d4de5dbfd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1157, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-62cf49f71bd3-I09", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InstanceOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not isinstance(value, self.type):\n            msg = f\"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        lI0O_dd49bd00, lI0O_a6b16c21 = 0, 0\n        while lI0O_a6b16c21 < 2:\n            lI0O_dd49bd00 ^= (lI0O_a6b16c21 << 1) ^ 0xc\n            lI0O_a6b16c21 += 1\n        lI0O_dd49bd00 ^= lI0O_dd49bd00\n        return f\"<instance_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-83a5be3d4de5dbfd", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "69d420d1fb4e4a6a935bba25415ab0bbcbc5aa519ae55d261f241126d2667fc0", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 33, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___InstanceOfValidator__49f71bd3.py", "order": 9, "original_content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "parent_variant_id": "pyint-83ed85f38231-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L94-L111", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 2}, "unit_kind": "class", "unit_name": "_InstanceOfValidator", "variant_id": "pyint-62cf49f71bd3-I09", "group_id": "py-83a5be3d4de5dbfd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1158, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-10be0f3108f3-I10", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InstanceOfValidator:\n    type = attrib()\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not isinstance(value, self.type):\n            msg = f\"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,             )\n\n    def __repr__(self):\n        return f\"<instance_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-83a5be3d4de5dbfd", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "d0b003dd14291c6c589309bf69f7ddaf4302a918908c6c82a8a97e55325ad9c5", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 25, "local_path": "layout/partially-compact-layout/I10__attrs___InstanceOfValidator__0f3108f3.py", "order": 10, "original_content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "parent_variant_id": "pyint-83ed85f38231-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L94-L111", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 8, "line_break_groups_removed": 3, "line_breaks_removed": 3, "whitespace_characters_removed": 2}, "unit_kind": "class", "unit_name": "_InstanceOfValidator", "variant_id": "pyint-10be0f3108f3-I10", "group_id": "py-83a5be3d4de5dbfd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1159, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c8f19fc9547b-I11", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InstanceOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not isinstance(value, self.type):\n            msg = f\"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<instance_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-83a5be3d4de5dbfd", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 28, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___InstanceOfValidator__9fc9547b.py", "order": 11, "original_content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "parent_variant_id": "pyint-83ed85f38231-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L94-L111", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "_InstanceOfValidator", "variant_id": "pyint-c8f19fc9547b-I11", "group_id": "py-83a5be3d4de5dbfd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1160, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a7583c59874b-I12", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InstanceOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not isinstance(value, self.type):\n            \n            raise TypeError(\n                (f\"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r}).\"),\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<instance_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-83a5be3d4de5dbfd", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "fce68900627ecc63cff14639e9445ba45bcee6d6b5bab7a9e22919b3279df55f", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 28, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___InstanceOfValidator__3c59874b.py", "order": 12, "original_content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "parent_variant_id": "pyint-83ed85f38231-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L94-L111", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_InstanceOfValidator", "variant_id": "pyint-a7583c59874b-I12", "group_id": "py-83a5be3d4de5dbfd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1161, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1d72ce529dce-I13", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _InstanceOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not isinstance(value, self.type):\n            msg = f\"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<instance_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-83a5be3d4de5dbfd", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 28, "local_path": "control-flow/lower-for-to-while/I13__attrs___InstanceOfValidator__ce529dce.py", "order": 13, "original_content_sha256": "5a147279804ca20de73ff65ae02a7c565b6df7f2c0e267e5fb6127665ec30723", "parent_variant_id": "pyint-83ed85f38231-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L94-L111", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "_InstanceOfValidator", "variant_id": "pyint-1d72ce529dce-I13", "group_id": "py-83a5be3d4de5dbfd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1162, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-27582e43d915-SRC", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassDict(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, dict)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        # JSON objects may only have string keys, so don't bother tagging the\n        # key here.\n        return {k: self.serializer.tag(v) for k, v in value.items()}\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-8865ce2baf227a85", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 24, "local_path": "source-original/SRC__flask__PassDict__2e43d915.py", "order": 0, "original_content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L119-L130", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "PassDict", "variant_id": "pyint-27582e43d915-SRC", "group_id": "py-8865ce2baf227a85", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 519, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cc63f0356815-I01", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassDict(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, dict)\n\n    def to_json(self, value: t.Any) -> t.Any:\n         \n         \n        return {k: self.serializer.tag(v) for k, v in value.items()}\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-8865ce2baf227a85", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "9f31a3ddbcc9f52a359e7d1747e5df6c190656960f7e1ff07bd38659854bc60e", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 24, "local_path": "comments/remove-comments/I01__flask__PassDict__f0356815.py", "order": 1, "original_content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "parent_variant_id": "pyint-27582e43d915-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L119-L130", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 78, "comments_removed": 2, "docstrings_removed": 0, "line_comments_removed": 2}, "unit_kind": "class", "unit_name": "PassDict", "variant_id": "pyint-cc63f0356815-I01", "group_id": "py-8865ce2baf227a85", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 520, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d1ec3ea64986-I02", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassDict(JSONTag):\n    __slots__ = ()\n\n    def che(self, val: t.Any) -> bool:\n        return isinstance(val, dict)\n\n    def to(self, val2: t.Any) -> t.Any:\n        # JSON objects may only have string keys, so don't bother tagging the\n        # key here.\n        return {k2: self.serializer.tag(v2) for k2, v2 in val2.items()}\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-8865ce2baf227a85", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "0b436b5f7a9a22ec64a62660014c79b79e4bcc8a0d416000c7272be4a676ec93", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 24, "local_path": "identifiers/shorten-identifiers/I02__flask__PassDict__3ea64986.py", "order": 2, "original_content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "parent_variant_id": "pyint-27582e43d915-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L119-L130", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 10, "identifiers_declared": 6}, "unit_kind": "class", "unit_name": "PassDict", "variant_id": "pyint-d1ec3ea64986-I02", "group_id": "py-8865ce2baf227a85", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 521, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8bf3fdb02613-I03", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassDict(JSONTag):\n    __slots__ = ()\n\n    def store(self, limit: t.Any) -> bool:\n        return isinstance(limit, dict)\n\n    def extract(self, order: t.Any) -> t.Any:\n        # JSON objects may only have string keys, so don't bother tagging the\n        # key here.\n        return {age: self.serializer.tag(map) for age, map in order.items()}\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-8865ce2baf227a85", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "f6015bd742a1d4fe0005b5929be4792299ecc159b2a8a1325edb3df309d9f86d", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 24, "local_path": "identifiers/mislead-identifiers/I03__flask__PassDict__fdb02613.py", "order": 3, "original_content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "parent_variant_id": "pyint-27582e43d915-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L119-L130", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 10, "identifiers_declared": 6, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 2, "local_random_pool_selections": 4, "local_total_length_difference": 4, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 2, "method_random_pool_selections": 2, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "PassDict", "variant_id": "pyint-8bf3fdb02613-I03", "group_id": "py-8865ce2baf227a85", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 522, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-29e6ce53d521-I04", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassDict(JSONTag):\n    __slots__ = ()\n\n    def a(self, c: t.Any) -> bool:\n        return isinstance(c, dict)\n\n    def b(self, d: t.Any) -> t.Any:\n        # JSON objects may only have string keys, so don't bother tagging the\n        # key here.\n        return {e: self.serializer.tag(f) for e, f in d.items()}\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-8865ce2baf227a85", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "01448d9cfcfc729f76f3dc46c7889f27de511d6dc41535676201d799a314e370", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 24, "local_path": "identifiers/garble-identifiers/I04__flask__PassDict__ce53d521.py", "order": 4, "original_content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "parent_variant_id": "pyint-27582e43d915-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L119-L130", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 10, "identifiers_declared": 6}, "unit_kind": "class", "unit_name": "PassDict", "variant_id": "pyint-29e6ce53d521-I04", "group_id": "py-8865ce2baf227a85", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 523, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1fcdfca830a4-I05", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassDict(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, dict)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        # JSON objects may only have string keys, so don't bother tagging the\n        # key here.\n        return {k: self.serializer.tag(v) for k, v in value.items()}\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-8865ce2baf227a85", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 24, "local_path": "expressions/encode-integer-literals/I05__flask__PassDict__fca830a4.py", "order": 5, "original_content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "parent_variant_id": "pyint-27582e43d915-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L119-L130", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "PassDict", "variant_id": "pyint-1fcdfca830a4-I05", "group_id": "py-8865ce2baf227a85", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 524, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-24bc0dca37b2-I06", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassDict(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, dict)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        # JSON objects may only have string keys, so don't bother tagging the\n        # key here.\n        return {k: self.serializer.tag(v) for k, v in value.items()}\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-8865ce2baf227a85", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 24, "local_path": "expressions/invert-conditions/I06__flask__PassDict__0dca37b2.py", "order": 6, "original_content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "parent_variant_id": "pyint-27582e43d915-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L119-L130", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "PassDict", "variant_id": "pyint-24bc0dca37b2-I06", "group_id": "py-8865ce2baf227a85", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 525, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dfc11948d809-I07", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassDict(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        if ((0xcb25 ^ 0xcb25) != 0):\n            raise AssertionError()\n        return isinstance(value, dict)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        # JSON objects may only have string keys, so don't bother tagging the\n        # key here.\n        if ((0x37d0 ^ 0x37d0) != 0):\n            raise AssertionError()\n        return {k: self.serializer.tag(v) for k, v in value.items()}\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-8865ce2baf227a85", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "2f6028f42ee289dd05a8215db9e564ea038747f31f97f32384b611477791ff18", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 28, "local_path": "code-injection/insert-dead-branches/I07__flask__PassDict__1948d809.py", "order": 7, "original_content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "parent_variant_id": "pyint-27582e43d915-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L119-L130", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "PassDict", "variant_id": "pyint-dfc11948d809-I07", "group_id": "py-8865ce2baf227a85", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 526, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-88aa0f9707dc-I08", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassDict(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, dict)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        # JSON objects may only have string keys, so don't bother tagging the\n        # key here.\n        previous_number = 0\n        current_number = 1\n        for sequence_step in range(4):\n            next_number = previous_number + current_number\n            previous_number = current_number\n            current_number = next_number\n        return {k: self.serializer.tag(v) for k, v in value.items()}\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-8865ce2baf227a85", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "77e3bf0f48b856d97e793c3ae292ac5eeeb5592fb0e184211def4f8b72b89c30", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 30, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__PassDict__0f9707dc.py", "order": 8, "original_content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "parent_variant_id": "pyint-27582e43d915-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L119-L130", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 8}, "unit_kind": "class", "unit_name": "PassDict", "variant_id": "pyint-88aa0f9707dc-I08", "group_id": "py-8865ce2baf227a85", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 527, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1fa9899cba62-I09", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassDict(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        lI0O_a7d7ff2f = 0xc029 ^ 0xc029\n        if lI0O_a7d7ff2f != 0:\n            if ((lI0O_a7d7ff2f | 1) & 1) == 0:\n                lI0O_a7d7ff2f += 1\n            else:\n                lI0O_a7d7ff2f -= 1\n        return isinstance(value, dict)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        # JSON objects may only have string keys, so don't bother tagging the\n        # key here.\n        return {k: self.serializer.tag(v) for k, v in value.items()}\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-8865ce2baf227a85", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "85e0f60dd9219a9ee45d62188a4c11333081840fecbd815fc4ddc8d3c778c8bb", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 30, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__PassDict__899cba62.py", "order": 9, "original_content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "parent_variant_id": "pyint-27582e43d915-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L119-L130", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 5}, "unit_kind": "class", "unit_name": "PassDict", "variant_id": "pyint-1fa9899cba62-I09", "group_id": "py-8865ce2baf227a85", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 528, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b29f41d36c46-I10", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassDict(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, dict)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        # JSON objects may only have string keys, so don't bother tagging the\n        # key here.\n        return {k: self.serializer.tag(v) for k, v in value.items()}\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-8865ce2baf227a85", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "595ace214c158b1a6ce9d716b727af3e88a0716ebb74917d11ef36436373c0d4", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 23, "local_path": "layout/partially-compact-layout/I10__flask__PassDict__41d36c46.py", "order": 10, "original_content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "parent_variant_id": "pyint-27582e43d915-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L119-L130", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 4, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "PassDict", "variant_id": "pyint-b29f41d36c46-I10", "group_id": "py-8865ce2baf227a85", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 529, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1b0ba91edb10-I11", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassDict(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, dict)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        # JSON objects may only have string keys, so don't bother tagging the\n        # key here.\n        return {k: self.serializer.tag(v) for k, v in value.items()}\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-8865ce2baf227a85", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 24, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__PassDict__a91edb10.py", "order": 11, "original_content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "parent_variant_id": "pyint-27582e43d915-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L119-L130", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "PassDict", "variant_id": "pyint-1b0ba91edb10-I11", "group_id": "py-8865ce2baf227a85", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 530, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1f55e91cf158-I12", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassDict(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, dict)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        # JSON objects may only have string keys, so don't bother tagging the\n        # key here.\n        return {k: self.serializer.tag(v) for k, v in value.items()}\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-8865ce2baf227a85", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 24, "local_path": "data-flow/inline-intermediate-variables/I12__flask__PassDict__e91cf158.py", "order": 12, "original_content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "parent_variant_id": "pyint-27582e43d915-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L119-L130", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "PassDict", "variant_id": "pyint-1f55e91cf158-I12", "group_id": "py-8865ce2baf227a85", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 531, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8a66c1dd6dc3-I13", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassDict(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, dict)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        # JSON objects may only have string keys, so don't bother tagging the\n        # key here.\n        return {k: self.serializer.tag(v) for k, v in value.items()}\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-8865ce2baf227a85", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 24, "local_path": "control-flow/lower-for-to-while/I13__flask__PassDict__c1dd6dc3.py", "order": 13, "original_content_sha256": "f0659cfc7d6bff1106319304f44c057a135ccb05a71f51638d61791f4dd630d4", "parent_variant_id": "pyint-27582e43d915-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L119-L130", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "PassDict", "variant_id": "pyint-8a66c1dd6dc3-I13", "group_id": "py-8865ce2baf227a85", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 532, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-648d155241c3-SRC", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass Config(dict):  # type: ignore[type-arg]\n    \"\"\"Works exactly like a dict but provides ways to fill it from files\n    or special dictionaries.  There are two common patterns to populate the\n    config.\n\n    Either you can fill the config from a config file::\n\n        app.config.from_pyfile('yourconfig.cfg')\n\n    Or alternatively you can define the configuration options in the\n    module that calls :meth:`from_object` or provide an import path to\n    a module that should be loaded.  It is also possible to tell it to\n    use the same module and with that provide the configuration values\n    just before the call::\n\n        DEBUG = True\n        SECRET_KEY = 'development key'\n        app.config.from_object(__name__)\n\n    In both cases (loading from any Python file or loading from modules),\n    only uppercase keys are added to the config.  This makes it possible to use\n    lowercase values in the config file for temporary values that are not added\n    to the config or to define the config keys in the same file that implements\n    the application.\n\n    Probably the most interesting way to load configurations is from an\n    environment variable pointing to a file::\n\n        app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\n    In this case before launching the application you have to set this\n    environment variable to the file you want to use.  On Linux and OS X\n    use the export statement::\n\n        export YOURAPPLICATION_SETTINGS='/path/to/config/file'\n\n    On windows use `set` instead.\n\n    :param root_path: path to which files are read relative from.  When the\n                      config object is created by the application, this is\n                      the application's :attr:`~flask.Flask.root_path`.\n    :param defaults: an optional dictionary of default values\n    \"\"\"\n\n    def __init__(\n        self,\n        root_path: str | os.PathLike[str],\n        defaults: dict[str, t.Any] | None = None,\n    ) -> None:\n        super().__init__(defaults or {})\n        self.root_path = root_path\n\n    def from_envvar(self, variable_name: str, silent: bool = False) -> bool:\n        \"\"\"Loads a configuration from an environment variable pointing to\n        a configuration file.  This is basically just a shortcut with nicer\n        error messages for this line of code::\n\n            app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n\n        :param variable_name: name of the environment variable\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n        \"\"\"\n        rv = os.environ.get(variable_name)\n        if not rv:\n            if silent:\n                return False\n            raise RuntimeError(\n                f\"The environment variable {variable_name!r} is not set\"\n                \" and as such configuration could not be loaded. Set\"\n                \" this variable and make it point to a configuration\"\n                \" file\"\n            )\n        return self.from_pyfile(rv, silent=silent)\n\n    def from_prefixed_env(\n        self, prefix: str = \"FLASK\", *, loads: t.Callable[[str], t.Any] = json.loads\n    ) -> bool:\n        \"\"\"Load any environment variables that start with ``FLASK_``,\n        dropping the prefix from the env key for the config key. Values\n        are passed through a loading function to attempt to convert them\n        to more specific types than strings.\n\n        Keys are loaded in :func:`sorted` order.\n\n        The default loading function attempts to parse values as any\n        valid JSON type, including dicts and lists.\n\n        Specific items in nested dicts can be set by separating the\n        keys with double underscores (``__``). If an intermediate key\n        doesn't exist, it will be initialized to an empty dict.\n\n        :param prefix: Load env vars that start with this prefix,\n            separated with an underscore (``_``).\n        :param loads: Pass each string value to this function and use\n            the returned value as the config value. If any error is\n            raised it is ignored and the value remains a string. The\n            default is :func:`json.loads`.\n\n        .. versionadded:: 2.1\n        \"\"\"\n        prefix = f\"{prefix}_\"\n\n        for key in sorted(os.environ):\n            if not key.startswith(prefix):\n                continue\n\n            value = os.environ[key]\n            key = key.removeprefix(prefix)\n\n            try:\n                value = loads(value)\n            except Exception:\n                # Keep the value as a string if loading failed.\n                pass\n\n            if \"__\" not in key:\n                # A non-nested key, set directly.\n                self[key] = value\n                continue\n\n            # Traverse nested dictionaries with keys separated by \"__\".\n            current = self\n            *parts, tail = key.split(\"__\")\n\n            for part in parts:\n                # If an intermediate dict does not exist, create it.\n                if part not in current:\n                    current[part] = {}\n\n                current = current[part]\n\n            current[tail] = value\n\n        return True\n\n    def from_pyfile(\n        self, filename: str | os.PathLike[str], silent: bool = False\n    ) -> bool:\n        \"\"\"Updates the values in the config from a Python file.  This function\n        behaves as if the file was imported as module with the\n        :meth:`from_object` function.\n\n        :param filename: the filename of the config.  This can either be an\n                         absolute filename or a filename relative to the\n                         root path.\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionadded:: 0.7\n           `silent` parameter.\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n        d = types.ModuleType(\"config\")\n        d.__file__ = filename\n        try:\n            with open(filename, mode=\"rb\") as config_file:\n                exec(compile(config_file.read(), filename, \"exec\"), d.__dict__)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n                return False\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        self.from_object(d)\n        return True\n\n    def from_object(self, obj: object | str) -> None:\n        \"\"\"Updates the values from the given object.  An object can be of one\n        of the following two types:\n\n        -   a string: in this case the object with that name will be imported\n        -   an actual object reference: that object is used directly\n\n        Objects are usually either modules or classes. :meth:`from_object`\n        loads only the uppercase attributes of the module/class. A ``dict``\n        object will not work with :meth:`from_object` because the keys of a\n        ``dict`` are not attributes of the ``dict`` class.\n\n        Example of module-based configuration::\n\n            app.config.from_object('yourapplication.default_config')\n            from yourapplication import default_config\n            app.config.from_object(default_config)\n\n        Nothing is done to the object before loading. If the object is a\n        class and has ``@property`` attributes, it needs to be\n        instantiated before being passed to this method.\n\n        You should not use this function to load the actual configuration but\n        rather configuration defaults.  The actual config should be loaded\n        with :meth:`from_pyfile` and ideally from a location not within the\n        package because the package might be installed system wide.\n\n        See :ref:`config-dev-prod` for an example of class-based configuration\n        using :meth:`from_object`.\n\n        :param obj: an import name or object\n        \"\"\"\n        if isinstance(obj, str):\n            obj = import_string(obj)\n        for key in dir(obj):\n            if key.isupper():\n                self[key] = getattr(obj, key)\n\n    def from_file(\n        self,\n        filename: str | os.PathLike[str],\n        load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n        silent: bool = False,\n        text: bool = True,\n    ) -> bool:\n        \"\"\"Update the values in the config from a file that is loaded\n        using the ``load`` parameter. The loaded data is passed to the\n        :meth:`from_mapping` method.\n\n        .. code-block:: python\n\n            import json\n            app.config.from_file(\"config.json\", load=json.load)\n\n            import tomllib\n            app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n        :param filename: The path to the data file. This can be an\n            absolute path or relative to the config root path.\n        :param load: A callable that takes a file handle and returns a\n            mapping of loaded data from the file.\n        :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n            implements a ``read`` method.\n        :param silent: Ignore the file if it doesn't exist.\n        :param text: Open the file in text or binary mode.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionchanged:: 2.3\n            The ``text`` parameter was added.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n\n        try:\n            with open(filename, \"r\" if text else \"rb\") as f:\n                obj = load(f)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR):\n                return False\n\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n\n        return self.from_mapping(obj)\n\n    def from_mapping(\n        self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any\n    ) -> bool:\n        \"\"\"Updates the config like :meth:`update` ignoring items with\n        non-upper keys.\n\n        :return: Always returns ``True``.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        mappings: dict[str, t.Any] = {}\n        if mapping is not None:\n            mappings.update(mapping)\n        mappings.update(kwargs)\n        for key, value in mappings.items():\n            if key.isupper():\n                self[key] = value\n        return True\n\n    def get_namespace(\n        self, namespace: str, lowercase: bool = True, trim_namespace: bool = True\n    ) -> dict[str, t.Any]:\n        \"\"\"Returns a dictionary containing a subset of configuration options\n        that match the specified namespace/prefix. Example usage::\n\n            app.config['IMAGE_STORE_TYPE'] = 'fs'\n            app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n            app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n            image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n        The resulting dictionary `image_store_config` would look like::\n\n            {\n                'type': 'fs',\n                'path': '/var/app/images',\n                'base_url': 'http://img.website.com'\n            }\n\n        This is often useful when configuration options map directly to\n        keyword arguments in functions or class constructors.\n\n        :param namespace: a configuration namespace\n        :param lowercase: a flag indicating if the keys of the resulting\n                          dictionary should be lowercase\n        :param trim_namespace: a flag indicating if the keys of the resulting\n                          dictionary should not include the namespace\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {}\n        for k, v in self.items():\n            if not k.startswith(namespace):\n                continue\n            if trim_namespace:\n                key = k[len(namespace) :]\n            else:\n                key = k\n            if lowercase:\n                key = key.lower()\n            rv[key] = v\n        return rv\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-8a49dce1d1f27976", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 326, "local_path": "source-original/SRC__flask__Config__155241c3.py", "order": 0, "original_content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L50-L367", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Config", "variant_id": "pyint-648d155241c3-SRC", "group_id": "py-8a49dce1d1f27976", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 659, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-95110e6ebfc5-I01", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass Config(dict):   \n    \n\n    def __init__(\n        self,\n        root_path: str | os.PathLike[str],\n        defaults: dict[str, t.Any] | None = None,\n    ) -> None:\n        super().__init__(defaults or {})\n        self.root_path = root_path\n\n    def from_envvar(self, variable_name: str, silent: bool = False) -> bool:\n        \n        rv = os.environ.get(variable_name)\n        if not rv:\n            if silent:\n                return False\n            raise RuntimeError(\n                f\"The environment variable {variable_name!r} is not set\"\n                \" and as such configuration could not be loaded. Set\"\n                \" this variable and make it point to a configuration\"\n                \" file\"\n            )\n        return self.from_pyfile(rv, silent=silent)\n\n    def from_prefixed_env(\n        self, prefix: str = \"FLASK\", *, loads: t.Callable[[str], t.Any] = json.loads\n    ) -> bool:\n        \n        prefix = f\"{prefix}_\"\n\n        for key in sorted(os.environ):\n            if not key.startswith(prefix):\n                continue\n\n            value = os.environ[key]\n            key = key.removeprefix(prefix)\n\n            try:\n                value = loads(value)\n            except Exception:\n                 \n                pass\n\n            if \"__\" not in key:\n                 \n                self[key] = value\n                continue\n\n             \n            current = self\n            *parts, tail = key.split(\"__\")\n\n            for part in parts:\n                 \n                if part not in current:\n                    current[part] = {}\n\n                current = current[part]\n\n            current[tail] = value\n\n        return True\n\n    def from_pyfile(\n        self, filename: str | os.PathLike[str], silent: bool = False\n    ) -> bool:\n        \n        filename = os.path.join(self.root_path, filename)\n        d = types.ModuleType(\"config\")\n        d.__file__ = filename\n        try:\n            with open(filename, mode=\"rb\") as config_file:\n                exec(compile(config_file.read(), filename, \"exec\"), d.__dict__)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n                return False\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        self.from_object(d)\n        return True\n\n    def from_object(self, obj: object | str) -> None:\n        \n        if isinstance(obj, str):\n            obj = import_string(obj)\n        for key in dir(obj):\n            if key.isupper():\n                self[key] = getattr(obj, key)\n\n    def from_file(\n        self,\n        filename: str | os.PathLike[str],\n        load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n        silent: bool = False,\n        text: bool = True,\n    ) -> bool:\n        \n        filename = os.path.join(self.root_path, filename)\n\n        try:\n            with open(filename, \"r\" if text else \"rb\") as f:\n                obj = load(f)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR):\n                return False\n\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n\n        return self.from_mapping(obj)\n\n    def from_mapping(\n        self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any\n    ) -> bool:\n        \n        mappings: dict[str, t.Any] = {}\n        if mapping is not None:\n            mappings.update(mapping)\n        mappings.update(kwargs)\n        for key, value in mappings.items():\n            if key.isupper():\n                self[key] = value\n        return True\n\n    def get_namespace(\n        self, namespace: str, lowercase: bool = True, trim_namespace: bool = True\n    ) -> dict[str, t.Any]:\n        \n        rv = {}\n        for k, v in self.items():\n            if not k.startswith(namespace):\n                continue\n            if trim_namespace:\n                key = k[len(namespace) :]\n            else:\n                key = k\n            if lowercase:\n                key = key.lower()\n            rv[key] = v\n        return rv\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-8a49dce1d1f27976", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "acafa9a1eab7b8f24f0b4b6fb1bc8d1cce4d2bb73eb07352eafa6ac2fb35ac04", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 152, "local_path": "comments/remove-comments/I01__flask__Config__0e6ebfc5.py", "order": 1, "original_content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "parent_variant_id": "pyint-648d155241c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L50-L367", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 7919, "comments_removed": 13, "docstrings_removed": 8, "line_comments_removed": 5}, "unit_kind": "class", "unit_name": "Config", "variant_id": "pyint-95110e6ebfc5-I01", "group_id": "py-8a49dce1d1f27976", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 660, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5858bb768ea4-I02", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass Config(dict):  # type: ignore[type-arg]\n    \"\"\"Works exactly like a dict but provides ways to fill it from files\n    or special dictionaries.  There are two common patterns to populate the\n    config.\n\n    Either you can fill the config from a config file::\n\n        app.config.from_pyfile('yourconfig.cfg')\n\n    Or alternatively you can define the configuration options in the\n    module that calls :meth:`from_object` or provide an import path to\n    a module that should be loaded.  It is also possible to tell it to\n    use the same module and with that provide the configuration values\n    just before the call::\n\n        DEBUG = True\n        SECRET_KEY = 'development key'\n        app.config.from_object(__name__)\n\n    In both cases (loading from any Python file or loading from modules),\n    only uppercase keys are added to the config.  This makes it possible to use\n    lowercase values in the config file for temporary values that are not added\n    to the config or to define the config keys in the same file that implements\n    the application.\n\n    Probably the most interesting way to load configurations is from an\n    environment variable pointing to a file::\n\n        app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\n    In this case before launching the application you have to set this\n    environment variable to the file you want to use.  On Linux and OS X\n    use the export statement::\n\n        export YOURAPPLICATION_SETTINGS='/path/to/config/file'\n\n    On windows use `set` instead.\n\n    :param root_path: path to which files are read relative from.  When the\n                      config object is created by the application, this is\n                      the application's :attr:`~flask.Flask.root_path`.\n    :param defaults: an optional dictionary of default values\n    \"\"\"\n\n    def __init__(\n        self,\n        root: str | os.PathLike[str],\n        def2: dict[str, t.Any] | None = None,\n    ) -> None:\n        super().__init__(def2 or {})\n        self.root_path = root\n\n    def from2(self, variable: str, sil: bool = False) -> bool:\n        \"\"\"Loads a configuration from an environment variable pointing to\n        a configuration file.  This is basically just a shortcut with nicer\n        error messages for this line of code::\n\n            app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n\n        :param variable_name: name of the environment variable\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n        \"\"\"\n        rv2 = os.environ.get(variable)\n        if not rv2:\n            if sil:\n                return False\n            raise RuntimeError(\n                f\"The environment variable {variable!r} is not set\"\n                \" and as such configuration could not be loaded. Set\"\n                \" this variable and make it point to a configuration\"\n                \" file\"\n            )\n        return self.from4(rv2, silent=sil)\n\n    def from3(\n        self, pre: str = \"FLASK\", *, loa: t.Callable[[str], t.Any] = json.loads\n    ) -> bool:\n        \"\"\"Load any environment variables that start with ``FLASK_``,\n        dropping the prefix from the env key for the config key. Values\n        are passed through a loading function to attempt to convert them\n        to more specific types than strings.\n\n        Keys are loaded in :func:`sorted` order.\n\n        The default loading function attempts to parse values as any\n        valid JSON type, including dicts and lists.\n\n        Specific items in nested dicts can be set by separating the\n        keys with double underscores (``__``). If an intermediate key\n        doesn't exist, it will be initialized to an empty dict.\n\n        :param prefix: Load env vars that start with this prefix,\n            separated with an underscore (``_``).\n        :param loads: Pass each string value to this function and use\n            the returned value as the config value. If any error is\n            raised it is ignored and the value remains a string. The\n            default is :func:`json.loads`.\n\n        .. versionadded:: 2.1\n        \"\"\"\n        pre = f\"{pre}_\"\n\n        for key2 in sorted(os.environ):\n            if not key2.startswith(pre):\n                continue\n\n            val = os.environ[key2]\n            key2 = key2.removeprefix(pre)\n\n            try:\n                val = loa(val)\n            except Exception:\n                # Keep the value as a string if loading failed.\n                pass\n\n            if \"__\" not in key2:\n                # A non-nested key, set directly.\n                self[key2] = val\n                continue\n\n            # Traverse nested dictionaries with keys separated by \"__\".\n            cur = self\n            *par, tai = key2.split(\"__\")\n\n            for par2 in par:\n                # If an intermediate dict does not exist, create it.\n                if par2 not in cur:\n                    cur[par2] = {}\n\n                cur = cur[par2]\n\n            cur[tai] = val\n\n        return True\n\n    def from4(\n        self, fil: str | os.PathLike[str], sil2: bool = False\n    ) -> bool:\n        \"\"\"Updates the values in the config from a Python file.  This function\n        behaves as if the file was imported as module with the\n        :meth:`from_object` function.\n\n        :param filename: the filename of the config.  This can either be an\n                         absolute filename or a filename relative to the\n                         root path.\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionadded:: 0.7\n           `silent` parameter.\n        \"\"\"\n        fil = os.path.join(self.root_path, fil)\n        d2 = types.ModuleType(\"config\")\n        d2.__file__ = fil\n        try:\n            with open(fil, mode=\"rb\") as config:\n                exec(compile(config.read(), fil, \"exec\"), d2.__dict__)\n        except OSError as e:\n            if sil2 and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n                return False\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        self.from5(d2)\n        return True\n\n    def from5(self, obj2: object | str) -> None:\n        \"\"\"Updates the values from the given object.  An object can be of one\n        of the following two types:\n\n        -   a string: in this case the object with that name will be imported\n        -   an actual object reference: that object is used directly\n\n        Objects are usually either modules or classes. :meth:`from_object`\n        loads only the uppercase attributes of the module/class. A ``dict``\n        object will not work with :meth:`from_object` because the keys of a\n        ``dict`` are not attributes of the ``dict`` class.\n\n        Example of module-based configuration::\n\n            app.config.from_object('yourapplication.default_config')\n            from yourapplication import default_config\n            app.config.from_object(default_config)\n\n        Nothing is done to the object before loading. If the object is a\n        class and has ``@property`` attributes, it needs to be\n        instantiated before being passed to this method.\n\n        You should not use this function to load the actual configuration but\n        rather configuration defaults.  The actual config should be loaded\n        with :meth:`from_pyfile` and ideally from a location not within the\n        package because the package might be installed system wide.\n\n        See :ref:`config-dev-prod` for an example of class-based configuration\n        using :meth:`from_object`.\n\n        :param obj: an import name or object\n        \"\"\"\n        if isinstance(obj2, str):\n            obj2 = import_string(obj2)\n        for key3 in dir(obj2):\n            if key3.isupper():\n                self[key3] = getattr(obj2, key3)\n\n    def from6(\n        self,\n        fil2: str | os.PathLike[str],\n        loa2: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n        sil3: bool = False,\n        tex: bool = True,\n    ) -> bool:\n        \"\"\"Update the values in the config from a file that is loaded\n        using the ``load`` parameter. The loaded data is passed to the\n        :meth:`from_mapping` method.\n\n        .. code-block:: python\n\n            import json\n            app.config.from_file(\"config.json\", load=json.load)\n\n            import tomllib\n            app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n        :param filename: The path to the data file. This can be an\n            absolute path or relative to the config root path.\n        :param load: A callable that takes a file handle and returns a\n            mapping of loaded data from the file.\n        :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n            implements a ``read`` method.\n        :param silent: Ignore the file if it doesn't exist.\n        :param text: Open the file in text or binary mode.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionchanged:: 2.3\n            The ``text`` parameter was added.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        fil2 = os.path.join(self.root_path, fil2)\n\n        try:\n            with open(fil2, \"r\" if tex else \"rb\") as f2:\n                obj3 = loa2(f2)\n        except OSError as e:\n            if sil3 and e.errno in (errno.ENOENT, errno.EISDIR):\n                return False\n\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n\n        return self.from7(obj3)\n\n    def from7(\n        self, map: t.Mapping[str, t.Any] | None = None, **kwa: t.Any\n    ) -> bool:\n        \"\"\"Updates the config like :meth:`update` ignoring items with\n        non-upper keys.\n\n        :return: Always returns ``True``.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        map2: dict[str, t.Any] = {}\n        if map is not None:\n            map2.update(map)\n        map2.update(kwa)\n        for key4, val2 in map2.items():\n            if key4.isupper():\n                self[key4] = val2\n        return True\n\n    def get2(\n        self, nam: str, low: bool = True, trim: bool = True\n    ) -> dict[str, t.Any]:\n        \"\"\"Returns a dictionary containing a subset of configuration options\n        that match the specified namespace/prefix. Example usage::\n\n            app.config['IMAGE_STORE_TYPE'] = 'fs'\n            app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n            app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n            image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n        The resulting dictionary `image_store_config` would look like::\n\n            {\n                'type': 'fs',\n                'path': '/var/app/images',\n                'base_url': 'http://img.website.com'\n            }\n\n        This is often useful when configuration options map directly to\n        keyword arguments in functions or class constructors.\n\n        :param namespace: a configuration namespace\n        :param lowercase: a flag indicating if the keys of the resulting\n                          dictionary should be lowercase\n        :param trim_namespace: a flag indicating if the keys of the resulting\n                          dictionary should not include the namespace\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv3 = {}\n        for k2, v2 in self.items():\n            if not k2.startswith(nam):\n                continue\n            if trim:\n                key5 = k2[len(nam) :]\n            else:\n                key5 = k2\n            if low:\n                key5 = key5.lower()\n            rv3[key5] = v2\n        return rv3\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-8a49dce1d1f27976", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "739e8df83775a23f454f0942ee1ee4fb7ccbc820de5f64a80533eaa73f0eccd6", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 326, "local_path": "identifiers/shorten-identifiers/I02__flask__Config__bb768ea4.py", "order": 2, "original_content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "parent_variant_id": "pyint-648d155241c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L50-L367", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 130, "identifiers_declared": 44}, "unit_kind": "class", "unit_name": "Config", "variant_id": "pyint-5858bb768ea4-I02", "group_id": "py-8a49dce1d1f27976", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 661, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-244ce8f577f0-I03", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass Config(dict):  # type: ignore[type-arg]\n    \"\"\"Works exactly like a dict but provides ways to fill it from files\n    or special dictionaries.  There are two common patterns to populate the\n    config.\n\n    Either you can fill the config from a config file::\n\n        app.config.from_pyfile('yourconfig.cfg')\n\n    Or alternatively you can define the configuration options in the\n    module that calls :meth:`from_object` or provide an import path to\n    a module that should be loaded.  It is also possible to tell it to\n    use the same module and with that provide the configuration values\n    just before the call::\n\n        DEBUG = True\n        SECRET_KEY = 'development key'\n        app.config.from_object(__name__)\n\n    In both cases (loading from any Python file or loading from modules),\n    only uppercase keys are added to the config.  This makes it possible to use\n    lowercase values in the config file for temporary values that are not added\n    to the config or to define the config keys in the same file that implements\n    the application.\n\n    Probably the most interesting way to load configurations is from an\n    environment variable pointing to a file::\n\n        app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\n    In this case before launching the application you have to set this\n    environment variable to the file you want to use.  On Linux and OS X\n    use the export statement::\n\n        export YOURAPPLICATION_SETTINGS='/path/to/config/file'\n\n    On windows use `set` instead.\n\n    :param root_path: path to which files are read relative from.  When the\n                      config object is created by the application, this is\n                      the application's :attr:`~flask.Flask.root_path`.\n    :param defaults: an optional dictionary of default values\n    \"\"\"\n\n    def __init__(\n        self,\n        operation: str | os.PathLike[str],\n        location: dict[str, t.Any] | None = None,\n    ) -> None:\n        super().__init__(location or {})\n        self.root_path = operation\n\n    def readMessage(self, backupMessage: str, status: bool = False) -> bool:\n        \"\"\"Loads a configuration from an environment variable pointing to\n        a configuration file.  This is basically just a shortcut with nicer\n        error messages for this line of code::\n\n            app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n\n        :param variable_name: name of the environment variable\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n        \"\"\"\n        key = os.environ.get(backupMessage)\n        if not key:\n            if status:\n                return False\n            raise RuntimeError(\n                f\"The environment variable {backupMessage!r} is not set\"\n                \" and as such configuration could not be loaded. Set\"\n                \" this variable and make it point to a configuration\"\n                \" file\"\n            )\n        return self.saveAddress(key, silent=status)\n\n    def validateRequest(\n        self, option: str = \"FLASK\", *, event: t.Callable[[str], t.Any] = json.loads\n    ) -> bool:\n        \"\"\"Load any environment variables that start with ``FLASK_``,\n        dropping the prefix from the env key for the config key. Values\n        are passed through a loading function to attempt to convert them\n        to more specific types than strings.\n\n        Keys are loaded in :func:`sorted` order.\n\n        The default loading function attempts to parse values as any\n        valid JSON type, including dicts and lists.\n\n        Specific items in nested dicts can be set by separating the\n        keys with double underscores (``__``). If an intermediate key\n        doesn't exist, it will be initialized to an empty dict.\n\n        :param prefix: Load env vars that start with this prefix,\n            separated with an underscore (``_``).\n        :param loads: Pass each string value to this function and use\n            the returned value as the config value. If any error is\n            raised it is ignored and the value remains a string. The\n            default is :func:`json.loads`.\n\n        .. versionadded:: 2.1\n        \"\"\"\n        option = f\"{option}_\"\n\n        for map in sorted(os.environ):\n            if not map.startswith(option):\n                continue\n\n            limit = os.environ[map]\n            map = map.removeprefix(option)\n\n            try:\n                limit = event(limit)\n            except Exception:\n                # Keep the value as a string if loading failed.\n                pass\n\n            if \"__\" not in map:\n                # A non-nested key, set directly.\n                self[map] = limit\n                continue\n\n            # Traverse nested dictionaries with keys separated by \"__\".\n            request = self\n            *total, item = map.split(\"__\")\n\n            for mode in total:\n                # If an intermediate dict does not exist, create it.\n                if mode not in request:\n                    request[mode] = {}\n\n                request = request[mode]\n\n            request[item] = limit\n\n        return True\n\n    def saveAddress(\n        self, customer: str | os.PathLike[str], window: bool = False\n    ) -> bool:\n        \"\"\"Updates the values in the config from a Python file.  This function\n        behaves as if the file was imported as module with the\n        :meth:`from_object` function.\n\n        :param filename: the filename of the config.  This can either be an\n                         absolute filename or a filename relative to the\n                         root path.\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionadded:: 0.7\n           `silent` parameter.\n        \"\"\"\n        customer = os.path.join(self.root_path, customer)\n        key = types.ModuleType(\"config\")\n        key.__file__ = customer\n        try:\n            with open(customer, mode=\"rb\") as cachedEvent:\n                exec(compile(cachedEvent.read(), customer, \"exec\"), key.__dict__)\n        except OSError as e:\n            if window and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n                return False\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        self.fetchConfig(key)\n        return True\n\n    def fetchConfig(self, age: object | str) -> None:\n        \"\"\"Updates the values from the given object.  An object can be of one\n        of the following two types:\n\n        -   a string: in this case the object with that name will be imported\n        -   an actual object reference: that object is used directly\n\n        Objects are usually either modules or classes. :meth:`from_object`\n        loads only the uppercase attributes of the module/class. A ``dict``\n        object will not work with :meth:`from_object` because the keys of a\n        ``dict`` are not attributes of the ``dict`` class.\n\n        Example of module-based configuration::\n\n            app.config.from_object('yourapplication.default_config')\n            from yourapplication import default_config\n            app.config.from_object(default_config)\n\n        Nothing is done to the object before loading. If the object is a\n        class and has ``@property`` attributes, it needs to be\n        instantiated before being passed to this method.\n\n        You should not use this function to load the actual configuration but\n        rather configuration defaults.  The actual config should be loaded\n        with :meth:`from_pyfile` and ideally from a location not within the\n        package because the package might be installed system wide.\n\n        See :ref:`config-dev-prod` for an example of class-based configuration\n        using :meth:`from_object`.\n\n        :param obj: an import name or object\n        \"\"\"\n        if isinstance(age, str):\n            age = import_string(age)\n        for map in dir(age):\n            if map.isupper():\n                self[map] = getattr(age, map)\n\n    def fetchItem(\n        self,\n        nextUser: str | os.PathLike[str],\n        node: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n        config: bool = False,\n        mode: bool = True,\n    ) -> bool:\n        \"\"\"Update the values in the config from a file that is loaded\n        using the ``load`` parameter. The loaded data is passed to the\n        :meth:`from_mapping` method.\n\n        .. code-block:: python\n\n            import json\n            app.config.from_file(\"config.json\", load=json.load)\n\n            import tomllib\n            app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n        :param filename: The path to the data file. This can be an\n            absolute path or relative to the config root path.\n        :param load: A callable that takes a file handle and returns a\n            mapping of loaded data from the file.\n        :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n            implements a ``read`` method.\n        :param silent: Ignore the file if it doesn't exist.\n        :param text: Open the file in text or binary mode.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionchanged:: 2.3\n            The ``text`` parameter was added.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        nextUser = os.path.join(self.root_path, nextUser)\n\n        try:\n            with open(nextUser, \"r\" if mode else \"rb\") as key:\n                age = node(key)\n        except OSError as e:\n            if config and e.errno in (errno.ENOENT, errno.EISDIR):\n                return False\n\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n\n        return self.refreshValue(age)\n\n    def refreshValue(\n        self, request: t.Mapping[str, t.Any] | None = None, **source: t.Any\n    ) -> bool:\n        \"\"\"Updates the config like :meth:`update` ignoring items with\n        non-upper keys.\n\n        :return: Always returns ``True``.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        localKey: dict[str, t.Any] = {}\n        if request is not None:\n            localKey.update(request)\n        localKey.update(source)\n        for map, event in localKey.items():\n            if map.isupper():\n                self[map] = event\n        return True\n\n    def refreshRecord(\n        self, localItem: str, nextBatch: bool = True, primaryAccount: bool = True\n    ) -> dict[str, t.Any]:\n        \"\"\"Returns a dictionary containing a subset of configuration options\n        that match the specified namespace/prefix. Example usage::\n\n            app.config['IMAGE_STORE_TYPE'] = 'fs'\n            app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n            app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n            image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n        The resulting dictionary `image_store_config` would look like::\n\n            {\n                'type': 'fs',\n                'path': '/var/app/images',\n                'base_url': 'http://img.website.com'\n            }\n\n        This is often useful when configuration options map directly to\n        keyword arguments in functions or class constructors.\n\n        :param namespace: a configuration namespace\n        :param lowercase: a flag indicating if the keys of the resulting\n                          dictionary should be lowercase\n        :param trim_namespace: a flag indicating if the keys of the resulting\n                          dictionary should not include the namespace\n\n        .. versionadded:: 0.11\n        \"\"\"\n        map = {}\n        for age, size in self.items():\n            if not age.startswith(localItem):\n                continue\n            if primaryAccount:\n                mode = age[len(localItem) :]\n            else:\n                mode = age\n            if nextBatch:\n                mode = mode.lower()\n            map[mode] = size\n        return map\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-8a49dce1d1f27976", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b0f22dd17c80241adaf6860cebe0ad5e5cce62dbf09c11d65f38855755481a00", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 326, "local_path": "identifiers/mislead-identifiers/I03__flask__Config__e8f577f0.py", "order": 3, "original_content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "parent_variant_id": "pyint-648d155241c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L50-L367", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 130, "identifiers_declared": 44, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 8, "local_exact_length_matches": 30, "local_random_pool_selections": 37, "local_total_length_difference": 12, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 6, "method_random_pool_selections": 7, "method_total_length_difference": 2}, "unit_kind": "class", "unit_name": "Config", "variant_id": "pyint-244ce8f577f0-I03", "group_id": "py-8a49dce1d1f27976", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 662, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dbf864a1fba1-I04", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass Config(dict):  # type: ignore[type-arg]\n    \"\"\"Works exactly like a dict but provides ways to fill it from files\n    or special dictionaries.  There are two common patterns to populate the\n    config.\n\n    Either you can fill the config from a config file::\n\n        app.config.from_pyfile('yourconfig.cfg')\n\n    Or alternatively you can define the configuration options in the\n    module that calls :meth:`from_object` or provide an import path to\n    a module that should be loaded.  It is also possible to tell it to\n    use the same module and with that provide the configuration values\n    just before the call::\n\n        DEBUG = True\n        SECRET_KEY = 'development key'\n        app.config.from_object(__name__)\n\n    In both cases (loading from any Python file or loading from modules),\n    only uppercase keys are added to the config.  This makes it possible to use\n    lowercase values in the config file for temporary values that are not added\n    to the config or to define the config keys in the same file that implements\n    the application.\n\n    Probably the most interesting way to load configurations is from an\n    environment variable pointing to a file::\n\n        app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\n    In this case before launching the application you have to set this\n    environment variable to the file you want to use.  On Linux and OS X\n    use the export statement::\n\n        export YOURAPPLICATION_SETTINGS='/path/to/config/file'\n\n    On windows use `set` instead.\n\n    :param root_path: path to which files are read relative from.  When the\n                      config object is created by the application, this is\n                      the application's :attr:`~flask.Flask.root_path`.\n    :param defaults: an optional dictionary of default values\n    \"\"\"\n\n    def __init__(\n        self,\n        l: str | os.PathLike[str],\n        m: dict[str, t.Any] | None = None,\n    ) -> None:\n        super().__init__(m or {})\n        self.root_path = l\n\n    def a(self, n: str, o: bool = False) -> bool:\n        \"\"\"Loads a configuration from an environment variable pointing to\n        a configuration file.  This is basically just a shortcut with nicer\n        error messages for this line of code::\n\n            app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n\n        :param variable_name: name of the environment variable\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n        \"\"\"\n        p = os.environ.get(n)\n        if not p:\n            if o:\n                return False\n            raise RuntimeError(\n                f\"The environment variable {n!r} is not set\"\n                \" and as such configuration could not be loaded. Set\"\n                \" this variable and make it point to a configuration\"\n                \" file\"\n            )\n        return self.c(p, silent=o)\n\n    def b(\n        self, q: str = \"FLASK\", *, r: t.Callable[[str], t.Any] = json.loads\n    ) -> bool:\n        \"\"\"Load any environment variables that start with ``FLASK_``,\n        dropping the prefix from the env key for the config key. Values\n        are passed through a loading function to attempt to convert them\n        to more specific types than strings.\n\n        Keys are loaded in :func:`sorted` order.\n\n        The default loading function attempts to parse values as any\n        valid JSON type, including dicts and lists.\n\n        Specific items in nested dicts can be set by separating the\n        keys with double underscores (``__``). If an intermediate key\n        doesn't exist, it will be initialized to an empty dict.\n\n        :param prefix: Load env vars that start with this prefix,\n            separated with an underscore (``_``).\n        :param loads: Pass each string value to this function and use\n            the returned value as the config value. If any error is\n            raised it is ignored and the value remains a string. The\n            default is :func:`json.loads`.\n\n        .. versionadded:: 2.1\n        \"\"\"\n        q = f\"{q}_\"\n\n        for s in sorted(os.environ):\n            if not s.startswith(q):\n                continue\n\n            u = os.environ[s]\n            s = s.removeprefix(q)\n\n            try:\n                u = r(u)\n            except Exception:\n                # Keep the value as a string if loading failed.\n                pass\n\n            if \"__\" not in s:\n                # A non-nested key, set directly.\n                self[s] = u\n                continue\n\n            # Traverse nested dictionaries with keys separated by \"__\".\n            w = self\n            *x, y = s.split(\"__\")\n\n            for z in x:\n                # If an intermediate dict does not exist, create it.\n                if z not in w:\n                    w[z] = {}\n\n                w = w[z]\n\n            w[y] = u\n\n        return True\n\n    def c(\n        self, A: str | os.PathLike[str], B: bool = False\n    ) -> bool:\n        \"\"\"Updates the values in the config from a Python file.  This function\n        behaves as if the file was imported as module with the\n        :meth:`from_object` function.\n\n        :param filename: the filename of the config.  This can either be an\n                         absolute filename or a filename relative to the\n                         root path.\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionadded:: 0.7\n           `silent` parameter.\n        \"\"\"\n        A = os.path.join(self.root_path, A)\n        C = types.ModuleType(\"config\")\n        C.__file__ = A\n        try:\n            with open(A, mode=\"rb\") as D:\n                exec(compile(D.read(), A, \"exec\"), C.__dict__)\n        except OSError as e:\n            if B and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n                return False\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        self.g(C)\n        return True\n\n    def g(self, E: object | str) -> None:\n        \"\"\"Updates the values from the given object.  An object can be of one\n        of the following two types:\n\n        -   a string: in this case the object with that name will be imported\n        -   an actual object reference: that object is used directly\n\n        Objects are usually either modules or classes. :meth:`from_object`\n        loads only the uppercase attributes of the module/class. A ``dict``\n        object will not work with :meth:`from_object` because the keys of a\n        ``dict`` are not attributes of the ``dict`` class.\n\n        Example of module-based configuration::\n\n            app.config.from_object('yourapplication.default_config')\n            from yourapplication import default_config\n            app.config.from_object(default_config)\n\n        Nothing is done to the object before loading. If the object is a\n        class and has ``@property`` attributes, it needs to be\n        instantiated before being passed to this method.\n\n        You should not use this function to load the actual configuration but\n        rather configuration defaults.  The actual config should be loaded\n        with :meth:`from_pyfile` and ideally from a location not within the\n        package because the package might be installed system wide.\n\n        See :ref:`config-dev-prod` for an example of class-based configuration\n        using :meth:`from_object`.\n\n        :param obj: an import name or object\n        \"\"\"\n        if isinstance(E, str):\n            E = import_string(E)\n        for F in dir(E):\n            if F.isupper():\n                self[F] = getattr(E, F)\n\n    def h(\n        self,\n        G: str | os.PathLike[str],\n        H: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n        I: bool = False,\n        J: bool = True,\n    ) -> bool:\n        \"\"\"Update the values in the config from a file that is loaded\n        using the ``load`` parameter. The loaded data is passed to the\n        :meth:`from_mapping` method.\n\n        .. code-block:: python\n\n            import json\n            app.config.from_file(\"config.json\", load=json.load)\n\n            import tomllib\n            app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n        :param filename: The path to the data file. This can be an\n            absolute path or relative to the config root path.\n        :param load: A callable that takes a file handle and returns a\n            mapping of loaded data from the file.\n        :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n            implements a ``read`` method.\n        :param silent: Ignore the file if it doesn't exist.\n        :param text: Open the file in text or binary mode.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionchanged:: 2.3\n            The ``text`` parameter was added.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        G = os.path.join(self.root_path, G)\n\n        try:\n            with open(G, \"r\" if J else \"rb\") as K:\n                L = H(K)\n        except OSError as e:\n            if I and e.errno in (errno.ENOENT, errno.EISDIR):\n                return False\n\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n\n        return self.i(L)\n\n    def i(\n        self, M: t.Mapping[str, t.Any] | None = None, **N: t.Any\n    ) -> bool:\n        \"\"\"Updates the config like :meth:`update` ignoring items with\n        non-upper keys.\n\n        :return: Always returns ``True``.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        O: dict[str, t.Any] = {}\n        if M is not None:\n            O.update(M)\n        O.update(N)\n        for P, Q in O.items():\n            if P.isupper():\n                self[P] = Q\n        return True\n\n    def j(\n        self, R: str, S: bool = True, T: bool = True\n    ) -> dict[str, t.Any]:\n        \"\"\"Returns a dictionary containing a subset of configuration options\n        that match the specified namespace/prefix. Example usage::\n\n            app.config['IMAGE_STORE_TYPE'] = 'fs'\n            app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n            app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n            image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n        The resulting dictionary `image_store_config` would look like::\n\n            {\n                'type': 'fs',\n                'path': '/var/app/images',\n                'base_url': 'http://img.website.com'\n            }\n\n        This is often useful when configuration options map directly to\n        keyword arguments in functions or class constructors.\n\n        :param namespace: a configuration namespace\n        :param lowercase: a flag indicating if the keys of the resulting\n                          dictionary should be lowercase\n        :param trim_namespace: a flag indicating if the keys of the resulting\n                          dictionary should not include the namespace\n\n        .. versionadded:: 0.11\n        \"\"\"\n        U = {}\n        for V, W in self.items():\n            if not V.startswith(R):\n                continue\n            if T:\n                X = V[len(R) :]\n            else:\n                X = V\n            if S:\n                X = X.lower()\n            U[X] = W\n        return U\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-8a49dce1d1f27976", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d3bdf068e3982bdb69fccd6c56422f56d832b2919d1c990597575745978355a1", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 326, "local_path": "identifiers/garble-identifiers/I04__flask__Config__64a1fba1.py", "order": 4, "original_content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "parent_variant_id": "pyint-648d155241c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L50-L367", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 130, "identifiers_declared": 44}, "unit_kind": "class", "unit_name": "Config", "variant_id": "pyint-dbf864a1fba1-I04", "group_id": "py-8a49dce1d1f27976", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 663, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-661b60e51d67-I05", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass Config(dict):  # type: ignore[type-arg]\n    \"\"\"Works exactly like a dict but provides ways to fill it from files\n    or special dictionaries.  There are two common patterns to populate the\n    config.\n\n    Either you can fill the config from a config file::\n\n        app.config.from_pyfile('yourconfig.cfg')\n\n    Or alternatively you can define the configuration options in the\n    module that calls :meth:`from_object` or provide an import path to\n    a module that should be loaded.  It is also possible to tell it to\n    use the same module and with that provide the configuration values\n    just before the call::\n\n        DEBUG = True\n        SECRET_KEY = 'development key'\n        app.config.from_object(__name__)\n\n    In both cases (loading from any Python file or loading from modules),\n    only uppercase keys are added to the config.  This makes it possible to use\n    lowercase values in the config file for temporary values that are not added\n    to the config or to define the config keys in the same file that implements\n    the application.\n\n    Probably the most interesting way to load configurations is from an\n    environment variable pointing to a file::\n\n        app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\n    In this case before launching the application you have to set this\n    environment variable to the file you want to use.  On Linux and OS X\n    use the export statement::\n\n        export YOURAPPLICATION_SETTINGS='/path/to/config/file'\n\n    On windows use `set` instead.\n\n    :param root_path: path to which files are read relative from.  When the\n                      config object is created by the application, this is\n                      the application's :attr:`~flask.Flask.root_path`.\n    :param defaults: an optional dictionary of default values\n    \"\"\"\n\n    def __init__(\n        self,\n        root_path: str | os.PathLike[str],\n        defaults: dict[str, t.Any] | None = None,\n    ) -> None:\n        super().__init__(defaults or {})\n        self.root_path = root_path\n\n    def from_envvar(self, variable_name: str, silent: bool = False) -> bool:\n        \"\"\"Loads a configuration from an environment variable pointing to\n        a configuration file.  This is basically just a shortcut with nicer\n        error messages for this line of code::\n\n            app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n\n        :param variable_name: name of the environment variable\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n        \"\"\"\n        rv = os.environ.get(variable_name)\n        if not rv:\n            if silent:\n                return False\n            raise RuntimeError(\n                f\"The environment variable {variable_name!r} is not set\"\n                \" and as such configuration could not be loaded. Set\"\n                \" this variable and make it point to a configuration\"\n                \" file\"\n            )\n        return self.from_pyfile(rv, silent=silent)\n\n    def from_prefixed_env(\n        self, prefix: str = \"FLASK\", *, loads: t.Callable[[str], t.Any] = json.loads\n    ) -> bool:\n        \"\"\"Load any environment variables that start with ``FLASK_``,\n        dropping the prefix from the env key for the config key. Values\n        are passed through a loading function to attempt to convert them\n        to more specific types than strings.\n\n        Keys are loaded in :func:`sorted` order.\n\n        The default loading function attempts to parse values as any\n        valid JSON type, including dicts and lists.\n\n        Specific items in nested dicts can be set by separating the\n        keys with double underscores (``__``). If an intermediate key\n        doesn't exist, it will be initialized to an empty dict.\n\n        :param prefix: Load env vars that start with this prefix,\n            separated with an underscore (``_``).\n        :param loads: Pass each string value to this function and use\n            the returned value as the config value. If any error is\n            raised it is ignored and the value remains a string. The\n            default is :func:`json.loads`.\n\n        .. versionadded:: 2.1\n        \"\"\"\n        prefix = f\"{prefix}_\"\n\n        for key in sorted(os.environ):\n            if not key.startswith(prefix):\n                continue\n\n            value = os.environ[key]\n            key = key.removeprefix(prefix)\n\n            try:\n                value = loads(value)\n            except Exception:\n                # Keep the value as a string if loading failed.\n                pass\n\n            if \"__\" not in key:\n                # A non-nested key, set directly.\n                self[key] = value\n                continue\n\n            # Traverse nested dictionaries with keys separated by \"__\".\n            current = self\n            *parts, tail = key.split(\"__\")\n\n            for part in parts:\n                # If an intermediate dict does not exist, create it.\n                if part not in current:\n                    current[part] = {}\n\n                current = current[part]\n\n            current[tail] = value\n\n        return True\n\n    def from_pyfile(\n        self, filename: str | os.PathLike[str], silent: bool = False\n    ) -> bool:\n        \"\"\"Updates the values in the config from a Python file.  This function\n        behaves as if the file was imported as module with the\n        :meth:`from_object` function.\n\n        :param filename: the filename of the config.  This can either be an\n                         absolute filename or a filename relative to the\n                         root path.\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionadded:: 0.7\n           `silent` parameter.\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n        d = types.ModuleType(\"config\")\n        d.__file__ = filename\n        try:\n            with open(filename, mode=\"rb\") as config_file:\n                exec(compile(config_file.read(), filename, \"exec\"), d.__dict__)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n                return False\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        self.from_object(d)\n        return True\n\n    def from_object(self, obj: object | str) -> None:\n        \"\"\"Updates the values from the given object.  An object can be of one\n        of the following two types:\n\n        -   a string: in this case the object with that name will be imported\n        -   an actual object reference: that object is used directly\n\n        Objects are usually either modules or classes. :meth:`from_object`\n        loads only the uppercase attributes of the module/class. A ``dict``\n        object will not work with :meth:`from_object` because the keys of a\n        ``dict`` are not attributes of the ``dict`` class.\n\n        Example of module-based configuration::\n\n            app.config.from_object('yourapplication.default_config')\n            from yourapplication import default_config\n            app.config.from_object(default_config)\n\n        Nothing is done to the object before loading. If the object is a\n        class and has ``@property`` attributes, it needs to be\n        instantiated before being passed to this method.\n\n        You should not use this function to load the actual configuration but\n        rather configuration defaults.  The actual config should be loaded\n        with :meth:`from_pyfile` and ideally from a location not within the\n        package because the package might be installed system wide.\n\n        See :ref:`config-dev-prod` for an example of class-based configuration\n        using :meth:`from_object`.\n\n        :param obj: an import name or object\n        \"\"\"\n        if isinstance(obj, str):\n            obj = import_string(obj)\n        for key in dir(obj):\n            if key.isupper():\n                self[key] = getattr(obj, key)\n\n    def from_file(\n        self,\n        filename: str | os.PathLike[str],\n        load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n        silent: bool = False,\n        text: bool = True,\n    ) -> bool:\n        \"\"\"Update the values in the config from a file that is loaded\n        using the ``load`` parameter. The loaded data is passed to the\n        :meth:`from_mapping` method.\n\n        .. code-block:: python\n\n            import json\n            app.config.from_file(\"config.json\", load=json.load)\n\n            import tomllib\n            app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n        :param filename: The path to the data file. This can be an\n            absolute path or relative to the config root path.\n        :param load: A callable that takes a file handle and returns a\n            mapping of loaded data from the file.\n        :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n            implements a ``read`` method.\n        :param silent: Ignore the file if it doesn't exist.\n        :param text: Open the file in text or binary mode.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionchanged:: 2.3\n            The ``text`` parameter was added.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n\n        try:\n            with open(filename, \"r\" if text else \"rb\") as f:\n                obj = load(f)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR):\n                return False\n\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n\n        return self.from_mapping(obj)\n\n    def from_mapping(\n        self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any\n    ) -> bool:\n        \"\"\"Updates the config like :meth:`update` ignoring items with\n        non-upper keys.\n\n        :return: Always returns ``True``.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        mappings: dict[str, t.Any] = {}\n        if mapping is not None:\n            mappings.update(mapping)\n        mappings.update(kwargs)\n        for key, value in mappings.items():\n            if key.isupper():\n                self[key] = value\n        return True\n\n    def get_namespace(\n        self, namespace: str, lowercase: bool = True, trim_namespace: bool = True\n    ) -> dict[str, t.Any]:\n        \"\"\"Returns a dictionary containing a subset of configuration options\n        that match the specified namespace/prefix. Example usage::\n\n            app.config['IMAGE_STORE_TYPE'] = 'fs'\n            app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n            app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n            image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n        The resulting dictionary `image_store_config` would look like::\n\n            {\n                'type': 'fs',\n                'path': '/var/app/images',\n                'base_url': 'http://img.website.com'\n            }\n\n        This is often useful when configuration options map directly to\n        keyword arguments in functions or class constructors.\n\n        :param namespace: a configuration namespace\n        :param lowercase: a flag indicating if the keys of the resulting\n                          dictionary should be lowercase\n        :param trim_namespace: a flag indicating if the keys of the resulting\n                          dictionary should not include the namespace\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {}\n        for k, v in self.items():\n            if not k.startswith(namespace):\n                continue\n            if trim_namespace:\n                key = k[len(namespace) :]\n            else:\n                key = k\n            if lowercase:\n                key = key.lower()\n            rv[key] = v\n        return rv\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-8a49dce1d1f27976", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 326, "local_path": "expressions/encode-integer-literals/I05__flask__Config__60e51d67.py", "order": 5, "original_content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "parent_variant_id": "pyint-648d155241c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L50-L367", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "Config", "variant_id": "pyint-661b60e51d67-I05", "group_id": "py-8a49dce1d1f27976", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 664, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-34f13e13b9fe-I06", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass Config(dict):  # type: ignore[type-arg]\n    \"\"\"Works exactly like a dict but provides ways to fill it from files\n    or special dictionaries.  There are two common patterns to populate the\n    config.\n\n    Either you can fill the config from a config file::\n\n        app.config.from_pyfile('yourconfig.cfg')\n\n    Or alternatively you can define the configuration options in the\n    module that calls :meth:`from_object` or provide an import path to\n    a module that should be loaded.  It is also possible to tell it to\n    use the same module and with that provide the configuration values\n    just before the call::\n\n        DEBUG = True\n        SECRET_KEY = 'development key'\n        app.config.from_object(__name__)\n\n    In both cases (loading from any Python file or loading from modules),\n    only uppercase keys are added to the config.  This makes it possible to use\n    lowercase values in the config file for temporary values that are not added\n    to the config or to define the config keys in the same file that implements\n    the application.\n\n    Probably the most interesting way to load configurations is from an\n    environment variable pointing to a file::\n\n        app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\n    In this case before launching the application you have to set this\n    environment variable to the file you want to use.  On Linux and OS X\n    use the export statement::\n\n        export YOURAPPLICATION_SETTINGS='/path/to/config/file'\n\n    On windows use `set` instead.\n\n    :param root_path: path to which files are read relative from.  When the\n                      config object is created by the application, this is\n                      the application's :attr:`~flask.Flask.root_path`.\n    :param defaults: an optional dictionary of default values\n    \"\"\"\n\n    def __init__(\n        self,\n        root_path: str | os.PathLike[str],\n        defaults: dict[str, t.Any] | None = None,\n    ) -> None:\n        super().__init__(defaults or {})\n        self.root_path = root_path\n\n    def from_envvar(self, variable_name: str, silent: bool = False) -> bool:\n        \"\"\"Loads a configuration from an environment variable pointing to\n        a configuration file.  This is basically just a shortcut with nicer\n        error messages for this line of code::\n\n            app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n\n        :param variable_name: name of the environment variable\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n        \"\"\"\n        rv = os.environ.get(variable_name)\n        if not (not rv):\n            pass\n        else:\n            if silent:\n                return False\n            raise RuntimeError(\n                f\"The environment variable {variable_name!r} is not set\"\n                \" and as such configuration could not be loaded. Set\"\n                \" this variable and make it point to a configuration\"\n                \" file\"\n            )\n        return self.from_pyfile(rv, silent=silent)\n\n    def from_prefixed_env(\n        self, prefix: str = \"FLASK\", *, loads: t.Callable[[str], t.Any] = json.loads\n    ) -> bool:\n        \"\"\"Load any environment variables that start with ``FLASK_``,\n        dropping the prefix from the env key for the config key. Values\n        are passed through a loading function to attempt to convert them\n        to more specific types than strings.\n\n        Keys are loaded in :func:`sorted` order.\n\n        The default loading function attempts to parse values as any\n        valid JSON type, including dicts and lists.\n\n        Specific items in nested dicts can be set by separating the\n        keys with double underscores (``__``). If an intermediate key\n        doesn't exist, it will be initialized to an empty dict.\n\n        :param prefix: Load env vars that start with this prefix,\n            separated with an underscore (``_``).\n        :param loads: Pass each string value to this function and use\n            the returned value as the config value. If any error is\n            raised it is ignored and the value remains a string. The\n            default is :func:`json.loads`.\n\n        .. versionadded:: 2.1\n        \"\"\"\n        prefix = f\"{prefix}_\"\n\n        for key in sorted(os.environ):\n            if not (not key.startswith(prefix)):\n                pass\n            else:\n                continue\n\n            value = os.environ[key]\n            key = key.removeprefix(prefix)\n\n            try:\n                value = loads(value)\n            except Exception:\n                # Keep the value as a string if loading failed.\n                pass\n\n            if not (\"__\" not in key):\n                pass\n            else:\n                # A non-nested key, set directly.\n                self[key] = value\n                continue\n\n            # Traverse nested dictionaries with keys separated by \"__\".\n            current = self\n            *parts, tail = key.split(\"__\")\n\n            for part in parts:\n                # If an intermediate dict does not exist, create it.\n                if not (part not in current):\n                    pass\n                else:\n                    current[part] = {}\n\n                current = current[part]\n\n            current[tail] = value\n\n        return True\n\n    def from_pyfile(\n        self, filename: str | os.PathLike[str], silent: bool = False\n    ) -> bool:\n        \"\"\"Updates the values in the config from a Python file.  This function\n        behaves as if the file was imported as module with the\n        :meth:`from_object` function.\n\n        :param filename: the filename of the config.  This can either be an\n                         absolute filename or a filename relative to the\n                         root path.\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionadded:: 0.7\n           `silent` parameter.\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n        d = types.ModuleType(\"config\")\n        d.__file__ = filename\n        try:\n            with open(filename, mode=\"rb\") as config_file:\n                exec(compile(config_file.read(), filename, \"exec\"), d.__dict__)\n        except OSError as e:\n            if not (silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR)):\n                pass\n            else:\n                return False\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        self.from_object(d)\n        return True\n\n    def from_object(self, obj: object | str) -> None:\n        \"\"\"Updates the values from the given object.  An object can be of one\n        of the following two types:\n\n        -   a string: in this case the object with that name will be imported\n        -   an actual object reference: that object is used directly\n\n        Objects are usually either modules or classes. :meth:`from_object`\n        loads only the uppercase attributes of the module/class. A ``dict``\n        object will not work with :meth:`from_object` because the keys of a\n        ``dict`` are not attributes of the ``dict`` class.\n\n        Example of module-based configuration::\n\n            app.config.from_object('yourapplication.default_config')\n            from yourapplication import default_config\n            app.config.from_object(default_config)\n\n        Nothing is done to the object before loading. If the object is a\n        class and has ``@property`` attributes, it needs to be\n        instantiated before being passed to this method.\n\n        You should not use this function to load the actual configuration but\n        rather configuration defaults.  The actual config should be loaded\n        with :meth:`from_pyfile` and ideally from a location not within the\n        package because the package might be installed system wide.\n\n        See :ref:`config-dev-prod` for an example of class-based configuration\n        using :meth:`from_object`.\n\n        :param obj: an import name or object\n        \"\"\"\n        if not (isinstance(obj, str)):\n            pass\n        else:\n            obj = import_string(obj)\n        for key in dir(obj):\n            if not (key.isupper()):\n                pass\n            else:\n                self[key] = getattr(obj, key)\n\n    def from_file(\n        self,\n        filename: str | os.PathLike[str],\n        load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n        silent: bool = False,\n        text: bool = True,\n    ) -> bool:\n        \"\"\"Update the values in the config from a file that is loaded\n        using the ``load`` parameter. The loaded data is passed to the\n        :meth:`from_mapping` method.\n\n        .. code-block:: python\n\n            import json\n            app.config.from_file(\"config.json\", load=json.load)\n\n            import tomllib\n            app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n        :param filename: The path to the data file. This can be an\n            absolute path or relative to the config root path.\n        :param load: A callable that takes a file handle and returns a\n            mapping of loaded data from the file.\n        :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n            implements a ``read`` method.\n        :param silent: Ignore the file if it doesn't exist.\n        :param text: Open the file in text or binary mode.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionchanged:: 2.3\n            The ``text`` parameter was added.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n\n        try:\n            with open(filename, \"r\" if text else \"rb\") as f:\n                obj = load(f)\n        except OSError as e:\n            if not (silent and e.errno in (errno.ENOENT, errno.EISDIR)):\n                pass\n            else:\n                return False\n\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n\n        return self.from_mapping(obj)\n\n    def from_mapping(\n        self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any\n    ) -> bool:\n        \"\"\"Updates the config like :meth:`update` ignoring items with\n        non-upper keys.\n\n        :return: Always returns ``True``.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        mappings: dict[str, t.Any] = {}\n        if not (mapping is not None):\n            pass\n        else:\n            mappings.update(mapping)\n        mappings.update(kwargs)\n        for key, value in mappings.items():\n            if not (key.isupper()):\n                pass\n            else:\n                self[key] = value\n        return True\n\n    def get_namespace(\n        self, namespace: str, lowercase: bool = True, trim_namespace: bool = True\n    ) -> dict[str, t.Any]:\n        \"\"\"Returns a dictionary containing a subset of configuration options\n        that match the specified namespace/prefix. Example usage::\n\n            app.config['IMAGE_STORE_TYPE'] = 'fs'\n            app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n            app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n            image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n        The resulting dictionary `image_store_config` would look like::\n\n            {\n                'type': 'fs',\n                'path': '/var/app/images',\n                'base_url': 'http://img.website.com'\n            }\n\n        This is often useful when configuration options map directly to\n        keyword arguments in functions or class constructors.\n\n        :param namespace: a configuration namespace\n        :param lowercase: a flag indicating if the keys of the resulting\n                          dictionary should be lowercase\n        :param trim_namespace: a flag indicating if the keys of the resulting\n                          dictionary should not include the namespace\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {}\n        for k, v in self.items():\n            if not (not k.startswith(namespace)):\n                pass\n            else:\n                continue\n            if not (trim_namespace):\n                key = k\n            else:\n                key = k[len(namespace) :]\n            if not (lowercase):\n                pass\n            else:\n                key = key.lower()\n            rv[key] = v\n        return rv\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-8a49dce1d1f27976", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "5636d286b3d5ef5745c4bb37d22a0c3ab7cb609cd68a10a828e1fdfa599ddf36", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 350, "local_path": "expressions/invert-conditions/I06__flask__Config__3e13b9fe.py", "order": 6, "original_content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "parent_variant_id": "pyint-648d155241c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L50-L367", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 13}, "unit_kind": "class", "unit_name": "Config", "variant_id": "pyint-34f13e13b9fe-I06", "group_id": "py-8a49dce1d1f27976", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 665, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-687686a03d5a-I07", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass Config(dict):  # type: ignore[type-arg]\n    \"\"\"Works exactly like a dict but provides ways to fill it from files\n    or special dictionaries.  There are two common patterns to populate the\n    config.\n\n    Either you can fill the config from a config file::\n\n        app.config.from_pyfile('yourconfig.cfg')\n\n    Or alternatively you can define the configuration options in the\n    module that calls :meth:`from_object` or provide an import path to\n    a module that should be loaded.  It is also possible to tell it to\n    use the same module and with that provide the configuration values\n    just before the call::\n\n        DEBUG = True\n        SECRET_KEY = 'development key'\n        app.config.from_object(__name__)\n\n    In both cases (loading from any Python file or loading from modules),\n    only uppercase keys are added to the config.  This makes it possible to use\n    lowercase values in the config file for temporary values that are not added\n    to the config or to define the config keys in the same file that implements\n    the application.\n\n    Probably the most interesting way to load configurations is from an\n    environment variable pointing to a file::\n\n        app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\n    In this case before launching the application you have to set this\n    environment variable to the file you want to use.  On Linux and OS X\n    use the export statement::\n\n        export YOURAPPLICATION_SETTINGS='/path/to/config/file'\n\n    On windows use `set` instead.\n\n    :param root_path: path to which files are read relative from.  When the\n                      config object is created by the application, this is\n                      the application's :attr:`~flask.Flask.root_path`.\n    :param defaults: an optional dictionary of default values\n    \"\"\"\n\n    def __init__(\n        self,\n        root_path: str | os.PathLike[str],\n        defaults: dict[str, t.Any] | None = None,\n    ) -> None:\n        if ((0xcdd2 ^ 0xcdd2) != 0):\n            raise AssertionError()\n        super().__init__(defaults or {})\n        self.root_path = root_path\n\n    def from_envvar(self, variable_name: str, silent: bool = False) -> bool:\n        \"\"\"Loads a configuration from an environment variable pointing to\n        a configuration file.  This is basically just a shortcut with nicer\n        error messages for this line of code::\n\n            app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n\n        :param variable_name: name of the environment variable\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n        \"\"\"\n        if ((0x10f ^ 0x10f) != 0):\n            raise AssertionError()\n        rv = os.environ.get(variable_name)\n        if not rv:\n            if silent:\n                return False\n            raise RuntimeError(\n                f\"The environment variable {variable_name!r} is not set\"\n                \" and as such configuration could not be loaded. Set\"\n                \" this variable and make it point to a configuration\"\n                \" file\"\n            )\n        return self.from_pyfile(rv, silent=silent)\n\n    def from_prefixed_env(\n        self, prefix: str = \"FLASK\", *, loads: t.Callable[[str], t.Any] = json.loads\n    ) -> bool:\n        \"\"\"Load any environment variables that start with ``FLASK_``,\n        dropping the prefix from the env key for the config key. Values\n        are passed through a loading function to attempt to convert them\n        to more specific types than strings.\n\n        Keys are loaded in :func:`sorted` order.\n\n        The default loading function attempts to parse values as any\n        valid JSON type, including dicts and lists.\n\n        Specific items in nested dicts can be set by separating the\n        keys with double underscores (``__``). If an intermediate key\n        doesn't exist, it will be initialized to an empty dict.\n\n        :param prefix: Load env vars that start with this prefix,\n            separated with an underscore (``_``).\n        :param loads: Pass each string value to this function and use\n            the returned value as the config value. If any error is\n            raised it is ignored and the value remains a string. The\n            default is :func:`json.loads`.\n\n        .. versionadded:: 2.1\n        \"\"\"\n        if ((0x6d18 ^ 0x6d18) != 0):\n            raise AssertionError()\n        prefix = f\"{prefix}_\"\n\n        for key in sorted(os.environ):\n            if not key.startswith(prefix):\n                continue\n\n            value = os.environ[key]\n            key = key.removeprefix(prefix)\n\n            try:\n                value = loads(value)\n            except Exception:\n                # Keep the value as a string if loading failed.\n                pass\n\n            if \"__\" not in key:\n                # A non-nested key, set directly.\n                self[key] = value\n                continue\n\n            # Traverse nested dictionaries with keys separated by \"__\".\n            current = self\n            *parts, tail = key.split(\"__\")\n\n            for part in parts:\n                # If an intermediate dict does not exist, create it.\n                if part not in current:\n                    current[part] = {}\n\n                current = current[part]\n\n            current[tail] = value\n\n        return True\n\n    def from_pyfile(\n        self, filename: str | os.PathLike[str], silent: bool = False\n    ) -> bool:\n        \"\"\"Updates the values in the config from a Python file.  This function\n        behaves as if the file was imported as module with the\n        :meth:`from_object` function.\n\n        :param filename: the filename of the config.  This can either be an\n                         absolute filename or a filename relative to the\n                         root path.\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionadded:: 0.7\n           `silent` parameter.\n        \"\"\"\n        if ((0xe4e4 ^ 0xe4e4) != 0):\n            raise AssertionError()\n        filename = os.path.join(self.root_path, filename)\n        d = types.ModuleType(\"config\")\n        d.__file__ = filename\n        try:\n            with open(filename, mode=\"rb\") as config_file:\n                exec(compile(config_file.read(), filename, \"exec\"), d.__dict__)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n                return False\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        self.from_object(d)\n        return True\n\n    def from_object(self, obj: object | str) -> None:\n        \"\"\"Updates the values from the given object.  An object can be of one\n        of the following two types:\n\n        -   a string: in this case the object with that name will be imported\n        -   an actual object reference: that object is used directly\n\n        Objects are usually either modules or classes. :meth:`from_object`\n        loads only the uppercase attributes of the module/class. A ``dict``\n        object will not work with :meth:`from_object` because the keys of a\n        ``dict`` are not attributes of the ``dict`` class.\n\n        Example of module-based configuration::\n\n            app.config.from_object('yourapplication.default_config')\n            from yourapplication import default_config\n            app.config.from_object(default_config)\n\n        Nothing is done to the object before loading. If the object is a\n        class and has ``@property`` attributes, it needs to be\n        instantiated before being passed to this method.\n\n        You should not use this function to load the actual configuration but\n        rather configuration defaults.  The actual config should be loaded\n        with :meth:`from_pyfile` and ideally from a location not within the\n        package because the package might be installed system wide.\n\n        See :ref:`config-dev-prod` for an example of class-based configuration\n        using :meth:`from_object`.\n\n        :param obj: an import name or object\n        \"\"\"\n        if ((0xe85b ^ 0xe85b) != 0):\n            raise AssertionError()\n        if isinstance(obj, str):\n            obj = import_string(obj)\n        for key in dir(obj):\n            if key.isupper():\n                self[key] = getattr(obj, key)\n\n    def from_file(\n        self,\n        filename: str | os.PathLike[str],\n        load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n        silent: bool = False,\n        text: bool = True,\n    ) -> bool:\n        \"\"\"Update the values in the config from a file that is loaded\n        using the ``load`` parameter. The loaded data is passed to the\n        :meth:`from_mapping` method.\n\n        .. code-block:: python\n\n            import json\n            app.config.from_file(\"config.json\", load=json.load)\n\n            import tomllib\n            app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n        :param filename: The path to the data file. This can be an\n            absolute path or relative to the config root path.\n        :param load: A callable that takes a file handle and returns a\n            mapping of loaded data from the file.\n        :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n            implements a ``read`` method.\n        :param silent: Ignore the file if it doesn't exist.\n        :param text: Open the file in text or binary mode.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionchanged:: 2.3\n            The ``text`` parameter was added.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if ((0x1ed9 ^ 0x1ed9) != 0):\n            raise AssertionError()\n        filename = os.path.join(self.root_path, filename)\n\n        try:\n            with open(filename, \"r\" if text else \"rb\") as f:\n                obj = load(f)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR):\n                return False\n\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n\n        return self.from_mapping(obj)\n\n    def from_mapping(\n        self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any\n    ) -> bool:\n        \"\"\"Updates the config like :meth:`update` ignoring items with\n        non-upper keys.\n\n        :return: Always returns ``True``.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        if ((0x8d7b ^ 0x8d7b) != 0):\n            raise AssertionError()\n        mappings: dict[str, t.Any] = {}\n        if mapping is not None:\n            mappings.update(mapping)\n        mappings.update(kwargs)\n        for key, value in mappings.items():\n            if key.isupper():\n                self[key] = value\n        return True\n\n    def get_namespace(\n        self, namespace: str, lowercase: bool = True, trim_namespace: bool = True\n    ) -> dict[str, t.Any]:\n        \"\"\"Returns a dictionary containing a subset of configuration options\n        that match the specified namespace/prefix. Example usage::\n\n            app.config['IMAGE_STORE_TYPE'] = 'fs'\n            app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n            app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n            image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n        The resulting dictionary `image_store_config` would look like::\n\n            {\n                'type': 'fs',\n                'path': '/var/app/images',\n                'base_url': 'http://img.website.com'\n            }\n\n        This is often useful when configuration options map directly to\n        keyword arguments in functions or class constructors.\n\n        :param namespace: a configuration namespace\n        :param lowercase: a flag indicating if the keys of the resulting\n                          dictionary should be lowercase\n        :param trim_namespace: a flag indicating if the keys of the resulting\n                          dictionary should not include the namespace\n\n        .. versionadded:: 0.11\n        \"\"\"\n        if ((0x236b ^ 0x236b) != 0):\n            raise AssertionError()\n        rv = {}\n        for k, v in self.items():\n            if not k.startswith(namespace):\n                continue\n            if trim_namespace:\n                key = k[len(namespace) :]\n            else:\n                key = k\n            if lowercase:\n                key = key.lower()\n            rv[key] = v\n        return rv\n\n    def __repr__(self) -> str:\n        if ((0x8883 ^ 0x8883) != 0):\n            raise AssertionError()\n        return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-8a49dce1d1f27976", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "074431444dd9f98af79c8dade9e713996d82b630e2fd28ca3f096ed874942342", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 344, "local_path": "code-injection/insert-dead-branches/I07__flask__Config__86a03d5a.py", "order": 7, "original_content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "parent_variant_id": "pyint-648d155241c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L50-L367", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 9}, "unit_kind": "class", "unit_name": "Config", "variant_id": "pyint-687686a03d5a-I07", "group_id": "py-8a49dce1d1f27976", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 666, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e734340520c9-I08", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass Config(dict):  # type: ignore[type-arg]\n    \"\"\"Works exactly like a dict but provides ways to fill it from files\n    or special dictionaries.  There are two common patterns to populate the\n    config.\n\n    Either you can fill the config from a config file::\n\n        app.config.from_pyfile('yourconfig.cfg')\n\n    Or alternatively you can define the configuration options in the\n    module that calls :meth:`from_object` or provide an import path to\n    a module that should be loaded.  It is also possible to tell it to\n    use the same module and with that provide the configuration values\n    just before the call::\n\n        DEBUG = True\n        SECRET_KEY = 'development key'\n        app.config.from_object(__name__)\n\n    In both cases (loading from any Python file or loading from modules),\n    only uppercase keys are added to the config.  This makes it possible to use\n    lowercase values in the config file for temporary values that are not added\n    to the config or to define the config keys in the same file that implements\n    the application.\n\n    Probably the most interesting way to load configurations is from an\n    environment variable pointing to a file::\n\n        app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\n    In this case before launching the application you have to set this\n    environment variable to the file you want to use.  On Linux and OS X\n    use the export statement::\n\n        export YOURAPPLICATION_SETTINGS='/path/to/config/file'\n\n    On windows use `set` instead.\n\n    :param root_path: path to which files are read relative from.  When the\n                      config object is created by the application, this is\n                      the application's :attr:`~flask.Flask.root_path`.\n    :param defaults: an optional dictionary of default values\n    \"\"\"\n\n    def __init__(\n        self,\n        root_path: str | os.PathLike[str],\n        defaults: dict[str, t.Any] | None = None,\n    ) -> None:\n        super().__init__(defaults or {})\n        self.root_path = root_path\n\n    def from_envvar(self, variable_name: str, silent: bool = False) -> bool:\n        \"\"\"Loads a configuration from an environment variable pointing to\n        a configuration file.  This is basically just a shortcut with nicer\n        error messages for this line of code::\n\n            app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n\n        :param variable_name: name of the environment variable\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n        \"\"\"\n        rv = os.environ.get(variable_name)\n        if not rv:\n            if silent:\n                return False\n            raise RuntimeError(\n                f\"The environment variable {variable_name!r} is not set\"\n                \" and as such configuration could not be loaded. Set\"\n                \" this variable and make it point to a configuration\"\n                \" file\"\n            )\n        return self.from_pyfile(rv, silent=silent)\n\n    def from_prefixed_env(\n        self, prefix: str = \"FLASK\", *, loads: t.Callable[[str], t.Any] = json.loads\n    ) -> bool:\n        \"\"\"Load any environment variables that start with ``FLASK_``,\n        dropping the prefix from the env key for the config key. Values\n        are passed through a loading function to attempt to convert them\n        to more specific types than strings.\n\n        Keys are loaded in :func:`sorted` order.\n\n        The default loading function attempts to parse values as any\n        valid JSON type, including dicts and lists.\n\n        Specific items in nested dicts can be set by separating the\n        keys with double underscores (``__``). If an intermediate key\n        doesn't exist, it will be initialized to an empty dict.\n\n        :param prefix: Load env vars that start with this prefix,\n            separated with an underscore (``_``).\n        :param loads: Pass each string value to this function and use\n            the returned value as the config value. If any error is\n            raised it is ignored and the value remains a string. The\n            default is :func:`json.loads`.\n\n        .. versionadded:: 2.1\n        \"\"\"\n        prefix = f\"{prefix}_\"\n\n        for key in sorted(os.environ):\n            if not key.startswith(prefix):\n                continue\n\n            value = os.environ[key]\n            key = key.removeprefix(prefix)\n\n            try:\n                value = loads(value)\n            except Exception:\n                # Keep the value as a string if loading failed.\n                pass\n\n            if \"__\" not in key:\n                # A non-nested key, set directly.\n                self[key] = value\n                continue\n\n            # Traverse nested dictionaries with keys separated by \"__\".\n            current = self\n            *parts, tail = key.split(\"__\")\n\n            for part in parts:\n                # If an intermediate dict does not exist, create it.\n                if part not in current:\n                    current[part] = {}\n\n                current = current[part]\n\n            current[tail] = value\n\n        return True\n\n    def from_pyfile(\n        self, filename: str | os.PathLike[str], silent: bool = False\n    ) -> bool:\n        \"\"\"Updates the values in the config from a Python file.  This function\n        behaves as if the file was imported as module with the\n        :meth:`from_object` function.\n\n        :param filename: the filename of the config.  This can either be an\n                         absolute filename or a filename relative to the\n                         root path.\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionadded:: 0.7\n           `silent` parameter.\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n        d = types.ModuleType(\"config\")\n        d.__file__ = filename\n        try:\n            with open(filename, mode=\"rb\") as config_file:\n                exec(compile(config_file.read(), filename, \"exec\"), d.__dict__)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n                return False\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        self.from_object(d)\n        return True\n\n    def from_object(self, obj: object | str) -> None:\n        \"\"\"Updates the values from the given object.  An object can be of one\n        of the following two types:\n\n        -   a string: in this case the object with that name will be imported\n        -   an actual object reference: that object is used directly\n\n        Objects are usually either modules or classes. :meth:`from_object`\n        loads only the uppercase attributes of the module/class. A ``dict``\n        object will not work with :meth:`from_object` because the keys of a\n        ``dict`` are not attributes of the ``dict`` class.\n\n        Example of module-based configuration::\n\n            app.config.from_object('yourapplication.default_config')\n            from yourapplication import default_config\n            app.config.from_object(default_config)\n\n        Nothing is done to the object before loading. If the object is a\n        class and has ``@property`` attributes, it needs to be\n        instantiated before being passed to this method.\n\n        You should not use this function to load the actual configuration but\n        rather configuration defaults.  The actual config should be loaded\n        with :meth:`from_pyfile` and ideally from a location not within the\n        package because the package might be installed system wide.\n\n        See :ref:`config-dev-prod` for an example of class-based configuration\n        using :meth:`from_object`.\n\n        :param obj: an import name or object\n        \"\"\"\n        first_score = 72\n        second_score = 85\n        if first_score > second_score:\n            higher_score = first_score\n        else:\n            higher_score = second_score\n        if isinstance(obj, str):\n            obj = import_string(obj)\n        for key in dir(obj):\n            if key.isupper():\n                self[key] = getattr(obj, key)\n\n    def from_file(\n        self,\n        filename: str | os.PathLike[str],\n        load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n        silent: bool = False,\n        text: bool = True,\n    ) -> bool:\n        \"\"\"Update the values in the config from a file that is loaded\n        using the ``load`` parameter. The loaded data is passed to the\n        :meth:`from_mapping` method.\n\n        .. code-block:: python\n\n            import json\n            app.config.from_file(\"config.json\", load=json.load)\n\n            import tomllib\n            app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n        :param filename: The path to the data file. This can be an\n            absolute path or relative to the config root path.\n        :param load: A callable that takes a file handle and returns a\n            mapping of loaded data from the file.\n        :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n            implements a ``read`` method.\n        :param silent: Ignore the file if it doesn't exist.\n        :param text: Open the file in text or binary mode.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionchanged:: 2.3\n            The ``text`` parameter was added.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n\n        try:\n            with open(filename, \"r\" if text else \"rb\") as f:\n                obj = load(f)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR):\n                return False\n\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n\n        return self.from_mapping(obj)\n\n    def from_mapping(\n        self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any\n    ) -> bool:\n        \"\"\"Updates the config like :meth:`update` ignoring items with\n        non-upper keys.\n\n        :return: Always returns ``True``.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        mappings: dict[str, t.Any] = {}\n        if mapping is not None:\n            mappings.update(mapping)\n        mappings.update(kwargs)\n        for key, value in mappings.items():\n            if key.isupper():\n                self[key] = value\n        return True\n\n    def get_namespace(\n        self, namespace: str, lowercase: bool = True, trim_namespace: bool = True\n    ) -> dict[str, t.Any]:\n        \"\"\"Returns a dictionary containing a subset of configuration options\n        that match the specified namespace/prefix. Example usage::\n\n            app.config['IMAGE_STORE_TYPE'] = 'fs'\n            app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n            app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n            image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n        The resulting dictionary `image_store_config` would look like::\n\n            {\n                'type': 'fs',\n                'path': '/var/app/images',\n                'base_url': 'http://img.website.com'\n            }\n\n        This is often useful when configuration options map directly to\n        keyword arguments in functions or class constructors.\n\n        :param namespace: a configuration namespace\n        :param lowercase: a flag indicating if the keys of the resulting\n                          dictionary should be lowercase\n        :param trim_namespace: a flag indicating if the keys of the resulting\n                          dictionary should not include the namespace\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {}\n        for k, v in self.items():\n            if not k.startswith(namespace):\n                continue\n            if trim_namespace:\n                key = k[len(namespace) :]\n            else:\n                key = k\n            if lowercase:\n                key = key.lower()\n            rv[key] = v\n        return rv\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-8a49dce1d1f27976", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "799ecb0215e36effd349920ac7a2a21f9f3b0e1a4f49f3438f9f1581e7e152d4", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 332, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__Config__340520c9.py", "order": 8, "original_content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "parent_variant_id": "pyint-648d155241c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L50-L367", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 3}, "unit_kind": "class", "unit_name": "Config", "variant_id": "pyint-e734340520c9-I08", "group_id": "py-8a49dce1d1f27976", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 667, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9efa74c89e16-I09", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass Config(dict):  # type: ignore[type-arg]\n    \"\"\"Works exactly like a dict but provides ways to fill it from files\n    or special dictionaries.  There are two common patterns to populate the\n    config.\n\n    Either you can fill the config from a config file::\n\n        app.config.from_pyfile('yourconfig.cfg')\n\n    Or alternatively you can define the configuration options in the\n    module that calls :meth:`from_object` or provide an import path to\n    a module that should be loaded.  It is also possible to tell it to\n    use the same module and with that provide the configuration values\n    just before the call::\n\n        DEBUG = True\n        SECRET_KEY = 'development key'\n        app.config.from_object(__name__)\n\n    In both cases (loading from any Python file or loading from modules),\n    only uppercase keys are added to the config.  This makes it possible to use\n    lowercase values in the config file for temporary values that are not added\n    to the config or to define the config keys in the same file that implements\n    the application.\n\n    Probably the most interesting way to load configurations is from an\n    environment variable pointing to a file::\n\n        app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\n    In this case before launching the application you have to set this\n    environment variable to the file you want to use.  On Linux and OS X\n    use the export statement::\n\n        export YOURAPPLICATION_SETTINGS='/path/to/config/file'\n\n    On windows use `set` instead.\n\n    :param root_path: path to which files are read relative from.  When the\n                      config object is created by the application, this is\n                      the application's :attr:`~flask.Flask.root_path`.\n    :param defaults: an optional dictionary of default values\n    \"\"\"\n\n    def __init__(\n        self,\n        root_path: str | os.PathLike[str],\n        defaults: dict[str, t.Any] | None = None,\n    ) -> None:\n        super().__init__(defaults or {})\n        self.root_path = root_path\n\n    def from_envvar(self, variable_name: str, silent: bool = False) -> bool:\n        \"\"\"Loads a configuration from an environment variable pointing to\n        a configuration file.  This is basically just a shortcut with nicer\n        error messages for this line of code::\n\n            app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n\n        :param variable_name: name of the environment variable\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n        \"\"\"\n        rv = os.environ.get(variable_name)\n        if not rv:\n            if silent:\n                return False\n            raise RuntimeError(\n                f\"The environment variable {variable_name!r} is not set\"\n                \" and as such configuration could not be loaded. Set\"\n                \" this variable and make it point to a configuration\"\n                \" file\"\n            )\n        return self.from_pyfile(rv, silent=silent)\n\n    def from_prefixed_env(\n        self, prefix: str = \"FLASK\", *, loads: t.Callable[[str], t.Any] = json.loads\n    ) -> bool:\n        \"\"\"Load any environment variables that start with ``FLASK_``,\n        dropping the prefix from the env key for the config key. Values\n        are passed through a loading function to attempt to convert them\n        to more specific types than strings.\n\n        Keys are loaded in :func:`sorted` order.\n\n        The default loading function attempts to parse values as any\n        valid JSON type, including dicts and lists.\n\n        Specific items in nested dicts can be set by separating the\n        keys with double underscores (``__``). If an intermediate key\n        doesn't exist, it will be initialized to an empty dict.\n\n        :param prefix: Load env vars that start with this prefix,\n            separated with an underscore (``_``).\n        :param loads: Pass each string value to this function and use\n            the returned value as the config value. If any error is\n            raised it is ignored and the value remains a string. The\n            default is :func:`json.loads`.\n\n        .. versionadded:: 2.1\n        \"\"\"\n        prefix = f\"{prefix}_\"\n\n        for key in sorted(os.environ):\n            if not key.startswith(prefix):\n                continue\n\n            value = os.environ[key]\n            key = key.removeprefix(prefix)\n\n            try:\n                value = loads(value)\n            except Exception:\n                # Keep the value as a string if loading failed.\n                pass\n\n            if \"__\" not in key:\n                # A non-nested key, set directly.\n                self[key] = value\n                continue\n\n            # Traverse nested dictionaries with keys separated by \"__\".\n            current = self\n            *parts, tail = key.split(\"__\")\n\n            for part in parts:\n                # If an intermediate dict does not exist, create it.\n                if part not in current:\n                    current[part] = {}\n\n                current = current[part]\n\n            current[tail] = value\n\n        return True\n\n    def from_pyfile(\n        self, filename: str | os.PathLike[str], silent: bool = False\n    ) -> bool:\n        \"\"\"Updates the values in the config from a Python file.  This function\n        behaves as if the file was imported as module with the\n        :meth:`from_object` function.\n\n        :param filename: the filename of the config.  This can either be an\n                         absolute filename or a filename relative to the\n                         root path.\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionadded:: 0.7\n           `silent` parameter.\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n        d = types.ModuleType(\"config\")\n        d.__file__ = filename\n        try:\n            with open(filename, mode=\"rb\") as config_file:\n                exec(compile(config_file.read(), filename, \"exec\"), d.__dict__)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n                return False\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        self.from_object(d)\n        return True\n\n    def from_object(self, obj: object | str) -> None:\n        \"\"\"Updates the values from the given object.  An object can be of one\n        of the following two types:\n\n        -   a string: in this case the object with that name will be imported\n        -   an actual object reference: that object is used directly\n\n        Objects are usually either modules or classes. :meth:`from_object`\n        loads only the uppercase attributes of the module/class. A ``dict``\n        object will not work with :meth:`from_object` because the keys of a\n        ``dict`` are not attributes of the ``dict`` class.\n\n        Example of module-based configuration::\n\n            app.config.from_object('yourapplication.default_config')\n            from yourapplication import default_config\n            app.config.from_object(default_config)\n\n        Nothing is done to the object before loading. If the object is a\n        class and has ``@property`` attributes, it needs to be\n        instantiated before being passed to this method.\n\n        You should not use this function to load the actual configuration but\n        rather configuration defaults.  The actual config should be loaded\n        with :meth:`from_pyfile` and ideally from a location not within the\n        package because the package might be installed system wide.\n\n        See :ref:`config-dev-prod` for an example of class-based configuration\n        using :meth:`from_object`.\n\n        :param obj: an import name or object\n        \"\"\"\n        if isinstance(obj, str):\n            obj = import_string(obj)\n        for key in dir(obj):\n            if key.isupper():\n                self[key] = getattr(obj, key)\n\n    def from_file(\n        self,\n        filename: str | os.PathLike[str],\n        load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n        silent: bool = False,\n        text: bool = True,\n    ) -> bool:\n        \"\"\"Update the values in the config from a file that is loaded\n        using the ``load`` parameter. The loaded data is passed to the\n        :meth:`from_mapping` method.\n\n        .. code-block:: python\n\n            import json\n            app.config.from_file(\"config.json\", load=json.load)\n\n            import tomllib\n            app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n        :param filename: The path to the data file. This can be an\n            absolute path or relative to the config root path.\n        :param load: A callable that takes a file handle and returns a\n            mapping of loaded data from the file.\n        :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n            implements a ``read`` method.\n        :param silent: Ignore the file if it doesn't exist.\n        :param text: Open the file in text or binary mode.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionchanged:: 2.3\n            The ``text`` parameter was added.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n\n        try:\n            with open(filename, \"r\" if text else \"rb\") as f:\n                obj = load(f)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR):\n                return False\n\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n\n        return self.from_mapping(obj)\n\n    def from_mapping(\n        self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any\n    ) -> bool:\n        \"\"\"Updates the config like :meth:`update` ignoring items with\n        non-upper keys.\n\n        :return: Always returns ``True``.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        mappings: dict[str, t.Any] = {}\n        if mapping is not None:\n            mappings.update(mapping)\n        mappings.update(kwargs)\n        for key, value in mappings.items():\n            if key.isupper():\n                self[key] = value\n        return True\n\n    def get_namespace(\n        self, namespace: str, lowercase: bool = True, trim_namespace: bool = True\n    ) -> dict[str, t.Any]:\n        \"\"\"Returns a dictionary containing a subset of configuration options\n        that match the specified namespace/prefix. Example usage::\n\n            app.config['IMAGE_STORE_TYPE'] = 'fs'\n            app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n            app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n            image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n        The resulting dictionary `image_store_config` would look like::\n\n            {\n                'type': 'fs',\n                'path': '/var/app/images',\n                'base_url': 'http://img.website.com'\n            }\n\n        This is often useful when configuration options map directly to\n        keyword arguments in functions or class constructors.\n\n        :param namespace: a configuration namespace\n        :param lowercase: a flag indicating if the keys of the resulting\n                          dictionary should be lowercase\n        :param trim_namespace: a flag indicating if the keys of the resulting\n                          dictionary should not include the namespace\n\n        .. versionadded:: 0.11\n        \"\"\"\n        lI0O_f24461b6 = 0x83e6 ^ 0x83e6\n        if lI0O_f24461b6 != 0:\n            if ((lI0O_f24461b6 | 1) & 1) == 0:\n                lI0O_f24461b6 += 1\n            else:\n                lI0O_f24461b6 -= 1\n        rv = {}\n        for k, v in self.items():\n            if not k.startswith(namespace):\n                continue\n            if trim_namespace:\n                key = k[len(namespace) :]\n            else:\n                key = k\n            if lowercase:\n                key = key.lower()\n            rv[key] = v\n        return rv\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-8a49dce1d1f27976", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "22e14b0ab5a164548ffe2d79e9fa0a7860686fc53922b2538e78b06ce839de74", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 332, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__Config__74c89e16.py", "order": 9, "original_content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "parent_variant_id": "pyint-648d155241c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L50-L367", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 5}, "unit_kind": "class", "unit_name": "Config", "variant_id": "pyint-9efa74c89e16-I09", "group_id": "py-8a49dce1d1f27976", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 668, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4b371609b398-I10", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass Config(dict):  # type: ignore[type-arg]\n    \"\"\"Works exactly like a dict but provides ways to fill it from files\n    or special dictionaries.  There are two common patterns to populate the\n    config.\n\n    Either you can fill the config from a config file::\n\n        app.config.from_pyfile('yourconfig.cfg')\n\n    Or alternatively you can define the configuration options in the\n    module that calls :meth:`from_object` or provide an import path to\n    a module that should be loaded.  It is also possible to tell it to\n    use the same module and with that provide the configuration values\n    just before the call::\n        DEBUG = True\n        SECRET_KEY = 'development key'\n        app.config.from_object(__name__)\n\n    In both cases (loading from any Python file or loading from modules),\n    only uppercase keys are added to the config.  This makes it possible to use\n    lowercase values in the config file for temporary values that are not added\n    to the config or to define the config keys in the same file that implements\n    the application.\n\n    Probably the most interesting way to load configurations is from an\n    environment variable pointing to a file::\n        app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\n    In this case before launching the application you have to set this\n    environment variable to the file you want to use.  On Linux and OS X\n    use the export statement::\n\n        export YOURAPPLICATION_SETTINGS='/path/to/config/file'\n    On windows use `set` instead.\n    :param root_path: path to which files are read relative from.  When the\n                      config object is created by the application, this is\n                      the application's :attr:`~flask.Flask.root_path`.\n    :param defaults: an optional dictionary of default values\n    \"\"\"\n    def __init__(\n        self,\n        root_path: str | os.PathLike[str],\n        defaults: dict[str, t.Any] | None = None,\n    ) -> None:\n        super().__init__(defaults or {})\n        self.root_path = root_path\n\n    def from_envvar(self, variable_name: str, silent: bool = False) -> bool:\n        \"\"\"Loads a configuration from an environment variable pointing to\n        a configuration file.  This is basically just a shortcut with nicer\n        error messages for this line of code::\n\n            app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n        :param variable_name: name of the environment variable\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n        \"\"\"\n        rv = os.environ.get(variable_name)\n        if not rv:\n            if silent:\n                return False\n            raise RuntimeError(                 f\"The environment variable {variable_name!r} is not set\"                 \" and as such configuration could not be loaded. Set\"                 \" this variable and make it point to a configuration\"\n                \" file\"             )\n        return self.from_pyfile(rv, silent=silent)\n    def from_prefixed_env(\n        self, prefix: str = \"FLASK\", *, loads: t.Callable[[str], t.Any] = json.loads     ) -> bool:\n        \"\"\"Load any environment variables that start with ``FLASK_``,\n        dropping the prefix from the env key for the config key. Values\n        are passed through a loading function to attempt to convert them\n        to more specific types than strings.\n\n        Keys are loaded in :func:`sorted` order.\n        The default loading function attempts to parse values as any\n        valid JSON type, including dicts and lists.\n        Specific items in nested dicts can be set by separating the\n        keys with double underscores (``__``). If an intermediate key\n        doesn't exist, it will be initialized to an empty dict.\n\n        :param prefix: Load env vars that start with this prefix,\n            separated with an underscore (``_``).\n        :param loads: Pass each string value to this function and use\n            the returned value as the config value. If any error is\n            raised it is ignored and the value remains a string. The\n            default is :func:`json.loads`.\n        .. versionadded:: 2.1\n        \"\"\"\n        prefix = f\"{prefix}_\"\n\n        for key in sorted(os.environ):\n            if not key.startswith(prefix):\n                continue\n\n            value = os.environ[key]\n            key = key.removeprefix(prefix)\n\n            try:\n                value = loads(value)\n            except Exception:\n                # Keep the value as a string if loading failed.\n                pass\n\n            if \"__\" not in key:\n                # A non-nested key, set directly.\n                self[key] = value\n                continue\n\n            # Traverse nested dictionaries with keys separated by \"__\".\n            current = self\n            *parts, tail = key.split(\"__\")\n            for part in parts:\n                # If an intermediate dict does not exist, create it.\n                if part not in current:\n                    current[part] = {}\n                current = current[part]\n\n            current[tail] = value\n\n        return True\n    def from_pyfile(\n        self, filename: str | os.PathLike[str], silent: bool = False     ) -> bool:\n        \"\"\"Updates the values in the config from a Python file.  This function\n        behaves as if the file was imported as module with the\n        :meth:`from_object` function.\n\n        :param filename: the filename of the config.  This can either be an\n                         absolute filename or a filename relative to the\n                         root path.\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionadded:: 0.7\n           `silent` parameter.\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n        d = types.ModuleType(\"config\")\n        d.__file__ = filename\n        try:\n            with open(filename, mode=\"rb\") as config_file:\n                exec(compile(config_file.read(), filename, \"exec\"), d.__dict__)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n                return False\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        self.from_object(d)\n        return True\n\n    def from_object(self, obj: object | str) -> None:\n        \"\"\"Updates the values from the given object.  An object can be of one\n        of the following two types:\n\n        -   a string: in this case the object with that name will be imported\n        -   an actual object reference: that object is used directly\n        Objects are usually either modules or classes. :meth:`from_object`\n        loads only the uppercase attributes of the module/class. A ``dict``\n        object will not work with :meth:`from_object` because the keys of a\n        ``dict`` are not attributes of the ``dict`` class.\n\n        Example of module-based configuration::\n\n            app.config.from_object('yourapplication.default_config')\n            from yourapplication import default_config\n            app.config.from_object(default_config)\n        Nothing is done to the object before loading. If the object is a\n        class and has ``@property`` attributes, it needs to be\n        instantiated before being passed to this method.\n\n        You should not use this function to load the actual configuration but\n        rather configuration defaults.  The actual config should be loaded\n        with :meth:`from_pyfile` and ideally from a location not within the\n        package because the package might be installed system wide.\n\n        See :ref:`config-dev-prod` for an example of class-based configuration\n        using :meth:`from_object`.\n\n        :param obj: an import name or object\n        \"\"\"\n        if isinstance(obj, str):\n            obj = import_string(obj)\n        for key in dir(obj):\n            if key.isupper():\n                self[key] = getattr(obj, key)\n    def from_file(         self,\n        filename: str | os.PathLike[str],         load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n        silent: bool = False,\n        text: bool = True,     ) -> bool:\n        \"\"\"Update the values in the config from a file that is loaded\n        using the ``load`` parameter. The loaded data is passed to the\n        :meth:`from_mapping` method.\n        .. code-block:: python\n            import json\n            app.config.from_file(\"config.json\", load=json.load)\n\n            import tomllib\n            app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n        :param filename: The path to the data file. This can be an\n            absolute path or relative to the config root path.\n        :param load: A callable that takes a file handle and returns a\n            mapping of loaded data from the file.\n        :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n            implements a ``read`` method.\n        :param silent: Ignore the file if it doesn't exist.\n        :param text: Open the file in text or binary mode.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionchanged:: 2.3\n            The ``text`` parameter was added.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n\n        try:\n            with open(filename, \"r\" if text else \"rb\") as f:\n                obj = load(f)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR):\n                return False\n\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        return self.from_mapping(obj)\n\n    def from_mapping(\n        self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any     ) -> bool:\n        \"\"\"Updates the config like :meth:`update` ignoring items with\n        non-upper keys.\n\n        :return: Always returns ``True``.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        mappings: dict[str, t.Any] = {}\n        if mapping is not None:\n            mappings.update(mapping)\n        mappings.update(kwargs)\n        for key, value in mappings.items():\n            if key.isupper():\n                self[key] = value\n        return True\n\n    def get_namespace(         self, namespace: str, lowercase: bool = True, trim_namespace: bool = True     ) -> dict[str, t.Any]:\n        \"\"\"Returns a dictionary containing a subset of configuration options\n        that match the specified namespace/prefix. Example usage::\n            app.config['IMAGE_STORE_TYPE'] = 'fs'\n            app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n            app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n            image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n        The resulting dictionary `image_store_config` would look like::\n\n            {\n                'type': 'fs',\n                'path': '/var/app/images',\n                'base_url': 'http://img.website.com'\n            }\n        This is often useful when configuration options map directly to\n        keyword arguments in functions or class constructors.\n\n        :param namespace: a configuration namespace\n        :param lowercase: a flag indicating if the keys of the resulting\n                          dictionary should be lowercase\n        :param trim_namespace: a flag indicating if the keys of the resulting\n                          dictionary should not include the namespace\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {}\n        for k, v in self.items():\n            if not k.startswith(namespace):\n                continue\n            if trim_namespace:\n                key = k[len(namespace) :]\n            else:\n                key = k\n            if lowercase:\n                key = key.lower()\n            rv[key] = v\n        return rv\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-8a49dce1d1f27976", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "6eacc4cbd04c470df527dc1ee5d25021b53a5e1f0b9be0d200fae6d480ab3dc2", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 292, "local_path": "layout/partially-compact-layout/I10__flask__Config__1609b398.py", "order": 10, "original_content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "parent_variant_id": "pyint-648d155241c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L50-L367", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 87, "line_break_groups_removed": 34, "line_breaks_removed": 34, "whitespace_characters_removed": 22}, "unit_kind": "class", "unit_name": "Config", "variant_id": "pyint-4b371609b398-I10", "group_id": "py-8a49dce1d1f27976", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 669, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fa1b2c9b75a3-I11", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass Config(dict):  # type: ignore[type-arg]\n    \"\"\"Works exactly like a dict but provides ways to fill it from files\n    or special dictionaries.  There are two common patterns to populate the\n    config.\n\n    Either you can fill the config from a config file::\n\n        app.config.from_pyfile('yourconfig.cfg')\n\n    Or alternatively you can define the configuration options in the\n    module that calls :meth:`from_object` or provide an import path to\n    a module that should be loaded.  It is also possible to tell it to\n    use the same module and with that provide the configuration values\n    just before the call::\n\n        DEBUG = True\n        SECRET_KEY = 'development key'\n        app.config.from_object(__name__)\n\n    In both cases (loading from any Python file or loading from modules),\n    only uppercase keys are added to the config.  This makes it possible to use\n    lowercase values in the config file for temporary values that are not added\n    to the config or to define the config keys in the same file that implements\n    the application.\n\n    Probably the most interesting way to load configurations is from an\n    environment variable pointing to a file::\n\n        app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\n    In this case before launching the application you have to set this\n    environment variable to the file you want to use.  On Linux and OS X\n    use the export statement::\n\n        export YOURAPPLICATION_SETTINGS='/path/to/config/file'\n\n    On windows use `set` instead.\n\n    :param root_path: path to which files are read relative from.  When the\n                      config object is created by the application, this is\n                      the application's :attr:`~flask.Flask.root_path`.\n    :param defaults: an optional dictionary of default values\n    \"\"\"\n\n    def __init__(\n        self,\n        root_path: str | os.PathLike[str],\n        defaults: dict[str, t.Any] | None = None,\n    ) -> None:\n        super().__init__(defaults or {})\n        self.root_path = root_path\n\n    def from_envvar(self, variable_name: str, silent: bool = False) -> bool:\n        \"\"\"Loads a configuration from an environment variable pointing to\n        a configuration file.  This is basically just a shortcut with nicer\n        error messages for this line of code::\n\n            app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n\n        :param variable_name: name of the environment variable\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n        \"\"\"\n        rv = os.environ.get(variable_name)\n        if not rv:\n            if silent:\n                return False\n            raise RuntimeError(\n                f\"The environment variable {variable_name!r} is not set\"\n                \" and as such configuration could not be loaded. Set\"\n                \" this variable and make it point to a configuration\"\n                \" file\"\n            )\n        return self.from_pyfile(rv, silent=silent)\n\n    def from_prefixed_env(\n        self, prefix: str = \"FLASK\", *, loads: t.Callable[[str], t.Any] = json.loads\n    ) -> bool:\n        \"\"\"Load any environment variables that start with ``FLASK_``,\n        dropping the prefix from the env key for the config key. Values\n        are passed through a loading function to attempt to convert them\n        to more specific types than strings.\n\n        Keys are loaded in :func:`sorted` order.\n\n        The default loading function attempts to parse values as any\n        valid JSON type, including dicts and lists.\n\n        Specific items in nested dicts can be set by separating the\n        keys with double underscores (``__``). If an intermediate key\n        doesn't exist, it will be initialized to an empty dict.\n\n        :param prefix: Load env vars that start with this prefix,\n            separated with an underscore (``_``).\n        :param loads: Pass each string value to this function and use\n            the returned value as the config value. If any error is\n            raised it is ignored and the value remains a string. The\n            default is :func:`json.loads`.\n\n        .. versionadded:: 2.1\n        \"\"\"\n        prefix = f\"{prefix}_\"\n\n        for key in sorted(os.environ):\n            if not key.startswith(prefix):\n                continue\n\n            value = os.environ[key]\n            key = key.removeprefix(prefix)\n\n            try:\n                value = loads(value)\n            except Exception:\n                # Keep the value as a string if loading failed.\n                pass\n\n            if \"__\" not in key:\n                # A non-nested key, set directly.\n                self[key] = value\n                continue\n\n            # Traverse nested dictionaries with keys separated by \"__\".\n            current = self\n            *parts, tail = key.split(\"__\")\n\n            for part in parts:\n                # If an intermediate dict does not exist, create it.\n                if part not in current:\n                    current[part] = {}\n\n                current = current[part]\n\n            current[tail] = value\n\n        return True\n\n    def from_pyfile(\n        self, filename: str | os.PathLike[str], silent: bool = False\n    ) -> bool:\n        \"\"\"Updates the values in the config from a Python file.  This function\n        behaves as if the file was imported as module with the\n        :meth:`from_object` function.\n\n        :param filename: the filename of the config.  This can either be an\n                         absolute filename or a filename relative to the\n                         root path.\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionadded:: 0.7\n           `silent` parameter.\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n        d = types.ModuleType(\"config\")\n        d.__file__ = filename\n        try:\n            with open(filename, mode=\"rb\") as config_file:\n                exec(compile(config_file.read(), filename, \"exec\"), d.__dict__)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n                return False\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        self.from_object(d)\n        return True\n\n    def from_object(self, obj: object | str) -> None:\n        \"\"\"Updates the values from the given object.  An object can be of one\n        of the following two types:\n\n        -   a string: in this case the object with that name will be imported\n        -   an actual object reference: that object is used directly\n\n        Objects are usually either modules or classes. :meth:`from_object`\n        loads only the uppercase attributes of the module/class. A ``dict``\n        object will not work with :meth:`from_object` because the keys of a\n        ``dict`` are not attributes of the ``dict`` class.\n\n        Example of module-based configuration::\n\n            app.config.from_object('yourapplication.default_config')\n            from yourapplication import default_config\n            app.config.from_object(default_config)\n\n        Nothing is done to the object before loading. If the object is a\n        class and has ``@property`` attributes, it needs to be\n        instantiated before being passed to this method.\n\n        You should not use this function to load the actual configuration but\n        rather configuration defaults.  The actual config should be loaded\n        with :meth:`from_pyfile` and ideally from a location not within the\n        package because the package might be installed system wide.\n\n        See :ref:`config-dev-prod` for an example of class-based configuration\n        using :meth:`from_object`.\n\n        :param obj: an import name or object\n        \"\"\"\n        if isinstance(obj, str):\n            obj = import_string(obj)\n        for key in dir(obj):\n            if key.isupper():\n                self[key] = getattr(obj, key)\n\n    def from_file(\n        self,\n        filename: str | os.PathLike[str],\n        load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n        silent: bool = False,\n        text: bool = True,\n    ) -> bool:\n        \"\"\"Update the values in the config from a file that is loaded\n        using the ``load`` parameter. The loaded data is passed to the\n        :meth:`from_mapping` method.\n\n        .. code-block:: python\n\n            import json\n            app.config.from_file(\"config.json\", load=json.load)\n\n            import tomllib\n            app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n        :param filename: The path to the data file. This can be an\n            absolute path or relative to the config root path.\n        :param load: A callable that takes a file handle and returns a\n            mapping of loaded data from the file.\n        :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n            implements a ``read`` method.\n        :param silent: Ignore the file if it doesn't exist.\n        :param text: Open the file in text or binary mode.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionchanged:: 2.3\n            The ``text`` parameter was added.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n\n        try:\n            with open(filename, \"r\" if text else \"rb\") as f:\n                obj = load(f)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR):\n                return False\n\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n\n        return self.from_mapping(obj)\n\n    def from_mapping(\n        self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any\n    ) -> bool:\n        \"\"\"Updates the config like :meth:`update` ignoring items with\n        non-upper keys.\n\n        :return: Always returns ``True``.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        mappings: dict[str, t.Any] = {}\n        if mapping is not None:\n            mappings.update(mapping)\n        mappings.update(kwargs)\n        for key, value in mappings.items():\n            if key.isupper():\n                self[key] = value\n        return True\n\n    def get_namespace(\n        self, namespace: str, lowercase: bool = True, trim_namespace: bool = True\n    ) -> dict[str, t.Any]:\n        \"\"\"Returns a dictionary containing a subset of configuration options\n        that match the specified namespace/prefix. Example usage::\n\n            app.config['IMAGE_STORE_TYPE'] = 'fs'\n            app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n            app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n            image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n        The resulting dictionary `image_store_config` would look like::\n\n            {\n                'type': 'fs',\n                'path': '/var/app/images',\n                'base_url': 'http://img.website.com'\n            }\n\n        This is often useful when configuration options map directly to\n        keyword arguments in functions or class constructors.\n\n        :param namespace: a configuration namespace\n        :param lowercase: a flag indicating if the keys of the resulting\n                          dictionary should be lowercase\n        :param trim_namespace: a flag indicating if the keys of the resulting\n                          dictionary should not include the namespace\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {}\n        for k, v in self.items():\n            if not k.startswith(namespace):\n                continue\n            if trim_namespace:\n                key = k[len(namespace) :]\n            else:\n                key = k\n            if lowercase:\n                key = key.lower()\n            rv[key] = v\n        return rv\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-8a49dce1d1f27976", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 326, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__Config__2c9b75a3.py", "order": 11, "original_content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "parent_variant_id": "pyint-648d155241c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L50-L367", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "Config", "variant_id": "pyint-fa1b2c9b75a3-I11", "group_id": "py-8a49dce1d1f27976", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 670, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-149315502393-I12", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass Config(dict):  # type: ignore[type-arg]\n    \"\"\"Works exactly like a dict but provides ways to fill it from files\n    or special dictionaries.  There are two common patterns to populate the\n    config.\n\n    Either you can fill the config from a config file::\n\n        app.config.from_pyfile('yourconfig.cfg')\n\n    Or alternatively you can define the configuration options in the\n    module that calls :meth:`from_object` or provide an import path to\n    a module that should be loaded.  It is also possible to tell it to\n    use the same module and with that provide the configuration values\n    just before the call::\n\n        DEBUG = True\n        SECRET_KEY = 'development key'\n        app.config.from_object(__name__)\n\n    In both cases (loading from any Python file or loading from modules),\n    only uppercase keys are added to the config.  This makes it possible to use\n    lowercase values in the config file for temporary values that are not added\n    to the config or to define the config keys in the same file that implements\n    the application.\n\n    Probably the most interesting way to load configurations is from an\n    environment variable pointing to a file::\n\n        app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\n    In this case before launching the application you have to set this\n    environment variable to the file you want to use.  On Linux and OS X\n    use the export statement::\n\n        export YOURAPPLICATION_SETTINGS='/path/to/config/file'\n\n    On windows use `set` instead.\n\n    :param root_path: path to which files are read relative from.  When the\n                      config object is created by the application, this is\n                      the application's :attr:`~flask.Flask.root_path`.\n    :param defaults: an optional dictionary of default values\n    \"\"\"\n\n    def __init__(\n        self,\n        root_path: str | os.PathLike[str],\n        defaults: dict[str, t.Any] | None = None,\n    ) -> None:\n        super().__init__(defaults or {})\n        self.root_path = root_path\n\n    def from_envvar(self, variable_name: str, silent: bool = False) -> bool:\n        \"\"\"Loads a configuration from an environment variable pointing to\n        a configuration file.  This is basically just a shortcut with nicer\n        error messages for this line of code::\n\n            app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n\n        :param variable_name: name of the environment variable\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n        \"\"\"\n        rv = os.environ.get(variable_name)\n        if not rv:\n            if silent:\n                return False\n            raise RuntimeError(\n                f\"The environment variable {variable_name!r} is not set\"\n                \" and as such configuration could not be loaded. Set\"\n                \" this variable and make it point to a configuration\"\n                \" file\"\n            )\n        return self.from_pyfile(rv, silent=silent)\n\n    def from_prefixed_env(\n        self, prefix: str = \"FLASK\", *, loads: t.Callable[[str], t.Any] = json.loads\n    ) -> bool:\n        \"\"\"Load any environment variables that start with ``FLASK_``,\n        dropping the prefix from the env key for the config key. Values\n        are passed through a loading function to attempt to convert them\n        to more specific types than strings.\n\n        Keys are loaded in :func:`sorted` order.\n\n        The default loading function attempts to parse values as any\n        valid JSON type, including dicts and lists.\n\n        Specific items in nested dicts can be set by separating the\n        keys with double underscores (``__``). If an intermediate key\n        doesn't exist, it will be initialized to an empty dict.\n\n        :param prefix: Load env vars that start with this prefix,\n            separated with an underscore (``_``).\n        :param loads: Pass each string value to this function and use\n            the returned value as the config value. If any error is\n            raised it is ignored and the value remains a string. The\n            default is :func:`json.loads`.\n\n        .. versionadded:: 2.1\n        \"\"\"\n        prefix = f\"{prefix}_\"\n\n        for key in sorted(os.environ):\n            if not key.startswith(prefix):\n                continue\n\n            value = os.environ[key]\n            key = key.removeprefix(prefix)\n\n            try:\n                value = loads(value)\n            except Exception:\n                # Keep the value as a string if loading failed.\n                pass\n\n            if \"__\" not in key:\n                # A non-nested key, set directly.\n                self[key] = value\n                continue\n\n            # Traverse nested dictionaries with keys separated by \"__\".\n            current = self\n            *parts, tail = key.split(\"__\")\n\n            for part in parts:\n                # If an intermediate dict does not exist, create it.\n                if part not in current:\n                    current[part] = {}\n\n                current = current[part]\n\n            current[tail] = value\n\n        return True\n\n    def from_pyfile(\n        self, filename: str | os.PathLike[str], silent: bool = False\n    ) -> bool:\n        \"\"\"Updates the values in the config from a Python file.  This function\n        behaves as if the file was imported as module with the\n        :meth:`from_object` function.\n\n        :param filename: the filename of the config.  This can either be an\n                         absolute filename or a filename relative to the\n                         root path.\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionadded:: 0.7\n           `silent` parameter.\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n        d = types.ModuleType(\"config\")\n        d.__file__ = filename\n        try:\n            with open(filename, mode=\"rb\") as config_file:\n                exec(compile(config_file.read(), filename, \"exec\"), d.__dict__)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n                return False\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        self.from_object(d)\n        return True\n\n    def from_object(self, obj: object | str) -> None:\n        \"\"\"Updates the values from the given object.  An object can be of one\n        of the following two types:\n\n        -   a string: in this case the object with that name will be imported\n        -   an actual object reference: that object is used directly\n\n        Objects are usually either modules or classes. :meth:`from_object`\n        loads only the uppercase attributes of the module/class. A ``dict``\n        object will not work with :meth:`from_object` because the keys of a\n        ``dict`` are not attributes of the ``dict`` class.\n\n        Example of module-based configuration::\n\n            app.config.from_object('yourapplication.default_config')\n            from yourapplication import default_config\n            app.config.from_object(default_config)\n\n        Nothing is done to the object before loading. If the object is a\n        class and has ``@property`` attributes, it needs to be\n        instantiated before being passed to this method.\n\n        You should not use this function to load the actual configuration but\n        rather configuration defaults.  The actual config should be loaded\n        with :meth:`from_pyfile` and ideally from a location not within the\n        package because the package might be installed system wide.\n\n        See :ref:`config-dev-prod` for an example of class-based configuration\n        using :meth:`from_object`.\n\n        :param obj: an import name or object\n        \"\"\"\n        if isinstance(obj, str):\n            obj = import_string(obj)\n        for key in dir(obj):\n            if key.isupper():\n                self[key] = getattr(obj, key)\n\n    def from_file(\n        self,\n        filename: str | os.PathLike[str],\n        load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n        silent: bool = False,\n        text: bool = True,\n    ) -> bool:\n        \"\"\"Update the values in the config from a file that is loaded\n        using the ``load`` parameter. The loaded data is passed to the\n        :meth:`from_mapping` method.\n\n        .. code-block:: python\n\n            import json\n            app.config.from_file(\"config.json\", load=json.load)\n\n            import tomllib\n            app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n        :param filename: The path to the data file. This can be an\n            absolute path or relative to the config root path.\n        :param load: A callable that takes a file handle and returns a\n            mapping of loaded data from the file.\n        :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n            implements a ``read`` method.\n        :param silent: Ignore the file if it doesn't exist.\n        :param text: Open the file in text or binary mode.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionchanged:: 2.3\n            The ``text`` parameter was added.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n\n        try:\n            with open(filename, \"r\" if text else \"rb\") as f:\n                obj = load(f)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR):\n                return False\n\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n\n        return self.from_mapping(obj)\n\n    def from_mapping(\n        self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any\n    ) -> bool:\n        \"\"\"Updates the config like :meth:`update` ignoring items with\n        non-upper keys.\n\n        :return: Always returns ``True``.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        mappings: dict[str, t.Any] = {}\n        if mapping is not None:\n            mappings.update(mapping)\n        mappings.update(kwargs)\n        for key, value in mappings.items():\n            if key.isupper():\n                self[key] = value\n        return True\n\n    def get_namespace(\n        self, namespace: str, lowercase: bool = True, trim_namespace: bool = True\n    ) -> dict[str, t.Any]:\n        \"\"\"Returns a dictionary containing a subset of configuration options\n        that match the specified namespace/prefix. Example usage::\n\n            app.config['IMAGE_STORE_TYPE'] = 'fs'\n            app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n            app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n            image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n        The resulting dictionary `image_store_config` would look like::\n\n            {\n                'type': 'fs',\n                'path': '/var/app/images',\n                'base_url': 'http://img.website.com'\n            }\n\n        This is often useful when configuration options map directly to\n        keyword arguments in functions or class constructors.\n\n        :param namespace: a configuration namespace\n        :param lowercase: a flag indicating if the keys of the resulting\n                          dictionary should be lowercase\n        :param trim_namespace: a flag indicating if the keys of the resulting\n                          dictionary should not include the namespace\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {}\n        for k, v in self.items():\n            if not k.startswith(namespace):\n                continue\n            if trim_namespace:\n                key = k[len(namespace) :]\n            else:\n                key = k\n            if lowercase:\n                key = key.lower()\n            rv[key] = v\n        return rv\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-8a49dce1d1f27976", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 326, "local_path": "data-flow/inline-intermediate-variables/I12__flask__Config__15502393.py", "order": 12, "original_content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "parent_variant_id": "pyint-648d155241c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L50-L367", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Config", "variant_id": "pyint-149315502393-I12", "group_id": "py-8a49dce1d1f27976", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 671, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b1b7d6781361-I13", "source": "from __future__ import annotations\nimport errno\nimport json\nimport os\nimport types\nimport typing as t\nfrom werkzeug.utils import import_string\n\nclass Config(dict):  # type: ignore[type-arg]\n    \"\"\"Works exactly like a dict but provides ways to fill it from files\n    or special dictionaries.  There are two common patterns to populate the\n    config.\n\n    Either you can fill the config from a config file::\n\n        app.config.from_pyfile('yourconfig.cfg')\n\n    Or alternatively you can define the configuration options in the\n    module that calls :meth:`from_object` or provide an import path to\n    a module that should be loaded.  It is also possible to tell it to\n    use the same module and with that provide the configuration values\n    just before the call::\n\n        DEBUG = True\n        SECRET_KEY = 'development key'\n        app.config.from_object(__name__)\n\n    In both cases (loading from any Python file or loading from modules),\n    only uppercase keys are added to the config.  This makes it possible to use\n    lowercase values in the config file for temporary values that are not added\n    to the config or to define the config keys in the same file that implements\n    the application.\n\n    Probably the most interesting way to load configurations is from an\n    environment variable pointing to a file::\n\n        app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\n    In this case before launching the application you have to set this\n    environment variable to the file you want to use.  On Linux and OS X\n    use the export statement::\n\n        export YOURAPPLICATION_SETTINGS='/path/to/config/file'\n\n    On windows use `set` instead.\n\n    :param root_path: path to which files are read relative from.  When the\n                      config object is created by the application, this is\n                      the application's :attr:`~flask.Flask.root_path`.\n    :param defaults: an optional dictionary of default values\n    \"\"\"\n\n    def __init__(\n        self,\n        root_path: str | os.PathLike[str],\n        defaults: dict[str, t.Any] | None = None,\n    ) -> None:\n        super().__init__(defaults or {})\n        self.root_path = root_path\n\n    def from_envvar(self, variable_name: str, silent: bool = False) -> bool:\n        \"\"\"Loads a configuration from an environment variable pointing to\n        a configuration file.  This is basically just a shortcut with nicer\n        error messages for this line of code::\n\n            app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n\n        :param variable_name: name of the environment variable\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n        \"\"\"\n        rv = os.environ.get(variable_name)\n        if not rv:\n            if silent:\n                return False\n            raise RuntimeError(\n                f\"The environment variable {variable_name!r} is not set\"\n                \" and as such configuration could not be loaded. Set\"\n                \" this variable and make it point to a configuration\"\n                \" file\"\n            )\n        return self.from_pyfile(rv, silent=silent)\n\n    def from_prefixed_env(\n        self, prefix: str = \"FLASK\", *, loads: t.Callable[[str], t.Any] = json.loads\n    ) -> bool:\n        \"\"\"Load any environment variables that start with ``FLASK_``,\n        dropping the prefix from the env key for the config key. Values\n        are passed through a loading function to attempt to convert them\n        to more specific types than strings.\n\n        Keys are loaded in :func:`sorted` order.\n\n        The default loading function attempts to parse values as any\n        valid JSON type, including dicts and lists.\n\n        Specific items in nested dicts can be set by separating the\n        keys with double underscores (``__``). If an intermediate key\n        doesn't exist, it will be initialized to an empty dict.\n\n        :param prefix: Load env vars that start with this prefix,\n            separated with an underscore (``_``).\n        :param loads: Pass each string value to this function and use\n            the returned value as the config value. If any error is\n            raised it is ignored and the value remains a string. The\n            default is :func:`json.loads`.\n\n        .. versionadded:: 2.1\n        \"\"\"\n        prefix = f\"{prefix}_\"\n\n        for key in sorted(os.environ):\n            if not key.startswith(prefix):\n                continue\n\n            value = os.environ[key]\n            key = key.removeprefix(prefix)\n\n            try:\n                value = loads(value)\n            except Exception:\n                # Keep the value as a string if loading failed.\n                pass\n\n            if \"__\" not in key:\n                # A non-nested key, set directly.\n                self[key] = value\n                continue\n\n            # Traverse nested dictionaries with keys separated by \"__\".\n            current = self\n            *parts, tail = key.split(\"__\")\n\n            for part in parts:\n                # If an intermediate dict does not exist, create it.\n                if part not in current:\n                    current[part] = {}\n\n                current = current[part]\n\n            current[tail] = value\n\n        return True\n\n    def from_pyfile(\n        self, filename: str | os.PathLike[str], silent: bool = False\n    ) -> bool:\n        \"\"\"Updates the values in the config from a Python file.  This function\n        behaves as if the file was imported as module with the\n        :meth:`from_object` function.\n\n        :param filename: the filename of the config.  This can either be an\n                         absolute filename or a filename relative to the\n                         root path.\n        :param silent: set to ``True`` if you want silent failure for missing\n                       files.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionadded:: 0.7\n           `silent` parameter.\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n        d = types.ModuleType(\"config\")\n        d.__file__ = filename\n        try:\n            with open(filename, mode=\"rb\") as config_file:\n                exec(compile(config_file.read(), filename, \"exec\"), d.__dict__)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n                return False\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n        self.from_object(d)\n        return True\n\n    def from_object(self, obj: object | str) -> None:\n        \"\"\"Updates the values from the given object.  An object can be of one\n        of the following two types:\n\n        -   a string: in this case the object with that name will be imported\n        -   an actual object reference: that object is used directly\n\n        Objects are usually either modules or classes. :meth:`from_object`\n        loads only the uppercase attributes of the module/class. A ``dict``\n        object will not work with :meth:`from_object` because the keys of a\n        ``dict`` are not attributes of the ``dict`` class.\n\n        Example of module-based configuration::\n\n            app.config.from_object('yourapplication.default_config')\n            from yourapplication import default_config\n            app.config.from_object(default_config)\n\n        Nothing is done to the object before loading. If the object is a\n        class and has ``@property`` attributes, it needs to be\n        instantiated before being passed to this method.\n\n        You should not use this function to load the actual configuration but\n        rather configuration defaults.  The actual config should be loaded\n        with :meth:`from_pyfile` and ideally from a location not within the\n        package because the package might be installed system wide.\n\n        See :ref:`config-dev-prod` for an example of class-based configuration\n        using :meth:`from_object`.\n\n        :param obj: an import name or object\n        \"\"\"\n        if isinstance(obj, str):\n            obj = import_string(obj)\n        loopIterator = __import__(\"builtins\").iter(dir(obj))\n        while True:\n            try:\n                key = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if key.isupper():\n                self[key] = getattr(obj, key)\n\n    def from_file(\n        self,\n        filename: str | os.PathLike[str],\n        load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n        silent: bool = False,\n        text: bool = True,\n    ) -> bool:\n        \"\"\"Update the values in the config from a file that is loaded\n        using the ``load`` parameter. The loaded data is passed to the\n        :meth:`from_mapping` method.\n\n        .. code-block:: python\n\n            import json\n            app.config.from_file(\"config.json\", load=json.load)\n\n            import tomllib\n            app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n        :param filename: The path to the data file. This can be an\n            absolute path or relative to the config root path.\n        :param load: A callable that takes a file handle and returns a\n            mapping of loaded data from the file.\n        :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n            implements a ``read`` method.\n        :param silent: Ignore the file if it doesn't exist.\n        :param text: Open the file in text or binary mode.\n        :return: ``True`` if the file was loaded successfully.\n\n        .. versionchanged:: 2.3\n            The ``text`` parameter was added.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        filename = os.path.join(self.root_path, filename)\n\n        try:\n            with open(filename, \"r\" if text else \"rb\") as f:\n                obj = load(f)\n        except OSError as e:\n            if silent and e.errno in (errno.ENOENT, errno.EISDIR):\n                return False\n\n            e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n            raise\n\n        return self.from_mapping(obj)\n\n    def from_mapping(\n        self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any\n    ) -> bool:\n        \"\"\"Updates the config like :meth:`update` ignoring items with\n        non-upper keys.\n\n        :return: Always returns ``True``.\n\n        .. versionadded:: 0.11\n        \"\"\"\n        mappings: dict[str, t.Any] = {}\n        if mapping is not None:\n            mappings.update(mapping)\n        mappings.update(kwargs)\n        loopIteratorA = __import__(\"builtins\").iter(mappings.items())\n        while True:\n            try:\n                key, value = __import__(\"builtins\").next(loopIteratorA)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if key.isupper():\n                self[key] = value\n        return True\n\n    def get_namespace(\n        self, namespace: str, lowercase: bool = True, trim_namespace: bool = True\n    ) -> dict[str, t.Any]:\n        \"\"\"Returns a dictionary containing a subset of configuration options\n        that match the specified namespace/prefix. Example usage::\n\n            app.config['IMAGE_STORE_TYPE'] = 'fs'\n            app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n            app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n            image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n        The resulting dictionary `image_store_config` would look like::\n\n            {\n                'type': 'fs',\n                'path': '/var/app/images',\n                'base_url': 'http://img.website.com'\n            }\n\n        This is often useful when configuration options map directly to\n        keyword arguments in functions or class constructors.\n\n        :param namespace: a configuration namespace\n        :param lowercase: a flag indicating if the keys of the resulting\n                          dictionary should be lowercase\n        :param trim_namespace: a flag indicating if the keys of the resulting\n                          dictionary should not include the namespace\n\n        .. versionadded:: 0.11\n        \"\"\"\n        rv = {}\n        loopIteratorB = __import__(\"builtins\").iter(self.items())\n        while True:\n            try:\n                k, v = __import__(\"builtins\").next(loopIteratorB)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if not k.startswith(namespace):\n                continue\n            if trim_namespace:\n                key = k[len(namespace) :]\n            else:\n                key = k\n            if lowercase:\n                key = key.lower()\n            rv[key] = v\n        return rv\n\n    def __repr__(self) -> str:\n        return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-8a49dce1d1f27976", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "e7ed8aa25fd727299ab77574fd33fb98047d11220157557b10232320b659ce55", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 341, "local_path": "control-flow/lower-for-to-while/I13__flask__Config__d6781361.py", "order": 13, "original_content_sha256": "306590e51b9eb19a161503b4a2432a445737d4633cba02e1ae91bdbd3910f840", "parent_variant_id": "pyint-648d155241c3-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/config.py#L50-L367", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 3, "for_loops_skipped_for_comment": 2, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 3, "synchronous_for_loops_eligible": 3, "synchronous_for_loops_found": 5}, "unit_kind": "class", "unit_name": "Config", "variant_id": "pyint-b1b7d6781361-I13", "group_id": "py-8a49dce1d1f27976", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 672, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7cb4c37b2d37-SRC", "source": "import itertools\nimport math\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import (\n    Case,\n    ColPairs,\n    Expression,\n    ExpressionList,\n    Func,\n    Value,\n    When,\n)\nfrom django.db.models.fields import (\n    BooleanField,\n    CharField,\n    DateTimeField,\n    Field,\n    IntegerField,\n    UUIDField,\n)\nfrom django.db.models.query_utils import RegisterLookupMixin\nfrom django.utils.datastructures import OrderedSet\nfrom django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\n@Field.register_lookup\nclass IExact(BuiltinLookup):\n    lookup_name = \"iexact\"\n    prepare_rhs = False\n\n    def process_rhs(self, qn, connection):\n        rhs, params = super().process_rhs(qn, connection)\n        if params:\n            params = (connection.ops.prep_for_iexact_query(params[0]), *params[1:])\n        return rhs, params\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-8e89bf37d351c40c", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 35, "local_path": "source-original/SRC__django__IExact__c37b2d37.py", "order": 0, "original_content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/lookups.py#L411-L419", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "IExact", "variant_id": "pyint-7cb4c37b2d37-SRC", "group_id": "py-8e89bf37d351c40c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 183, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-566a278a9ffe-I01", "source": "import itertools\nimport math\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import (\n    Case,\n    ColPairs,\n    Expression,\n    ExpressionList,\n    Func,\n    Value,\n    When,\n)\nfrom django.db.models.fields import (\n    BooleanField,\n    CharField,\n    DateTimeField,\n    Field,\n    IntegerField,\n    UUIDField,\n)\nfrom django.db.models.query_utils import RegisterLookupMixin\nfrom django.utils.datastructures import OrderedSet\nfrom django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\n@Field.register_lookup\nclass IExact(BuiltinLookup):\n    lookup_name = \"iexact\"\n    prepare_rhs = False\n\n    def process_rhs(self, qn, connection):\n        rhs, params = super().process_rhs(qn, connection)\n        if params:\n            params = (connection.ops.prep_for_iexact_query(params[0]), *params[1:])\n        return rhs, params\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-8e89bf37d351c40c", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 35, "local_path": "comments/remove-comments/I01__django__IExact__278a9ffe.py", "order": 1, "original_content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "parent_variant_id": "pyint-7cb4c37b2d37-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/lookups.py#L411-L419", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "IExact", "variant_id": "pyint-566a278a9ffe-I01", "group_id": "py-8e89bf37d351c40c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 184, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c379b06a4f51-I02", "source": "import itertools\nimport math\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import (\n    Case,\n    ColPairs,\n    Expression,\n    ExpressionList,\n    Func,\n    Value,\n    When,\n)\nfrom django.db.models.fields import (\n    BooleanField,\n    CharField,\n    DateTimeField,\n    Field,\n    IntegerField,\n    UUIDField,\n)\nfrom django.db.models.query_utils import RegisterLookupMixin\nfrom django.utils.datastructures import OrderedSet\nfrom django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\n@Field.register_lookup\nclass IExact(BuiltinLookup):\n    lookup_name = \"iexact\"\n    prepare_rhs = False\n\n    def process(self, qn2, con):\n        rhs2, par = super().process_rhs(qn2, con)\n        if par:\n            par = (con.ops.prep_for_iexact_query(par[0]), *par[1:])\n        return rhs2, par\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-8e89bf37d351c40c", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "87cfaecf94d49a99b6ced7770a6b6da083fc5700bca40e9286b4604772203d2a", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 35, "local_path": "identifiers/shorten-identifiers/I02__django__IExact__b06a4f51.py", "order": 2, "original_content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "parent_variant_id": "pyint-7cb4c37b2d37-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/lookups.py#L411-L419", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 14, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "IExact", "variant_id": "pyint-c379b06a4f51-I02", "group_id": "py-8e89bf37d351c40c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 185, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7e4c6b577809-I03", "source": "import itertools\nimport math\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import (\n    Case,\n    ColPairs,\n    Expression,\n    ExpressionList,\n    Func,\n    Value,\n    When,\n)\nfrom django.db.models.fields import (\n    BooleanField,\n    CharField,\n    DateTimeField,\n    Field,\n    IntegerField,\n    UUIDField,\n)\nfrom django.db.models.query_utils import RegisterLookupMixin\nfrom django.utils.datastructures import OrderedSet\nfrom django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\n@Field.register_lookup\nclass IExact(BuiltinLookup):\n    lookup_name = \"iexact\"\n    prepare_rhs = False\n\n    def readBalance(self, age, activeMode):\n        key, config = super().process_rhs(age, activeMode)\n        if config:\n            config = (activeMode.ops.prep_for_iexact_query(config[0]), *config[1:])\n        return key, config\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-8e89bf37d351c40c", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "c94c4432002e9700e600374ac0d68fafa363a1ccdd2a83b141b8f9d063bbf135", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 35, "local_path": "identifiers/mislead-identifiers/I03__django__IExact__6b577809.py", "order": 3, "original_content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "parent_variant_id": "pyint-7cb4c37b2d37-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/lookups.py#L411-L419", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 14, "identifiers_declared": 5, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 3, "local_random_pool_selections": 4, "local_total_length_difference": 1, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "IExact", "variant_id": "pyint-7e4c6b577809-I03", "group_id": "py-8e89bf37d351c40c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 186, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ba0a5261f42e-I04", "source": "import itertools\nimport math\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import (\n    Case,\n    ColPairs,\n    Expression,\n    ExpressionList,\n    Func,\n    Value,\n    When,\n)\nfrom django.db.models.fields import (\n    BooleanField,\n    CharField,\n    DateTimeField,\n    Field,\n    IntegerField,\n    UUIDField,\n)\nfrom django.db.models.query_utils import RegisterLookupMixin\nfrom django.utils.datastructures import OrderedSet\nfrom django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\n@Field.register_lookup\nclass IExact(BuiltinLookup):\n    lookup_name = \"iexact\"\n    prepare_rhs = False\n\n    def a(self, b, c):\n        d, e = super().process_rhs(b, c)\n        if e:\n            e = (c.ops.prep_for_iexact_query(e[0]), *e[1:])\n        return d, e\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-8e89bf37d351c40c", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "40a8bb35033434cb917425c1469cbbb3fe2dd961c9cfadab64fbc3bde65adb44", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 35, "local_path": "identifiers/garble-identifiers/I04__django__IExact__5261f42e.py", "order": 4, "original_content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "parent_variant_id": "pyint-7cb4c37b2d37-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/lookups.py#L411-L419", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 14, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "IExact", "variant_id": "pyint-ba0a5261f42e-I04", "group_id": "py-8e89bf37d351c40c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 187, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d686d0219306-I05", "source": "import itertools\nimport math\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import (\n    Case,\n    ColPairs,\n    Expression,\n    ExpressionList,\n    Func,\n    Value,\n    When,\n)\nfrom django.db.models.fields import (\n    BooleanField,\n    CharField,\n    DateTimeField,\n    Field,\n    IntegerField,\n    UUIDField,\n)\nfrom django.db.models.query_utils import RegisterLookupMixin\nfrom django.utils.datastructures import OrderedSet\nfrom django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\n@Field.register_lookup\nclass IExact(BuiltinLookup):\n    lookup_name = \"iexact\"\n    prepare_rhs = False\n\n    def process_rhs(self, qn, connection):\n        rhs, params = super().process_rhs(qn, connection)\n        if params:\n            params = (connection.ops.prep_for_iexact_query(params[0x0]), *params[0x1:])\n        return rhs, params\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-8e89bf37d351c40c", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "2f511f3645835de8a71b02cf9bfb8853c9b4e79cec6540c97731da880cda0d16", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 35, "local_path": "expressions/encode-integer-literals/I05__django__IExact__d0219306.py", "order": 5, "original_content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "parent_variant_id": "pyint-7cb4c37b2d37-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/lookups.py#L411-L419", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 2}, "unit_kind": "class", "unit_name": "IExact", "variant_id": "pyint-d686d0219306-I05", "group_id": "py-8e89bf37d351c40c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 188, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-39056a917315-I06", "source": "import itertools\nimport math\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import (\n    Case,\n    ColPairs,\n    Expression,\n    ExpressionList,\n    Func,\n    Value,\n    When,\n)\nfrom django.db.models.fields import (\n    BooleanField,\n    CharField,\n    DateTimeField,\n    Field,\n    IntegerField,\n    UUIDField,\n)\nfrom django.db.models.query_utils import RegisterLookupMixin\nfrom django.utils.datastructures import OrderedSet\nfrom django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\n@Field.register_lookup\nclass IExact(BuiltinLookup):\n    lookup_name = \"iexact\"\n    prepare_rhs = False\n\n    def process_rhs(self, qn, connection):\n        rhs, params = super().process_rhs(qn, connection)\n        if not (params):\n            pass\n        else:\n            params = (connection.ops.prep_for_iexact_query(params[0]), *params[1:])\n        return rhs, params\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-8e89bf37d351c40c", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "3702e444da1ae6f28bbdb85a82fdc79f95d14d3cfe4cd92bbb84fe118c807737", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 37, "local_path": "expressions/invert-conditions/I06__django__IExact__6a917315.py", "order": 6, "original_content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "parent_variant_id": "pyint-7cb4c37b2d37-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/lookups.py#L411-L419", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "IExact", "variant_id": "pyint-39056a917315-I06", "group_id": "py-8e89bf37d351c40c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 189, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8cb04631dd4a-I07", "source": "import itertools\nimport math\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import (\n    Case,\n    ColPairs,\n    Expression,\n    ExpressionList,\n    Func,\n    Value,\n    When,\n)\nfrom django.db.models.fields import (\n    BooleanField,\n    CharField,\n    DateTimeField,\n    Field,\n    IntegerField,\n    UUIDField,\n)\nfrom django.db.models.query_utils import RegisterLookupMixin\nfrom django.utils.datastructures import OrderedSet\nfrom django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\n@Field.register_lookup\nclass IExact(BuiltinLookup):\n    lookup_name = \"iexact\"\n    prepare_rhs = False\n\n    def process_rhs(self, qn, connection):\n        if ((0xcab8 ^ 0xcab8) != 0):\n            raise AssertionError()\n        rhs, params = super().process_rhs(qn, connection)\n        if params:\n            params = (connection.ops.prep_for_iexact_query(params[0]), *params[1:])\n        return rhs, params\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-8e89bf37d351c40c", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "7778f98ef6c587cf389bd96bf1fe48146fd458ebefe2b9d8680dbb35e47bf297", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 37, "local_path": "code-injection/insert-dead-branches/I07__django__IExact__4631dd4a.py", "order": 7, "original_content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "parent_variant_id": "pyint-7cb4c37b2d37-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/lookups.py#L411-L419", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "IExact", "variant_id": "pyint-8cb04631dd4a-I07", "group_id": "py-8e89bf37d351c40c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 190, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ffd99dc23b3f-I08", "source": "import itertools\nimport math\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import (\n    Case,\n    ColPairs,\n    Expression,\n    ExpressionList,\n    Func,\n    Value,\n    When,\n)\nfrom django.db.models.fields import (\n    BooleanField,\n    CharField,\n    DateTimeField,\n    Field,\n    IntegerField,\n    UUIDField,\n)\nfrom django.db.models.query_utils import RegisterLookupMixin\nfrom django.utils.datastructures import OrderedSet\nfrom django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\n@Field.register_lookup\nclass IExact(BuiltinLookup):\n    lookup_name = \"iexact\"\n    prepare_rhs = False\n\n    def process_rhs(self, qn, connection):\n        remaining_steps = 3\n        while remaining_steps > 0:\n            remaining_steps -= 1\n        rhs, params = super().process_rhs(qn, connection)\n        if params:\n            params = (connection.ops.prep_for_iexact_query(params[0]), *params[1:])\n        return rhs, params\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-8e89bf37d351c40c", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "4718cff358453e472d216f35958fa0c55e8ba319aa0d72197e701adc41f8539b", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 38, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__IExact__9dc23b3f.py", "order": 8, "original_content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "parent_variant_id": "pyint-7cb4c37b2d37-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/lookups.py#L411-L419", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 1}, "unit_kind": "class", "unit_name": "IExact", "variant_id": "pyint-ffd99dc23b3f-I08", "group_id": "py-8e89bf37d351c40c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 191, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8c73e81b7703-I09", "source": "import itertools\nimport math\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import (\n    Case,\n    ColPairs,\n    Expression,\n    ExpressionList,\n    Func,\n    Value,\n    When,\n)\nfrom django.db.models.fields import (\n    BooleanField,\n    CharField,\n    DateTimeField,\n    Field,\n    IntegerField,\n    UUIDField,\n)\nfrom django.db.models.query_utils import RegisterLookupMixin\nfrom django.utils.datastructures import OrderedSet\nfrom django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\n@Field.register_lookup\nclass IExact(BuiltinLookup):\n    lookup_name = \"iexact\"\n    prepare_rhs = False\n\n    def process_rhs(self, qn, connection):\n        lI0O_77ccc4b7 = 0xd8fc\n        lI0O_77ccc4b7 = ((lI0O_77ccc4b7 ^ 0xd8fc) | 0) & -1\n        if (lI0O_77ccc4b7 & 1) == 1:\n            lI0O_77ccc4b7 ^= lI0O_77ccc4b7\n        rhs, params = super().process_rhs(qn, connection)\n        if params:\n            params = (connection.ops.prep_for_iexact_query(params[0]), *params[1:])\n        return rhs, params\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-8e89bf37d351c40c", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d2ef82b71a2cbc1f9653a8a63dd638a998cdd7df21ea75f6102232a50db82285", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 39, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__IExact__e81b7703.py", "order": 9, "original_content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "parent_variant_id": "pyint-7cb4c37b2d37-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/lookups.py#L411-L419", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 0}, "unit_kind": "class", "unit_name": "IExact", "variant_id": "pyint-8c73e81b7703-I09", "group_id": "py-8e89bf37d351c40c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 192, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dda159c809f0-I10", "source": "import itertools\nimport math\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import (\n    Case,\n    ColPairs,\n    Expression,\n    ExpressionList,     Func,\n    Value,     When, )\nfrom django.db.models.fields import (\n    BooleanField,     CharField,     DateTimeField,     Field,\n    IntegerField,\n    UUIDField,\n)\nfrom django.db.models.query_utils import RegisterLookupMixin\nfrom django.utils.datastructures import OrderedSet\nfrom django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\n@Field.register_lookup\nclass IExact(BuiltinLookup):\n    lookup_name = \"iexact\"\n    prepare_rhs = False\n\n    def process_rhs(self, qn, connection):\n        rhs, params = super().process_rhs(qn, connection)\n        if params:\n            params = (connection.ops.prep_for_iexact_query(params[0]), *params[1:])\n        return rhs, params\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-8e89bf37d351c40c", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "7328351045a6337ae43f7bd31d10c30052bc9edf0586a390e506dc29ac0ca4e5", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 29, "local_path": "layout/partially-compact-layout/I10__django__IExact__59c809f0.py", "order": 10, "original_content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "parent_variant_id": "pyint-7cb4c37b2d37-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/lookups.py#L411-L419", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 17, "line_break_groups_removed": 6, "line_breaks_removed": 6, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "IExact", "variant_id": "pyint-dda159c809f0-I10", "group_id": "py-8e89bf37d351c40c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 193, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-eadb1ea9b487-I11", "source": "import itertools\nimport math\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import (\n    Case,\n    ColPairs,\n    Expression,\n    ExpressionList,\n    Func,\n    Value,\n    When,\n)\nfrom django.db.models.fields import (\n    BooleanField,\n    CharField,\n    DateTimeField,\n    Field,\n    IntegerField,\n    UUIDField,\n)\nfrom django.db.models.query_utils import RegisterLookupMixin\nfrom django.utils.datastructures import OrderedSet\nfrom django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\n@Field.register_lookup\nclass IExact(BuiltinLookup):\n    lookup_name = \"iexact\"\n    prepare_rhs = False\n\n    def process_rhs(self, qn, connection):\n        rhs, params = super().process_rhs(qn, connection)\n        if params:\n            a = 1\n            b = -1\n            c = 2\n            d = -1\n            params = (connection.ops.prep_for_iexact_query(params[(a + b)]), *params[(c + d):])\n        return rhs, params\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-8e89bf37d351c40c", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "8cd8a65be89d1b3b8f1f09ef9f85967d88047341f4cc36f0391208b3148977da", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 39, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__IExact__1ea9b487.py", "order": 11, "original_content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "parent_variant_id": "pyint-7cb4c37b2d37-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/lookups.py#L411-L419", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 2, "intermediate_variables_introduced": 4, "statements_augmented": 1}, "unit_kind": "class", "unit_name": "IExact", "variant_id": "pyint-eadb1ea9b487-I11", "group_id": "py-8e89bf37d351c40c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 194, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3cf227b3c1fa-I12", "source": "import itertools\nimport math\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import (\n    Case,\n    ColPairs,\n    Expression,\n    ExpressionList,\n    Func,\n    Value,\n    When,\n)\nfrom django.db.models.fields import (\n    BooleanField,\n    CharField,\n    DateTimeField,\n    Field,\n    IntegerField,\n    UUIDField,\n)\nfrom django.db.models.query_utils import RegisterLookupMixin\nfrom django.utils.datastructures import OrderedSet\nfrom django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\n@Field.register_lookup\nclass IExact(BuiltinLookup):\n    lookup_name = \"iexact\"\n    prepare_rhs = False\n\n    def process_rhs(self, qn, connection):\n        rhs, params = super().process_rhs(qn, connection)\n        if params:\n            params = (connection.ops.prep_for_iexact_query(params[0]), *params[1:])\n        return rhs, params\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-8e89bf37d351c40c", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 35, "local_path": "data-flow/inline-intermediate-variables/I12__django__IExact__27b3c1fa.py", "order": 12, "original_content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "parent_variant_id": "pyint-7cb4c37b2d37-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/lookups.py#L411-L419", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "IExact", "variant_id": "pyint-3cf227b3c1fa-I12", "group_id": "py-8e89bf37d351c40c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 195, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d76034c3cfba-I13", "source": "import itertools\nimport math\nfrom django.core.exceptions import EmptyResultSet, FullResultSet\nfrom django.db.models.expressions import (\n    Case,\n    ColPairs,\n    Expression,\n    ExpressionList,\n    Func,\n    Value,\n    When,\n)\nfrom django.db.models.fields import (\n    BooleanField,\n    CharField,\n    DateTimeField,\n    Field,\n    IntegerField,\n    UUIDField,\n)\nfrom django.db.models.query_utils import RegisterLookupMixin\nfrom django.utils.datastructures import OrderedSet\nfrom django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\n@Field.register_lookup\nclass IExact(BuiltinLookup):\n    lookup_name = \"iexact\"\n    prepare_rhs = False\n\n    def process_rhs(self, qn, connection):\n        rhs, params = super().process_rhs(qn, connection)\n        if params:\n            params = (connection.ops.prep_for_iexact_query(params[0]), *params[1:])\n        return rhs, params\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-8e89bf37d351c40c", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 35, "local_path": "control-flow/lower-for-to-while/I13__django__IExact__34c3cfba.py", "order": 13, "original_content_sha256": "9e99934f0bed3b134af6f5671261f61a7e964321812c5d1799e41025d617627f", "parent_variant_id": "pyint-7cb4c37b2d37-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/lookups.py#L411-L419", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "IExact", "variant_id": "pyint-d76034c3cfba-I13", "group_id": "py-8e89bf37d351c40c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 196, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-77678a4ca97a-SRC", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n    \"\"\"Base class for sessions based on signed cookies.\n\n    This session backend will set the :attr:`modified` and\n    :attr:`accessed` attributes. It cannot reliably track whether a\n    session is new (vs. empty), so :attr:`new` remains hard coded to\n    ``False``.\n    \"\"\"\n\n    #: When data is changed, this is set to ``True``. Only the session\n    #: dictionary itself is tracked; if the session contains mutable\n    #: data (for example a nested dict) then this must be set to\n    #: ``True`` manually when modifying that data. The session cookie\n    #: will only be written to the response if this is ``True``.\n    modified = False\n\n    def __init__(\n        self,\n        initial: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        def on_update(self: te.Self) -> None:\n            self.modified = True\n\n        super().__init__(initial, on_update)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-8fde5744af1af284", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 36, "local_path": "source-original/SRC__flask__SecureCookieSession__8a4ca97a.py", "order": 0, "original_content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L57-L80", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "SecureCookieSession", "variant_id": "pyint-77678a4ca97a-SRC", "group_id": "py-8fde5744af1af284", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 547, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6433180d8bba-I01", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n    \n\n     \n     \n     \n     \n     \n    modified = False\n\n    def __init__(\n        self,\n        initial: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        def on_update(self: te.Self) -> None:\n            self.modified = True\n\n        super().__init__(initial, on_update)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-8fde5744af1af284", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "51883707648c11b675fe1594ae229510a3f57bbae4bc205684c3e1a9b4df6288", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 30, "local_path": "comments/remove-comments/I01__flask__SecureCookieSession__180d8bba.py", "order": 1, "original_content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "parent_variant_id": "pyint-77678a4ca97a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L57-L80", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 581, "comments_removed": 6, "docstrings_removed": 1, "line_comments_removed": 5}, "unit_kind": "class", "unit_name": "SecureCookieSession", "variant_id": "pyint-6433180d8bba-I01", "group_id": "py-8fde5744af1af284", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 548, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-97a83eab0bd2-I02", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n    \"\"\"Base class for sessions based on signed cookies.\n\n    This session backend will set the :attr:`modified` and\n    :attr:`accessed` attributes. It cannot reliably track whether a\n    session is new (vs. empty), so :attr:`new` remains hard coded to\n    ``False``.\n    \"\"\"\n\n    #: When data is changed, this is set to ``True``. Only the session\n    #: dictionary itself is tracked; if the session contains mutable\n    #: data (for example a nested dict) then this must be set to\n    #: ``True`` manually when modifying that data. The session cookie\n    #: will only be written to the response if this is ``True``.\n    modified = False\n\n    def __init__(\n        self,\n        ini: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        def on_update(self: te.Self) -> None:\n            self.modified = True\n\n        super().__init__(ini, on_update)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-8fde5744af1af284", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "4d17dfcd5d6a7e0e0702b77180dff956a959df3e8a9e67d0c36d0f763d987f62", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 36, "local_path": "identifiers/shorten-identifiers/I02__flask__SecureCookieSession__3eab0bd2.py", "order": 2, "original_content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "parent_variant_id": "pyint-77678a4ca97a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L57-L80", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "SecureCookieSession", "variant_id": "pyint-97a83eab0bd2-I02", "group_id": "py-8fde5744af1af284", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 549, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4e2d127f86eb-I03", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n    \"\"\"Base class for sessions based on signed cookies.\n\n    This session backend will set the :attr:`modified` and\n    :attr:`accessed` attributes. It cannot reliably track whether a\n    session is new (vs. empty), so :attr:`new` remains hard coded to\n    ``False``.\n    \"\"\"\n\n    #: When data is changed, this is set to ``True``. Only the session\n    #: dictionary itself is tracked; if the session contains mutable\n    #: data (for example a nested dict) then this must be set to\n    #: ``True`` manually when modifying that data. The session cookie\n    #: will only be written to the response if this is ``True``.\n    modified = False\n\n    def __init__(\n        self,\n        history: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        def on_update(self: te.Self) -> None:\n            self.modified = True\n\n        super().__init__(history, on_update)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-8fde5744af1af284", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "3e036d6883c6940ab077b7c2d127743e7ffffabc237dffb9adfed6ec488a869f", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 36, "local_path": "identifiers/mislead-identifiers/I03__flask__SecureCookieSession__127f86eb.py", "order": 3, "original_content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "parent_variant_id": "pyint-77678a4ca97a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L57-L80", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2, "identifiers_declared": 1, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 1, "local_random_pool_selections": 1, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "SecureCookieSession", "variant_id": "pyint-4e2d127f86eb-I03", "group_id": "py-8fde5744af1af284", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 550, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b6057b665be9-I04", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n    \"\"\"Base class for sessions based on signed cookies.\n\n    This session backend will set the :attr:`modified` and\n    :attr:`accessed` attributes. It cannot reliably track whether a\n    session is new (vs. empty), so :attr:`new` remains hard coded to\n    ``False``.\n    \"\"\"\n\n    #: When data is changed, this is set to ``True``. Only the session\n    #: dictionary itself is tracked; if the session contains mutable\n    #: data (for example a nested dict) then this must be set to\n    #: ``True`` manually when modifying that data. The session cookie\n    #: will only be written to the response if this is ``True``.\n    modified = False\n\n    def __init__(\n        self,\n        a: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        def on_update(self: te.Self) -> None:\n            self.modified = True\n\n        super().__init__(a, on_update)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-8fde5744af1af284", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "1d52dff3080861818e91c315349b00ad778cc3dfd615a9b54bad5d1ad5b595f7", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 36, "local_path": "identifiers/garble-identifiers/I04__flask__SecureCookieSession__7b665be9.py", "order": 4, "original_content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "parent_variant_id": "pyint-77678a4ca97a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L57-L80", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "SecureCookieSession", "variant_id": "pyint-b6057b665be9-I04", "group_id": "py-8fde5744af1af284", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 551, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0584e01592e1-I05", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n    \"\"\"Base class for sessions based on signed cookies.\n\n    This session backend will set the :attr:`modified` and\n    :attr:`accessed` attributes. It cannot reliably track whether a\n    session is new (vs. empty), so :attr:`new` remains hard coded to\n    ``False``.\n    \"\"\"\n\n    #: When data is changed, this is set to ``True``. Only the session\n    #: dictionary itself is tracked; if the session contains mutable\n    #: data (for example a nested dict) then this must be set to\n    #: ``True`` manually when modifying that data. The session cookie\n    #: will only be written to the response if this is ``True``.\n    modified = False\n\n    def __init__(\n        self,\n        initial: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        def on_update(self: te.Self) -> None:\n            self.modified = True\n\n        super().__init__(initial, on_update)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-8fde5744af1af284", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 36, "local_path": "expressions/encode-integer-literals/I05__flask__SecureCookieSession__e01592e1.py", "order": 5, "original_content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "parent_variant_id": "pyint-77678a4ca97a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L57-L80", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "SecureCookieSession", "variant_id": "pyint-0584e01592e1-I05", "group_id": "py-8fde5744af1af284", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 552, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7e199a2dcc25-I06", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n    \"\"\"Base class for sessions based on signed cookies.\n\n    This session backend will set the :attr:`modified` and\n    :attr:`accessed` attributes. It cannot reliably track whether a\n    session is new (vs. empty), so :attr:`new` remains hard coded to\n    ``False``.\n    \"\"\"\n\n    #: When data is changed, this is set to ``True``. Only the session\n    #: dictionary itself is tracked; if the session contains mutable\n    #: data (for example a nested dict) then this must be set to\n    #: ``True`` manually when modifying that data. The session cookie\n    #: will only be written to the response if this is ``True``.\n    modified = False\n\n    def __init__(\n        self,\n        initial: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        def on_update(self: te.Self) -> None:\n            self.modified = True\n\n        super().__init__(initial, on_update)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-8fde5744af1af284", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 36, "local_path": "expressions/invert-conditions/I06__flask__SecureCookieSession__9a2dcc25.py", "order": 6, "original_content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "parent_variant_id": "pyint-77678a4ca97a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L57-L80", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "SecureCookieSession", "variant_id": "pyint-7e199a2dcc25-I06", "group_id": "py-8fde5744af1af284", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 553, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1b067201b93f-I07", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n    \"\"\"Base class for sessions based on signed cookies.\n\n    This session backend will set the :attr:`modified` and\n    :attr:`accessed` attributes. It cannot reliably track whether a\n    session is new (vs. empty), so :attr:`new` remains hard coded to\n    ``False``.\n    \"\"\"\n\n    #: When data is changed, this is set to ``True``. Only the session\n    #: dictionary itself is tracked; if the session contains mutable\n    #: data (for example a nested dict) then this must be set to\n    #: ``True`` manually when modifying that data. The session cookie\n    #: will only be written to the response if this is ``True``.\n    modified = False\n\n    def __init__(\n        self,\n        initial: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        if ((0x9e6e ^ 0x9e6e) != 0):\n            raise AssertionError()\n        def on_update(self: te.Self) -> None:\n            if ((0x8623 ^ 0x8623) != 0):\n                raise AssertionError()\n            self.modified = True\n\n        super().__init__(initial, on_update)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-8fde5744af1af284", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "845c630ee985c40e244b2510073b8a26dd4678b08a41b9c957ede4860297c4c7", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 40, "local_path": "code-injection/insert-dead-branches/I07__flask__SecureCookieSession__7201b93f.py", "order": 7, "original_content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "parent_variant_id": "pyint-77678a4ca97a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L57-L80", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "SecureCookieSession", "variant_id": "pyint-1b067201b93f-I07", "group_id": "py-8fde5744af1af284", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 554, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-026ea9800389-I08", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n    \"\"\"Base class for sessions based on signed cookies.\n\n    This session backend will set the :attr:`modified` and\n    :attr:`accessed` attributes. It cannot reliably track whether a\n    session is new (vs. empty), so :attr:`new` remains hard coded to\n    ``False``.\n    \"\"\"\n\n    #: When data is changed, this is set to ``True``. Only the session\n    #: dictionary itself is tracked; if the session contains mutable\n    #: data (for example a nested dict) then this must be set to\n    #: ``True`` manually when modifying that data. The session cookie\n    #: will only be written to the response if this is ``True``.\n    modified = False\n\n    def __init__(\n        self,\n        initial: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        def on_update(self: te.Self) -> None:\n            running_total = 0\n            for current_number in range(1, 6):\n                running_total += current_number\n            self.modified = True\n\n        super().__init__(initial, on_update)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-8fde5744af1af284", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "79e133ed0e1259bc0548c668aa945db81612129c7c80282056bfea739ec3af28", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 39, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__SecureCookieSession__a9800389.py", "order": 8, "original_content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "parent_variant_id": "pyint-77678a4ca97a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L57-L80", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 0}, "unit_kind": "class", "unit_name": "SecureCookieSession", "variant_id": "pyint-026ea9800389-I08", "group_id": "py-8fde5744af1af284", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 555, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9dfc2da13e8a-I09", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n    \"\"\"Base class for sessions based on signed cookies.\n\n    This session backend will set the :attr:`modified` and\n    :attr:`accessed` attributes. It cannot reliably track whether a\n    session is new (vs. empty), so :attr:`new` remains hard coded to\n    ``False``.\n    \"\"\"\n\n    #: When data is changed, this is set to ``True``. Only the session\n    #: dictionary itself is tracked; if the session contains mutable\n    #: data (for example a nested dict) then this must be set to\n    #: ``True`` manually when modifying that data. The session cookie\n    #: will only be written to the response if this is ``True``.\n    modified = False\n\n    def __init__(\n        self,\n        initial: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        lI0O_de0f30ca = 0xd032\n        lI0O_de0f30ca = (0 if (lI0O_de0f30ca ^ lI0O_de0f30ca) == 0 else 1) if (lI0O_de0f30ca & 0) == 0 else 2\n        def on_update(self: te.Self) -> None:\n            self.modified = True\n\n        super().__init__(initial, on_update)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-8fde5744af1af284", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "85edf073721bf4de6f67ca4d59fce99751388fea8e35e5a7dc3264c57054460f", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 38, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__SecureCookieSession__2da13e8a.py", "order": 9, "original_content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "parent_variant_id": "pyint-77678a4ca97a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L57-L80", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 8}, "unit_kind": "class", "unit_name": "SecureCookieSession", "variant_id": "pyint-9dfc2da13e8a-I09", "group_id": "py-8fde5744af1af284", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 556, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-801130c57895-I10", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n    \"\"\"Base class for sessions based on signed cookies.\n    This session backend will set the :attr:`modified` and\n    :attr:`accessed` attributes. It cannot reliably track whether a\n    session is new (vs. empty), so :attr:`new` remains hard coded to\n    ``False``.\n    \"\"\"\n\n    #: When data is changed, this is set to ``True``. Only the session\n    #: dictionary itself is tracked; if the session contains mutable\n    #: data (for example a nested dict) then this must be set to\n    #: ``True`` manually when modifying that data. The session cookie\n    #: will only be written to the response if this is ``True``.\n    modified = False\n\n    def __init__(\n        self,         initial: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        def on_update(self: te.Self) -> None:\n            self.modified = True\n        super().__init__(initial, on_update)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-8fde5744af1af284", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "3f19d00e7869f086aaa606ea7e4113f6cc468cf06296cabf3960d7598d0bf59d", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 33, "local_path": "layout/partially-compact-layout/I10__flask__SecureCookieSession__30c57895.py", "order": 10, "original_content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "parent_variant_id": "pyint-77678a4ca97a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L57-L80", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 8, "line_break_groups_removed": 3, "line_breaks_removed": 3, "whitespace_characters_removed": 2}, "unit_kind": "class", "unit_name": "SecureCookieSession", "variant_id": "pyint-801130c57895-I10", "group_id": "py-8fde5744af1af284", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 557, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-31a3e4311095-I11", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n    \"\"\"Base class for sessions based on signed cookies.\n\n    This session backend will set the :attr:`modified` and\n    :attr:`accessed` attributes. It cannot reliably track whether a\n    session is new (vs. empty), so :attr:`new` remains hard coded to\n    ``False``.\n    \"\"\"\n\n    #: When data is changed, this is set to ``True``. Only the session\n    #: dictionary itself is tracked; if the session contains mutable\n    #: data (for example a nested dict) then this must be set to\n    #: ``True`` manually when modifying that data. The session cookie\n    #: will only be written to the response if this is ``True``.\n    modified = False\n\n    def __init__(\n        self,\n        initial: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        def on_update(self: te.Self) -> None:\n            self.modified = True\n\n        super().__init__(initial, on_update)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-8fde5744af1af284", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 36, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__SecureCookieSession__e4311095.py", "order": 11, "original_content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "parent_variant_id": "pyint-77678a4ca97a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L57-L80", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "SecureCookieSession", "variant_id": "pyint-31a3e4311095-I11", "group_id": "py-8fde5744af1af284", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 558, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d869dd2a306f-I12", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n    \"\"\"Base class for sessions based on signed cookies.\n\n    This session backend will set the :attr:`modified` and\n    :attr:`accessed` attributes. It cannot reliably track whether a\n    session is new (vs. empty), so :attr:`new` remains hard coded to\n    ``False``.\n    \"\"\"\n\n    #: When data is changed, this is set to ``True``. Only the session\n    #: dictionary itself is tracked; if the session contains mutable\n    #: data (for example a nested dict) then this must be set to\n    #: ``True`` manually when modifying that data. The session cookie\n    #: will only be written to the response if this is ``True``.\n    modified = False\n\n    def __init__(\n        self,\n        initial: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        def on_update(self: te.Self) -> None:\n            self.modified = True\n\n        super().__init__(initial, on_update)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-8fde5744af1af284", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 36, "local_path": "data-flow/inline-intermediate-variables/I12__flask__SecureCookieSession__dd2a306f.py", "order": 12, "original_content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "parent_variant_id": "pyint-77678a4ca97a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L57-L80", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "SecureCookieSession", "variant_id": "pyint-d869dd2a306f-I12", "group_id": "py-8fde5744af1af284", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 559, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-68d5f3258005-I13", "source": "from __future__ import annotations\nimport collections.abc as c\nimport hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\nfrom .json.tag import TaggedJSONSerializer\n\nclass SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n    \"\"\"Base class for sessions based on signed cookies.\n\n    This session backend will set the :attr:`modified` and\n    :attr:`accessed` attributes. It cannot reliably track whether a\n    session is new (vs. empty), so :attr:`new` remains hard coded to\n    ``False``.\n    \"\"\"\n\n    #: When data is changed, this is set to ``True``. Only the session\n    #: dictionary itself is tracked; if the session contains mutable\n    #: data (for example a nested dict) then this must be set to\n    #: ``True`` manually when modifying that data. The session cookie\n    #: will only be written to the response if this is ``True``.\n    modified = False\n\n    def __init__(\n        self,\n        initial: c.Mapping[str, t.Any] | None = None,\n    ) -> None:\n        def on_update(self: te.Self) -> None:\n            self.modified = True\n\n        super().__init__(initial, on_update)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-8fde5744af1af284", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 36, "local_path": "control-flow/lower-for-to-while/I13__flask__SecureCookieSession__f3258005.py", "order": 13, "original_content_sha256": "2cc3e6be6b280868cfc049ac1bde1b4ba94159824bde4e8a6a0cc0e7c126faab", "parent_variant_id": "pyint-77678a4ca97a-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sessions.py#L57-L80", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "SecureCookieSession", "variant_id": "pyint-68d5f3258005-I13", "group_id": "py-8fde5744af1af284", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 560, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a2c8065af72b-SRC", "source": "from __future__ import annotations\nimport typing as t\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nclass Response(ResponseBase):\n    \"\"\"The response object that is used by default in Flask.  Works like the\n    response object from Werkzeug but is set to have an HTML mimetype by\n    default.  Quite often you don't have to create this object yourself because\n    :meth:`~flask.Flask.make_response` will take care of that for you.\n\n    If you want to replace the response object used you can subclass this and\n    set :attr:`~flask.Flask.response_class` to your subclass.\n\n    .. versionchanged:: 1.0\n        JSON support is added to the response, like the request. This is useful\n        when testing to get the test client response data as JSON.\n\n    .. versionchanged:: 1.0\n\n        Added :attr:`max_cookie_size`.\n    \"\"\"\n\n    default_mimetype: str | None = \"text/html\"\n\n    json_module = json\n\n    autocorrect_location_header = False\n\n    @property\n    def max_cookie_size(self) -> int:  # type: ignore\n        \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n        See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n        Werkzeug's docs.\n        \"\"\"\n        if current_app:\n            return current_app.config[\"MAX_COOKIE_SIZE\"]  # type: ignore[no-any-return]\n\n        # return Werkzeug's default when not in an app context\n        return super().max_cookie_size\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-97c0b066731d01aa", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 46, "local_path": "source-original/SRC__flask__Response__065af72b.py", "order": 0, "original_content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/wrappers.py#L222-L257", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-a2c8065af72b-SRC", "group_id": "py-97c0b066731d01aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 449, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-82f810058f55-I01", "source": "from __future__ import annotations\nimport typing as t\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nclass Response(ResponseBase):\n    \n\n    default_mimetype: str | None = \"text/html\"\n\n    json_module = json\n\n    autocorrect_location_header = False\n\n    @property\n    def max_cookie_size(self) -> int:   \n        \n        if current_app:\n            return current_app.config[\"MAX_COOKIE_SIZE\"]   \n\n         \n        return super().max_cookie_size\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-97c0b066731d01aa", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "6d275e745e9c581994c24a6a04ac25d9dc503bb06b678e6d417d4d2d66a2a265", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 27, "local_path": "comments/remove-comments/I01__flask__Response__10058f55.py", "order": 1, "original_content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "parent_variant_id": "pyint-a2c8065af72b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/wrappers.py#L222-L257", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 949, "comments_removed": 5, "docstrings_removed": 2, "line_comments_removed": 3}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-82f810058f55-I01", "group_id": "py-97c0b066731d01aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 450, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4371fa4f30e3-I02", "source": "from __future__ import annotations\nimport typing as t\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nclass Response(ResponseBase):\n    \"\"\"The response object that is used by default in Flask.  Works like the\n    response object from Werkzeug but is set to have an HTML mimetype by\n    default.  Quite often you don't have to create this object yourself because\n    :meth:`~flask.Flask.make_response` will take care of that for you.\n\n    If you want to replace the response object used you can subclass this and\n    set :attr:`~flask.Flask.response_class` to your subclass.\n\n    .. versionchanged:: 1.0\n        JSON support is added to the response, like the request. This is useful\n        when testing to get the test client response data as JSON.\n\n    .. versionchanged:: 1.0\n\n        Added :attr:`max_cookie_size`.\n    \"\"\"\n\n    default_mimetype: str | None = \"text/html\"\n\n    json_module = json\n\n    autocorrect_location_header = False\n\n    @property\n    def max(self) -> int:  # type: ignore\n        \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n        See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n        Werkzeug's docs.\n        \"\"\"\n        if current_app:\n            return current_app.config[\"MAX_COOKIE_SIZE\"]  # type: ignore[no-any-return]\n\n        # return Werkzeug's default when not in an app context\n        return super().max_cookie_size\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-97c0b066731d01aa", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "1fea45f38ed49af0c0086e943a3453de1094d494ee83ce8c2d3136d4b6153ec3", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 46, "local_path": "identifiers/shorten-identifiers/I02__flask__Response__fa4f30e3.py", "order": 2, "original_content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "parent_variant_id": "pyint-a2c8065af72b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/wrappers.py#L222-L257", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-4371fa4f30e3-I02", "group_id": "py-97c0b066731d01aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 451, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6195b26dd8fa-I03", "source": "from __future__ import annotations\nimport typing as t\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nclass Response(ResponseBase):\n    \"\"\"The response object that is used by default in Flask.  Works like the\n    response object from Werkzeug but is set to have an HTML mimetype by\n    default.  Quite often you don't have to create this object yourself because\n    :meth:`~flask.Flask.make_response` will take care of that for you.\n\n    If you want to replace the response object used you can subclass this and\n    set :attr:`~flask.Flask.response_class` to your subclass.\n\n    .. versionchanged:: 1.0\n        JSON support is added to the response, like the request. This is useful\n        when testing to get the test client response data as JSON.\n\n    .. versionchanged:: 1.0\n\n        Added :attr:`max_cookie_size`.\n    \"\"\"\n\n    default_mimetype: str | None = \"text/html\"\n\n    json_module = json\n\n    autocorrect_location_header = False\n\n    @property\n    def validateMessage(self) -> int:  # type: ignore\n        \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n        See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n        Werkzeug's docs.\n        \"\"\"\n        if current_app:\n            return current_app.config[\"MAX_COOKIE_SIZE\"]  # type: ignore[no-any-return]\n\n        # return Werkzeug's default when not in an app context\n        return super().max_cookie_size\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-97c0b066731d01aa", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "bff4c26b4b2e0702d0b7676b00b417eeb7be1495763eacc346df3d86c53d79ec", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 46, "local_path": "identifiers/mislead-identifiers/I03__flask__Response__b26dd8fa.py", "order": 3, "original_content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "parent_variant_id": "pyint-a2c8065af72b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/wrappers.py#L222-L257", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 0, "local_random_pool_selections": 0, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-6195b26dd8fa-I03", "group_id": "py-97c0b066731d01aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 452, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c4379654e7df-I04", "source": "from __future__ import annotations\nimport typing as t\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nclass Response(ResponseBase):\n    \"\"\"The response object that is used by default in Flask.  Works like the\n    response object from Werkzeug but is set to have an HTML mimetype by\n    default.  Quite often you don't have to create this object yourself because\n    :meth:`~flask.Flask.make_response` will take care of that for you.\n\n    If you want to replace the response object used you can subclass this and\n    set :attr:`~flask.Flask.response_class` to your subclass.\n\n    .. versionchanged:: 1.0\n        JSON support is added to the response, like the request. This is useful\n        when testing to get the test client response data as JSON.\n\n    .. versionchanged:: 1.0\n\n        Added :attr:`max_cookie_size`.\n    \"\"\"\n\n    default_mimetype: str | None = \"text/html\"\n\n    json_module = json\n\n    autocorrect_location_header = False\n\n    @property\n    def a(self) -> int:  # type: ignore\n        \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n        See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n        Werkzeug's docs.\n        \"\"\"\n        if current_app:\n            return current_app.config[\"MAX_COOKIE_SIZE\"]  # type: ignore[no-any-return]\n\n        # return Werkzeug's default when not in an app context\n        return super().max_cookie_size\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-97c0b066731d01aa", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "12116c91a8319f0300f60ad1437355392fa74c3de80709adb392884f4f00c352", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 46, "local_path": "identifiers/garble-identifiers/I04__flask__Response__9654e7df.py", "order": 4, "original_content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "parent_variant_id": "pyint-a2c8065af72b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/wrappers.py#L222-L257", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-c4379654e7df-I04", "group_id": "py-97c0b066731d01aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 453, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d946caec3454-I05", "source": "from __future__ import annotations\nimport typing as t\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nclass Response(ResponseBase):\n    \"\"\"The response object that is used by default in Flask.  Works like the\n    response object from Werkzeug but is set to have an HTML mimetype by\n    default.  Quite often you don't have to create this object yourself because\n    :meth:`~flask.Flask.make_response` will take care of that for you.\n\n    If you want to replace the response object used you can subclass this and\n    set :attr:`~flask.Flask.response_class` to your subclass.\n\n    .. versionchanged:: 1.0\n        JSON support is added to the response, like the request. This is useful\n        when testing to get the test client response data as JSON.\n\n    .. versionchanged:: 1.0\n\n        Added :attr:`max_cookie_size`.\n    \"\"\"\n\n    default_mimetype: str | None = \"text/html\"\n\n    json_module = json\n\n    autocorrect_location_header = False\n\n    @property\n    def max_cookie_size(self) -> int:  # type: ignore\n        \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n        See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n        Werkzeug's docs.\n        \"\"\"\n        if current_app:\n            return current_app.config[\"MAX_COOKIE_SIZE\"]  # type: ignore[no-any-return]\n\n        # return Werkzeug's default when not in an app context\n        return super().max_cookie_size\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-97c0b066731d01aa", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 46, "local_path": "expressions/encode-integer-literals/I05__flask__Response__caec3454.py", "order": 5, "original_content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "parent_variant_id": "pyint-a2c8065af72b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/wrappers.py#L222-L257", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-d946caec3454-I05", "group_id": "py-97c0b066731d01aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 454, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-05ef9f200e6b-I06", "source": "from __future__ import annotations\nimport typing as t\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nclass Response(ResponseBase):\n    \"\"\"The response object that is used by default in Flask.  Works like the\n    response object from Werkzeug but is set to have an HTML mimetype by\n    default.  Quite often you don't have to create this object yourself because\n    :meth:`~flask.Flask.make_response` will take care of that for you.\n\n    If you want to replace the response object used you can subclass this and\n    set :attr:`~flask.Flask.response_class` to your subclass.\n\n    .. versionchanged:: 1.0\n        JSON support is added to the response, like the request. This is useful\n        when testing to get the test client response data as JSON.\n\n    .. versionchanged:: 1.0\n\n        Added :attr:`max_cookie_size`.\n    \"\"\"\n\n    default_mimetype: str | None = \"text/html\"\n\n    json_module = json\n\n    autocorrect_location_header = False\n\n    @property\n    def max_cookie_size(self) -> int:  # type: ignore\n        \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n        See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n        Werkzeug's docs.\n        \"\"\"\n        if not (current_app):\n            pass\n        else:\n            return current_app.config[\"MAX_COOKIE_SIZE\"]  # type: ignore[no-any-return]  # type: ignore[no-any-return]\n\n        # return Werkzeug's default when not in an app context\n        return super().max_cookie_size\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-97c0b066731d01aa", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "55b847f40fa94cd4c1cba707492f948d69d5c98e3e70449004c2aa034fbf831e", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 48, "local_path": "expressions/invert-conditions/I06__flask__Response__9f200e6b.py", "order": 6, "original_content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "parent_variant_id": "pyint-a2c8065af72b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/wrappers.py#L222-L257", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-05ef9f200e6b-I06", "group_id": "py-97c0b066731d01aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 455, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-eabc9dfd2a8f-I07", "source": "from __future__ import annotations\nimport typing as t\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nclass Response(ResponseBase):\n    \"\"\"The response object that is used by default in Flask.  Works like the\n    response object from Werkzeug but is set to have an HTML mimetype by\n    default.  Quite often you don't have to create this object yourself because\n    :meth:`~flask.Flask.make_response` will take care of that for you.\n\n    If you want to replace the response object used you can subclass this and\n    set :attr:`~flask.Flask.response_class` to your subclass.\n\n    .. versionchanged:: 1.0\n        JSON support is added to the response, like the request. This is useful\n        when testing to get the test client response data as JSON.\n\n    .. versionchanged:: 1.0\n\n        Added :attr:`max_cookie_size`.\n    \"\"\"\n\n    default_mimetype: str | None = \"text/html\"\n\n    json_module = json\n\n    autocorrect_location_header = False\n\n    @property\n    def max_cookie_size(self) -> int:  # type: ignore\n        \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n        See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n        Werkzeug's docs.\n        \"\"\"\n        if ((0x35b0 ^ 0x35b0) != 0):\n            raise AssertionError()\n        if current_app:\n            return current_app.config[\"MAX_COOKIE_SIZE\"]  # type: ignore[no-any-return]\n\n        # return Werkzeug's default when not in an app context\n        return super().max_cookie_size\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-97c0b066731d01aa", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "75e0ac60b4298e551e9ba9a621574e26e4f93520a73cf4183160c88123d48f17", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 48, "local_path": "code-injection/insert-dead-branches/I07__flask__Response__9dfd2a8f.py", "order": 7, "original_content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "parent_variant_id": "pyint-a2c8065af72b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/wrappers.py#L222-L257", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-eabc9dfd2a8f-I07", "group_id": "py-97c0b066731d01aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 456, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-85cb547422f4-I08", "source": "from __future__ import annotations\nimport typing as t\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nclass Response(ResponseBase):\n    \"\"\"The response object that is used by default in Flask.  Works like the\n    response object from Werkzeug but is set to have an HTML mimetype by\n    default.  Quite often you don't have to create this object yourself because\n    :meth:`~flask.Flask.make_response` will take care of that for you.\n\n    If you want to replace the response object used you can subclass this and\n    set :attr:`~flask.Flask.response_class` to your subclass.\n\n    .. versionchanged:: 1.0\n        JSON support is added to the response, like the request. This is useful\n        when testing to get the test client response data as JSON.\n\n    .. versionchanged:: 1.0\n\n        Added :attr:`max_cookie_size`.\n    \"\"\"\n\n    default_mimetype: str | None = \"text/html\"\n\n    json_module = json\n\n    autocorrect_location_header = False\n\n    @property\n    def max_cookie_size(self) -> int:  # type: ignore\n        \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n        See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n        Werkzeug's docs.\n        \"\"\"\n        total_score = 240\n        number_of_scores = 3\n        average_score = total_score / number_of_scores\n        if current_app:\n            return current_app.config[\"MAX_COOKIE_SIZE\"]  # type: ignore[no-any-return]\n\n        # return Werkzeug's default when not in an app context\n        return super().max_cookie_size\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-97c0b066731d01aa", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "042e78554068f531559ca065e2399e0058ef23aa623a8788bfe676018925986b", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 49, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__Response__547422f4.py", "order": 8, "original_content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "parent_variant_id": "pyint-a2c8065af72b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/wrappers.py#L222-L257", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 5}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-85cb547422f4-I08", "group_id": "py-97c0b066731d01aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 457, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2ba97a1f844d-I09", "source": "from __future__ import annotations\nimport typing as t\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nclass Response(ResponseBase):\n    \"\"\"The response object that is used by default in Flask.  Works like the\n    response object from Werkzeug but is set to have an HTML mimetype by\n    default.  Quite often you don't have to create this object yourself because\n    :meth:`~flask.Flask.make_response` will take care of that for you.\n\n    If you want to replace the response object used you can subclass this and\n    set :attr:`~flask.Flask.response_class` to your subclass.\n\n    .. versionchanged:: 1.0\n        JSON support is added to the response, like the request. This is useful\n        when testing to get the test client response data as JSON.\n\n    .. versionchanged:: 1.0\n\n        Added :attr:`max_cookie_size`.\n    \"\"\"\n\n    default_mimetype: str | None = \"text/html\"\n\n    json_module = json\n\n    autocorrect_location_header = False\n\n    @property\n    def max_cookie_size(self) -> int:  # type: ignore\n        \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n        See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n        Werkzeug's docs.\n        \"\"\"\n        lI0O_4ca476b5, lI0O_d61a4e09 = 0, 0\n        while lI0O_d61a4e09 < 2:\n            lI0O_4ca476b5 ^= (lI0O_d61a4e09 << 1) ^ 0xf\n            lI0O_d61a4e09 += 1\n        lI0O_4ca476b5 ^= lI0O_4ca476b5\n        if current_app:\n            return current_app.config[\"MAX_COOKIE_SIZE\"]  # type: ignore[no-any-return]\n\n        # return Werkzeug's default when not in an app context\n        return super().max_cookie_size\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-97c0b066731d01aa", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "582498041a30a6290dcc2bfdeb6650a83381758789fe1dba6f57054384f6717e", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 51, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__Response__7a1f844d.py", "order": 9, "original_content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "parent_variant_id": "pyint-a2c8065af72b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/wrappers.py#L222-L257", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 2}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-2ba97a1f844d-I09", "group_id": "py-97c0b066731d01aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 458, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c01309ea49e0-I10", "source": "from __future__ import annotations\nimport typing as t\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nclass Response(ResponseBase):\n    \"\"\"The response object that is used by default in Flask.  Works like the\n    response object from Werkzeug but is set to have an HTML mimetype by\n    default.  Quite often you don't have to create this object yourself because\n    :meth:`~flask.Flask.make_response` will take care of that for you.\n    If you want to replace the response object used you can subclass this and\n    set :attr:`~flask.Flask.response_class` to your subclass.\n    .. versionchanged:: 1.0\n        JSON support is added to the response, like the request. This is useful\n        when testing to get the test client response data as JSON.\n\n    .. versionchanged:: 1.0\n\n        Added :attr:`max_cookie_size`.\n    \"\"\"\n\n    default_mimetype: str | None = \"text/html\"\n\n    json_module = json\n    autocorrect_location_header = False\n\n    @property\n    def max_cookie_size(self) -> int:  # type: ignore\n        \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n        See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n        Werkzeug's docs.\n        \"\"\"\n        if current_app:\n            return current_app.config[\"MAX_COOKIE_SIZE\"]  # type: ignore[no-any-return]\n        # return Werkzeug's default when not in an app context\n        return super().max_cookie_size\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-97c0b066731d01aa", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "2b9eef03259afb2531ccb455d35e03eabbb638e87a4e9f9cc3a67d69304fd4ef", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 42, "local_path": "layout/partially-compact-layout/I10__flask__Response__09ea49e0.py", "order": 10, "original_content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "parent_variant_id": "pyint-a2c8065af72b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/wrappers.py#L222-L257", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 11, "line_break_groups_removed": 4, "line_breaks_removed": 4, "whitespace_characters_removed": 4}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-c01309ea49e0-I10", "group_id": "py-97c0b066731d01aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 459, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f000b176d36c-I11", "source": "from __future__ import annotations\nimport typing as t\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nclass Response(ResponseBase):\n    \"\"\"The response object that is used by default in Flask.  Works like the\n    response object from Werkzeug but is set to have an HTML mimetype by\n    default.  Quite often you don't have to create this object yourself because\n    :meth:`~flask.Flask.make_response` will take care of that for you.\n\n    If you want to replace the response object used you can subclass this and\n    set :attr:`~flask.Flask.response_class` to your subclass.\n\n    .. versionchanged:: 1.0\n        JSON support is added to the response, like the request. This is useful\n        when testing to get the test client response data as JSON.\n\n    .. versionchanged:: 1.0\n\n        Added :attr:`max_cookie_size`.\n    \"\"\"\n\n    default_mimetype: str | None = \"text/html\"\n\n    json_module = json\n\n    autocorrect_location_header = False\n\n    @property\n    def max_cookie_size(self) -> int:  # type: ignore\n        \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n        See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n        Werkzeug's docs.\n        \"\"\"\n        if current_app:\n            return current_app.config[\"MAX_COOKIE_SIZE\"]  # type: ignore[no-any-return]\n\n        # return Werkzeug's default when not in an app context\n        return super().max_cookie_size\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-97c0b066731d01aa", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 46, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__Response__b176d36c.py", "order": 11, "original_content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "parent_variant_id": "pyint-a2c8065af72b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/wrappers.py#L222-L257", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-f000b176d36c-I11", "group_id": "py-97c0b066731d01aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 460, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-afebac86b09b-I12", "source": "from __future__ import annotations\nimport typing as t\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nclass Response(ResponseBase):\n    \"\"\"The response object that is used by default in Flask.  Works like the\n    response object from Werkzeug but is set to have an HTML mimetype by\n    default.  Quite often you don't have to create this object yourself because\n    :meth:`~flask.Flask.make_response` will take care of that for you.\n\n    If you want to replace the response object used you can subclass this and\n    set :attr:`~flask.Flask.response_class` to your subclass.\n\n    .. versionchanged:: 1.0\n        JSON support is added to the response, like the request. This is useful\n        when testing to get the test client response data as JSON.\n\n    .. versionchanged:: 1.0\n\n        Added :attr:`max_cookie_size`.\n    \"\"\"\n\n    default_mimetype: str | None = \"text/html\"\n\n    json_module = json\n\n    autocorrect_location_header = False\n\n    @property\n    def max_cookie_size(self) -> int:  # type: ignore\n        \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n        See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n        Werkzeug's docs.\n        \"\"\"\n        if current_app:\n            return current_app.config[\"MAX_COOKIE_SIZE\"]  # type: ignore[no-any-return]\n\n        # return Werkzeug's default when not in an app context\n        return super().max_cookie_size\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-97c0b066731d01aa", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 46, "local_path": "data-flow/inline-intermediate-variables/I12__flask__Response__ac86b09b.py", "order": 12, "original_content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "parent_variant_id": "pyint-a2c8065af72b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/wrappers.py#L222-L257", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-afebac86b09b-I12", "group_id": "py-97c0b066731d01aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 461, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4edfe2388282-I13", "source": "from __future__ import annotations\nimport typing as t\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nclass Response(ResponseBase):\n    \"\"\"The response object that is used by default in Flask.  Works like the\n    response object from Werkzeug but is set to have an HTML mimetype by\n    default.  Quite often you don't have to create this object yourself because\n    :meth:`~flask.Flask.make_response` will take care of that for you.\n\n    If you want to replace the response object used you can subclass this and\n    set :attr:`~flask.Flask.response_class` to your subclass.\n\n    .. versionchanged:: 1.0\n        JSON support is added to the response, like the request. This is useful\n        when testing to get the test client response data as JSON.\n\n    .. versionchanged:: 1.0\n\n        Added :attr:`max_cookie_size`.\n    \"\"\"\n\n    default_mimetype: str | None = \"text/html\"\n\n    json_module = json\n\n    autocorrect_location_header = False\n\n    @property\n    def max_cookie_size(self) -> int:  # type: ignore\n        \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n        See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n        Werkzeug's docs.\n        \"\"\"\n        if current_app:\n            return current_app.config[\"MAX_COOKIE_SIZE\"]  # type: ignore[no-any-return]\n\n        # return Werkzeug's default when not in an app context\n        return super().max_cookie_size\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-97c0b066731d01aa", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 46, "local_path": "control-flow/lower-for-to-while/I13__flask__Response__e2388282.py", "order": 13, "original_content_sha256": "186975218804fc07b8b9908ee0c37a4c35567117696a4ddea961445c43c39322", "parent_variant_id": "pyint-a2c8065af72b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/wrappers.py#L222-L257", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "Response", "variant_id": "pyint-4edfe2388282-I13", "group_id": "py-97c0b066731d01aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 462, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-838b0a48e856-SRC", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestEncodingMixin:\n    url: str | None\n\n    @property\n    def path_url(self) -> str:\n        \"\"\"Build the path URL to use.\"\"\"\n\n        url: list[str] = []\n\n        p = urlsplit(cast(str, self.url))\n\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n            url.append(\"?\")\n            url.append(query)\n\n        return \"\".join(url)\n\n    @overload\n    @staticmethod\n    def _encode_params(data: str) -> str: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: bytes) -> bytes: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(\n        data: _t.SupportsRead[str | bytes],\n    ) -> _t.SupportsRead[str | bytes]: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: _t.KVDataType) -> str: ...\n\n    @staticmethod\n    def _encode_params(\n        data: _t.EncodableDataType,\n    ) -> str | bytes | _t.SupportsRead[str | bytes]:\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n\n        if isinstance(data, (str, bytes)):\n            return data\n        elif _t.has_read(data):\n            return data\n        elif hasattr(data, \"__iter__\"):\n            result: list[tuple[bytes, bytes]] = []\n            for k, vs in to_key_val_list(data):\n                if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n                    vs = [vs]\n                for v in vs:\n                    if v is not None:\n                        result.append(\n                            (\n                                k.encode(\"utf-8\") if isinstance(k, str) else k,\n                                v.encode(\"utf-8\") if isinstance(v, str) else v,\n                            )\n                        )\n            return urlencode(result, doseq=True)\n        else:\n            return data  # type: ignore[return-value]  # unreachable for valid _t.DataType\n\n    @staticmethod\n    def _encode_files(\n        files: _t.FilesType, data: _t.RawDataType | None\n    ) -> tuple[bytes, str]:\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if not files:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(data, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        new_fields: list[RequestField | tuple[str, bytes]] = []\n        fields = to_key_val_list(data or {})\n        files = to_key_val_list(files or {})\n\n        for field, val in fields:\n            if isinstance(val, basestring) or not hasattr(val, \"__iter__\"):\n                val = [val]\n            for v in val:\n                if v is not None:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(v, bytes):\n                        v = str(v)\n\n                    new_fields.append(\n                        (\n                            field.decode(\"utf-8\")\n                            if isinstance(field, bytes)\n                            else field,\n                            v.encode(\"utf-8\") if isinstance(v, str) else v,\n                        )\n                    )\n\n        for k, v in files:\n            # support for explicit filename\n            ft = None\n            fh = None\n            if isinstance(v, (tuple, list)):\n                if len(v) == 2:\n                    fn, fp = v\n                elif len(v) == 3:\n                    fn, fp, ft = v\n                else:\n                    fn, fp, ft, fh = v\n            else:\n                fn = guess_filename(v) or k\n                fp = v\n\n            if isinstance(fp, (str, bytes, bytearray)):\n                fdata = fp\n            elif _t.has_read(fp):\n                fdata = fp.read()\n            elif fp is None:  # defensive check for untyped callers\n                continue\n            else:\n                fdata = fp\n\n            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n            rf.make_multipart(content_type=ft)\n            new_fields.append(rf)\n\n        body, content_type = encode_multipart_formdata(new_fields)\n\n        return body, content_type\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-9a65114ab4a55ac6", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 214, "local_path": "source-original/SRC__requests__RequestEncodingMixin__0a48e856.py", "order": 0, "original_content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L108-L251", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "RequestEncodingMixin", "variant_id": "pyint-838b0a48e856-SRC", "group_id": "py-9a65114ab4a55ac6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 757, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b0d43fbb9c3a-I01", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna   \nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestEncodingMixin:\n    url: str | None\n\n    @property\n    def path_url(self) -> str:\n        \n\n        url: list[str] = []\n\n        p = urlsplit(cast(str, self.url))\n\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n            url.append(\"?\")\n            url.append(query)\n\n        return \"\".join(url)\n\n    @overload\n    @staticmethod\n    def _encode_params(data: str) -> str: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: bytes) -> bytes: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(\n        data: _t.SupportsRead[str | bytes],\n    ) -> _t.SupportsRead[str | bytes]: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: _t.KVDataType) -> str: ...\n\n    @staticmethod\n    def _encode_params(\n        data: _t.EncodableDataType,\n    ) -> str | bytes | _t.SupportsRead[str | bytes]:\n        \n\n        if isinstance(data, (str, bytes)):\n            return data\n        elif _t.has_read(data):\n            return data\n        elif hasattr(data, \"__iter__\"):\n            result: list[tuple[bytes, bytes]] = []\n            for k, vs in to_key_val_list(data):\n                if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n                    vs = [vs]\n                for v in vs:\n                    if v is not None:\n                        result.append(\n                            (\n                                k.encode(\"utf-8\") if isinstance(k, str) else k,\n                                v.encode(\"utf-8\") if isinstance(v, str) else v,\n                            )\n                        )\n            return urlencode(result, doseq=True)\n        else:\n            return data   \n\n    @staticmethod\n    def _encode_files(\n        files: _t.FilesType, data: _t.RawDataType | None\n    ) -> tuple[bytes, str]:\n        \n        if not files:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(data, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        new_fields: list[RequestField | tuple[str, bytes]] = []\n        fields = to_key_val_list(data or {})\n        files = to_key_val_list(files or {})\n\n        for field, val in fields:\n            if isinstance(val, basestring) or not hasattr(val, \"__iter__\"):\n                val = [val]\n            for v in val:\n                if v is not None:\n                     \n                    if not isinstance(v, bytes):\n                        v = str(v)\n\n                    new_fields.append(\n                        (\n                            field.decode(\"utf-8\")\n                            if isinstance(field, bytes)\n                            else field,\n                            v.encode(\"utf-8\") if isinstance(v, str) else v,\n                        )\n                    )\n\n        for k, v in files:\n             \n            ft = None\n            fh = None\n            if isinstance(v, (tuple, list)):\n                if len(v) == 2:\n                    fn, fp = v\n                elif len(v) == 3:\n                    fn, fp, ft = v\n                else:\n                    fn, fp, ft, fh = v\n            else:\n                fn = guess_filename(v) or k\n                fp = v\n\n            if isinstance(fp, (str, bytes, bytearray)):\n                fdata = fp\n            elif _t.has_read(fp):\n                fdata = fp.read()\n            elif fp is None:   \n                continue\n            else:\n                fdata = fp\n\n            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n            rf.make_multipart(content_type=ft)\n            new_fields.append(rf)\n\n        body, content_type = encode_multipart_formdata(new_fields)\n\n        return body, content_type\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-9a65114ab4a55ac6", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "7aea7f777703c57d3bc8f2f39a72fe86d918ef0d9e58ef12dbb3c242cf91c784", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 202, "local_path": "comments/remove-comments/I01__requests__RequestEncodingMixin__3fbb9c3a.py", "order": 1, "original_content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "parent_variant_id": "pyint-838b0a48e856-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L108-L251", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 917, "comments_removed": 8, "docstrings_removed": 3, "line_comments_removed": 5}, "unit_kind": "class", "unit_name": "RequestEncodingMixin", "variant_id": "pyint-b0d43fbb9c3a-I01", "group_id": "py-9a65114ab4a55ac6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 758, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-064fb432e990-I02", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestEncodingMixin:\n    url: str | None\n\n    @property\n    def path2(self) -> str:\n        \"\"\"Build the path URL to use.\"\"\"\n\n        url2: list[str] = []\n\n        p2 = urlsplit(cast(str, self.url))\n\n        pat = p2.path\n        if not pat:\n            pat = \"/\"\n\n        url2.append(pat)\n\n        que = p2.query\n        if que:\n            url2.append(\"?\")\n            url2.append(que)\n\n        return \"\".join(url2)\n\n    @overload\n    @staticmethod\n    def encode6(dat: str) -> str: ...\n\n    @overload\n    @staticmethod\n    def encode6(dat2: bytes) -> bytes: ...\n\n    @overload\n    @staticmethod\n    def encode6(\n        dat3: _t.SupportsRead[str | bytes],\n    ) -> _t.SupportsRead[str | bytes]: ...\n\n    @overload\n    @staticmethod\n    def encode6(dat4: _t.KVDataType) -> str: ...\n\n    @staticmethod\n    def encode6(\n        dat5: _t.EncodableDataType,\n    ) -> str | bytes | _t.SupportsRead[str | bytes]:\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n\n        if isinstance(dat5, (str, bytes)):\n            return dat5\n        elif _t.has_read(dat5):\n            return dat5\n        elif hasattr(dat5, \"__iter__\"):\n            res: list[tuple[bytes, bytes]] = []\n            for k2, vs2 in to_key_val_list(dat5):\n                if isinstance(vs2, basestring) or not hasattr(vs2, \"__iter__\"):\n                    vs2 = [vs2]\n                for v2 in vs2:\n                    if v2 is not None:\n                        res.append(\n                            (\n                                k2.encode(\"utf-8\") if isinstance(k2, str) else k2,\n                                v2.encode(\"utf-8\") if isinstance(v2, str) else v2,\n                            )\n                        )\n            return urlencode(res, doseq=True)\n        else:\n            return dat5  # type: ignore[return-value]  # unreachable for valid _t.DataType\n\n    @staticmethod\n    def encode7(\n        fil: _t.FilesType, dat6: _t.RawDataType | None\n    ) -> tuple[bytes, str]:\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if not fil:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(dat6, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        new: list[RequestField | tuple[str, bytes]] = []\n        fie = to_key_val_list(dat6 or {})\n        fil = to_key_val_list(fil or {})\n\n        for fie2, val2 in fie:\n            if isinstance(val2, basestring) or not hasattr(val2, \"__iter__\"):\n                val2 = [val2]\n            for v3 in val2:\n                if v3 is not None:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(v3, bytes):\n                        v3 = str(v3)\n\n                    new.append(\n                        (\n                            fie2.decode(\"utf-8\")\n                            if isinstance(fie2, bytes)\n                            else fie2,\n                            v3.encode(\"utf-8\") if isinstance(v3, str) else v3,\n                        )\n                    )\n\n        for k3, v3 in fil:\n            # support for explicit filename\n            ft2 = None\n            fh2 = None\n            if isinstance(v3, (tuple, list)):\n                if len(v3) == 2:\n                    fn2, fp2 = v3\n                elif len(v3) == 3:\n                    fn2, fp2, ft2 = v3\n                else:\n                    fn2, fp2, ft2, fh2 = v3\n            else:\n                fn2 = guess_filename(v3) or k3\n                fp2 = v3\n\n            if isinstance(fp2, (str, bytes, bytearray)):\n                fda = fp2\n            elif _t.has_read(fp2):\n                fda = fp2.read()\n            elif fp2 is None:  # defensive check for untyped callers\n                continue\n            else:\n                fda = fp2\n\n            rf2 = RequestField(name=k3, data=fda, filename=fn2, headers=fh2)\n            rf2.make_multipart(content_type=ft2)\n            new.append(rf2)\n\n        bod, content = encode_multipart_formdata(new)\n\n        return bod, content\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-9a65114ab4a55ac6", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "337e23d8cd70a55d96d625b9d9a39366129bf048d43b2d139dacc3396347e75e", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 214, "local_path": "identifiers/shorten-identifiers/I02__requests__RequestEncodingMixin__b432e990.py", "order": 2, "original_content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "parent_variant_id": "pyint-838b0a48e856-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L108-L251", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 129, "identifiers_declared": 36}, "unit_kind": "class", "unit_name": "RequestEncodingMixin", "variant_id": "pyint-064fb432e990-I02", "group_id": "py-9a65114ab4a55ac6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 759, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-05cb3c018c91-I03", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestEncodingMixin:\n    url: str | None\n\n    @property\n    def findItem(self) -> str:\n        \"\"\"Build the path URL to use.\"\"\"\n\n        age: list[str] = []\n\n        key = urlsplit(cast(str, self.url))\n\n        date = key.path\n        if not date:\n            date = \"/\"\n\n        age.append(date)\n\n        limit = key.query\n        if limit:\n            age.append(\"?\")\n            age.append(limit)\n\n        return \"\".join(age)\n\n    @overload\n    @staticmethod\n    def validateClient(node: str) -> str: ...\n\n    @overload\n    @staticmethod\n    def validateClient(flag: bytes) -> bytes: ...\n\n    @overload\n    @staticmethod\n    def validateClient(\n        user: _t.SupportsRead[str | bytes],\n    ) -> _t.SupportsRead[str | bytes]: ...\n\n    @overload\n    @staticmethod\n    def validateClient(date: _t.KVDataType) -> str: ...\n\n    @staticmethod\n    def validateClient(\n        path: _t.EncodableDataType,\n    ) -> str | bytes | _t.SupportsRead[str | bytes]:\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n\n        if isinstance(path, (str, bytes)):\n            return path\n        elif _t.has_read(path):\n            return path\n        elif hasattr(path, \"__iter__\"):\n            source: list[tuple[bytes, bytes]] = []\n            for age, map in to_key_val_list(path):\n                if isinstance(map, basestring) or not hasattr(map, \"__iter__\"):\n                    map = [map]\n                for key in map:\n                    if key is not None:\n                        source.append(\n                            (\n                                age.encode(\"utf-8\") if isinstance(age, str) else age,\n                                key.encode(\"utf-8\") if isinstance(key, str) else key,\n                            )\n                        )\n            return urlencode(source, doseq=True)\n        else:\n            return path  # type: ignore[return-value]  # unreachable for valid _t.DataType\n\n    @staticmethod\n    def validateOrder(\n        count: _t.FilesType, user: _t.RawDataType | None\n    ) -> tuple[bytes, str]:\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if not count:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(user, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        finalCount: list[RequestField | tuple[str, bytes]] = []\n        amount = to_key_val_list(user or {})\n        count = to_key_val_list(count or {})\n\n        for price, map in amount:\n            if isinstance(map, basestring) or not hasattr(map, \"__iter__\"):\n                map = [map]\n            for age in map:\n                if age is not None:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(age, bytes):\n                        age = str(age)\n\n                    finalCount.append(\n                        (\n                            price.decode(\"utf-8\")\n                            if isinstance(price, bytes)\n                            else price,\n                            age.encode(\"utf-8\") if isinstance(age, str) else age,\n                        )\n                    )\n\n        for key, age in count:\n            # support for explicit filename\n            step = None\n            date = None\n            if isinstance(age, (tuple, list)):\n                if len(age) == 2:\n                    size, node = age\n                elif len(age) == 3:\n                    size, node, step = age\n                else:\n                    size, node, step, date = age\n            else:\n                size = guess_filename(age) or key\n                node = age\n\n            if isinstance(node, (str, bytes, bytearray)):\n                score = node\n            elif _t.has_read(node):\n                score = node.read()\n            elif node is None:  # defensive check for untyped callers\n                continue\n            else:\n                score = node\n\n            item = RequestField(name=key, data=score, filename=size, headers=date)\n            item.make_multipart(content_type=step)\n            finalCount.append(item)\n\n        mode, pendingIndex = encode_multipart_formdata(finalCount)\n\n        return mode, pendingIndex\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-9a65114ab4a55ac6", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "3b6f3fc27cbe5ba5444f16e7f238bab1a2eff275cdf0d8aaeb49e8ff7c222b1f", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 214, "local_path": "identifiers/mislead-identifiers/I03__requests__RequestEncodingMixin__3c018c91.py", "order": 3, "original_content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "parent_variant_id": "pyint-838b0a48e856-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L108-L251", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 129, "identifiers_declared": 36, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 26, "local_exact_length_matches": 18, "local_random_pool_selections": 29, "local_total_length_difference": 21, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 3, "method_random_pool_selections": 7, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "RequestEncodingMixin", "variant_id": "pyint-05cb3c018c91-I03", "group_id": "py-9a65114ab4a55ac6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 760, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-57f9b8e629ff-I04", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestEncodingMixin:\n    url: str | None\n\n    @property\n    def a(self) -> str:\n        \"\"\"Build the path URL to use.\"\"\"\n\n        h: list[str] = []\n\n        i = urlsplit(cast(str, self.url))\n\n        j = i.path\n        if not j:\n            j = \"/\"\n\n        h.append(j)\n\n        l = i.query\n        if l:\n            h.append(\"?\")\n            h.append(l)\n\n        return \"\".join(h)\n\n    @overload\n    @staticmethod\n    def f(m: str) -> str: ...\n\n    @overload\n    @staticmethod\n    def f(n: bytes) -> bytes: ...\n\n    @overload\n    @staticmethod\n    def f(\n        o: _t.SupportsRead[str | bytes],\n    ) -> _t.SupportsRead[str | bytes]: ...\n\n    @overload\n    @staticmethod\n    def f(q: _t.KVDataType) -> str: ...\n\n    @staticmethod\n    def f(\n        r: _t.EncodableDataType,\n    ) -> str | bytes | _t.SupportsRead[str | bytes]:\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n\n        if isinstance(r, (str, bytes)):\n            return r\n        elif _t.has_read(r):\n            return r\n        elif hasattr(r, \"__iter__\"):\n            s: list[tuple[bytes, bytes]] = []\n            for t, u in to_key_val_list(r):\n                if isinstance(u, basestring) or not hasattr(u, \"__iter__\"):\n                    u = [u]\n                for w in u:\n                    if w is not None:\n                        s.append(\n                            (\n                                t.encode(\"utf-8\") if isinstance(t, str) else t,\n                                w.encode(\"utf-8\") if isinstance(w, str) else w,\n                            )\n                        )\n            return urlencode(s, doseq=True)\n        else:\n            return r  # type: ignore[return-value]  # unreachable for valid _t.DataType\n\n    @staticmethod\n    def g(\n        x: _t.FilesType, y: _t.RawDataType | None\n    ) -> tuple[bytes, str]:\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if not x:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(y, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        z: list[RequestField | tuple[str, bytes]] = []\n        A = to_key_val_list(y or {})\n        x = to_key_val_list(x or {})\n\n        for B, C in A:\n            if isinstance(C, basestring) or not hasattr(C, \"__iter__\"):\n                C = [C]\n            for D in C:\n                if D is not None:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(D, bytes):\n                        D = str(D)\n\n                    z.append(\n                        (\n                            B.decode(\"utf-8\")\n                            if isinstance(B, bytes)\n                            else B,\n                            D.encode(\"utf-8\") if isinstance(D, str) else D,\n                        )\n                    )\n\n        for E, D in x:\n            # support for explicit filename\n            F = None\n            G = None\n            if isinstance(D, (tuple, list)):\n                if len(D) == 2:\n                    H, I = D\n                elif len(D) == 3:\n                    H, I, F = D\n                else:\n                    H, I, F, G = D\n            else:\n                H = guess_filename(D) or E\n                I = D\n\n            if isinstance(I, (str, bytes, bytearray)):\n                J = I\n            elif _t.has_read(I):\n                J = I.read()\n            elif I is None:  # defensive check for untyped callers\n                continue\n            else:\n                J = I\n\n            K = RequestField(name=E, data=J, filename=H, headers=G)\n            K.make_multipart(content_type=F)\n            z.append(K)\n\n        L, M = encode_multipart_formdata(z)\n\n        return L, M\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-9a65114ab4a55ac6", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "1fc8f57b63f9daae2774898e6a193034fad2caa70b682f4f01881b265bd71869", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 214, "local_path": "identifiers/garble-identifiers/I04__requests__RequestEncodingMixin__b8e629ff.py", "order": 4, "original_content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "parent_variant_id": "pyint-838b0a48e856-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L108-L251", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 129, "identifiers_declared": 36}, "unit_kind": "class", "unit_name": "RequestEncodingMixin", "variant_id": "pyint-57f9b8e629ff-I04", "group_id": "py-9a65114ab4a55ac6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 761, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0b39cd0f771e-I05", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestEncodingMixin:\n    url: str | None\n\n    @property\n    def path_url(self) -> str:\n        \"\"\"Build the path URL to use.\"\"\"\n\n        url: list[str] = []\n\n        p = urlsplit(cast(str, self.url))\n\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n            url.append(\"?\")\n            url.append(query)\n\n        return \"\".join(url)\n\n    @overload\n    @staticmethod\n    def _encode_params(data: str) -> str: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: bytes) -> bytes: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(\n        data: _t.SupportsRead[str | bytes],\n    ) -> _t.SupportsRead[str | bytes]: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: _t.KVDataType) -> str: ...\n\n    @staticmethod\n    def _encode_params(\n        data: _t.EncodableDataType,\n    ) -> str | bytes | _t.SupportsRead[str | bytes]:\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n\n        if isinstance(data, (str, bytes)):\n            return data\n        elif _t.has_read(data):\n            return data\n        elif hasattr(data, \"__iter__\"):\n            result: list[tuple[bytes, bytes]] = []\n            for k, vs in to_key_val_list(data):\n                if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n                    vs = [vs]\n                for v in vs:\n                    if v is not None:\n                        result.append(\n                            (\n                                k.encode(\"utf-8\") if isinstance(k, str) else k,\n                                v.encode(\"utf-8\") if isinstance(v, str) else v,\n                            )\n                        )\n            return urlencode(result, doseq=True)\n        else:\n            return data  # type: ignore[return-value]  # unreachable for valid _t.DataType\n\n    @staticmethod\n    def _encode_files(\n        files: _t.FilesType, data: _t.RawDataType | None\n    ) -> tuple[bytes, str]:\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if not files:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(data, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        new_fields: list[RequestField | tuple[str, bytes]] = []\n        fields = to_key_val_list(data or {})\n        files = to_key_val_list(files or {})\n\n        for field, val in fields:\n            if isinstance(val, basestring) or not hasattr(val, \"__iter__\"):\n                val = [val]\n            for v in val:\n                if v is not None:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(v, bytes):\n                        v = str(v)\n\n                    new_fields.append(\n                        (\n                            field.decode(\"utf-8\")\n                            if isinstance(field, bytes)\n                            else field,\n                            v.encode(\"utf-8\") if isinstance(v, str) else v,\n                        )\n                    )\n\n        for k, v in files:\n            # support for explicit filename\n            ft = None\n            fh = None\n            if isinstance(v, (tuple, list)):\n                if len(v) == 0x2:\n                    fn, fp = v\n                elif len(v) == 0x3:\n                    fn, fp, ft = v\n                else:\n                    fn, fp, ft, fh = v\n            else:\n                fn = guess_filename(v) or k\n                fp = v\n\n            if isinstance(fp, (str, bytes, bytearray)):\n                fdata = fp\n            elif _t.has_read(fp):\n                fdata = fp.read()\n            elif fp is None:  # defensive check for untyped callers\n                continue\n            else:\n                fdata = fp\n\n            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n            rf.make_multipart(content_type=ft)\n            new_fields.append(rf)\n\n        body, content_type = encode_multipart_formdata(new_fields)\n\n        return body, content_type\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-9a65114ab4a55ac6", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "06e9ed98c5455b97163f51f254e874e35b81a079f7f6caeef1ffbf41154b26ed", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 214, "local_path": "expressions/encode-integer-literals/I05__requests__RequestEncodingMixin__cd0f771e.py", "order": 5, "original_content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "parent_variant_id": "pyint-838b0a48e856-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L108-L251", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 2}, "unit_kind": "class", "unit_name": "RequestEncodingMixin", "variant_id": "pyint-0b39cd0f771e-I05", "group_id": "py-9a65114ab4a55ac6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 762, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-554d82fc50e3-I06", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestEncodingMixin:\n    url: str | None\n\n    @property\n    def path_url(self) -> str:\n        \"\"\"Build the path URL to use.\"\"\"\n\n        url: list[str] = []\n\n        p = urlsplit(cast(str, self.url))\n\n        path = p.path\n        if not (not path):\n            pass\n        else:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if not (query):\n            pass\n        else:\n            url.append(\"?\")\n            url.append(query)\n\n        return \"\".join(url)\n\n    @overload\n    @staticmethod\n    def _encode_params(data: str) -> str: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: bytes) -> bytes: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(\n        data: _t.SupportsRead[str | bytes],\n    ) -> _t.SupportsRead[str | bytes]: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: _t.KVDataType) -> str: ...\n\n    @staticmethod\n    def _encode_params(\n        data: _t.EncodableDataType,\n    ) -> str | bytes | _t.SupportsRead[str | bytes]:\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n\n        if isinstance(data, (str, bytes)):\n            return data\n        elif _t.has_read(data):\n            return data\n        elif hasattr(data, \"__iter__\"):\n            result: list[tuple[bytes, bytes]] = []\n            for k, vs in to_key_val_list(data):\n                if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n                    vs = [vs]\n                for v in vs:\n                    if v is not None:\n                        result.append(\n                            (\n                                k.encode(\"utf-8\") if isinstance(k, str) else k,\n                                v.encode(\"utf-8\") if isinstance(v, str) else v,\n                            )\n                        )\n            return urlencode(result, doseq=True)\n        else:\n            return data  # type: ignore[return-value]  # unreachable for valid _t.DataType\n\n    @staticmethod\n    def _encode_files(\n        files: _t.FilesType, data: _t.RawDataType | None\n    ) -> tuple[bytes, str]:\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if not files:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(data, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        new_fields: list[RequestField | tuple[str, bytes]] = []\n        fields = to_key_val_list(data or {})\n        files = to_key_val_list(files or {})\n\n        for field, val in fields:\n            if not (isinstance(val, basestring) or not hasattr(val, \"__iter__\")):\n                pass\n            else:\n                val = [val]\n            for v in val:\n                if not (v is not None):\n                    pass\n                else:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(v, bytes):\n                        v = str(v)\n\n                    new_fields.append(\n                        (\n                            field.decode(\"utf-8\")\n                            if isinstance(field, bytes)\n                            else field,\n                            v.encode(\"utf-8\") if isinstance(v, str) else v,\n                        )\n                    )\n\n        for k, v in files:\n            # support for explicit filename\n            ft = None\n            fh = None\n            if not (isinstance(v, (tuple, list))):\n                fn = guess_filename(v) or k\n                fp = v\n            else:\n                if len(v) == 2:\n                    fn, fp = v\n                elif len(v) == 3:\n                    fn, fp, ft = v\n                else:\n                    fn, fp, ft, fh = v\n\n            if isinstance(fp, (str, bytes, bytearray)):\n                fdata = fp\n            elif _t.has_read(fp):\n                fdata = fp.read()\n            elif fp is None:  # defensive check for untyped callers\n                continue\n            else:\n                fdata = fp\n\n            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n            rf.make_multipart(content_type=ft)\n            new_fields.append(rf)\n\n        body, content_type = encode_multipart_formdata(new_fields)\n\n        return body, content_type\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-9a65114ab4a55ac6", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "acbf35f9b8cea250b904f573ba2b6f88a41db99a112b6ff828f955fb461db8dd", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 222, "local_path": "expressions/invert-conditions/I06__requests__RequestEncodingMixin__82fc50e3.py", "order": 6, "original_content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "parent_variant_id": "pyint-838b0a48e856-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L108-L251", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 5}, "unit_kind": "class", "unit_name": "RequestEncodingMixin", "variant_id": "pyint-554d82fc50e3-I06", "group_id": "py-9a65114ab4a55ac6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 763, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9603ff0fba0d-I07", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestEncodingMixin:\n    url: str | None\n\n    @property\n    def path_url(self) -> str:\n        \"\"\"Build the path URL to use.\"\"\"\n        if ((0xc14c ^ 0xc14c) != 0):\n            raise AssertionError()\n\n        url: list[str] = []\n\n        p = urlsplit(cast(str, self.url))\n\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n            url.append(\"?\")\n            url.append(query)\n\n        return \"\".join(url)\n\n    @overload\n    @staticmethod\n    def _encode_params(data: str) -> str: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: bytes) -> bytes: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(\n        data: _t.SupportsRead[str | bytes],\n    ) -> _t.SupportsRead[str | bytes]: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: _t.KVDataType) -> str: ...\n\n    @staticmethod\n    def _encode_params(\n        data: _t.EncodableDataType,\n    ) -> str | bytes | _t.SupportsRead[str | bytes]:\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n        if ((0x1d02 ^ 0x1d02) != 0):\n            raise AssertionError()\n\n        if isinstance(data, (str, bytes)):\n            return data\n        elif _t.has_read(data):\n            return data\n        elif hasattr(data, \"__iter__\"):\n            result: list[tuple[bytes, bytes]] = []\n            for k, vs in to_key_val_list(data):\n                if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n                    vs = [vs]\n                for v in vs:\n                    if v is not None:\n                        result.append(\n                            (\n                                k.encode(\"utf-8\") if isinstance(k, str) else k,\n                                v.encode(\"utf-8\") if isinstance(v, str) else v,\n                            )\n                        )\n            return urlencode(result, doseq=True)\n        else:\n            return data  # type: ignore[return-value]  # unreachable for valid _t.DataType\n\n    @staticmethod\n    def _encode_files(\n        files: _t.FilesType, data: _t.RawDataType | None\n    ) -> tuple[bytes, str]:\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if ((0x5d2c ^ 0x5d2c) != 0):\n            raise AssertionError()\n        if not files:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(data, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        new_fields: list[RequestField | tuple[str, bytes]] = []\n        fields = to_key_val_list(data or {})\n        files = to_key_val_list(files or {})\n\n        for field, val in fields:\n            if isinstance(val, basestring) or not hasattr(val, \"__iter__\"):\n                val = [val]\n            for v in val:\n                if v is not None:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(v, bytes):\n                        v = str(v)\n\n                    new_fields.append(\n                        (\n                            field.decode(\"utf-8\")\n                            if isinstance(field, bytes)\n                            else field,\n                            v.encode(\"utf-8\") if isinstance(v, str) else v,\n                        )\n                    )\n\n        for k, v in files:\n            # support for explicit filename\n            ft = None\n            fh = None\n            if isinstance(v, (tuple, list)):\n                if len(v) == 2:\n                    fn, fp = v\n                elif len(v) == 3:\n                    fn, fp, ft = v\n                else:\n                    fn, fp, ft, fh = v\n            else:\n                fn = guess_filename(v) or k\n                fp = v\n\n            if isinstance(fp, (str, bytes, bytearray)):\n                fdata = fp\n            elif _t.has_read(fp):\n                fdata = fp.read()\n            elif fp is None:  # defensive check for untyped callers\n                continue\n            else:\n                fdata = fp\n\n            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n            rf.make_multipart(content_type=ft)\n            new_fields.append(rf)\n\n        body, content_type = encode_multipart_formdata(new_fields)\n\n        return body, content_type\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-9a65114ab4a55ac6", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "efa115b620f61486ef63f1cdd9aa5423e50a6677b190968b347eaa06168f3989", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 220, "local_path": "code-injection/insert-dead-branches/I07__requests__RequestEncodingMixin__ff0fba0d.py", "order": 7, "original_content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "parent_variant_id": "pyint-838b0a48e856-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L108-L251", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 3}, "unit_kind": "class", "unit_name": "RequestEncodingMixin", "variant_id": "pyint-9603ff0fba0d-I07", "group_id": "py-9a65114ab4a55ac6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 764, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e7601f2d1d27-I08", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestEncodingMixin:\n    url: str | None\n\n    @property\n    def path_url(self) -> str:\n        \"\"\"Build the path URL to use.\"\"\"\n        remaining_steps = 3\n        while remaining_steps > 0:\n            remaining_steps -= 1\n\n        url: list[str] = []\n\n        p = urlsplit(cast(str, self.url))\n\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n            url.append(\"?\")\n            url.append(query)\n\n        return \"\".join(url)\n\n    @overload\n    @staticmethod\n    def _encode_params(data: str) -> str: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: bytes) -> bytes: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(\n        data: _t.SupportsRead[str | bytes],\n    ) -> _t.SupportsRead[str | bytes]: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: _t.KVDataType) -> str: ...\n\n    @staticmethod\n    def _encode_params(\n        data: _t.EncodableDataType,\n    ) -> str | bytes | _t.SupportsRead[str | bytes]:\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n\n        if isinstance(data, (str, bytes)):\n            return data\n        elif _t.has_read(data):\n            return data\n        elif hasattr(data, \"__iter__\"):\n            result: list[tuple[bytes, bytes]] = []\n            for k, vs in to_key_val_list(data):\n                if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n                    vs = [vs]\n                for v in vs:\n                    if v is not None:\n                        result.append(\n                            (\n                                k.encode(\"utf-8\") if isinstance(k, str) else k,\n                                v.encode(\"utf-8\") if isinstance(v, str) else v,\n                            )\n                        )\n            return urlencode(result, doseq=True)\n        else:\n            return data  # type: ignore[return-value]  # unreachable for valid _t.DataType\n\n    @staticmethod\n    def _encode_files(\n        files: _t.FilesType, data: _t.RawDataType | None\n    ) -> tuple[bytes, str]:\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if not files:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(data, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        new_fields: list[RequestField | tuple[str, bytes]] = []\n        fields = to_key_val_list(data or {})\n        files = to_key_val_list(files or {})\n\n        for field, val in fields:\n            if isinstance(val, basestring) or not hasattr(val, \"__iter__\"):\n                val = [val]\n            for v in val:\n                if v is not None:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(v, bytes):\n                        v = str(v)\n\n                    new_fields.append(\n                        (\n                            field.decode(\"utf-8\")\n                            if isinstance(field, bytes)\n                            else field,\n                            v.encode(\"utf-8\") if isinstance(v, str) else v,\n                        )\n                    )\n\n        for k, v in files:\n            # support for explicit filename\n            ft = None\n            fh = None\n            if isinstance(v, (tuple, list)):\n                if len(v) == 2:\n                    fn, fp = v\n                elif len(v) == 3:\n                    fn, fp, ft = v\n                else:\n                    fn, fp, ft, fh = v\n            else:\n                fn = guess_filename(v) or k\n                fp = v\n\n            if isinstance(fp, (str, bytes, bytearray)):\n                fdata = fp\n            elif _t.has_read(fp):\n                fdata = fp.read()\n            elif fp is None:  # defensive check for untyped callers\n                continue\n            else:\n                fdata = fp\n\n            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n            rf.make_multipart(content_type=ft)\n            new_fields.append(rf)\n\n        body, content_type = encode_multipart_formdata(new_fields)\n\n        return body, content_type\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-9a65114ab4a55ac6", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "aef239afdf7e6daf62995cd939fe353ff3eb9b630d27a7329e5fd0ef1560bfa5", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 217, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__RequestEncodingMixin__1f2d1d27.py", "order": 8, "original_content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "parent_variant_id": "pyint-838b0a48e856-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L108-L251", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 1}, "unit_kind": "class", "unit_name": "RequestEncodingMixin", "variant_id": "pyint-e7601f2d1d27-I08", "group_id": "py-9a65114ab4a55ac6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 765, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6f2e4bdacd4c-I09", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestEncodingMixin:\n    url: str | None\n\n    @property\n    def path_url(self) -> str:\n        \"\"\"Build the path URL to use.\"\"\"\n\n        url: list[str] = []\n\n        p = urlsplit(cast(str, self.url))\n\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n            url.append(\"?\")\n            url.append(query)\n\n        return \"\".join(url)\n\n    @overload\n    @staticmethod\n    def _encode_params(data: str) -> str: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: bytes) -> bytes: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(\n        data: _t.SupportsRead[str | bytes],\n    ) -> _t.SupportsRead[str | bytes]: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: _t.KVDataType) -> str: ...\n\n    @staticmethod\n    def _encode_params(\n        data: _t.EncodableDataType,\n    ) -> str | bytes | _t.SupportsRead[str | bytes]:\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n        lI0O_03302cbf = 0xee57 ^ 0xee57\n        if lI0O_03302cbf != 0:\n            if ((lI0O_03302cbf | 1) & 1) == 0:\n                lI0O_03302cbf += 1\n            else:\n                lI0O_03302cbf -= 1\n\n        if isinstance(data, (str, bytes)):\n            return data\n        elif _t.has_read(data):\n            return data\n        elif hasattr(data, \"__iter__\"):\n            result: list[tuple[bytes, bytes]] = []\n            for k, vs in to_key_val_list(data):\n                if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n                    vs = [vs]\n                for v in vs:\n                    if v is not None:\n                        result.append(\n                            (\n                                k.encode(\"utf-8\") if isinstance(k, str) else k,\n                                v.encode(\"utf-8\") if isinstance(v, str) else v,\n                            )\n                        )\n            return urlencode(result, doseq=True)\n        else:\n            return data  # type: ignore[return-value]  # unreachable for valid _t.DataType\n\n    @staticmethod\n    def _encode_files(\n        files: _t.FilesType, data: _t.RawDataType | None\n    ) -> tuple[bytes, str]:\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if not files:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(data, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        new_fields: list[RequestField | tuple[str, bytes]] = []\n        fields = to_key_val_list(data or {})\n        files = to_key_val_list(files or {})\n\n        for field, val in fields:\n            if isinstance(val, basestring) or not hasattr(val, \"__iter__\"):\n                val = [val]\n            for v in val:\n                if v is not None:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(v, bytes):\n                        v = str(v)\n\n                    new_fields.append(\n                        (\n                            field.decode(\"utf-8\")\n                            if isinstance(field, bytes)\n                            else field,\n                            v.encode(\"utf-8\") if isinstance(v, str) else v,\n                        )\n                    )\n\n        for k, v in files:\n            # support for explicit filename\n            ft = None\n            fh = None\n            if isinstance(v, (tuple, list)):\n                if len(v) == 2:\n                    fn, fp = v\n                elif len(v) == 3:\n                    fn, fp, ft = v\n                else:\n                    fn, fp, ft, fh = v\n            else:\n                fn = guess_filename(v) or k\n                fp = v\n\n            if isinstance(fp, (str, bytes, bytearray)):\n                fdata = fp\n            elif _t.has_read(fp):\n                fdata = fp.read()\n            elif fp is None:  # defensive check for untyped callers\n                continue\n            else:\n                fdata = fp\n\n            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n            rf.make_multipart(content_type=ft)\n            new_fields.append(rf)\n\n        body, content_type = encode_multipart_formdata(new_fields)\n\n        return body, content_type\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-9a65114ab4a55ac6", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "2d95e3c56e77b31aa3bdd5a1177b576061e8e07b1d4ab7a2998d38927827a77f", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 220, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__RequestEncodingMixin__4bdacd4c.py", "order": 9, "original_content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "parent_variant_id": "pyint-838b0a48e856-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L108-L251", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 5}, "unit_kind": "class", "unit_name": "RequestEncodingMixin", "variant_id": "pyint-6f2e4bdacd4c-I09", "group_id": "py-9a65114ab4a55ac6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 766, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cb5bcf6d3ffa-I10", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,     Any,     Final,\n    Literal,     cast,     overload,\n)\nfrom urllib3.exceptions import (     DecodeError,     LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError, )\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,     builtin_str,\n    chardet,     cookielib,\n    urlencode,     urlsplit,     urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,     get_cookie_header, )\nfrom .exceptions import (\n    ChunkedEncodingError,     ConnectionError,\n    ContentDecodingError,\n    HTTPError,     InvalidJSONError,     InvalidURL,\n    MissingSchema,     StreamConsumedError, )\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (     check_header_validity,     get_auth_from_url,     guess_filename,\n    guess_json_utf,     iter_slices,\n    parse_header_links,     requote_uri,\n    stream_decode_response_unicode,\n    super_len,     to_key_val_list, )\n\nclass RequestEncodingMixin:\n    url: str | None\n    @property\n    def path_url(self) -> str:\n        \"\"\"Build the path URL to use.\"\"\"\n\n        url: list[str] = []\n        p = urlsplit(cast(str, self.url))\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n            url.append(\"?\")\n            url.append(query)\n\n        return \"\".join(url)\n\n    @overload\n    @staticmethod\n    def _encode_params(data: str) -> str: ...\n    @overload\n    @staticmethod\n    def _encode_params(data: bytes) -> bytes: ...\n    @overload\n    @staticmethod\n    def _encode_params(\n        data: _t.SupportsRead[str | bytes],\n    ) -> _t.SupportsRead[str | bytes]: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: _t.KVDataType) -> str: ...\n\n    @staticmethod\n    def _encode_params(\n        data: _t.EncodableDataType,\n    ) -> str | bytes | _t.SupportsRead[str | bytes]:\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n\n        if isinstance(data, (str, bytes)):\n            return data\n        elif _t.has_read(data):\n            return data\n        elif hasattr(data, \"__iter__\"):\n            result: list[tuple[bytes, bytes]] = []\n            for k, vs in to_key_val_list(data):\n                if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n                    vs = [vs]\n                for v in vs:\n                    if v is not None:\n                        result.append(\n                            (\n                                k.encode(\"utf-8\") if isinstance(k, str) else k,\n                                v.encode(\"utf-8\") if isinstance(v, str) else v,\n                            )\n                        )\n            return urlencode(result, doseq=True)\n        else:\n            return data  # type: ignore[return-value]  # unreachable for valid _t.DataType\n\n    @staticmethod\n    def _encode_files(\n        files: _t.FilesType, data: _t.RawDataType | None     ) -> tuple[bytes, str]:\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if not files:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(data, basestring):\n            raise ValueError(\"Data must not be a string.\")\n        new_fields: list[RequestField | tuple[str, bytes]] = []\n        fields = to_key_val_list(data or {})\n        files = to_key_val_list(files or {})\n\n        for field, val in fields:\n            if isinstance(val, basestring) or not hasattr(val, \"__iter__\"):\n                val = [val]\n            for v in val:\n                if v is not None:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(v, bytes):\n                        v = str(v)\n\n                    new_fields.append(\n                        (                             field.decode(\"utf-8\")                             if isinstance(field, bytes)\n                            else field,\n                            v.encode(\"utf-8\") if isinstance(v, str) else v,\n                        )\n                    )\n\n        for k, v in files:\n            # support for explicit filename\n            ft = None\n            fh = None\n            if isinstance(v, (tuple, list)):\n                if len(v) == 2:\n                    fn, fp = v\n                elif len(v) == 3:\n                    fn, fp, ft = v\n                else:\n                    fn, fp, ft, fh = v\n            else:\n                fn = guess_filename(v) or k\n                fp = v\n\n            if isinstance(fp, (str, bytes, bytearray)):\n                fdata = fp\n            elif _t.has_read(fp):\n                fdata = fp.read()\n            elif fp is None:  # defensive check for untyped callers\n                continue\n            else:\n                fdata = fp\n\n            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n            rf.make_multipart(content_type=ft)\n            new_fields.append(rf)\n\n        body, content_type = encode_multipart_formdata(new_fields)\n        return body, content_type\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-9a65114ab4a55ac6", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "121179172a45e0b3662c48e72d984afed33ea8ca7702af6d419eb22aec68d0c7", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 179, "local_path": "layout/partially-compact-layout/I10__requests__RequestEncodingMixin__cf6d3ffa.py", "order": 10, "original_content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "parent_variant_id": "pyint-838b0a48e856-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L108-L251", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 89, "line_break_groups_removed": 35, "line_breaks_removed": 35, "whitespace_characters_removed": 7}, "unit_kind": "class", "unit_name": "RequestEncodingMixin", "variant_id": "pyint-cb5bcf6d3ffa-I10", "group_id": "py-9a65114ab4a55ac6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 767, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a733b3338019-I11", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestEncodingMixin:\n    url: str | None\n\n    @property\n    def path_url(self) -> str:\n        \"\"\"Build the path URL to use.\"\"\"\n\n        url: list[str] = []\n\n        p = urlsplit(cast(str, self.url))\n\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n            url.append(\"?\")\n            url.append(query)\n\n        return \"\".join(url)\n\n    @overload\n    @staticmethod\n    def _encode_params(data: str) -> str: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: bytes) -> bytes: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(\n        data: _t.SupportsRead[str | bytes],\n    ) -> _t.SupportsRead[str | bytes]: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: _t.KVDataType) -> str: ...\n\n    @staticmethod\n    def _encode_params(\n        data: _t.EncodableDataType,\n    ) -> str | bytes | _t.SupportsRead[str | bytes]:\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n\n        if isinstance(data, (str, bytes)):\n            return data\n        elif _t.has_read(data):\n            return data\n        elif hasattr(data, \"__iter__\"):\n            result: list[tuple[bytes, bytes]] = []\n            for k, vs in to_key_val_list(data):\n                if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n                    vs = [vs]\n                for v in vs:\n                    if v is not None:\n                        result.append(\n                            (\n                                k.encode(\"utf-8\") if isinstance(k, str) else k,\n                                v.encode(\"utf-8\") if isinstance(v, str) else v,\n                            )\n                        )\n            return urlencode(result, doseq=True)\n        else:\n            return data  # type: ignore[return-value]  # unreachable for valid _t.DataType\n\n    @staticmethod\n    def _encode_files(\n        files: _t.FilesType, data: _t.RawDataType | None\n    ) -> tuple[bytes, str]:\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if not files:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(data, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        new_fields: list[RequestField | tuple[str, bytes]] = []\n        fields = to_key_val_list(data or {})\n        files = to_key_val_list(files or {})\n\n        for field, val in fields:\n            if isinstance(val, basestring) or not hasattr(val, \"__iter__\"):\n                val = [val]\n            for v in val:\n                if v is not None:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(v, bytes):\n                        v = str(v)\n\n                    new_fields.append(\n                        (\n                            field.decode(\"utf-8\")\n                            if isinstance(field, bytes)\n                            else field,\n                            v.encode(\"utf-8\") if isinstance(v, str) else v,\n                        )\n                    )\n\n        for k, v in files:\n            # support for explicit filename\n            ft = None\n            fh = None\n            if isinstance(v, (tuple, list)):\n                a = 1\n                b = 1\n                c = 1\n                d = 2\n                if len(v) == (a + b):\n                    fn, fp = v\n                elif len(v) == (c + d):\n                    fn, fp, ft = v\n                else:\n                    fn, fp, ft, fh = v\n            else:\n                fn = guess_filename(v) or k\n                fp = v\n\n            if isinstance(fp, (str, bytes, bytearray)):\n                fdata = fp\n            elif _t.has_read(fp):\n                fdata = fp.read()\n            elif fp is None:  # defensive check for untyped callers\n                continue\n            else:\n                fdata = fp\n\n            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n            rf.make_multipart(content_type=ft)\n            new_fields.append(rf)\n\n        body, content_type = encode_multipart_formdata(new_fields)\n\n        return body, content_type\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-9a65114ab4a55ac6", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "20957ec19d734d1fb08a1f7a550372fcd65d183f12cbdc596ca7cbee824fa033", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 218, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__RequestEncodingMixin__b3338019.py", "order": 11, "original_content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "parent_variant_id": "pyint-838b0a48e856-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L108-L251", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 2, "intermediate_variables_introduced": 4, "statements_augmented": 1}, "unit_kind": "class", "unit_name": "RequestEncodingMixin", "variant_id": "pyint-a733b3338019-I11", "group_id": "py-9a65114ab4a55ac6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 768, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8fc2acb2f957-I12", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestEncodingMixin:\n    url: str | None\n\n    @property\n    def path_url(self) -> str:\n        \"\"\"Build the path URL to use.\"\"\"\n\n        url: list[str] = []\n\n        p = urlsplit(cast(str, self.url))\n\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n            url.append(\"?\")\n            url.append(query)\n\n        return \"\".join(url)\n\n    @overload\n    @staticmethod\n    def _encode_params(data: str) -> str: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: bytes) -> bytes: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(\n        data: _t.SupportsRead[str | bytes],\n    ) -> _t.SupportsRead[str | bytes]: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: _t.KVDataType) -> str: ...\n\n    @staticmethod\n    def _encode_params(\n        data: _t.EncodableDataType,\n    ) -> str | bytes | _t.SupportsRead[str | bytes]:\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n\n        if isinstance(data, (str, bytes)):\n            return data\n        elif _t.has_read(data):\n            return data\n        elif hasattr(data, \"__iter__\"):\n            result: list[tuple[bytes, bytes]] = []\n            for k, vs in to_key_val_list(data):\n                if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n                    vs = [vs]\n                for v in vs:\n                    if v is not None:\n                        result.append(\n                            (\n                                k.encode(\"utf-8\") if isinstance(k, str) else k,\n                                v.encode(\"utf-8\") if isinstance(v, str) else v,\n                            )\n                        )\n            return urlencode(result, doseq=True)\n        else:\n            return data  # type: ignore[return-value]  # unreachable for valid _t.DataType\n\n    @staticmethod\n    def _encode_files(\n        files: _t.FilesType, data: _t.RawDataType | None\n    ) -> tuple[bytes, str]:\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if not files:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(data, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        new_fields: list[RequestField | tuple[str, bytes]] = []\n        fields = to_key_val_list(data or {})\n        files = to_key_val_list(files or {})\n\n        for field, val in fields:\n            if isinstance(val, basestring) or not hasattr(val, \"__iter__\"):\n                val = [val]\n            for v in val:\n                if v is not None:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(v, bytes):\n                        v = str(v)\n\n                    new_fields.append(\n                        (\n                            field.decode(\"utf-8\")\n                            if isinstance(field, bytes)\n                            else field,\n                            v.encode(\"utf-8\") if isinstance(v, str) else v,\n                        )\n                    )\n\n        for k, v in files:\n            # support for explicit filename\n            ft = None\n            fh = None\n            if isinstance(v, (tuple, list)):\n                if len(v) == 2:\n                    fn, fp = v\n                elif len(v) == 3:\n                    fn, fp, ft = v\n                else:\n                    fn, fp, ft, fh = v\n            else:\n                fn = guess_filename(v) or k\n                fp = v\n\n            if isinstance(fp, (str, bytes, bytearray)):\n                fdata = fp\n            elif _t.has_read(fp):\n                fdata = fp.read()\n            elif fp is None:  # defensive check for untyped callers\n                continue\n            else:\n                fdata = fp\n\n            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n            rf.make_multipart(content_type=ft)\n            new_fields.append(rf)\n\n        body, content_type = encode_multipart_formdata(new_fields)\n\n        return body, content_type\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-9a65114ab4a55ac6", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 214, "local_path": "data-flow/inline-intermediate-variables/I12__requests__RequestEncodingMixin__acb2f957.py", "order": 12, "original_content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "parent_variant_id": "pyint-838b0a48e856-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L108-L251", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "RequestEncodingMixin", "variant_id": "pyint-8fc2acb2f957-I12", "group_id": "py-9a65114ab4a55ac6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 769, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-232e3838bfa8-I13", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass RequestEncodingMixin:\n    url: str | None\n\n    @property\n    def path_url(self) -> str:\n        \"\"\"Build the path URL to use.\"\"\"\n\n        url: list[str] = []\n\n        p = urlsplit(cast(str, self.url))\n\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n            url.append(\"?\")\n            url.append(query)\n\n        return \"\".join(url)\n\n    @overload\n    @staticmethod\n    def _encode_params(data: str) -> str: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: bytes) -> bytes: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(\n        data: _t.SupportsRead[str | bytes],\n    ) -> _t.SupportsRead[str | bytes]: ...\n\n    @overload\n    @staticmethod\n    def _encode_params(data: _t.KVDataType) -> str: ...\n\n    @staticmethod\n    def _encode_params(\n        data: _t.EncodableDataType,\n    ) -> str | bytes | _t.SupportsRead[str | bytes]:\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n\n        if isinstance(data, (str, bytes)):\n            return data\n        elif _t.has_read(data):\n            return data\n        elif hasattr(data, \"__iter__\"):\n            result: list[tuple[bytes, bytes]] = []\n            loopIteratorA = __import__(\"builtins\").iter(to_key_val_list(data))\n            while True:\n                try:\n                    k, vs = __import__(\"builtins\").next(loopIteratorA)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n                    vs = [vs]\n                loopIterator = __import__(\"builtins\").iter(vs)\n                while True:\n                    try:\n                        v = __import__(\"builtins\").next(loopIterator)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    if v is not None:\n                        result.append(\n                            (\n                                k.encode(\"utf-8\") if isinstance(k, str) else k,\n                                v.encode(\"utf-8\") if isinstance(v, str) else v,\n                            )\n                        )\n            return urlencode(result, doseq=True)\n        else:\n            return data  # type: ignore[return-value]  # unreachable for valid _t.DataType\n\n    @staticmethod\n    def _encode_files(\n        files: _t.FilesType, data: _t.RawDataType | None\n    ) -> tuple[bytes, str]:\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if not files:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(data, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        new_fields: list[RequestField | tuple[str, bytes]] = []\n        fields = to_key_val_list(data or {})\n        files = to_key_val_list(files or {})\n\n        for field, val in fields:\n            if isinstance(val, basestring) or not hasattr(val, \"__iter__\"):\n                val = [val]\n            for v in val:\n                if v is not None:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(v, bytes):\n                        v = str(v)\n\n                    new_fields.append(\n                        (\n                            field.decode(\"utf-8\")\n                            if isinstance(field, bytes)\n                            else field,\n                            v.encode(\"utf-8\") if isinstance(v, str) else v,\n                        )\n                    )\n\n        for k, v in files:\n            # support for explicit filename\n            ft = None\n            fh = None\n            if isinstance(v, (tuple, list)):\n                if len(v) == 2:\n                    fn, fp = v\n                elif len(v) == 3:\n                    fn, fp, ft = v\n                else:\n                    fn, fp, ft, fh = v\n            else:\n                fn = guess_filename(v) or k\n                fp = v\n\n            if isinstance(fp, (str, bytes, bytearray)):\n                fdata = fp\n            elif _t.has_read(fp):\n                fdata = fp.read()\n            elif fp is None:  # defensive check for untyped callers\n                continue\n            else:\n                fdata = fp\n\n            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n            rf.make_multipart(content_type=ft)\n            new_fields.append(rf)\n\n        body, content_type = encode_multipart_formdata(new_fields)\n\n        return body, content_type\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-9a65114ab4a55ac6", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "087d1b0263b548ca6bfc4ae555a77d16a3ba7724dbfcd834397719204f38e8a7", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 224, "local_path": "control-flow/lower-for-to-while/I13__requests__RequestEncodingMixin__3838bfa8.py", "order": 13, "original_content_sha256": "e7802a43f83819a2888cb3c1f77a055ced8699c28d20a01294bbc19162cf8451", "parent_variant_id": "pyint-838b0a48e856-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L108-L251", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 2, "for_loops_skipped_for_comment": 3, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 2, "synchronous_for_loops_eligible": 2, "synchronous_for_loops_found": 5}, "unit_kind": "class", "unit_name": "RequestEncodingMixin", "variant_id": "pyint-232e3838bfa8-I13", "group_id": "py-9a65114ab4a55ac6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 770, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-468cb5a6293b-SRC", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _SubclassOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not issubclass(value, self.type):\n            msg = f\"'{attr.name}' must be a subclass of {self.type!r} (got {value!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<subclass_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-a0458689b6c2d4b5", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 28, "local_path": "source-original/SRC__attrs___SubclassOfValidator__b5a6293b.py", "order": 0, "original_content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L613-L630", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_SubclassOfValidator", "variant_id": "pyint-468cb5a6293b-SRC", "group_id": "py-a0458689b6c2d4b5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1387, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-be063c5f97a4-I01", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _SubclassOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \n        if not issubclass(value, self.type):\n            msg = f\"'{attr.name}' must be a subclass of {self.type!r} (got {value!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<subclass_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-a0458689b6c2d4b5", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "f13d7deb3ed979ce3974a84782f4cfb9c16eaadebfea480f45ed985133082bc8", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 26, "local_path": "comments/remove-comments/I01__attrs___SubclassOfValidator__3c5f97a4.py", "order": 1, "original_content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "parent_variant_id": "pyint-468cb5a6293b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L613-L630", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 86, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "_SubclassOfValidator", "variant_id": "pyint-be063c5f97a4-I01", "group_id": "py-a0458689b6c2d4b5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1388, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e6c6b601f20d-I02", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _SubclassOfValidator:\n    type = attrib()\n\n    def __call__(self, ins, att, val):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not issubclass(val, self.type):\n            msg2 = f\"'{att.name}' must be a subclass of {self.type!r} (got {val!r}).\"\n            raise TypeError(\n                msg2,\n                att,\n                self.type,\n                val,\n            )\n\n    def __repr__(self):\n        return f\"<subclass_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-a0458689b6c2d4b5", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "5343b5dec29b675cf3d1495731e49c2259d86248bb2bfc2d8e6c936e0e1994e9", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 28, "local_path": "identifiers/shorten-identifiers/I02__attrs___SubclassOfValidator__b601f20d.py", "order": 2, "original_content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "parent_variant_id": "pyint-468cb5a6293b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L613-L630", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 10, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_SubclassOfValidator", "variant_id": "pyint-e6c6b601f20d-I02", "group_id": "py-a0458689b6c2d4b5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1389, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-954ed110648b-I03", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _SubclassOfValidator:\n    type = attrib()\n\n    def __call__(self, flag, item, batch):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not issubclass(batch, self.type):\n            age = f\"'{item.name}' must be a subclass of {self.type!r} (got {batch!r}).\"\n            raise TypeError(\n                age,\n                item,\n                self.type,\n                batch,\n            )\n\n    def __repr__(self):\n        return f\"<subclass_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-a0458689b6c2d4b5", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "af1fd3f777b0302cb2c43d04b47165caa1ece84968de95275077c18efe73188b", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 28, "local_path": "identifiers/mislead-identifiers/I03__attrs___SubclassOfValidator__d110648b.py", "order": 3, "original_content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "parent_variant_id": "pyint-468cb5a6293b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L613-L630", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 10, "identifiers_declared": 4, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 4, "local_random_pool_selections": 4, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_SubclassOfValidator", "variant_id": "pyint-954ed110648b-I03", "group_id": "py-a0458689b6c2d4b5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1390, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-aedffb489c12-I04", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _SubclassOfValidator:\n    type = attrib()\n\n    def __call__(self, a, b, c):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not issubclass(c, self.type):\n            d = f\"'{b.name}' must be a subclass of {self.type!r} (got {c!r}).\"\n            raise TypeError(\n                d,\n                b,\n                self.type,\n                c,\n            )\n\n    def __repr__(self):\n        return f\"<subclass_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-a0458689b6c2d4b5", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "de54a4920141f8f5f8571f64a320d314b36b9aeaceb4f59698c6beddaa0f62c0", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 28, "local_path": "identifiers/garble-identifiers/I04__attrs___SubclassOfValidator__fb489c12.py", "order": 4, "original_content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "parent_variant_id": "pyint-468cb5a6293b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L613-L630", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 10, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_SubclassOfValidator", "variant_id": "pyint-aedffb489c12-I04", "group_id": "py-a0458689b6c2d4b5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1391, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-659e581d989a-I05", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _SubclassOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not issubclass(value, self.type):\n            msg = f\"'{attr.name}' must be a subclass of {self.type!r} (got {value!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<subclass_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-a0458689b6c2d4b5", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 28, "local_path": "expressions/encode-integer-literals/I05__attrs___SubclassOfValidator__581d989a.py", "order": 5, "original_content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "parent_variant_id": "pyint-468cb5a6293b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L613-L630", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "_SubclassOfValidator", "variant_id": "pyint-659e581d989a-I05", "group_id": "py-a0458689b6c2d4b5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1392, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-00e292c8cab2-I06", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _SubclassOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not (not issubclass(value, self.type)):\n            pass\n        else:\n            msg = f\"'{attr.name}' must be a subclass of {self.type!r} (got {value!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<subclass_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-a0458689b6c2d4b5", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "09759bdec7ee2ec24e7a5fc97392b9e7ad35fc6404e7e2252b92f365cf51053e", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 30, "local_path": "expressions/invert-conditions/I06__attrs___SubclassOfValidator__92c8cab2.py", "order": 6, "original_content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "parent_variant_id": "pyint-468cb5a6293b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L613-L630", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "_SubclassOfValidator", "variant_id": "pyint-00e292c8cab2-I06", "group_id": "py-a0458689b6c2d4b5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1393, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-05b4256d3455-I07", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _SubclassOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if ((0x233 ^ 0x233) != 0):\n            raise AssertionError()\n        if not issubclass(value, self.type):\n            msg = f\"'{attr.name}' must be a subclass of {self.type!r} (got {value!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        if ((0xe3da ^ 0xe3da) != 0):\n            raise AssertionError()\n        return f\"<subclass_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-a0458689b6c2d4b5", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "305884c69c6ec8e214872b9da85cbcd68179586e275e91bffb5dc7619dee96b0", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 32, "local_path": "code-injection/insert-dead-branches/I07__attrs___SubclassOfValidator__256d3455.py", "order": 7, "original_content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "parent_variant_id": "pyint-468cb5a6293b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L613-L630", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "_SubclassOfValidator", "variant_id": "pyint-05b4256d3455-I07", "group_id": "py-a0458689b6c2d4b5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1394, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-958354d03863-I08", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _SubclassOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        if not issubclass(value, self.type):\n            msg = f\"'{attr.name}' must be a subclass of {self.type!r} (got {value!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<subclass_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-a0458689b6c2d4b5", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "a209bcd71d41506fbe065c57f243d81eadf6d9bb408237a90e14f81e02e214f7", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 33, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___SubclassOfValidator__54d03863.py", "order": 8, "original_content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "parent_variant_id": "pyint-468cb5a6293b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L613-L630", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "_SubclassOfValidator", "variant_id": "pyint-958354d03863-I08", "group_id": "py-a0458689b6c2d4b5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1395, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-425c3cf1d11f-I09", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _SubclassOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        lI0O_216670bc = 0x7b7a\n        lI0O_216670bc = (lI0O_216670bc << 1) ^ (lI0O_216670bc >> 1)\n        lI0O_216670bc &= 0\n        if not issubclass(value, self.type):\n            msg = f\"'{attr.name}' must be a subclass of {self.type!r} (got {value!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<subclass_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-a0458689b6c2d4b5", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "10b36f0205aab5703a704fbed3aa6718111354df32895bf7a36e73596a237f6a", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 31, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___SubclassOfValidator__3cf1d11f.py", "order": 9, "original_content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "parent_variant_id": "pyint-468cb5a6293b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L613-L630", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 3}, "unit_kind": "class", "unit_name": "_SubclassOfValidator", "variant_id": "pyint-425c3cf1d11f-I09", "group_id": "py-a0458689b6c2d4b5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1396, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-40c7a0dc7227-I10", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _SubclassOfValidator:\n    type = attrib()\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not issubclass(value, self.type):\n            msg = f\"'{attr.name}' must be a subclass of {self.type!r} (got {value!r}).\"\n            raise TypeError(                 msg,                 attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<subclass_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-a0458689b6c2d4b5", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "51bf2fb63915a05a8a6bffada782c4b19ede81b7974bcf6eedfaca80eaf7887d", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 25, "local_path": "layout/partially-compact-layout/I10__attrs___SubclassOfValidator__a0dc7227.py", "order": 10, "original_content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "parent_variant_id": "pyint-468cb5a6293b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L613-L630", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 8, "line_break_groups_removed": 3, "line_breaks_removed": 3, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "_SubclassOfValidator", "variant_id": "pyint-40c7a0dc7227-I10", "group_id": "py-a0458689b6c2d4b5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1397, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-19ce79017e60-I11", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _SubclassOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not issubclass(value, self.type):\n            msg = f\"'{attr.name}' must be a subclass of {self.type!r} (got {value!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<subclass_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-a0458689b6c2d4b5", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 28, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___SubclassOfValidator__79017e60.py", "order": 11, "original_content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "parent_variant_id": "pyint-468cb5a6293b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L613-L630", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "_SubclassOfValidator", "variant_id": "pyint-19ce79017e60-I11", "group_id": "py-a0458689b6c2d4b5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1398, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-07a38e1f22c4-I12", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _SubclassOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not issubclass(value, self.type):\n            \n            raise TypeError(\n                (f\"'{attr.name}' must be a subclass of {self.type!r} (got {value!r}).\"),\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<subclass_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-a0458689b6c2d4b5", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "3699c28b3c5ce681198ebd799994139b4fa576fbc830f79fb38fefa198e711c2", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 28, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___SubclassOfValidator__8e1f22c4.py", "order": 12, "original_content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "parent_variant_id": "pyint-468cb5a6293b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L613-L630", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_SubclassOfValidator", "variant_id": "pyint-07a38e1f22c4-I12", "group_id": "py-a0458689b6c2d4b5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1399, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-df8d75e9f805-I13", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _SubclassOfValidator:\n    type = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not issubclass(value, self.type):\n            msg = f\"'{attr.name}' must be a subclass of {self.type!r} (got {value!r}).\"\n            raise TypeError(\n                msg,\n                attr,\n                self.type,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<subclass_of validator for type {self.type!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-a0458689b6c2d4b5", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 28, "local_path": "control-flow/lower-for-to-while/I13__attrs___SubclassOfValidator__75e9f805.py", "order": 13, "original_content_sha256": "ca21604c807c0d3abc88de03654a2cafddc1054aaef6512520de1c5370adeeac", "parent_variant_id": "pyint-468cb5a6293b-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L613-L630", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "_SubclassOfValidator", "variant_id": "pyint-df8d75e9f805-I13", "group_id": "py-a0458689b6c2d4b5", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1400, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5ac70d007478-SRC", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-a05c9dcfd09c8004", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 14, "local_path": "source-original/SRC__requests__SupportsItems__0d007478.py", "order": 0, "original_content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L38-L39", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "SupportsItems", "variant_id": "pyint-5ac70d007478-SRC", "group_id": "py-a05c9dcfd09c8004", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 995, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ba0ec94337e6-I01", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-a05c9dcfd09c8004", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 14, "local_path": "comments/remove-comments/I01__requests__SupportsItems__c94337e6.py", "order": 1, "original_content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "parent_variant_id": "pyint-5ac70d007478-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L38-L39", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "SupportsItems", "variant_id": "pyint-ba0ec94337e6-I01", "group_id": "py-a05c9dcfd09c8004", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 996, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ba1d7915da57-I02", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def ite(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-a05c9dcfd09c8004", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "80b070336af2bc814fd6a485a639238a13a52b07acca52479257e6e7d0430680", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 14, "local_path": "identifiers/shorten-identifiers/I02__requests__SupportsItems__7915da57.py", "order": 2, "original_content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "parent_variant_id": "pyint-5ac70d007478-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L38-L39", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "SupportsItems", "variant_id": "pyint-ba1d7915da57-I02", "group_id": "py-a05c9dcfd09c8004", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 997, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-892676ac1bea-I03", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def route(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-a05c9dcfd09c8004", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "0efc30e08bb60fd6634c6cbf572631537fbce78a07257d8bd1da1cfba0a01a56", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 14, "local_path": "identifiers/mislead-identifiers/I03__requests__SupportsItems__76ac1bea.py", "order": 3, "original_content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "parent_variant_id": "pyint-5ac70d007478-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L38-L39", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 0, "local_random_pool_selections": 0, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "SupportsItems", "variant_id": "pyint-892676ac1bea-I03", "group_id": "py-a05c9dcfd09c8004", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 998, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-78333b872497-I04", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def a(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-a05c9dcfd09c8004", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "221fadebbacc753f840073f3790380d11eb95ef283854a966c4cc46b0139f122", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 14, "local_path": "identifiers/garble-identifiers/I04__requests__SupportsItems__3b872497.py", "order": 4, "original_content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "parent_variant_id": "pyint-5ac70d007478-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L38-L39", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "SupportsItems", "variant_id": "pyint-78333b872497-I04", "group_id": "py-a05c9dcfd09c8004", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 999, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cc19994d5566-I05", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-a05c9dcfd09c8004", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 14, "local_path": "expressions/encode-integer-literals/I05__requests__SupportsItems__994d5566.py", "order": 5, "original_content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "parent_variant_id": "pyint-5ac70d007478-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L38-L39", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "SupportsItems", "variant_id": "pyint-cc19994d5566-I05", "group_id": "py-a05c9dcfd09c8004", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1000, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ab0cfd72f969-I06", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-a05c9dcfd09c8004", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 14, "local_path": "expressions/invert-conditions/I06__requests__SupportsItems__fd72f969.py", "order": 6, "original_content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "parent_variant_id": "pyint-5ac70d007478-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L38-L39", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "SupportsItems", "variant_id": "pyint-ab0cfd72f969-I06", "group_id": "py-a05c9dcfd09c8004", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1001, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1ffeae524646-I07", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-a05c9dcfd09c8004", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 14, "local_path": "code-injection/insert-dead-branches/I07__requests__SupportsItems__ae524646.py", "order": 7, "original_content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "parent_variant_id": "pyint-5ac70d007478-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L38-L39", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 0}, "unit_kind": "class", "unit_name": "SupportsItems", "variant_id": "pyint-1ffeae524646-I07", "group_id": "py-a05c9dcfd09c8004", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1002, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4158757dc6a4-I08", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-a05c9dcfd09c8004", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 14, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__SupportsItems__757dc6a4.py", "order": 8, "original_content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "parent_variant_id": "pyint-5ac70d007478-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L38-L39", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 0, "readable_lines_injected": 0, "readable_template_index": -1}, "unit_kind": "class", "unit_name": "SupportsItems", "variant_id": "pyint-4158757dc6a4-I08", "group_id": "py-a05c9dcfd09c8004", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1003, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a651a5d68aa5-I09", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-a05c9dcfd09c8004", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 14, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__SupportsItems__a5d68aa5.py", "order": 9, "original_content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "parent_variant_id": "pyint-5ac70d007478-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L38-L39", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 0, "low_readability_template_index": -1}, "unit_kind": "class", "unit_name": "SupportsItems", "variant_id": "pyint-a651a5d68aa5-I09", "group_id": "py-a05c9dcfd09c8004", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1004, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-55bfc8bb8b5a-I10", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (     TYPE_CHECKING,     Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n@runtime_checkable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-a05c9dcfd09c8004", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "51f89ce8ebac10e11d53b9996b6ee7dfc7325d6ea792074440edb9c383563002", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 11, "local_path": "layout/partially-compact-layout/I10__requests__SupportsItems__c8bb8b5a.py", "order": 10, "original_content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "parent_variant_id": "pyint-5ac70d007478-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L38-L39", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 8, "line_break_groups_removed": 3, "line_breaks_removed": 3, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "SupportsItems", "variant_id": "pyint-55bfc8bb8b5a-I10", "group_id": "py-a05c9dcfd09c8004", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1005, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4b6ceb45fba7-I11", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-a05c9dcfd09c8004", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 14, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__SupportsItems__eb45fba7.py", "order": 11, "original_content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "parent_variant_id": "pyint-5ac70d007478-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L38-L39", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "SupportsItems", "variant_id": "pyint-4b6ceb45fba7-I11", "group_id": "py-a05c9dcfd09c8004", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1006, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-521c60ebc0c2-I12", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-a05c9dcfd09c8004", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 14, "local_path": "data-flow/inline-intermediate-variables/I12__requests__SupportsItems__60ebc0c2.py", "order": 12, "original_content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "parent_variant_id": "pyint-5ac70d007478-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L38-L39", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "SupportsItems", "variant_id": "pyint-521c60ebc0c2-I12", "group_id": "py-a05c9dcfd09c8004", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1007, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-da363a7ee51f-I13", "source": "from __future__ import annotations\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Protocol,\n    TypeAlias,\n    TypeVar,\n    runtime_checkable,\n)\n\n@runtime_checkable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-a05c9dcfd09c8004", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 14, "local_path": "control-flow/lower-for-to-while/I13__requests__SupportsItems__3a7ee51f.py", "order": 13, "original_content_sha256": "3127b4c5266bcd01f1fbd2c458dfbeab16a3d1576dddc1d62b31f3fe2b42c94c", "parent_variant_id": "pyint-5ac70d007478-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/_types.py#L38-L39", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "SupportsItems", "variant_id": "pyint-da363a7ee51f-I13", "group_id": "py-a05c9dcfd09c8004", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1008, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d7199f8ad572-SRC", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__: list[str] = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    max_retries: Retry\n    config: dict[str, Any]\n    proxy_manager: dict[str, Any]\n    _pool_connections: int\n    _pool_maxsize: int\n    _pool_block: bool\n    poolmanager: _PoolManager\n\n    def __init__(\n        self,\n        pool_connections: int = DEFAULT_POOLSIZE,\n        pool_maxsize: int = DEFAULT_POOLSIZE,\n        max_retries: int | Retry = DEFAULT_RETRIES,\n        pool_block: bool = DEFAULT_POOLBLOCK,\n    ) -> None:\n        if max_retries == DEFAULT_RETRIES:\n            self.max_retries = Retry(0, read=False)\n        else:\n            self.max_retries = Retry.from_int(max_retries)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = pool_connections\n        self._pool_maxsize = pool_maxsize\n        self._pool_block = pool_block\n\n        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n\n    def __getstate__(self) -> dict[str, Any]:\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        self.proxy_manager = {}\n        self.config = {}\n\n        for attr, value in state.items():\n            setattr(self, attr, value)\n\n        self.init_poolmanager(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def init_poolmanager(\n        self,\n        connections: int,\n        maxsize: int,\n        block: bool = DEFAULT_POOLBLOCK,\n        **pool_kwargs: Any,\n    ) -> None:\n        \"\"\"Initializes a urllib3 PoolManager.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        # save these values for pickling\n        self._pool_connections = connections\n        self._pool_maxsize = maxsize\n        self._pool_block = block\n\n        self.poolmanager = PoolManager(\n            num_pools=connections,\n            maxsize=maxsize,\n            block=block,\n            **pool_kwargs,\n        )\n\n    def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any:\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if proxy in self.proxy_manager:\n            manager = self.proxy_manager[proxy]\n        elif proxy.lower().startswith(\"socks\"):\n            username, password = get_auth_from_url(proxy)\n            manager = self.proxy_manager[proxy] = SOCKSProxyManager(\n                proxy,\n                username=username,\n                password=password,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n        else:\n            proxy_headers = self.proxy_headers(proxy)\n            manager = self.proxy_manager[proxy] = proxy_from_url(\n                proxy,\n                proxy_headers=proxy_headers,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n\n        return manager\n\n    def cert_verify(\n        self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType\n    ) -> None:\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if url.lower().startswith(\"https\") and verify:\n            cert_loc = None\n\n            # Allow self-specified cert location.\n            if verify is not True:\n                cert_loc = verify\n\n            if not cert_loc:\n                cert_loc = DEFAULT_CA_BUNDLE_PATH\n\n            if not cert_loc or not os.path.exists(cert_loc):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {cert_loc}\"\n                )\n\n            conn.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(cert_loc):\n                conn.ca_certs = cert_loc\n            else:\n                conn.ca_cert_dir = cert_loc\n        else:\n            conn.cert_reqs = \"CERT_NONE\"\n            conn.ca_certs = None\n            conn.ca_cert_dir = None\n\n        if cert:\n            if not isinstance(cert, basestring):\n                conn.cert_file = cert[0]\n                conn.key_file = cert[1]\n            else:\n                conn.cert_file = cert\n                conn.key_file = None\n            if conn.cert_file and not os.path.exists(conn.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {conn.cert_file}\"\n                )\n            if conn.key_file and not os.path.exists(conn.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {conn.key_file}\"\n                )\n\n    def build_response(self, req: PreparedRequest, resp: Any) -> Response:\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        assert _is_prepared(req)\n        response = Response()\n\n        # Fallback to None if there's no status_code, for whatever reason.\n        response.status_code = getattr(resp, \"status\", None)  # type: ignore[assignment]\n\n        # Make headers case-insensitive.\n        response.headers = CaseInsensitiveDict(getattr(resp, \"headers\", {}))\n\n        # Set encoding.\n        response.encoding = get_encoding_from_headers(response.headers)\n        response.raw = resp\n        response.reason = response.raw.reason\n\n        if isinstance(req.url, bytes):\n            response.url = req.url.decode(\"utf-8\")\n        else:\n            response.url = req.url\n\n        # Add new cookies from the server.\n        extract_cookies_to_jar(response.cookies, req, resp)\n\n        # Give the Response some context.\n        response.request = req\n        response.connection = self\n\n        return response\n\n    def build_connection_pool_key_attributes(\n        self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None\n    ) -> tuple[dict[str, Any], dict[str, Any]]:\n        \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n\n        This looks at the PreparedRequest, the user-specified verify value,\n        and the value of the cert parameter to determine what PoolKey values\n        to use to select a connection from a given urllib3 Connection Pool.\n\n        The SSL related pool key arguments are not consistently set. As of\n        this writing, use the following to determine what keys may be in that\n        dictionary:\n\n        * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n          default Requests SSL Context\n        * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n          ``\"cert_reqs\"`` will be set\n        * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n          ``\"ca_certs\"`` will be set if the string is not a directory recognized\n          by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n          set.\n        * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n          ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n          be present\n\n        To override these settings, one may subclass this class, call this\n        method and use the above logic to change parameters as desired. For\n        example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n        must both set ``\"ssl_context\"`` and based on what else they require,\n        alter the other keys to ensure the desired behaviour.\n\n        :param request:\n            The PreparedRequest being sent over the connection.\n        :type request:\n            :class:`~requests.models.PreparedRequest`\n        :param verify:\n            Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use.\n        :param cert:\n            (optional) Any user-provided SSL certificate for client\n            authentication (a.k.a., mTLS). This may be a string (i.e., just\n            the path to a file which holds both certificate and key) or a\n            tuple of length 2 with the certificate file path and key file\n            path.\n        :returns:\n            A tuple of two dictionaries. The first is the \"host parameters\"\n            portion of the Pool Key including scheme, hostname, and port. The\n            second is a dictionary of SSLContext related parameters.\n        \"\"\"\n        return _urllib3_request_context(request, verify, cert, self.poolmanager)\n\n    def get_connection_with_tls_context(\n        self,\n        request: PreparedRequest,\n        verify: _t.VerifyType,\n        proxies: dict[str, str] | None = None,\n        cert: _t.CertType = None,\n    ) -> HTTPConnectionPool:\n        \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request:\n            The :class:`PreparedRequest <PreparedRequest>` object to be sent\n            over the connection.\n        :param verify:\n            Either a boolean, in which case it controls whether we verify the\n            server's TLS certificate, or a string, in which case it must be a\n            path to a CA bundle to use.\n        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.HTTPConnectionPool\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        try:\n            host_params, pool_kwargs = self.build_connection_pool_key_attributes(\n                request,\n                verify,\n                cert,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=request)\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n        else:\n            # Only scheme should be lower case\n            conn = self.poolmanager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n\n        return conn\n\n    def get_connection(\n        self, url: str, proxies: dict[str, str] | None = None\n    ) -> HTTPConnectionPool:\n        \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n        for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n        Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.HTTPConnectionPool\n        \"\"\"\n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        proxy = select_proxy(url, proxies)\n\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_url(url)\n        else:\n            # Only scheme should be lower case\n            parsed = urlparse(url)\n            url = parsed.geturl()\n            conn = self.poolmanager.connection_from_url(url)\n\n        return conn\n\n    def close(self) -> None:\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        for proxy in self.proxy_manager.values():\n            proxy.clear()\n\n    def request_url(\n        self, request: PreparedRequest, proxies: dict[str, str] | None\n    ) -> str:\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        scheme = urlparse(request.url).scheme\n\n        is_proxied_http_request = proxy and scheme != \"https\"\n        using_socks_proxy = False\n        if proxy:\n            proxy_scheme = urlparse(proxy).scheme.lower()\n            using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n        url = request.path_url\n\n        if is_proxied_http_request and not using_socks_proxy:\n            url = urldefragauth(request.url)\n\n        return url\n\n    def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None:\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        pass\n\n    def proxy_headers(self, proxy: str) -> dict[str, str]:\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        headers: dict[str, str] = {}\n        username, password = get_auth_from_url(proxy)\n\n        if username:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return headers\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n\n        assert _is_prepared(request)\n\n        try:\n            conn = self.get_connection_with_tls_context(\n                request, verify, proxies=proxies, cert=cert\n            )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n            stream=stream,\n            timeout=timeout,\n            verify=verify,\n            cert=cert,\n            proxies=proxies,\n        )\n\n        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n\n        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                resolved_timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            resolved_timeout = timeout\n        else:\n            resolved_timeout = TimeoutSauce(connect=timeout, read=timeout)\n\n        try:\n            resp = conn.urlopen(\n                method=request.method,\n                url=url,\n                body=request.body,  # type: ignore[arg-type]  # urllib3 stubs don't accept Iterable[bytes | str]\n                headers=request.headers,  # type: ignore[arg-type]  # urllib3#3072\n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=resolved_timeout,\n                chunked=chunked,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=request)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=request)\n\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=request)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=request)\n\n            if isinstance(e.reason, _SSLError):\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=request)\n\n            raise ConnectionError(e, request=request)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=request)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=request)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=request)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=request)\n            else:\n                raise\n\n        return self.build_response(request, resp)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-a0e3de19d1287dec", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 642, "local_path": "source-original/SRC__requests__HTTPAdapter__9f8ad572.py", "order": 0, "original_content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L158-L748", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "HTTPAdapter", "variant_id": "pyint-d7199f8ad572-SRC", "group_id": "py-a0e3de19d1287dec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 729, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a4e668f13f61-I01", "source": "from __future__ import annotations\nimport os.path\nimport socket   \nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass HTTPAdapter(BaseAdapter):\n    \n\n    __attrs__: list[str] = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    max_retries: Retry\n    config: dict[str, Any]\n    proxy_manager: dict[str, Any]\n    _pool_connections: int\n    _pool_maxsize: int\n    _pool_block: bool\n    poolmanager: _PoolManager\n\n    def __init__(\n        self,\n        pool_connections: int = DEFAULT_POOLSIZE,\n        pool_maxsize: int = DEFAULT_POOLSIZE,\n        max_retries: int | Retry = DEFAULT_RETRIES,\n        pool_block: bool = DEFAULT_POOLBLOCK,\n    ) -> None:\n        if max_retries == DEFAULT_RETRIES:\n            self.max_retries = Retry(0, read=False)\n        else:\n            self.max_retries = Retry.from_int(max_retries)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = pool_connections\n        self._pool_maxsize = pool_maxsize\n        self._pool_block = pool_block\n\n        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n\n    def __getstate__(self) -> dict[str, Any]:\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n         \n         \n        self.proxy_manager = {}\n        self.config = {}\n\n        for attr, value in state.items():\n            setattr(self, attr, value)\n\n        self.init_poolmanager(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def init_poolmanager(\n        self,\n        connections: int,\n        maxsize: int,\n        block: bool = DEFAULT_POOLBLOCK,\n        **pool_kwargs: Any,\n    ) -> None:\n        \n         \n        self._pool_connections = connections\n        self._pool_maxsize = maxsize\n        self._pool_block = block\n\n        self.poolmanager = PoolManager(\n            num_pools=connections,\n            maxsize=maxsize,\n            block=block,\n            **pool_kwargs,\n        )\n\n    def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any:\n        \n        if proxy in self.proxy_manager:\n            manager = self.proxy_manager[proxy]\n        elif proxy.lower().startswith(\"socks\"):\n            username, password = get_auth_from_url(proxy)\n            manager = self.proxy_manager[proxy] = SOCKSProxyManager(\n                proxy,\n                username=username,\n                password=password,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n        else:\n            proxy_headers = self.proxy_headers(proxy)\n            manager = self.proxy_manager[proxy] = proxy_from_url(\n                proxy,\n                proxy_headers=proxy_headers,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n\n        return manager\n\n    def cert_verify(\n        self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType\n    ) -> None:\n        \n        if url.lower().startswith(\"https\") and verify:\n            cert_loc = None\n\n             \n            if verify is not True:\n                cert_loc = verify\n\n            if not cert_loc:\n                cert_loc = DEFAULT_CA_BUNDLE_PATH\n\n            if not cert_loc or not os.path.exists(cert_loc):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {cert_loc}\"\n                )\n\n            conn.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(cert_loc):\n                conn.ca_certs = cert_loc\n            else:\n                conn.ca_cert_dir = cert_loc\n        else:\n            conn.cert_reqs = \"CERT_NONE\"\n            conn.ca_certs = None\n            conn.ca_cert_dir = None\n\n        if cert:\n            if not isinstance(cert, basestring):\n                conn.cert_file = cert[0]\n                conn.key_file = cert[1]\n            else:\n                conn.cert_file = cert\n                conn.key_file = None\n            if conn.cert_file and not os.path.exists(conn.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {conn.cert_file}\"\n                )\n            if conn.key_file and not os.path.exists(conn.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {conn.key_file}\"\n                )\n\n    def build_response(self, req: PreparedRequest, resp: Any) -> Response:\n        \n        assert _is_prepared(req)\n        response = Response()\n\n         \n        response.status_code = getattr(resp, \"status\", None)   \n\n         \n        response.headers = CaseInsensitiveDict(getattr(resp, \"headers\", {}))\n\n         \n        response.encoding = get_encoding_from_headers(response.headers)\n        response.raw = resp\n        response.reason = response.raw.reason\n\n        if isinstance(req.url, bytes):\n            response.url = req.url.decode(\"utf-8\")\n        else:\n            response.url = req.url\n\n         \n        extract_cookies_to_jar(response.cookies, req, resp)\n\n         \n        response.request = req\n        response.connection = self\n\n        return response\n\n    def build_connection_pool_key_attributes(\n        self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None\n    ) -> tuple[dict[str, Any], dict[str, Any]]:\n        \n        return _urllib3_request_context(request, verify, cert, self.poolmanager)\n\n    def get_connection_with_tls_context(\n        self,\n        request: PreparedRequest,\n        verify: _t.VerifyType,\n        proxies: dict[str, str] | None = None,\n        cert: _t.CertType = None,\n    ) -> HTTPConnectionPool:\n        \n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        try:\n            host_params, pool_kwargs = self.build_connection_pool_key_attributes(\n                request,\n                verify,\n                cert,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=request)\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n        else:\n             \n            conn = self.poolmanager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n\n        return conn\n\n    def get_connection(\n        self, url: str, proxies: dict[str, str] | None = None\n    ) -> HTTPConnectionPool:\n        \n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        proxy = select_proxy(url, proxies)\n\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_url(url)\n        else:\n             \n            parsed = urlparse(url)\n            url = parsed.geturl()\n            conn = self.poolmanager.connection_from_url(url)\n\n        return conn\n\n    def close(self) -> None:\n        \n        self.poolmanager.clear()\n        for proxy in self.proxy_manager.values():\n            proxy.clear()\n\n    def request_url(\n        self, request: PreparedRequest, proxies: dict[str, str] | None\n    ) -> str:\n        \n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        scheme = urlparse(request.url).scheme\n\n        is_proxied_http_request = proxy and scheme != \"https\"\n        using_socks_proxy = False\n        if proxy:\n            proxy_scheme = urlparse(proxy).scheme.lower()\n            using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n        url = request.path_url\n\n        if is_proxied_http_request and not using_socks_proxy:\n            url = urldefragauth(request.url)\n\n        return url\n\n    def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None:\n        \n        pass\n\n    def proxy_headers(self, proxy: str) -> dict[str, str]:\n        \n        headers: dict[str, str] = {}\n        username, password = get_auth_from_url(proxy)\n\n        if username:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return headers\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \n\n        assert _is_prepared(request)\n\n        try:\n            conn = self.get_connection_with_tls_context(\n                request, verify, proxies=proxies, cert=cert\n            )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n            stream=stream,\n            timeout=timeout,\n            verify=verify,\n            cert=cert,\n            proxies=proxies,\n        )\n\n        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n\n        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                resolved_timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            resolved_timeout = timeout\n        else:\n            resolved_timeout = TimeoutSauce(connect=timeout, read=timeout)\n\n        try:\n            resp = conn.urlopen(\n                method=request.method,\n                url=url,\n                body=request.body,   \n                headers=request.headers,   \n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=resolved_timeout,\n                chunked=chunked,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=request)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                 \n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=request)\n\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=request)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=request)\n\n            if isinstance(e.reason, _SSLError):\n                 \n                raise SSLError(e, request=request)\n\n            raise ConnectionError(e, request=request)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=request)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                 \n                raise SSLError(e, request=request)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=request)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=request)\n            else:\n                raise\n\n        return self.build_response(request, resp)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-a0e3de19d1287dec", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "6dad1184a9418861ead4a28105eb2b5f7d47605837275241dd68292e803a56d9", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 455, "local_path": "comments/remove-comments/I01__requests__HTTPAdapter__68f13f61.py", "order": 1, "original_content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "parent_variant_id": "pyint-d7199f8ad572-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L158-L748", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 10578, "comments_removed": 31, "docstrings_removed": 13, "line_comments_removed": 18}, "unit_kind": "class", "unit_name": "HTTPAdapter", "variant_id": "pyint-a4e668f13f61-I01", "group_id": "py-a0e3de19d1287dec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 730, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c7132a660dce-I02", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__: list[str] = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    max_retries: Retry\n    config: dict[str, Any]\n    proxy_manager: dict[str, Any]\n    _pool_connections: int\n    _pool_maxsize: int\n    _pool_block: bool\n    poolmanager: _PoolManager\n\n    def __init__(\n        self,\n        pool: int = DEFAULT_POOLSIZE,\n        pool2: int = DEFAULT_POOLSIZE,\n        max: int | Retry = DEFAULT_RETRIES,\n        pool3: bool = DEFAULT_POOLBLOCK,\n    ) -> None:\n        if max == DEFAULT_RETRIES:\n            self.max_retries = Retry(0, read=False)\n        else:\n            self.max_retries = Retry.from_int(max)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = pool\n        self._pool_maxsize = pool2\n        self._pool_block = pool3\n\n        self.init(pool, pool2, block=pool3)\n\n    def __getstate__(self) -> dict[str, Any]:\n        return {att: getattr(self, att, None) for att in self.__attrs__}\n\n    def __setstate__(self, sta: dict[str, Any]) -> None:\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        self.proxy_manager = {}\n        self.config = {}\n\n        for att2, val in sta.items():\n            setattr(self, att2, val)\n\n        self.init(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def init(\n        self,\n        con: int,\n        max2: int,\n        blo: bool = DEFAULT_POOLBLOCK,\n        **pool4: Any,\n    ) -> None:\n        \"\"\"Initializes a urllib3 PoolManager.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        # save these values for pickling\n        self._pool_connections = con\n        self._pool_maxsize = max2\n        self._pool_block = blo\n\n        self.poolmanager = PoolManager(\n            num_pools=con,\n            maxsize=max2,\n            block=blo,\n            **pool4,\n        )\n\n    def proxy2(self, pro: str, **proxy4: Any) -> Any:\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if pro in self.proxy_manager:\n            man = self.proxy_manager[pro]\n        elif pro.lower().startswith(\"socks\"):\n            use, pas = get_auth_from_url(pro)\n            man = self.proxy_manager[pro] = SOCKSProxyManager(\n                pro,\n                username=use,\n                password=pas,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy4,\n            )\n        else:\n            proxy5 = self.proxy3(pro)\n            man = self.proxy_manager[pro] = proxy_from_url(\n                pro,\n                proxy_headers=proxy5,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy4,\n            )\n\n        return man\n\n    def cert2(\n        self, con2: Any, url2: str, ver: _t.VerifyType, cer: _t.CertType\n    ) -> None:\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if url2.lower().startswith(\"https\") and ver:\n            cert3 = None\n\n            # Allow self-specified cert location.\n            if ver is not True:\n                cert3 = ver\n\n            if not cert3:\n                cert3 = DEFAULT_CA_BUNDLE_PATH\n\n            if not cert3 or not os.path.exists(cert3):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {cert3}\"\n                )\n\n            con2.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(cert3):\n                con2.ca_certs = cert3\n            else:\n                con2.ca_cert_dir = cert3\n        else:\n            con2.cert_reqs = \"CERT_NONE\"\n            con2.ca_certs = None\n            con2.ca_cert_dir = None\n\n        if cer:\n            if not isinstance(cer, basestring):\n                con2.cert_file = cer[0]\n                con2.key_file = cer[1]\n            else:\n                con2.cert_file = cer\n                con2.key_file = None\n            if con2.cert_file and not os.path.exists(con2.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {con2.cert_file}\"\n                )\n            if con2.key_file and not os.path.exists(con2.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {con2.key_file}\"\n                )\n\n    def build(self, req2: PreparedRequest, res: Any) -> Response:\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        assert _is_prepared(req2)\n        res2 = Response()\n\n        # Fallback to None if there's no status_code, for whatever reason.\n        res2.status_code = getattr(res, \"status\", None)  # type: ignore[assignment]\n\n        # Make headers case-insensitive.\n        res2.headers = CaseInsensitiveDict(getattr(res, \"headers\", {}))\n\n        # Set encoding.\n        res2.encoding = get_encoding_from_headers(res2.headers)\n        res2.raw = res\n        res2.reason = res2.raw.reason\n\n        if isinstance(req2.url, bytes):\n            res2.url = req2.url.decode(\"utf-8\")\n        else:\n            res2.url = req2.url\n\n        # Add new cookies from the server.\n        extract_cookies_to_jar(res2.cookies, req2, res)\n\n        # Give the Response some context.\n        res2.request = req2\n        res2.connection = self\n\n        return res2\n\n    def build2(\n        self, req3: PreparedRequest, ver2: _t.VerifyType, cer2: _t.CertType = None\n    ) -> tuple[dict[str, Any], dict[str, Any]]:\n        \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n\n        This looks at the PreparedRequest, the user-specified verify value,\n        and the value of the cert parameter to determine what PoolKey values\n        to use to select a connection from a given urllib3 Connection Pool.\n\n        The SSL related pool key arguments are not consistently set. As of\n        this writing, use the following to determine what keys may be in that\n        dictionary:\n\n        * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n          default Requests SSL Context\n        * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n          ``\"cert_reqs\"`` will be set\n        * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n          ``\"ca_certs\"`` will be set if the string is not a directory recognized\n          by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n          set.\n        * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n          ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n          be present\n\n        To override these settings, one may subclass this class, call this\n        method and use the above logic to change parameters as desired. For\n        example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n        must both set ``\"ssl_context\"`` and based on what else they require,\n        alter the other keys to ensure the desired behaviour.\n\n        :param request:\n            The PreparedRequest being sent over the connection.\n        :type request:\n            :class:`~requests.models.PreparedRequest`\n        :param verify:\n            Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use.\n        :param cert:\n            (optional) Any user-provided SSL certificate for client\n            authentication (a.k.a., mTLS). This may be a string (i.e., just\n            the path to a file which holds both certificate and key) or a\n            tuple of length 2 with the certificate file path and key file\n            path.\n        :returns:\n            A tuple of two dictionaries. The first is the \"host parameters\"\n            portion of the Pool Key including scheme, hostname, and port. The\n            second is a dictionary of SSLContext related parameters.\n        \"\"\"\n        return _urllib3_request_context(req3, ver2, cer2, self.poolmanager)\n\n    def get(\n        self,\n        req4: PreparedRequest,\n        ver3: _t.VerifyType,\n        pro2: dict[str, str] | None = None,\n        cer3: _t.CertType = None,\n    ) -> HTTPConnectionPool:\n        \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request:\n            The :class:`PreparedRequest <PreparedRequest>` object to be sent\n            over the connection.\n        :param verify:\n            Either a boolean, in which case it controls whether we verify the\n            server's TLS certificate, or a string, in which case it must be a\n            path to a CA bundle to use.\n        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.HTTPConnectionPool\n        \"\"\"\n        assert _is_prepared(req4)\n\n        pro3 = select_proxy(req4.url, pro2)\n        try:\n            host2, pool5 = self.build2(\n                req4,\n                ver3,\n                cer3,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=req4)\n        if pro3:\n            pro3 = prepend_scheme_if_needed(pro3, \"http\")\n            proxy6 = parse_url(pro3)\n            if not proxy6.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy7 = self.proxy2(pro3)\n            con3 = proxy7.connection_from_host(\n                **host2, pool_kwargs=pool5\n            )\n        else:\n            # Only scheme should be lower case\n            con3 = self.poolmanager.connection_from_host(\n                **host2, pool_kwargs=pool5\n            )\n\n        return con3\n\n    def get2(\n        self, url3: str, pro4: dict[str, str] | None = None\n    ) -> HTTPConnectionPool:\n        \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n        for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n        Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.HTTPConnectionPool\n        \"\"\"\n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        pro5 = select_proxy(url3, pro4)\n\n        if pro5:\n            pro5 = prepend_scheme_if_needed(pro5, \"http\")\n            proxy8 = parse_url(pro5)\n            if not proxy8.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy9 = self.proxy2(pro5)\n            con4 = proxy9.connection_from_url(url3)\n        else:\n            # Only scheme should be lower case\n            par = urlparse(url3)\n            url3 = par.geturl()\n            con4 = self.poolmanager.connection_from_url(url3)\n\n        return con4\n\n    def clo(self) -> None:\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        for pro6 in self.proxy_manager.values():\n            pro6.clear()\n\n    def request2(\n        self, req5: PreparedRequest, pro7: dict[str, str] | None\n    ) -> str:\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        assert _is_prepared(req5)\n\n        pro8 = select_proxy(req5.url, pro7)\n        sch = urlparse(req5.url).scheme\n\n        is2 = pro8 and sch != \"https\"\n        using = False\n        if pro8:\n            proxy10 = urlparse(pro8).scheme.lower()\n            using = proxy10.startswith(\"socks\")\n\n        url4 = req5.path_url\n\n        if is2 and not using:\n            url4 = urldefragauth(req5.url)\n\n        return url4\n\n    def add(self, req6: PreparedRequest, **kwa: Any) -> None:\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        pass\n\n    def proxy3(self, pro9: str) -> dict[str, str]:\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        hea: dict[str, str] = {}\n        use2, pas2 = get_auth_from_url(pro9)\n\n        if use2:\n            hea[\"Proxy-Authorization\"] = _basic_auth_str(use2, pas2)\n\n        return hea\n\n    def sen(\n        self,\n        req7: PreparedRequest,\n        str2: bool = False,\n        tim: _t.TimeoutType = None,\n        ver4: _t.VerifyType = True,\n        cer4: _t.CertType = None,\n        pro10: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n\n        assert _is_prepared(req7)\n\n        try:\n            con5 = self.get(\n                req7, ver4, proxies=pro10, cert=cer4\n            )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=req7)\n\n        self.cert2(con5, req7.url, ver4, cer4)\n        url5 = self.request2(req7, pro10)\n        self.add(\n            req7,\n            stream=str2,\n            timeout=tim,\n            verify=ver4,\n            cert=cer4,\n            proxies=pro10,\n        )\n\n        chu = not (req7.body is None or \"Content-Length\" in req7.headers)\n\n        if isinstance(tim, tuple):\n            try:\n                con6, rea = tim\n                resolved = TimeoutSauce(connect=con6, read=rea)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {tim}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(tim, TimeoutSauce):\n            resolved = tim\n        else:\n            resolved = TimeoutSauce(connect=tim, read=tim)\n\n        try:\n            res3 = con5.urlopen(\n                method=req7.method,\n                url=url5,\n                body=req7.body,  # type: ignore[arg-type]  # urllib3 stubs don't accept Iterable[bytes | str]\n                headers=req7.headers,  # type: ignore[arg-type]  # urllib3#3072\n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=resolved,\n                chunked=chu,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=req7)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=req7)\n\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=req7)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=req7)\n\n            if isinstance(e.reason, _SSLError):\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=req7)\n\n            raise ConnectionError(e, request=req7)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=req7)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=req7)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=req7)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=req7)\n            else:\n                raise\n\n        return self.build(req7, res3)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-a0e3de19d1287dec", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "8e61cb219a20208f411a28607101632d91a34cb19eadde8cd43ae2a91c7b36cf", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 642, "local_path": "identifiers/shorten-identifiers/I02__requests__HTTPAdapter__2a660dce.py", "order": 2, "original_content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "parent_variant_id": "pyint-d7199f8ad572-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L158-L748", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 303, "identifiers_declared": 86}, "unit_kind": "class", "unit_name": "HTTPAdapter", "variant_id": "pyint-c7132a660dce-I02", "group_id": "py-a0e3de19d1287dec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 731, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8c73e1b18d59-I03", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__: list[str] = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    max_retries: Retry\n    config: dict[str, Any]\n    proxy_manager: dict[str, Any]\n    _pool_connections: int\n    _pool_maxsize: int\n    _pool_block: bool\n    poolmanager: _PoolManager\n\n    def __init__(\n        self,\n        primaryRequest: int = DEFAULT_POOLSIZE,\n        sharedStatus: int = DEFAULT_POOLSIZE,\n        activeCache: int | Retry = DEFAULT_RETRIES,\n        backupPath: bool = DEFAULT_POOLBLOCK,\n    ) -> None:\n        if activeCache == DEFAULT_RETRIES:\n            self.max_retries = Retry(0, read=False)\n        else:\n            self.max_retries = Retry.from_int(activeCache)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = primaryRequest\n        self._pool_maxsize = sharedStatus\n        self._pool_block = backupPath\n\n        self.validateMessage(primaryRequest, sharedStatus, block=backupPath)\n\n    def __getstate__(self) -> dict[str, Any]:\n        return {mode: getattr(self, mode, None) for mode in self.__attrs__}\n\n    def __setstate__(self, score: dict[str, Any]) -> None:\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        self.proxy_manager = {}\n        self.config = {}\n\n        for date, group in score.items():\n            setattr(self, date, group)\n\n        self.validateMessage(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def validateMessage(\n        self,\n        pendingPath: int,\n        address: int,\n        group: bool = DEFAULT_POOLBLOCK,\n        **primaryItem: Any,\n    ) -> None:\n        \"\"\"Initializes a urllib3 PoolManager.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        # save these values for pickling\n        self._pool_connections = pendingPath\n        self._pool_maxsize = address\n        self._pool_block = group\n\n        self.poolmanager = PoolManager(\n            num_pools=pendingPath,\n            maxsize=address,\n            block=group,\n            **primaryItem,\n        )\n\n    def validateAddress(self, order: str, **pendingScore: Any) -> Any:\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if order in self.proxy_manager:\n            address = self.proxy_manager[order]\n        elif order.lower().startswith(\"socks\"):\n            location, nextPath = get_auth_from_url(order)\n            address = self.proxy_manager[order] = SOCKSProxyManager(\n                order,\n                username=location,\n                password=nextPath,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **pendingScore,\n            )\n        else:\n            pendingConfig = self.updateAccount(order)\n            address = self.proxy_manager[order] = proxy_from_url(\n                order,\n                proxy_headers=pendingConfig,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **pendingScore,\n            )\n\n        return address\n\n    def readAddress(\n        self, date: Any, key: str, status: _t.VerifyType, node: _t.CertType\n    ) -> None:\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if key.lower().startswith(\"https\") and status:\n            response = None\n\n            # Allow self-specified cert location.\n            if status is not True:\n                response = status\n\n            if not response:\n                response = DEFAULT_CA_BUNDLE_PATH\n\n            if not response or not os.path.exists(response):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {response}\"\n                )\n\n            date.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(response):\n                date.ca_certs = response\n            else:\n                date.ca_cert_dir = response\n        else:\n            date.cert_reqs = \"CERT_NONE\"\n            date.ca_certs = None\n            date.ca_cert_dir = None\n\n        if node:\n            if not isinstance(node, basestring):\n                date.cert_file = node[0]\n                date.key_file = node[1]\n            else:\n                date.cert_file = node\n                date.key_file = None\n            if date.cert_file and not os.path.exists(date.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {date.cert_file}\"\n                )\n            if date.key_file and not os.path.exists(date.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {date.key_file}\"\n                )\n\n    def refreshAccount(self, age: PreparedRequest, flag: Any) -> Response:\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        assert _is_prepared(age)\n        category = Response()\n\n        # Fallback to None if there's no status_code, for whatever reason.\n        category.status_code = getattr(flag, \"status\", None)  # type: ignore[assignment]\n\n        # Make headers case-insensitive.\n        category.headers = CaseInsensitiveDict(getattr(flag, \"headers\", {}))\n\n        # Set encoding.\n        category.encoding = get_encoding_from_headers(category.headers)\n        category.raw = flag\n        category.reason = category.raw.reason\n\n        if isinstance(age.url, bytes):\n            category.url = age.url.decode(\"utf-8\")\n        else:\n            category.url = age.url\n\n        # Add new cookies from the server.\n        extract_cookies_to_jar(category.cookies, age, flag)\n\n        # Give the Response some context.\n        category.request = age\n        category.connection = self\n\n        return category\n\n    def validateBalance(\n        self, payload: PreparedRequest, target: _t.VerifyType, step: _t.CertType = None\n    ) -> tuple[dict[str, Any], dict[str, Any]]:\n        \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n\n        This looks at the PreparedRequest, the user-specified verify value,\n        and the value of the cert parameter to determine what PoolKey values\n        to use to select a connection from a given urllib3 Connection Pool.\n\n        The SSL related pool key arguments are not consistently set. As of\n        this writing, use the following to determine what keys may be in that\n        dictionary:\n\n        * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n          default Requests SSL Context\n        * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n          ``\"cert_reqs\"`` will be set\n        * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n          ``\"ca_certs\"`` will be set if the string is not a directory recognized\n          by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n          set.\n        * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n          ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n          be present\n\n        To override these settings, one may subclass this class, call this\n        method and use the above logic to change parameters as desired. For\n        example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n        must both set ``\"ssl_context\"`` and based on what else they require,\n        alter the other keys to ensure the desired behaviour.\n\n        :param request:\n            The PreparedRequest being sent over the connection.\n        :type request:\n            :class:`~requests.models.PreparedRequest`\n        :param verify:\n            Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use.\n        :param cert:\n            (optional) Any user-provided SSL certificate for client\n            authentication (a.k.a., mTLS). This may be a string (i.e., just\n            the path to a file which holds both certificate and key) or a\n            tuple of length 2 with the certificate file path and key file\n            path.\n        :returns:\n            A tuple of two dictionaries. The first is the \"host parameters\"\n            portion of the Pool Key including scheme, hostname, and port. The\n            second is a dictionary of SSLContext related parameters.\n        \"\"\"\n        return _urllib3_request_context(payload, target, step, self.poolmanager)\n\n    def validateSession(\n        self,\n        session: PreparedRequest,\n        option: _t.VerifyType,\n        channel: dict[str, str] | None = None,\n        item: _t.CertType = None,\n    ) -> HTTPConnectionPool:\n        \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request:\n            The :class:`PreparedRequest <PreparedRequest>` object to be sent\n            over the connection.\n        :param verify:\n            Either a boolean, in which case it controls whether we verify the\n            server's TLS certificate, or a string, in which case it must be a\n            path to a CA bundle to use.\n        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.HTTPConnectionPool\n        \"\"\"\n        assert _is_prepared(session)\n\n        token = select_proxy(session.url, channel)\n        try:\n            finalClient, primaryData = self.validateBalance(\n                session,\n                option,\n                item,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=session)\n        if token:\n            token = prepend_scheme_if_needed(token, \"http\")\n            cachedKey = parse_url(token)\n            if not cachedKey.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            cachedSession = self.validateAddress(token)\n            path = cachedSession.connection_from_host(\n                **finalClient, pool_kwargs=primaryData\n            )\n        else:\n            # Only scheme should be lower case\n            path = self.poolmanager.connection_from_host(\n                **finalClient, pool_kwargs=primaryData\n            )\n\n        return path\n\n    def validateWindow(\n        self, key: str, message: dict[str, str] | None = None\n    ) -> HTTPConnectionPool:\n        \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n        for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n        Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.HTTPConnectionPool\n        \"\"\"\n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        total = select_proxy(key, message)\n\n        if total:\n            total = prepend_scheme_if_needed(total, \"http\")\n            finalNode = parse_url(total)\n            if not finalNode.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            sharedBalance = self.validateAddress(total)\n            item = sharedBalance.connection_from_url(key)\n        else:\n            # Only scheme should be lower case\n            status = urlparse(key)\n            key = status.geturl()\n            item = self.poolmanager.connection_from_url(key)\n\n        return item\n\n    def audit(self) -> None:\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        for entry in self.proxy_manager.values():\n            entry.clear()\n\n    def refreshNode(\n        self, profile: PreparedRequest, version: dict[str, str] | None\n    ) -> str:\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        assert _is_prepared(profile)\n\n        total = select_proxy(profile.url, version)\n        window = urlparse(profile.url).scheme\n\n        pendingRequest = total and window != \"https\"\n        currentRequest = False\n        if total:\n            defaultEvent = urlparse(total).scheme.lower()\n            currentRequest = defaultEvent.startswith(\"socks\")\n\n        age = profile.path_url\n\n        if pendingRequest and not currentRequest:\n            age = urldefragauth(profile.url)\n\n        return age\n\n    def removeState(self, nextKey: PreparedRequest, **status: Any) -> None:\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        pass\n\n    def updateAccount(self, token: str) -> dict[str, str]:\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        channel: dict[str, str] = {}\n        shipment, nextItem = get_auth_from_url(token)\n\n        if shipment:\n            channel[\"Proxy-Authorization\"] = _basic_auth_str(shipment, nextItem)\n\n        return channel\n\n    def join(\n        self,\n        message: PreparedRequest,\n        amount: bool = False,\n        session: _t.TimeoutType = None,\n        source: _t.VerifyType = True,\n        size: _t.CertType = None,\n        address: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n\n        assert _is_prepared(message)\n\n        try:\n            node = self.validateSession(\n                message, source, proxies=address, cert=size\n            )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=message)\n\n        self.readAddress(node, message.url, source, size)\n        age = self.refreshNode(message, address)\n        self.removeState(\n            message,\n            stream=amount,\n            timeout=session,\n            verify=source,\n            cert=size,\n            proxies=address,\n        )\n\n        channel = not (message.body is None or \"Content-Length\" in message.headers)\n\n        if isinstance(session, tuple):\n            try:\n                profile, mode = session\n                currentAddress = TimeoutSauce(connect=profile, read=mode)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {session}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(session, TimeoutSauce):\n            currentAddress = session\n        else:\n            currentAddress = TimeoutSauce(connect=session, read=session)\n\n        try:\n            date = node.urlopen(\n                method=message.method,\n                url=age,\n                body=message.body,  # type: ignore[arg-type]  # urllib3 stubs don't accept Iterable[bytes | str]\n                headers=message.headers,  # type: ignore[arg-type]  # urllib3#3072\n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=currentAddress,\n                chunked=channel,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=message)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=message)\n\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=message)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=message)\n\n            if isinstance(e.reason, _SSLError):\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=message)\n\n            raise ConnectionError(e, request=message)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=message)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=message)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=message)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=message)\n            else:\n                raise\n\n        return self.refreshAccount(message, date)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-a0e3de19d1287dec", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "87bcb832a2a948753948d9c685dec680f76f1332ec80b13da5be4376012fdcb4", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 642, "local_path": "identifiers/mislead-identifiers/I03__requests__HTTPAdapter__e1b18d59.py", "order": 3, "original_content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "parent_variant_id": "pyint-d7199f8ad572-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L158-L748", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 303, "identifiers_declared": 86, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 2, "local_exact_length_matches": 70, "local_random_pool_selections": 74, "local_total_length_difference": 16, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 1, "method_exact_length_matches": 8, "method_random_pool_selections": 12, "method_total_length_difference": 40}, "unit_kind": "class", "unit_name": "HTTPAdapter", "variant_id": "pyint-8c73e1b18d59-I03", "group_id": "py-a0e3de19d1287dec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 732, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-75b7cbd53524-I04", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__: list[str] = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    max_retries: Retry\n    config: dict[str, Any]\n    proxy_manager: dict[str, Any]\n    _pool_connections: int\n    _pool_maxsize: int\n    _pool_block: bool\n    poolmanager: _PoolManager\n\n    def __init__(\n        self,\n        n: int = DEFAULT_POOLSIZE,\n        o: int = DEFAULT_POOLSIZE,\n        p: int | Retry = DEFAULT_RETRIES,\n        q: bool = DEFAULT_POOLBLOCK,\n    ) -> None:\n        if p == DEFAULT_RETRIES:\n            self.max_retries = Retry(0, read=False)\n        else:\n            self.max_retries = Retry.from_int(p)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = n\n        self._pool_maxsize = o\n        self._pool_block = q\n\n        self.a(n, o, block=q)\n\n    def __getstate__(self) -> dict[str, Any]:\n        return {r: getattr(self, r, None) for r in self.__attrs__}\n\n    def __setstate__(self, s: dict[str, Any]) -> None:\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        self.proxy_manager = {}\n        self.config = {}\n\n        for t, u in s.items():\n            setattr(self, t, u)\n\n        self.a(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def a(\n        self,\n        v: int,\n        w: int,\n        x: bool = DEFAULT_POOLBLOCK,\n        **y: Any,\n    ) -> None:\n        \"\"\"Initializes a urllib3 PoolManager.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        # save these values for pickling\n        self._pool_connections = v\n        self._pool_maxsize = w\n        self._pool_block = x\n\n        self.poolmanager = PoolManager(\n            num_pools=v,\n            maxsize=w,\n            block=x,\n            **y,\n        )\n\n    def b(self, z: str, **A: Any) -> Any:\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if z in self.proxy_manager:\n            B = self.proxy_manager[z]\n        elif z.lower().startswith(\"socks\"):\n            C, D = get_auth_from_url(z)\n            B = self.proxy_manager[z] = SOCKSProxyManager(\n                z,\n                username=C,\n                password=D,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **A,\n            )\n        else:\n            E = self.l(z)\n            B = self.proxy_manager[z] = proxy_from_url(\n                z,\n                proxy_headers=E,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **A,\n            )\n\n        return B\n\n    def c(\n        self, F: Any, G: str, H: _t.VerifyType, I: _t.CertType\n    ) -> None:\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if G.lower().startswith(\"https\") and H:\n            J = None\n\n            # Allow self-specified cert location.\n            if H is not True:\n                J = H\n\n            if not J:\n                J = DEFAULT_CA_BUNDLE_PATH\n\n            if not J or not os.path.exists(J):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {J}\"\n                )\n\n            F.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(J):\n                F.ca_certs = J\n            else:\n                F.ca_cert_dir = J\n        else:\n            F.cert_reqs = \"CERT_NONE\"\n            F.ca_certs = None\n            F.ca_cert_dir = None\n\n        if I:\n            if not isinstance(I, basestring):\n                F.cert_file = I[0]\n                F.key_file = I[1]\n            else:\n                F.cert_file = I\n                F.key_file = None\n            if F.cert_file and not os.path.exists(F.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {F.cert_file}\"\n                )\n            if F.key_file and not os.path.exists(F.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {F.key_file}\"\n                )\n\n    def d(self, K: PreparedRequest, L: Any) -> Response:\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        assert _is_prepared(K)\n        M = Response()\n\n        # Fallback to None if there's no status_code, for whatever reason.\n        M.status_code = getattr(L, \"status\", None)  # type: ignore[assignment]\n\n        # Make headers case-insensitive.\n        M.headers = CaseInsensitiveDict(getattr(L, \"headers\", {}))\n\n        # Set encoding.\n        M.encoding = get_encoding_from_headers(M.headers)\n        M.raw = L\n        M.reason = M.raw.reason\n\n        if isinstance(K.url, bytes):\n            M.url = K.url.decode(\"utf-8\")\n        else:\n            M.url = K.url\n\n        # Add new cookies from the server.\n        extract_cookies_to_jar(M.cookies, K, L)\n\n        # Give the Response some context.\n        M.request = K\n        M.connection = self\n\n        return M\n\n    def f(\n        self, N: PreparedRequest, O: _t.VerifyType, P: _t.CertType = None\n    ) -> tuple[dict[str, Any], dict[str, Any]]:\n        \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n\n        This looks at the PreparedRequest, the user-specified verify value,\n        and the value of the cert parameter to determine what PoolKey values\n        to use to select a connection from a given urllib3 Connection Pool.\n\n        The SSL related pool key arguments are not consistently set. As of\n        this writing, use the following to determine what keys may be in that\n        dictionary:\n\n        * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n          default Requests SSL Context\n        * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n          ``\"cert_reqs\"`` will be set\n        * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n          ``\"ca_certs\"`` will be set if the string is not a directory recognized\n          by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n          set.\n        * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n          ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n          be present\n\n        To override these settings, one may subclass this class, call this\n        method and use the above logic to change parameters as desired. For\n        example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n        must both set ``\"ssl_context\"`` and based on what else they require,\n        alter the other keys to ensure the desired behaviour.\n\n        :param request:\n            The PreparedRequest being sent over the connection.\n        :type request:\n            :class:`~requests.models.PreparedRequest`\n        :param verify:\n            Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use.\n        :param cert:\n            (optional) Any user-provided SSL certificate for client\n            authentication (a.k.a., mTLS). This may be a string (i.e., just\n            the path to a file which holds both certificate and key) or a\n            tuple of length 2 with the certificate file path and key file\n            path.\n        :returns:\n            A tuple of two dictionaries. The first is the \"host parameters\"\n            portion of the Pool Key including scheme, hostname, and port. The\n            second is a dictionary of SSLContext related parameters.\n        \"\"\"\n        return _urllib3_request_context(N, O, P, self.poolmanager)\n\n    def g(\n        self,\n        Q: PreparedRequest,\n        R: _t.VerifyType,\n        S: dict[str, str] | None = None,\n        T: _t.CertType = None,\n    ) -> HTTPConnectionPool:\n        \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request:\n            The :class:`PreparedRequest <PreparedRequest>` object to be sent\n            over the connection.\n        :param verify:\n            Either a boolean, in which case it controls whether we verify the\n            server's TLS certificate, or a string, in which case it must be a\n            path to a CA bundle to use.\n        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.HTTPConnectionPool\n        \"\"\"\n        assert _is_prepared(Q)\n\n        U = select_proxy(Q.url, S)\n        try:\n            V, W = self.f(\n                Q,\n                R,\n                T,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=Q)\n        if U:\n            U = prepend_scheme_if_needed(U, \"http\")\n            X = parse_url(U)\n            if not X.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            Y = self.b(U)\n            Z = Y.connection_from_host(\n                **V, pool_kwargs=W\n            )\n        else:\n            # Only scheme should be lower case\n            Z = self.poolmanager.connection_from_host(\n                **V, pool_kwargs=W\n            )\n\n        return Z\n\n    def h(\n        self, aa: str, ab: dict[str, str] | None = None\n    ) -> HTTPConnectionPool:\n        \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n        for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n        Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.HTTPConnectionPool\n        \"\"\"\n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        ac = select_proxy(aa, ab)\n\n        if ac:\n            ac = prepend_scheme_if_needed(ac, \"http\")\n            ad = parse_url(ac)\n            if not ad.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            ae = self.b(ac)\n            af = ae.connection_from_url(aa)\n        else:\n            # Only scheme should be lower case\n            ag = urlparse(aa)\n            aa = ag.geturl()\n            af = self.poolmanager.connection_from_url(aa)\n\n        return af\n\n    def i(self) -> None:\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        for ah in self.proxy_manager.values():\n            ah.clear()\n\n    def j(\n        self, ai: PreparedRequest, aj: dict[str, str] | None\n    ) -> str:\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        assert _is_prepared(ai)\n\n        ak = select_proxy(ai.url, aj)\n        al = urlparse(ai.url).scheme\n\n        am = ak and al != \"https\"\n        an = False\n        if ak:\n            ao = urlparse(ak).scheme.lower()\n            an = ao.startswith(\"socks\")\n\n        ap = ai.path_url\n\n        if am and not an:\n            ap = urldefragauth(ai.url)\n\n        return ap\n\n    def k(self, aq: PreparedRequest, **ar: Any) -> None:\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        pass\n\n    def l(self, at: str) -> dict[str, str]:\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        au: dict[str, str] = {}\n        av, aw = get_auth_from_url(at)\n\n        if av:\n            au[\"Proxy-Authorization\"] = _basic_auth_str(av, aw)\n\n        return au\n\n    def m(\n        self,\n        ax: PreparedRequest,\n        ay: bool = False,\n        az: _t.TimeoutType = None,\n        aA: _t.VerifyType = True,\n        aB: _t.CertType = None,\n        aC: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n\n        assert _is_prepared(ax)\n\n        try:\n            aD = self.g(\n                ax, aA, proxies=aC, cert=aB\n            )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=ax)\n\n        self.c(aD, ax.url, aA, aB)\n        aE = self.j(ax, aC)\n        self.k(\n            ax,\n            stream=ay,\n            timeout=az,\n            verify=aA,\n            cert=aB,\n            proxies=aC,\n        )\n\n        aF = not (ax.body is None or \"Content-Length\" in ax.headers)\n\n        if isinstance(az, tuple):\n            try:\n                aG, aH = az\n                aI = TimeoutSauce(connect=aG, read=aH)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {az}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(az, TimeoutSauce):\n            aI = az\n        else:\n            aI = TimeoutSauce(connect=az, read=az)\n\n        try:\n            aJ = aD.urlopen(\n                method=ax.method,\n                url=aE,\n                body=ax.body,  # type: ignore[arg-type]  # urllib3 stubs don't accept Iterable[bytes | str]\n                headers=ax.headers,  # type: ignore[arg-type]  # urllib3#3072\n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=aI,\n                chunked=aF,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=ax)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=ax)\n\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=ax)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=ax)\n\n            if isinstance(e.reason, _SSLError):\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=ax)\n\n            raise ConnectionError(e, request=ax)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=ax)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=ax)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=ax)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=ax)\n            else:\n                raise\n\n        return self.d(ax, aJ)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-a0e3de19d1287dec", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "c4676d144ca2505101bcdc781208914982fd17b71cafadb9d86fef5e5fc01574", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 642, "local_path": "identifiers/garble-identifiers/I04__requests__HTTPAdapter__cbd53524.py", "order": 4, "original_content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "parent_variant_id": "pyint-d7199f8ad572-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L158-L748", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 303, "identifiers_declared": 86}, "unit_kind": "class", "unit_name": "HTTPAdapter", "variant_id": "pyint-75b7cbd53524-I04", "group_id": "py-a0e3de19d1287dec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 733, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8e8afbf56431-I05", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__: list[str] = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    max_retries: Retry\n    config: dict[str, Any]\n    proxy_manager: dict[str, Any]\n    _pool_connections: int\n    _pool_maxsize: int\n    _pool_block: bool\n    poolmanager: _PoolManager\n\n    def __init__(\n        self,\n        pool_connections: int = DEFAULT_POOLSIZE,\n        pool_maxsize: int = DEFAULT_POOLSIZE,\n        max_retries: int | Retry = DEFAULT_RETRIES,\n        pool_block: bool = DEFAULT_POOLBLOCK,\n    ) -> None:\n        if max_retries == DEFAULT_RETRIES:\n            self.max_retries = Retry(0x0, read=False)\n        else:\n            self.max_retries = Retry.from_int(max_retries)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = pool_connections\n        self._pool_maxsize = pool_maxsize\n        self._pool_block = pool_block\n\n        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n\n    def __getstate__(self) -> dict[str, Any]:\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        self.proxy_manager = {}\n        self.config = {}\n\n        for attr, value in state.items():\n            setattr(self, attr, value)\n\n        self.init_poolmanager(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def init_poolmanager(\n        self,\n        connections: int,\n        maxsize: int,\n        block: bool = DEFAULT_POOLBLOCK,\n        **pool_kwargs: Any,\n    ) -> None:\n        \"\"\"Initializes a urllib3 PoolManager.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        # save these values for pickling\n        self._pool_connections = connections\n        self._pool_maxsize = maxsize\n        self._pool_block = block\n\n        self.poolmanager = PoolManager(\n            num_pools=connections,\n            maxsize=maxsize,\n            block=block,\n            **pool_kwargs,\n        )\n\n    def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any:\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if proxy in self.proxy_manager:\n            manager = self.proxy_manager[proxy]\n        elif proxy.lower().startswith(\"socks\"):\n            username, password = get_auth_from_url(proxy)\n            manager = self.proxy_manager[proxy] = SOCKSProxyManager(\n                proxy,\n                username=username,\n                password=password,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n        else:\n            proxy_headers = self.proxy_headers(proxy)\n            manager = self.proxy_manager[proxy] = proxy_from_url(\n                proxy,\n                proxy_headers=proxy_headers,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n\n        return manager\n\n    def cert_verify(\n        self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType\n    ) -> None:\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if url.lower().startswith(\"https\") and verify:\n            cert_loc = None\n\n            # Allow self-specified cert location.\n            if verify is not True:\n                cert_loc = verify\n\n            if not cert_loc:\n                cert_loc = DEFAULT_CA_BUNDLE_PATH\n\n            if not cert_loc or not os.path.exists(cert_loc):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {cert_loc}\"\n                )\n\n            conn.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(cert_loc):\n                conn.ca_certs = cert_loc\n            else:\n                conn.ca_cert_dir = cert_loc\n        else:\n            conn.cert_reqs = \"CERT_NONE\"\n            conn.ca_certs = None\n            conn.ca_cert_dir = None\n\n        if cert:\n            if not isinstance(cert, basestring):\n                conn.cert_file = cert[0x0]\n                conn.key_file = cert[0x1]\n            else:\n                conn.cert_file = cert\n                conn.key_file = None\n            if conn.cert_file and not os.path.exists(conn.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {conn.cert_file}\"\n                )\n            if conn.key_file and not os.path.exists(conn.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {conn.key_file}\"\n                )\n\n    def build_response(self, req: PreparedRequest, resp: Any) -> Response:\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        assert _is_prepared(req)\n        response = Response()\n\n        # Fallback to None if there's no status_code, for whatever reason.\n        response.status_code = getattr(resp, \"status\", None)  # type: ignore[assignment]\n\n        # Make headers case-insensitive.\n        response.headers = CaseInsensitiveDict(getattr(resp, \"headers\", {}))\n\n        # Set encoding.\n        response.encoding = get_encoding_from_headers(response.headers)\n        response.raw = resp\n        response.reason = response.raw.reason\n\n        if isinstance(req.url, bytes):\n            response.url = req.url.decode(\"utf-8\")\n        else:\n            response.url = req.url\n\n        # Add new cookies from the server.\n        extract_cookies_to_jar(response.cookies, req, resp)\n\n        # Give the Response some context.\n        response.request = req\n        response.connection = self\n\n        return response\n\n    def build_connection_pool_key_attributes(\n        self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None\n    ) -> tuple[dict[str, Any], dict[str, Any]]:\n        \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n\n        This looks at the PreparedRequest, the user-specified verify value,\n        and the value of the cert parameter to determine what PoolKey values\n        to use to select a connection from a given urllib3 Connection Pool.\n\n        The SSL related pool key arguments are not consistently set. As of\n        this writing, use the following to determine what keys may be in that\n        dictionary:\n\n        * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n          default Requests SSL Context\n        * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n          ``\"cert_reqs\"`` will be set\n        * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n          ``\"ca_certs\"`` will be set if the string is not a directory recognized\n          by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n          set.\n        * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n          ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n          be present\n\n        To override these settings, one may subclass this class, call this\n        method and use the above logic to change parameters as desired. For\n        example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n        must both set ``\"ssl_context\"`` and based on what else they require,\n        alter the other keys to ensure the desired behaviour.\n\n        :param request:\n            The PreparedRequest being sent over the connection.\n        :type request:\n            :class:`~requests.models.PreparedRequest`\n        :param verify:\n            Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use.\n        :param cert:\n            (optional) Any user-provided SSL certificate for client\n            authentication (a.k.a., mTLS). This may be a string (i.e., just\n            the path to a file which holds both certificate and key) or a\n            tuple of length 2 with the certificate file path and key file\n            path.\n        :returns:\n            A tuple of two dictionaries. The first is the \"host parameters\"\n            portion of the Pool Key including scheme, hostname, and port. The\n            second is a dictionary of SSLContext related parameters.\n        \"\"\"\n        return _urllib3_request_context(request, verify, cert, self.poolmanager)\n\n    def get_connection_with_tls_context(\n        self,\n        request: PreparedRequest,\n        verify: _t.VerifyType,\n        proxies: dict[str, str] | None = None,\n        cert: _t.CertType = None,\n    ) -> HTTPConnectionPool:\n        \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request:\n            The :class:`PreparedRequest <PreparedRequest>` object to be sent\n            over the connection.\n        :param verify:\n            Either a boolean, in which case it controls whether we verify the\n            server's TLS certificate, or a string, in which case it must be a\n            path to a CA bundle to use.\n        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.HTTPConnectionPool\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        try:\n            host_params, pool_kwargs = self.build_connection_pool_key_attributes(\n                request,\n                verify,\n                cert,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=request)\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n        else:\n            # Only scheme should be lower case\n            conn = self.poolmanager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n\n        return conn\n\n    def get_connection(\n        self, url: str, proxies: dict[str, str] | None = None\n    ) -> HTTPConnectionPool:\n        \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n        for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n        Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.HTTPConnectionPool\n        \"\"\"\n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        proxy = select_proxy(url, proxies)\n\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_url(url)\n        else:\n            # Only scheme should be lower case\n            parsed = urlparse(url)\n            url = parsed.geturl()\n            conn = self.poolmanager.connection_from_url(url)\n\n        return conn\n\n    def close(self) -> None:\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        for proxy in self.proxy_manager.values():\n            proxy.clear()\n\n    def request_url(\n        self, request: PreparedRequest, proxies: dict[str, str] | None\n    ) -> str:\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        scheme = urlparse(request.url).scheme\n\n        is_proxied_http_request = proxy and scheme != \"https\"\n        using_socks_proxy = False\n        if proxy:\n            proxy_scheme = urlparse(proxy).scheme.lower()\n            using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n        url = request.path_url\n\n        if is_proxied_http_request and not using_socks_proxy:\n            url = urldefragauth(request.url)\n\n        return url\n\n    def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None:\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        pass\n\n    def proxy_headers(self, proxy: str) -> dict[str, str]:\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        headers: dict[str, str] = {}\n        username, password = get_auth_from_url(proxy)\n\n        if username:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return headers\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n\n        assert _is_prepared(request)\n\n        try:\n            conn = self.get_connection_with_tls_context(\n                request, verify, proxies=proxies, cert=cert\n            )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n            stream=stream,\n            timeout=timeout,\n            verify=verify,\n            cert=cert,\n            proxies=proxies,\n        )\n\n        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n\n        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                resolved_timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            resolved_timeout = timeout\n        else:\n            resolved_timeout = TimeoutSauce(connect=timeout, read=timeout)\n\n        try:\n            resp = conn.urlopen(\n                method=request.method,\n                url=url,\n                body=request.body,  # type: ignore[arg-type]  # urllib3 stubs don't accept Iterable[bytes | str]\n                headers=request.headers,  # type: ignore[arg-type]  # urllib3#3072\n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=resolved_timeout,\n                chunked=chunked,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=request)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=request)\n\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=request)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=request)\n\n            if isinstance(e.reason, _SSLError):\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=request)\n\n            raise ConnectionError(e, request=request)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=request)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=request)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=request)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=request)\n            else:\n                raise\n\n        return self.build_response(request, resp)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-a0e3de19d1287dec", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "ed5ef2a390438d85e769cc03761b99a5ea64ebafb104b8c4427e4dc32ad2c83e", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 642, "local_path": "expressions/encode-integer-literals/I05__requests__HTTPAdapter__fbf56431.py", "order": 5, "original_content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "parent_variant_id": "pyint-d7199f8ad572-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L158-L748", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 3}, "unit_kind": "class", "unit_name": "HTTPAdapter", "variant_id": "pyint-8e8afbf56431-I05", "group_id": "py-a0e3de19d1287dec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 734, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c9ccd683a6e4-I06", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__: list[str] = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    max_retries: Retry\n    config: dict[str, Any]\n    proxy_manager: dict[str, Any]\n    _pool_connections: int\n    _pool_maxsize: int\n    _pool_block: bool\n    poolmanager: _PoolManager\n\n    def __init__(\n        self,\n        pool_connections: int = DEFAULT_POOLSIZE,\n        pool_maxsize: int = DEFAULT_POOLSIZE,\n        max_retries: int | Retry = DEFAULT_RETRIES,\n        pool_block: bool = DEFAULT_POOLBLOCK,\n    ) -> None:\n        if not (max_retries == DEFAULT_RETRIES):\n            self.max_retries = Retry.from_int(max_retries)\n        else:\n            self.max_retries = Retry(0, read=False)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = pool_connections\n        self._pool_maxsize = pool_maxsize\n        self._pool_block = pool_block\n\n        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n\n    def __getstate__(self) -> dict[str, Any]:\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        self.proxy_manager = {}\n        self.config = {}\n\n        for attr, value in state.items():\n            setattr(self, attr, value)\n\n        self.init_poolmanager(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def init_poolmanager(\n        self,\n        connections: int,\n        maxsize: int,\n        block: bool = DEFAULT_POOLBLOCK,\n        **pool_kwargs: Any,\n    ) -> None:\n        \"\"\"Initializes a urllib3 PoolManager.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        # save these values for pickling\n        self._pool_connections = connections\n        self._pool_maxsize = maxsize\n        self._pool_block = block\n\n        self.poolmanager = PoolManager(\n            num_pools=connections,\n            maxsize=maxsize,\n            block=block,\n            **pool_kwargs,\n        )\n\n    def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any:\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if proxy in self.proxy_manager:\n            manager = self.proxy_manager[proxy]\n        elif proxy.lower().startswith(\"socks\"):\n            username, password = get_auth_from_url(proxy)\n            manager = self.proxy_manager[proxy] = SOCKSProxyManager(\n                proxy,\n                username=username,\n                password=password,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n        else:\n            proxy_headers = self.proxy_headers(proxy)\n            manager = self.proxy_manager[proxy] = proxy_from_url(\n                proxy,\n                proxy_headers=proxy_headers,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n\n        return manager\n\n    def cert_verify(\n        self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType\n    ) -> None:\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if not (url.lower().startswith(\"https\") and verify):\n            conn.cert_reqs = \"CERT_NONE\"\n            conn.ca_certs = None\n            conn.ca_cert_dir = None\n        else:\n            cert_loc = None\n\n            # Allow self-specified cert location.\n            if verify is not True:\n                cert_loc = verify\n\n            if not cert_loc:\n                cert_loc = DEFAULT_CA_BUNDLE_PATH\n\n            if not cert_loc or not os.path.exists(cert_loc):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {cert_loc}\"\n                )\n\n            conn.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(cert_loc):\n                conn.ca_certs = cert_loc\n            else:\n                conn.ca_cert_dir = cert_loc\n\n        if not (cert):\n            pass\n        else:\n            if not isinstance(cert, basestring):\n                conn.cert_file = cert[0]\n                conn.key_file = cert[1]\n            else:\n                conn.cert_file = cert\n                conn.key_file = None\n            if conn.cert_file and not os.path.exists(conn.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {conn.cert_file}\"\n                )\n            if conn.key_file and not os.path.exists(conn.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {conn.key_file}\"\n                )\n\n    def build_response(self, req: PreparedRequest, resp: Any) -> Response:\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        assert _is_prepared(req)\n        response = Response()\n\n        # Fallback to None if there's no status_code, for whatever reason.\n        response.status_code = getattr(resp, \"status\", None)  # type: ignore[assignment]\n\n        # Make headers case-insensitive.\n        response.headers = CaseInsensitiveDict(getattr(resp, \"headers\", {}))\n\n        # Set encoding.\n        response.encoding = get_encoding_from_headers(response.headers)\n        response.raw = resp\n        response.reason = response.raw.reason\n\n        if not (isinstance(req.url, bytes)):\n            response.url = req.url\n        else:\n            response.url = req.url.decode(\"utf-8\")\n\n        # Add new cookies from the server.\n        extract_cookies_to_jar(response.cookies, req, resp)\n\n        # Give the Response some context.\n        response.request = req\n        response.connection = self\n\n        return response\n\n    def build_connection_pool_key_attributes(\n        self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None\n    ) -> tuple[dict[str, Any], dict[str, Any]]:\n        \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n\n        This looks at the PreparedRequest, the user-specified verify value,\n        and the value of the cert parameter to determine what PoolKey values\n        to use to select a connection from a given urllib3 Connection Pool.\n\n        The SSL related pool key arguments are not consistently set. As of\n        this writing, use the following to determine what keys may be in that\n        dictionary:\n\n        * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n          default Requests SSL Context\n        * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n          ``\"cert_reqs\"`` will be set\n        * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n          ``\"ca_certs\"`` will be set if the string is not a directory recognized\n          by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n          set.\n        * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n          ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n          be present\n\n        To override these settings, one may subclass this class, call this\n        method and use the above logic to change parameters as desired. For\n        example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n        must both set ``\"ssl_context\"`` and based on what else they require,\n        alter the other keys to ensure the desired behaviour.\n\n        :param request:\n            The PreparedRequest being sent over the connection.\n        :type request:\n            :class:`~requests.models.PreparedRequest`\n        :param verify:\n            Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use.\n        :param cert:\n            (optional) Any user-provided SSL certificate for client\n            authentication (a.k.a., mTLS). This may be a string (i.e., just\n            the path to a file which holds both certificate and key) or a\n            tuple of length 2 with the certificate file path and key file\n            path.\n        :returns:\n            A tuple of two dictionaries. The first is the \"host parameters\"\n            portion of the Pool Key including scheme, hostname, and port. The\n            second is a dictionary of SSLContext related parameters.\n        \"\"\"\n        return _urllib3_request_context(request, verify, cert, self.poolmanager)\n\n    def get_connection_with_tls_context(\n        self,\n        request: PreparedRequest,\n        verify: _t.VerifyType,\n        proxies: dict[str, str] | None = None,\n        cert: _t.CertType = None,\n    ) -> HTTPConnectionPool:\n        \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request:\n            The :class:`PreparedRequest <PreparedRequest>` object to be sent\n            over the connection.\n        :param verify:\n            Either a boolean, in which case it controls whether we verify the\n            server's TLS certificate, or a string, in which case it must be a\n            path to a CA bundle to use.\n        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.HTTPConnectionPool\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        try:\n            host_params, pool_kwargs = self.build_connection_pool_key_attributes(\n                request,\n                verify,\n                cert,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=request)\n        if not (proxy):\n            # Only scheme should be lower case\n            conn = self.poolmanager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n        else:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n\n        return conn\n\n    def get_connection(\n        self, url: str, proxies: dict[str, str] | None = None\n    ) -> HTTPConnectionPool:\n        \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n        for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n        Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.HTTPConnectionPool\n        \"\"\"\n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        proxy = select_proxy(url, proxies)\n\n        if not (proxy):\n            # Only scheme should be lower case\n            parsed = urlparse(url)\n            url = parsed.geturl()\n            conn = self.poolmanager.connection_from_url(url)\n        else:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_url(url)\n\n        return conn\n\n    def close(self) -> None:\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        for proxy in self.proxy_manager.values():\n            proxy.clear()\n\n    def request_url(\n        self, request: PreparedRequest, proxies: dict[str, str] | None\n    ) -> str:\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        scheme = urlparse(request.url).scheme\n\n        is_proxied_http_request = proxy and scheme != \"https\"\n        using_socks_proxy = False\n        if not (proxy):\n            pass\n        else:\n            proxy_scheme = urlparse(proxy).scheme.lower()\n            using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n        url = request.path_url\n\n        if not (is_proxied_http_request and not using_socks_proxy):\n            pass\n        else:\n            url = urldefragauth(request.url)\n\n        return url\n\n    def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None:\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        pass\n\n    def proxy_headers(self, proxy: str) -> dict[str, str]:\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        headers: dict[str, str] = {}\n        username, password = get_auth_from_url(proxy)\n\n        if not (username):\n            pass\n        else:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return headers\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n\n        assert _is_prepared(request)\n\n        try:\n            conn = self.get_connection_with_tls_context(\n                request, verify, proxies=proxies, cert=cert\n            )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n            stream=stream,\n            timeout=timeout,\n            verify=verify,\n            cert=cert,\n            proxies=proxies,\n        )\n\n        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n\n        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                resolved_timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            resolved_timeout = timeout\n        else:\n            resolved_timeout = TimeoutSauce(connect=timeout, read=timeout)\n\n        try:\n            resp = conn.urlopen(\n                method=request.method,\n                url=url,\n                body=request.body,  # type: ignore[arg-type]  # urllib3 stubs don't accept Iterable[bytes | str]\n                headers=request.headers,  # type: ignore[arg-type]  # urllib3#3072\n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=resolved_timeout,\n                chunked=chunked,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=request)\n\n        except MaxRetryError as e:\n            if not (isinstance(e.reason, ConnectTimeoutError)):\n                pass\n            else:\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=request)\n\n            if not (isinstance(e.reason, ResponseError)):\n                pass\n            else:\n                raise RetryError(e, request=request)\n\n            if not (isinstance(e.reason, _ProxyError)):\n                pass\n            else:\n                raise ProxyError(e, request=request)\n\n            if not (isinstance(e.reason, _SSLError)):\n                pass\n            else:\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=request)\n\n            raise ConnectionError(e, request=request)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=request)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=request)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=request)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=request)\n            else:\n                raise\n\n        return self.build_response(request, resp)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-a0e3de19d1287dec", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "8f98c59843bbba8fb150f8b80a293b10a253d5e5ee5bf084a531cf9d9b96bd1a", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 658, "local_path": "expressions/invert-conditions/I06__requests__HTTPAdapter__d683a6e4.py", "order": 6, "original_content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "parent_variant_id": "pyint-d7199f8ad572-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L158-L748", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 13}, "unit_kind": "class", "unit_name": "HTTPAdapter", "variant_id": "pyint-c9ccd683a6e4-I06", "group_id": "py-a0e3de19d1287dec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 735, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-21e65f3bb035-I07", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__: list[str] = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    max_retries: Retry\n    config: dict[str, Any]\n    proxy_manager: dict[str, Any]\n    _pool_connections: int\n    _pool_maxsize: int\n    _pool_block: bool\n    poolmanager: _PoolManager\n\n    def __init__(\n        self,\n        pool_connections: int = DEFAULT_POOLSIZE,\n        pool_maxsize: int = DEFAULT_POOLSIZE,\n        max_retries: int | Retry = DEFAULT_RETRIES,\n        pool_block: bool = DEFAULT_POOLBLOCK,\n    ) -> None:\n        if ((0xdd31 ^ 0xdd31) != 0):\n            raise AssertionError()\n        if max_retries == DEFAULT_RETRIES:\n            self.max_retries = Retry(0, read=False)\n        else:\n            self.max_retries = Retry.from_int(max_retries)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = pool_connections\n        self._pool_maxsize = pool_maxsize\n        self._pool_block = pool_block\n\n        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n\n    def __getstate__(self) -> dict[str, Any]:\n        if ((0x8f8b ^ 0x8f8b) != 0):\n            raise AssertionError()\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        if ((0xd743 ^ 0xd743) != 0):\n            raise AssertionError()\n        self.proxy_manager = {}\n        self.config = {}\n\n        for attr, value in state.items():\n            setattr(self, attr, value)\n\n        self.init_poolmanager(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def init_poolmanager(\n        self,\n        connections: int,\n        maxsize: int,\n        block: bool = DEFAULT_POOLBLOCK,\n        **pool_kwargs: Any,\n    ) -> None:\n        \"\"\"Initializes a urllib3 PoolManager.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        if ((0x8a30 ^ 0x8a30) != 0):\n            raise AssertionError()\n        # save these values for pickling\n        self._pool_connections = connections\n        self._pool_maxsize = maxsize\n        self._pool_block = block\n\n        self.poolmanager = PoolManager(\n            num_pools=connections,\n            maxsize=maxsize,\n            block=block,\n            **pool_kwargs,\n        )\n\n    def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any:\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if ((0x42d1 ^ 0x42d1) != 0):\n            raise AssertionError()\n        if proxy in self.proxy_manager:\n            manager = self.proxy_manager[proxy]\n        elif proxy.lower().startswith(\"socks\"):\n            username, password = get_auth_from_url(proxy)\n            manager = self.proxy_manager[proxy] = SOCKSProxyManager(\n                proxy,\n                username=username,\n                password=password,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n        else:\n            proxy_headers = self.proxy_headers(proxy)\n            manager = self.proxy_manager[proxy] = proxy_from_url(\n                proxy,\n                proxy_headers=proxy_headers,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n\n        return manager\n\n    def cert_verify(\n        self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType\n    ) -> None:\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if ((0x6d36 ^ 0x6d36) != 0):\n            raise AssertionError()\n        if url.lower().startswith(\"https\") and verify:\n            cert_loc = None\n\n            # Allow self-specified cert location.\n            if verify is not True:\n                cert_loc = verify\n\n            if not cert_loc:\n                cert_loc = DEFAULT_CA_BUNDLE_PATH\n\n            if not cert_loc or not os.path.exists(cert_loc):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {cert_loc}\"\n                )\n\n            conn.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(cert_loc):\n                conn.ca_certs = cert_loc\n            else:\n                conn.ca_cert_dir = cert_loc\n        else:\n            conn.cert_reqs = \"CERT_NONE\"\n            conn.ca_certs = None\n            conn.ca_cert_dir = None\n\n        if cert:\n            if not isinstance(cert, basestring):\n                conn.cert_file = cert[0]\n                conn.key_file = cert[1]\n            else:\n                conn.cert_file = cert\n                conn.key_file = None\n            if conn.cert_file and not os.path.exists(conn.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {conn.cert_file}\"\n                )\n            if conn.key_file and not os.path.exists(conn.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {conn.key_file}\"\n                )\n\n    def build_response(self, req: PreparedRequest, resp: Any) -> Response:\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        if ((0x5ef1 ^ 0x5ef1) != 0):\n            raise AssertionError()\n        assert _is_prepared(req)\n        response = Response()\n\n        # Fallback to None if there's no status_code, for whatever reason.\n        response.status_code = getattr(resp, \"status\", None)  # type: ignore[assignment]\n\n        # Make headers case-insensitive.\n        response.headers = CaseInsensitiveDict(getattr(resp, \"headers\", {}))\n\n        # Set encoding.\n        response.encoding = get_encoding_from_headers(response.headers)\n        response.raw = resp\n        response.reason = response.raw.reason\n\n        if isinstance(req.url, bytes):\n            response.url = req.url.decode(\"utf-8\")\n        else:\n            response.url = req.url\n\n        # Add new cookies from the server.\n        extract_cookies_to_jar(response.cookies, req, resp)\n\n        # Give the Response some context.\n        response.request = req\n        response.connection = self\n\n        return response\n\n    def build_connection_pool_key_attributes(\n        self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None\n    ) -> tuple[dict[str, Any], dict[str, Any]]:\n        \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n\n        This looks at the PreparedRequest, the user-specified verify value,\n        and the value of the cert parameter to determine what PoolKey values\n        to use to select a connection from a given urllib3 Connection Pool.\n\n        The SSL related pool key arguments are not consistently set. As of\n        this writing, use the following to determine what keys may be in that\n        dictionary:\n\n        * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n          default Requests SSL Context\n        * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n          ``\"cert_reqs\"`` will be set\n        * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n          ``\"ca_certs\"`` will be set if the string is not a directory recognized\n          by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n          set.\n        * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n          ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n          be present\n\n        To override these settings, one may subclass this class, call this\n        method and use the above logic to change parameters as desired. For\n        example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n        must both set ``\"ssl_context\"`` and based on what else they require,\n        alter the other keys to ensure the desired behaviour.\n\n        :param request:\n            The PreparedRequest being sent over the connection.\n        :type request:\n            :class:`~requests.models.PreparedRequest`\n        :param verify:\n            Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use.\n        :param cert:\n            (optional) Any user-provided SSL certificate for client\n            authentication (a.k.a., mTLS). This may be a string (i.e., just\n            the path to a file which holds both certificate and key) or a\n            tuple of length 2 with the certificate file path and key file\n            path.\n        :returns:\n            A tuple of two dictionaries. The first is the \"host parameters\"\n            portion of the Pool Key including scheme, hostname, and port. The\n            second is a dictionary of SSLContext related parameters.\n        \"\"\"\n        if ((0x7405 ^ 0x7405) != 0):\n            raise AssertionError()\n        return _urllib3_request_context(request, verify, cert, self.poolmanager)\n\n    def get_connection_with_tls_context(\n        self,\n        request: PreparedRequest,\n        verify: _t.VerifyType,\n        proxies: dict[str, str] | None = None,\n        cert: _t.CertType = None,\n    ) -> HTTPConnectionPool:\n        \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request:\n            The :class:`PreparedRequest <PreparedRequest>` object to be sent\n            over the connection.\n        :param verify:\n            Either a boolean, in which case it controls whether we verify the\n            server's TLS certificate, or a string, in which case it must be a\n            path to a CA bundle to use.\n        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.HTTPConnectionPool\n        \"\"\"\n        if ((0x184e ^ 0x184e) != 0):\n            raise AssertionError()\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        try:\n            host_params, pool_kwargs = self.build_connection_pool_key_attributes(\n                request,\n                verify,\n                cert,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=request)\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n        else:\n            # Only scheme should be lower case\n            conn = self.poolmanager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n\n        return conn\n\n    def get_connection(\n        self, url: str, proxies: dict[str, str] | None = None\n    ) -> HTTPConnectionPool:\n        \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n        for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n        Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.HTTPConnectionPool\n        \"\"\"\n        if ((0xb5f3 ^ 0xb5f3) != 0):\n            raise AssertionError()\n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        proxy = select_proxy(url, proxies)\n\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_url(url)\n        else:\n            # Only scheme should be lower case\n            parsed = urlparse(url)\n            url = parsed.geturl()\n            conn = self.poolmanager.connection_from_url(url)\n\n        return conn\n\n    def close(self) -> None:\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        if ((0xcf80 ^ 0xcf80) != 0):\n            raise AssertionError()\n        self.poolmanager.clear()\n        for proxy in self.proxy_manager.values():\n            proxy.clear()\n\n    def request_url(\n        self, request: PreparedRequest, proxies: dict[str, str] | None\n    ) -> str:\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        if ((0x692b ^ 0x692b) != 0):\n            raise AssertionError()\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        scheme = urlparse(request.url).scheme\n\n        is_proxied_http_request = proxy and scheme != \"https\"\n        using_socks_proxy = False\n        if proxy:\n            proxy_scheme = urlparse(proxy).scheme.lower()\n            using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n        url = request.path_url\n\n        if is_proxied_http_request and not using_socks_proxy:\n            url = urldefragauth(request.url)\n\n        return url\n\n    def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None:\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        if ((0x298d ^ 0x298d) != 0):\n            raise AssertionError()\n        pass\n\n    def proxy_headers(self, proxy: str) -> dict[str, str]:\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        if ((0xc89 ^ 0xc89) != 0):\n            raise AssertionError()\n        headers: dict[str, str] = {}\n        username, password = get_auth_from_url(proxy)\n\n        if username:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return headers\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n        if ((0x6d10 ^ 0x6d10) != 0):\n            raise AssertionError()\n\n        assert _is_prepared(request)\n\n        try:\n            conn = self.get_connection_with_tls_context(\n                request, verify, proxies=proxies, cert=cert\n            )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n            stream=stream,\n            timeout=timeout,\n            verify=verify,\n            cert=cert,\n            proxies=proxies,\n        )\n\n        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n\n        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                resolved_timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            resolved_timeout = timeout\n        else:\n            resolved_timeout = TimeoutSauce(connect=timeout, read=timeout)\n\n        try:\n            resp = conn.urlopen(\n                method=request.method,\n                url=url,\n                body=request.body,  # type: ignore[arg-type]  # urllib3 stubs don't accept Iterable[bytes | str]\n                headers=request.headers,  # type: ignore[arg-type]  # urllib3#3072\n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=resolved_timeout,\n                chunked=chunked,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=request)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=request)\n\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=request)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=request)\n\n            if isinstance(e.reason, _SSLError):\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=request)\n\n            raise ConnectionError(e, request=request)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=request)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=request)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=request)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=request)\n            else:\n                raise\n\n        return self.build_response(request, resp)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-a0e3de19d1287dec", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "9bf7ef4bdba8e4a62d0b2a996032900ee08f1910a7c88b8f2cd7d8703a2affa4", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 672, "local_path": "code-injection/insert-dead-branches/I07__requests__HTTPAdapter__5f3bb035.py", "order": 7, "original_content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "parent_variant_id": "pyint-d7199f8ad572-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L158-L748", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 15}, "unit_kind": "class", "unit_name": "HTTPAdapter", "variant_id": "pyint-21e65f3bb035-I07", "group_id": "py-a0e3de19d1287dec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 736, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2baa735815e2-I08", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__: list[str] = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    max_retries: Retry\n    config: dict[str, Any]\n    proxy_manager: dict[str, Any]\n    _pool_connections: int\n    _pool_maxsize: int\n    _pool_block: bool\n    poolmanager: _PoolManager\n\n    def __init__(\n        self,\n        pool_connections: int = DEFAULT_POOLSIZE,\n        pool_maxsize: int = DEFAULT_POOLSIZE,\n        max_retries: int | Retry = DEFAULT_RETRIES,\n        pool_block: bool = DEFAULT_POOLBLOCK,\n    ) -> None:\n        if max_retries == DEFAULT_RETRIES:\n            self.max_retries = Retry(0, read=False)\n        else:\n            self.max_retries = Retry.from_int(max_retries)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = pool_connections\n        self._pool_maxsize = pool_maxsize\n        self._pool_block = pool_block\n\n        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n\n    def __getstate__(self) -> dict[str, Any]:\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        self.proxy_manager = {}\n        self.config = {}\n\n        for attr, value in state.items():\n            setattr(self, attr, value)\n\n        self.init_poolmanager(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def init_poolmanager(\n        self,\n        connections: int,\n        maxsize: int,\n        block: bool = DEFAULT_POOLBLOCK,\n        **pool_kwargs: Any,\n    ) -> None:\n        \"\"\"Initializes a urllib3 PoolManager.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        # save these values for pickling\n        self._pool_connections = connections\n        self._pool_maxsize = maxsize\n        self._pool_block = block\n\n        self.poolmanager = PoolManager(\n            num_pools=connections,\n            maxsize=maxsize,\n            block=block,\n            **pool_kwargs,\n        )\n\n    def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any:\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if proxy in self.proxy_manager:\n            manager = self.proxy_manager[proxy]\n        elif proxy.lower().startswith(\"socks\"):\n            username, password = get_auth_from_url(proxy)\n            manager = self.proxy_manager[proxy] = SOCKSProxyManager(\n                proxy,\n                username=username,\n                password=password,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n        else:\n            proxy_headers = self.proxy_headers(proxy)\n            manager = self.proxy_manager[proxy] = proxy_from_url(\n                proxy,\n                proxy_headers=proxy_headers,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n\n        return manager\n\n    def cert_verify(\n        self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType\n    ) -> None:\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if url.lower().startswith(\"https\") and verify:\n            cert_loc = None\n\n            # Allow self-specified cert location.\n            if verify is not True:\n                cert_loc = verify\n\n            if not cert_loc:\n                cert_loc = DEFAULT_CA_BUNDLE_PATH\n\n            if not cert_loc or not os.path.exists(cert_loc):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {cert_loc}\"\n                )\n\n            conn.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(cert_loc):\n                conn.ca_certs = cert_loc\n            else:\n                conn.ca_cert_dir = cert_loc\n        else:\n            conn.cert_reqs = \"CERT_NONE\"\n            conn.ca_certs = None\n            conn.ca_cert_dir = None\n\n        if cert:\n            if not isinstance(cert, basestring):\n                conn.cert_file = cert[0]\n                conn.key_file = cert[1]\n            else:\n                conn.cert_file = cert\n                conn.key_file = None\n            if conn.cert_file and not os.path.exists(conn.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {conn.cert_file}\"\n                )\n            if conn.key_file and not os.path.exists(conn.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {conn.key_file}\"\n                )\n\n    def build_response(self, req: PreparedRequest, resp: Any) -> Response:\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        assert _is_prepared(req)\n        response = Response()\n\n        # Fallback to None if there's no status_code, for whatever reason.\n        response.status_code = getattr(resp, \"status\", None)  # type: ignore[assignment]\n\n        # Make headers case-insensitive.\n        response.headers = CaseInsensitiveDict(getattr(resp, \"headers\", {}))\n\n        # Set encoding.\n        response.encoding = get_encoding_from_headers(response.headers)\n        response.raw = resp\n        response.reason = response.raw.reason\n\n        if isinstance(req.url, bytes):\n            response.url = req.url.decode(\"utf-8\")\n        else:\n            response.url = req.url\n\n        # Add new cookies from the server.\n        extract_cookies_to_jar(response.cookies, req, resp)\n\n        # Give the Response some context.\n        response.request = req\n        response.connection = self\n\n        return response\n\n    def build_connection_pool_key_attributes(\n        self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None\n    ) -> tuple[dict[str, Any], dict[str, Any]]:\n        \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n\n        This looks at the PreparedRequest, the user-specified verify value,\n        and the value of the cert parameter to determine what PoolKey values\n        to use to select a connection from a given urllib3 Connection Pool.\n\n        The SSL related pool key arguments are not consistently set. As of\n        this writing, use the following to determine what keys may be in that\n        dictionary:\n\n        * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n          default Requests SSL Context\n        * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n          ``\"cert_reqs\"`` will be set\n        * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n          ``\"ca_certs\"`` will be set if the string is not a directory recognized\n          by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n          set.\n        * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n          ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n          be present\n\n        To override these settings, one may subclass this class, call this\n        method and use the above logic to change parameters as desired. For\n        example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n        must both set ``\"ssl_context\"`` and based on what else they require,\n        alter the other keys to ensure the desired behaviour.\n\n        :param request:\n            The PreparedRequest being sent over the connection.\n        :type request:\n            :class:`~requests.models.PreparedRequest`\n        :param verify:\n            Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use.\n        :param cert:\n            (optional) Any user-provided SSL certificate for client\n            authentication (a.k.a., mTLS). This may be a string (i.e., just\n            the path to a file which holds both certificate and key) or a\n            tuple of length 2 with the certificate file path and key file\n            path.\n        :returns:\n            A tuple of two dictionaries. The first is the \"host parameters\"\n            portion of the Pool Key including scheme, hostname, and port. The\n            second is a dictionary of SSLContext related parameters.\n        \"\"\"\n        return _urllib3_request_context(request, verify, cert, self.poolmanager)\n\n    def get_connection_with_tls_context(\n        self,\n        request: PreparedRequest,\n        verify: _t.VerifyType,\n        proxies: dict[str, str] | None = None,\n        cert: _t.CertType = None,\n    ) -> HTTPConnectionPool:\n        \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request:\n            The :class:`PreparedRequest <PreparedRequest>` object to be sent\n            over the connection.\n        :param verify:\n            Either a boolean, in which case it controls whether we verify the\n            server's TLS certificate, or a string, in which case it must be a\n            path to a CA bundle to use.\n        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.HTTPConnectionPool\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        try:\n            host_params, pool_kwargs = self.build_connection_pool_key_attributes(\n                request,\n                verify,\n                cert,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=request)\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n        else:\n            # Only scheme should be lower case\n            conn = self.poolmanager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n\n        return conn\n\n    def get_connection(\n        self, url: str, proxies: dict[str, str] | None = None\n    ) -> HTTPConnectionPool:\n        \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n        for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n        Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.HTTPConnectionPool\n        \"\"\"\n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        proxy = select_proxy(url, proxies)\n\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_url(url)\n        else:\n            # Only scheme should be lower case\n            parsed = urlparse(url)\n            url = parsed.geturl()\n            conn = self.poolmanager.connection_from_url(url)\n\n        return conn\n\n    def close(self) -> None:\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        for proxy in self.proxy_manager.values():\n            proxy.clear()\n\n    def request_url(\n        self, request: PreparedRequest, proxies: dict[str, str] | None\n    ) -> str:\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        scheme = urlparse(request.url).scheme\n\n        is_proxied_http_request = proxy and scheme != \"https\"\n        using_socks_proxy = False\n        if proxy:\n            proxy_scheme = urlparse(proxy).scheme.lower()\n            using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n        url = request.path_url\n\n        if is_proxied_http_request and not using_socks_proxy:\n            url = urldefragauth(request.url)\n\n        return url\n\n    def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None:\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        pass\n\n    def proxy_headers(self, proxy: str) -> dict[str, str]:\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        headers: dict[str, str] = {}\n        username, password = get_auth_from_url(proxy)\n\n        if username:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return headers\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n\n        assert _is_prepared(request)\n\n        try:\n            conn = self.get_connection_with_tls_context(\n                request, verify, proxies=proxies, cert=cert\n            )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n            stream=stream,\n            timeout=timeout,\n            verify=verify,\n            cert=cert,\n            proxies=proxies,\n        )\n\n        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n\n        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                resolved_timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            resolved_timeout = timeout\n        else:\n            resolved_timeout = TimeoutSauce(connect=timeout, read=timeout)\n\n        try:\n            resp = conn.urlopen(\n                method=request.method,\n                url=url,\n                body=request.body,  # type: ignore[arg-type]  # urllib3 stubs don't accept Iterable[bytes | str]\n                headers=request.headers,  # type: ignore[arg-type]  # urllib3#3072\n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=resolved_timeout,\n                chunked=chunked,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=request)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=request)\n\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=request)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=request)\n\n            if isinstance(e.reason, _SSLError):\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=request)\n\n            raise ConnectionError(e, request=request)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=request)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=request)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=request)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=request)\n            else:\n                raise\n\n        return self.build_response(request, resp)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-a0e3de19d1287dec", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "1407758f7a8d5113d9aba6782d6d58a54e65e76916bd4fba2d39ed8ea9e249a7", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 647, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__HTTPAdapter__735815e2.py", "order": 8, "original_content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "parent_variant_id": "pyint-d7199f8ad572-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L158-L748", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "HTTPAdapter", "variant_id": "pyint-2baa735815e2-I08", "group_id": "py-a0e3de19d1287dec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 737, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8717729f8522-I09", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__: list[str] = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    max_retries: Retry\n    config: dict[str, Any]\n    proxy_manager: dict[str, Any]\n    _pool_connections: int\n    _pool_maxsize: int\n    _pool_block: bool\n    poolmanager: _PoolManager\n\n    def __init__(\n        self,\n        pool_connections: int = DEFAULT_POOLSIZE,\n        pool_maxsize: int = DEFAULT_POOLSIZE,\n        max_retries: int | Retry = DEFAULT_RETRIES,\n        pool_block: bool = DEFAULT_POOLBLOCK,\n    ) -> None:\n        if max_retries == DEFAULT_RETRIES:\n            self.max_retries = Retry(0, read=False)\n        else:\n            self.max_retries = Retry.from_int(max_retries)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = pool_connections\n        self._pool_maxsize = pool_maxsize\n        self._pool_block = pool_block\n\n        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n\n    def __getstate__(self) -> dict[str, Any]:\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        self.proxy_manager = {}\n        self.config = {}\n\n        for attr, value in state.items():\n            setattr(self, attr, value)\n\n        self.init_poolmanager(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def init_poolmanager(\n        self,\n        connections: int,\n        maxsize: int,\n        block: bool = DEFAULT_POOLBLOCK,\n        **pool_kwargs: Any,\n    ) -> None:\n        \"\"\"Initializes a urllib3 PoolManager.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        # save these values for pickling\n        self._pool_connections = connections\n        self._pool_maxsize = maxsize\n        self._pool_block = block\n\n        self.poolmanager = PoolManager(\n            num_pools=connections,\n            maxsize=maxsize,\n            block=block,\n            **pool_kwargs,\n        )\n\n    def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any:\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if proxy in self.proxy_manager:\n            manager = self.proxy_manager[proxy]\n        elif proxy.lower().startswith(\"socks\"):\n            username, password = get_auth_from_url(proxy)\n            manager = self.proxy_manager[proxy] = SOCKSProxyManager(\n                proxy,\n                username=username,\n                password=password,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n        else:\n            proxy_headers = self.proxy_headers(proxy)\n            manager = self.proxy_manager[proxy] = proxy_from_url(\n                proxy,\n                proxy_headers=proxy_headers,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n\n        return manager\n\n    def cert_verify(\n        self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType\n    ) -> None:\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if url.lower().startswith(\"https\") and verify:\n            cert_loc = None\n\n            # Allow self-specified cert location.\n            if verify is not True:\n                cert_loc = verify\n\n            if not cert_loc:\n                cert_loc = DEFAULT_CA_BUNDLE_PATH\n\n            if not cert_loc or not os.path.exists(cert_loc):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {cert_loc}\"\n                )\n\n            conn.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(cert_loc):\n                conn.ca_certs = cert_loc\n            else:\n                conn.ca_cert_dir = cert_loc\n        else:\n            conn.cert_reqs = \"CERT_NONE\"\n            conn.ca_certs = None\n            conn.ca_cert_dir = None\n\n        if cert:\n            if not isinstance(cert, basestring):\n                conn.cert_file = cert[0]\n                conn.key_file = cert[1]\n            else:\n                conn.cert_file = cert\n                conn.key_file = None\n            if conn.cert_file and not os.path.exists(conn.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {conn.cert_file}\"\n                )\n            if conn.key_file and not os.path.exists(conn.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {conn.key_file}\"\n                )\n\n    def build_response(self, req: PreparedRequest, resp: Any) -> Response:\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        assert _is_prepared(req)\n        response = Response()\n\n        # Fallback to None if there's no status_code, for whatever reason.\n        response.status_code = getattr(resp, \"status\", None)  # type: ignore[assignment]\n\n        # Make headers case-insensitive.\n        response.headers = CaseInsensitiveDict(getattr(resp, \"headers\", {}))\n\n        # Set encoding.\n        response.encoding = get_encoding_from_headers(response.headers)\n        response.raw = resp\n        response.reason = response.raw.reason\n\n        if isinstance(req.url, bytes):\n            response.url = req.url.decode(\"utf-8\")\n        else:\n            response.url = req.url\n\n        # Add new cookies from the server.\n        extract_cookies_to_jar(response.cookies, req, resp)\n\n        # Give the Response some context.\n        response.request = req\n        response.connection = self\n\n        return response\n\n    def build_connection_pool_key_attributes(\n        self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None\n    ) -> tuple[dict[str, Any], dict[str, Any]]:\n        \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n\n        This looks at the PreparedRequest, the user-specified verify value,\n        and the value of the cert parameter to determine what PoolKey values\n        to use to select a connection from a given urllib3 Connection Pool.\n\n        The SSL related pool key arguments are not consistently set. As of\n        this writing, use the following to determine what keys may be in that\n        dictionary:\n\n        * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n          default Requests SSL Context\n        * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n          ``\"cert_reqs\"`` will be set\n        * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n          ``\"ca_certs\"`` will be set if the string is not a directory recognized\n          by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n          set.\n        * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n          ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n          be present\n\n        To override these settings, one may subclass this class, call this\n        method and use the above logic to change parameters as desired. For\n        example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n        must both set ``\"ssl_context\"`` and based on what else they require,\n        alter the other keys to ensure the desired behaviour.\n\n        :param request:\n            The PreparedRequest being sent over the connection.\n        :type request:\n            :class:`~requests.models.PreparedRequest`\n        :param verify:\n            Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use.\n        :param cert:\n            (optional) Any user-provided SSL certificate for client\n            authentication (a.k.a., mTLS). This may be a string (i.e., just\n            the path to a file which holds both certificate and key) or a\n            tuple of length 2 with the certificate file path and key file\n            path.\n        :returns:\n            A tuple of two dictionaries. The first is the \"host parameters\"\n            portion of the Pool Key including scheme, hostname, and port. The\n            second is a dictionary of SSLContext related parameters.\n        \"\"\"\n        return _urllib3_request_context(request, verify, cert, self.poolmanager)\n\n    def get_connection_with_tls_context(\n        self,\n        request: PreparedRequest,\n        verify: _t.VerifyType,\n        proxies: dict[str, str] | None = None,\n        cert: _t.CertType = None,\n    ) -> HTTPConnectionPool:\n        \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request:\n            The :class:`PreparedRequest <PreparedRequest>` object to be sent\n            over the connection.\n        :param verify:\n            Either a boolean, in which case it controls whether we verify the\n            server's TLS certificate, or a string, in which case it must be a\n            path to a CA bundle to use.\n        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.HTTPConnectionPool\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        try:\n            host_params, pool_kwargs = self.build_connection_pool_key_attributes(\n                request,\n                verify,\n                cert,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=request)\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n        else:\n            # Only scheme should be lower case\n            conn = self.poolmanager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n\n        return conn\n\n    def get_connection(\n        self, url: str, proxies: dict[str, str] | None = None\n    ) -> HTTPConnectionPool:\n        \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n        for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n        Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.HTTPConnectionPool\n        \"\"\"\n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        proxy = select_proxy(url, proxies)\n\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_url(url)\n        else:\n            # Only scheme should be lower case\n            parsed = urlparse(url)\n            url = parsed.geturl()\n            conn = self.poolmanager.connection_from_url(url)\n\n        return conn\n\n    def close(self) -> None:\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        for proxy in self.proxy_manager.values():\n            proxy.clear()\n\n    def request_url(\n        self, request: PreparedRequest, proxies: dict[str, str] | None\n    ) -> str:\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        scheme = urlparse(request.url).scheme\n\n        is_proxied_http_request = proxy and scheme != \"https\"\n        using_socks_proxy = False\n        if proxy:\n            proxy_scheme = urlparse(proxy).scheme.lower()\n            using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n        url = request.path_url\n\n        if is_proxied_http_request and not using_socks_proxy:\n            url = urldefragauth(request.url)\n\n        return url\n\n    def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None:\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        pass\n\n    def proxy_headers(self, proxy: str) -> dict[str, str]:\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        lI0O_05344678, lI0O_a849f27d = 0x4006, True\n        while lI0O_a849f27d:\n            lI0O_05344678 ^= 0x4006\n            lI0O_a849f27d = False\n        headers: dict[str, str] = {}\n        username, password = get_auth_from_url(proxy)\n\n        if username:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return headers\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n\n        assert _is_prepared(request)\n\n        try:\n            conn = self.get_connection_with_tls_context(\n                request, verify, proxies=proxies, cert=cert\n            )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n            stream=stream,\n            timeout=timeout,\n            verify=verify,\n            cert=cert,\n            proxies=proxies,\n        )\n\n        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n\n        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                resolved_timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            resolved_timeout = timeout\n        else:\n            resolved_timeout = TimeoutSauce(connect=timeout, read=timeout)\n\n        try:\n            resp = conn.urlopen(\n                method=request.method,\n                url=url,\n                body=request.body,  # type: ignore[arg-type]  # urllib3 stubs don't accept Iterable[bytes | str]\n                headers=request.headers,  # type: ignore[arg-type]  # urllib3#3072\n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=resolved_timeout,\n                chunked=chunked,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=request)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=request)\n\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=request)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=request)\n\n            if isinstance(e.reason, _SSLError):\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=request)\n\n            raise ConnectionError(e, request=request)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=request)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=request)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=request)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=request)\n            else:\n                raise\n\n        return self.build_response(request, resp)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-a0e3de19d1287dec", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "5a79a51913bb6a6258742167af34bb920068cdf698b5e330ede63a064cea7802", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 646, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__HTTPAdapter__729f8522.py", "order": 9, "original_content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "parent_variant_id": "pyint-d7199f8ad572-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L158-L748", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 7}, "unit_kind": "class", "unit_name": "HTTPAdapter", "variant_id": "pyint-8717729f8522-I09", "group_id": "py-a0e3de19d1287dec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 738, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ecc6d40e514b-I10", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (     ClosedPoolError,\n    ConnectTimeoutError,     LocationValueError,     MaxRetryError,\n    NewConnectionError,     ProtocolError,     ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,     InvalidSchema,     InvalidURL,     ProxyError,\n    ReadTimeout,     RetryError,     SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,     get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__: list[str] = [\n        \"max_retries\",         \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",     ]\n\n    max_retries: Retry\n    config: dict[str, Any]\n    proxy_manager: dict[str, Any]\n    _pool_connections: int\n    _pool_maxsize: int\n    _pool_block: bool\n    poolmanager: _PoolManager\n\n    def __init__(\n        self,\n        pool_connections: int = DEFAULT_POOLSIZE,\n        pool_maxsize: int = DEFAULT_POOLSIZE,\n        max_retries: int | Retry = DEFAULT_RETRIES,\n        pool_block: bool = DEFAULT_POOLBLOCK,     ) -> None:\n        if max_retries == DEFAULT_RETRIES:\n            self.max_retries = Retry(0, read=False)\n        else:\n            self.max_retries = Retry.from_int(max_retries)\n        self.config = {}\n        self.proxy_manager = {}\n        super().__init__()\n        self._pool_connections = pool_connections\n        self._pool_maxsize = pool_maxsize\n        self._pool_block = pool_block\n\n        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n\n    def __getstate__(self) -> dict[str, Any]:\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        self.proxy_manager = {}\n        self.config = {}\n        for attr, value in state.items():\n            setattr(self, attr, value)\n        self.init_poolmanager(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block         )\n\n    def init_poolmanager(\n        self,\n        connections: int,\n        maxsize: int,         block: bool = DEFAULT_POOLBLOCK,         **pool_kwargs: Any,     ) -> None:\n        \"\"\"Initializes a urllib3 PoolManager.\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        # save these values for pickling\n        self._pool_connections = connections\n        self._pool_maxsize = maxsize\n        self._pool_block = block\n\n        self.poolmanager = PoolManager(\n            num_pools=connections,             maxsize=maxsize,             block=block,             **pool_kwargs,         )\n\n    def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any:\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if proxy in self.proxy_manager:\n            manager = self.proxy_manager[proxy]\n        elif proxy.lower().startswith(\"socks\"):\n            username, password = get_auth_from_url(proxy)\n            manager = self.proxy_manager[proxy] = SOCKSProxyManager(\n                proxy,                 username=username,\n                password=password,\n                num_pools=self._pool_connections,                 maxsize=self._pool_maxsize,                 block=self._pool_block,                 **proxy_kwargs,\n            )\n        else:\n            proxy_headers = self.proxy_headers(proxy)\n            manager = self.proxy_manager[proxy] = proxy_from_url(\n                proxy,                 proxy_headers=proxy_headers,\n                num_pools=self._pool_connections,                 maxsize=self._pool_maxsize,\n                block=self._pool_block,                 **proxy_kwargs,\n            )\n\n        return manager\n\n    def cert_verify(         self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType\n    ) -> None:\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if url.lower().startswith(\"https\") and verify:\n            cert_loc = None\n\n            # Allow self-specified cert location.\n            if verify is not True:\n                cert_loc = verify\n            if not cert_loc:\n                cert_loc = DEFAULT_CA_BUNDLE_PATH\n            if not cert_loc or not os.path.exists(cert_loc):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"                     f\"invalid path: {cert_loc}\"\n                )\n            conn.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(cert_loc):\n                conn.ca_certs = cert_loc\n            else:\n                conn.ca_cert_dir = cert_loc\n        else:\n            conn.cert_reqs = \"CERT_NONE\"\n            conn.ca_certs = None\n            conn.ca_cert_dir = None\n\n        if cert:\n            if not isinstance(cert, basestring):\n                conn.cert_file = cert[0]\n                conn.key_file = cert[1]\n            else:\n                conn.cert_file = cert\n                conn.key_file = None\n            if conn.cert_file and not os.path.exists(conn.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {conn.cert_file}\"                 )\n            if conn.key_file and not os.path.exists(conn.key_file):\n                raise OSError(                     f\"Could not find the TLS key file, invalid path: {conn.key_file}\"                 )\n\n    def build_response(self, req: PreparedRequest, resp: Any) -> Response:\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        assert _is_prepared(req)\n        response = Response()\n        # Fallback to None if there's no status_code, for whatever reason.\n        response.status_code = getattr(resp, \"status\", None)  # type: ignore[assignment]\n        # Make headers case-insensitive.\n        response.headers = CaseInsensitiveDict(getattr(resp, \"headers\", {}))\n        # Set encoding.\n        response.encoding = get_encoding_from_headers(response.headers)\n        response.raw = resp\n        response.reason = response.raw.reason\n        if isinstance(req.url, bytes):\n            response.url = req.url.decode(\"utf-8\")\n        else:\n            response.url = req.url\n        # Add new cookies from the server.\n        extract_cookies_to_jar(response.cookies, req, resp)\n\n        # Give the Response some context.\n        response.request = req\n        response.connection = self\n        return response\n\n    def build_connection_pool_key_attributes(\n        self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None\n    ) -> tuple[dict[str, Any], dict[str, Any]]:\n        \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n        This looks at the PreparedRequest, the user-specified verify value,\n        and the value of the cert parameter to determine what PoolKey values\n        to use to select a connection from a given urllib3 Connection Pool.\n\n        The SSL related pool key arguments are not consistently set. As of\n        this writing, use the following to determine what keys may be in that\n        dictionary:\n\n        * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n          default Requests SSL Context\n        * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n          ``\"cert_reqs\"`` will be set\n        * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n          ``\"ca_certs\"`` will be set if the string is not a directory recognized\n          by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n          set.\n        * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n          ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n          be present\n\n        To override these settings, one may subclass this class, call this\n        method and use the above logic to change parameters as desired. For\n        example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n        must both set ``\"ssl_context\"`` and based on what else they require,\n        alter the other keys to ensure the desired behaviour.\n        :param request:\n            The PreparedRequest being sent over the connection.\n        :type request:\n            :class:`~requests.models.PreparedRequest`\n        :param verify:\n            Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use.\n        :param cert:\n            (optional) Any user-provided SSL certificate for client\n            authentication (a.k.a., mTLS). This may be a string (i.e., just\n            the path to a file which holds both certificate and key) or a\n            tuple of length 2 with the certificate file path and key file\n            path.\n        :returns:\n            A tuple of two dictionaries. The first is the \"host parameters\"\n            portion of the Pool Key including scheme, hostname, and port. The\n            second is a dictionary of SSLContext related parameters.\n        \"\"\"\n        return _urllib3_request_context(request, verify, cert, self.poolmanager)\n\n    def get_connection_with_tls_context(\n        self,         request: PreparedRequest,\n        verify: _t.VerifyType,\n        proxies: dict[str, str] | None = None,\n        cert: _t.CertType = None,\n    ) -> HTTPConnectionPool:\n        \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n        :param request:\n            The :class:`PreparedRequest <PreparedRequest>` object to be sent\n            over the connection.\n        :param verify:\n            Either a boolean, in which case it controls whether we verify the\n            server's TLS certificate, or a string, in which case it must be a\n            path to a CA bundle to use.\n        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.HTTPConnectionPool\n        \"\"\"\n        assert _is_prepared(request)\n        proxy = select_proxy(request.url, proxies)\n        try:\n            host_params, pool_kwargs = self.build_connection_pool_key_attributes(\n                request,\n                verify,                 cert,             )\n        except ValueError as e:\n            raise InvalidURL(e, request=request)\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(                     \"Please check proxy URL. It is malformed \"                     \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_host(                 **host_params, pool_kwargs=pool_kwargs\n            )\n        else:\n            # Only scheme should be lower case\n            conn = self.poolmanager.connection_from_host(                 **host_params, pool_kwargs=pool_kwargs             )\n        return conn\n    def get_connection(\n        self, url: str, proxies: dict[str, str] | None = None\n    ) -> HTTPConnectionPool:\n        \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n        for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n        Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.HTTPConnectionPool\n        \"\"\"\n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        proxy = select_proxy(url, proxies)\n\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_url(url)\n        else:\n            # Only scheme should be lower case\n            parsed = urlparse(url)\n            url = parsed.geturl()\n            conn = self.poolmanager.connection_from_url(url)\n\n        return conn\n    def close(self) -> None:\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        for proxy in self.proxy_manager.values():\n            proxy.clear()\n\n    def request_url(\n        self, request: PreparedRequest, proxies: dict[str, str] | None\n    ) -> str:\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        scheme = urlparse(request.url).scheme\n        is_proxied_http_request = proxy and scheme != \"https\"\n        using_socks_proxy = False\n        if proxy:\n            proxy_scheme = urlparse(proxy).scheme.lower()\n            using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n        url = request.path_url\n\n        if is_proxied_http_request and not using_socks_proxy:\n            url = urldefragauth(request.url)\n\n        return url\n\n    def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None:\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        pass\n\n    def proxy_headers(self, proxy: str) -> dict[str, str]:\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        headers: dict[str, str] = {}\n        username, password = get_auth_from_url(proxy)\n\n        if username:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n        return headers\n\n    def send(         self,\n        request: PreparedRequest,\n        stream: bool = False,         timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,         cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n        assert _is_prepared(request)\n        try:\n            conn = self.get_connection_with_tls_context(\n                request, verify, proxies=proxies, cert=cert             )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n            stream=stream,             timeout=timeout,             verify=verify,\n            cert=cert,\n            proxies=proxies,\n        )\n\n        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                resolved_timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            resolved_timeout = timeout\n        else:\n            resolved_timeout = TimeoutSauce(connect=timeout, read=timeout)\n        try:\n            resp = conn.urlopen(\n                method=request.method,\n                url=url,                 body=request.body,  # type: ignore[arg-type]  # urllib3 stubs don't accept Iterable[bytes | str]\n                headers=request.headers,  # type: ignore[arg-type]  # urllib3#3072\n                redirect=False,                 assert_same_host=False,                 preload_content=False,                 decode_content=False,\n                retries=self.max_retries,\n                timeout=resolved_timeout,                 chunked=chunked,             )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=request)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=request)\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=request)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=request)\n\n            if isinstance(e.reason, _SSLError):\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=request)\n            raise ConnectionError(e, request=request)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=request)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=request)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=request)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=request)\n            else:\n                raise\n\n        return self.build_response(request, resp)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-a0e3de19d1287dec", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "6bfa69d02425c60c1527e58adb397c9af05b8aff108c3adb5b2bb364311e8d0b", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 549, "local_path": "layout/partially-compact-layout/I10__requests__HTTPAdapter__d40e514b.py", "order": 10, "original_content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "parent_variant_id": "pyint-d7199f8ad572-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L158-L748", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 233, "line_break_groups_removed": 93, "line_breaks_removed": 93, "whitespace_characters_removed": 39}, "unit_kind": "class", "unit_name": "HTTPAdapter", "variant_id": "pyint-ecc6d40e514b-I10", "group_id": "py-a0e3de19d1287dec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 739, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f5b678e9739d-I11", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__: list[str] = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    max_retries: Retry\n    config: dict[str, Any]\n    proxy_manager: dict[str, Any]\n    _pool_connections: int\n    _pool_maxsize: int\n    _pool_block: bool\n    poolmanager: _PoolManager\n\n    def __init__(\n        self,\n        pool_connections: int = DEFAULT_POOLSIZE,\n        pool_maxsize: int = DEFAULT_POOLSIZE,\n        max_retries: int | Retry = DEFAULT_RETRIES,\n        pool_block: bool = DEFAULT_POOLBLOCK,\n    ) -> None:\n        if max_retries == DEFAULT_RETRIES:\n            a = 1\n            b = -1\n            self.max_retries = Retry((a + b), read=False)\n        else:\n            self.max_retries = Retry.from_int(max_retries)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = pool_connections\n        self._pool_maxsize = pool_maxsize\n        self._pool_block = pool_block\n\n        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n\n    def __getstate__(self) -> dict[str, Any]:\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        self.proxy_manager = {}\n        self.config = {}\n\n        for attr, value in state.items():\n            setattr(self, attr, value)\n\n        self.init_poolmanager(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def init_poolmanager(\n        self,\n        connections: int,\n        maxsize: int,\n        block: bool = DEFAULT_POOLBLOCK,\n        **pool_kwargs: Any,\n    ) -> None:\n        \"\"\"Initializes a urllib3 PoolManager.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        # save these values for pickling\n        self._pool_connections = connections\n        self._pool_maxsize = maxsize\n        self._pool_block = block\n\n        self.poolmanager = PoolManager(\n            num_pools=connections,\n            maxsize=maxsize,\n            block=block,\n            **pool_kwargs,\n        )\n\n    def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any:\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if proxy in self.proxy_manager:\n            manager = self.proxy_manager[proxy]\n        elif proxy.lower().startswith(\"socks\"):\n            username, password = get_auth_from_url(proxy)\n            manager = self.proxy_manager[proxy] = SOCKSProxyManager(\n                proxy,\n                username=username,\n                password=password,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n        else:\n            proxy_headers = self.proxy_headers(proxy)\n            manager = self.proxy_manager[proxy] = proxy_from_url(\n                proxy,\n                proxy_headers=proxy_headers,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n\n        return manager\n\n    def cert_verify(\n        self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType\n    ) -> None:\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if url.lower().startswith(\"https\") and verify:\n            cert_loc = None\n\n            # Allow self-specified cert location.\n            if verify is not True:\n                cert_loc = verify\n\n            if not cert_loc:\n                cert_loc = DEFAULT_CA_BUNDLE_PATH\n\n            if not cert_loc or not os.path.exists(cert_loc):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {cert_loc}\"\n                )\n\n            conn.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(cert_loc):\n                conn.ca_certs = cert_loc\n            else:\n                conn.ca_cert_dir = cert_loc\n        else:\n            conn.cert_reqs = \"CERT_NONE\"\n            conn.ca_certs = None\n            conn.ca_cert_dir = None\n\n        if cert:\n            if not isinstance(cert, basestring):\n                c = 1\n                d = -1\n                conn.cert_file = cert[(c + d)]\n                f = 2\n                g = -1\n                conn.key_file = cert[(f + g)]\n            else:\n                conn.cert_file = cert\n                conn.key_file = None\n            if conn.cert_file and not os.path.exists(conn.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {conn.cert_file}\"\n                )\n            if conn.key_file and not os.path.exists(conn.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {conn.key_file}\"\n                )\n\n    def build_response(self, req: PreparedRequest, resp: Any) -> Response:\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        assert _is_prepared(req)\n        response = Response()\n\n        # Fallback to None if there's no status_code, for whatever reason.\n        response.status_code = getattr(resp, \"status\", None)  # type: ignore[assignment]\n\n        # Make headers case-insensitive.\n        response.headers = CaseInsensitiveDict(getattr(resp, \"headers\", {}))\n\n        # Set encoding.\n        response.encoding = get_encoding_from_headers(response.headers)\n        response.raw = resp\n        response.reason = response.raw.reason\n\n        if isinstance(req.url, bytes):\n            response.url = req.url.decode(\"utf-8\")\n        else:\n            response.url = req.url\n\n        # Add new cookies from the server.\n        extract_cookies_to_jar(response.cookies, req, resp)\n\n        # Give the Response some context.\n        response.request = req\n        response.connection = self\n\n        return response\n\n    def build_connection_pool_key_attributes(\n        self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None\n    ) -> tuple[dict[str, Any], dict[str, Any]]:\n        \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n\n        This looks at the PreparedRequest, the user-specified verify value,\n        and the value of the cert parameter to determine what PoolKey values\n        to use to select a connection from a given urllib3 Connection Pool.\n\n        The SSL related pool key arguments are not consistently set. As of\n        this writing, use the following to determine what keys may be in that\n        dictionary:\n\n        * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n          default Requests SSL Context\n        * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n          ``\"cert_reqs\"`` will be set\n        * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n          ``\"ca_certs\"`` will be set if the string is not a directory recognized\n          by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n          set.\n        * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n          ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n          be present\n\n        To override these settings, one may subclass this class, call this\n        method and use the above logic to change parameters as desired. For\n        example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n        must both set ``\"ssl_context\"`` and based on what else they require,\n        alter the other keys to ensure the desired behaviour.\n\n        :param request:\n            The PreparedRequest being sent over the connection.\n        :type request:\n            :class:`~requests.models.PreparedRequest`\n        :param verify:\n            Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use.\n        :param cert:\n            (optional) Any user-provided SSL certificate for client\n            authentication (a.k.a., mTLS). This may be a string (i.e., just\n            the path to a file which holds both certificate and key) or a\n            tuple of length 2 with the certificate file path and key file\n            path.\n        :returns:\n            A tuple of two dictionaries. The first is the \"host parameters\"\n            portion of the Pool Key including scheme, hostname, and port. The\n            second is a dictionary of SSLContext related parameters.\n        \"\"\"\n        return _urllib3_request_context(request, verify, cert, self.poolmanager)\n\n    def get_connection_with_tls_context(\n        self,\n        request: PreparedRequest,\n        verify: _t.VerifyType,\n        proxies: dict[str, str] | None = None,\n        cert: _t.CertType = None,\n    ) -> HTTPConnectionPool:\n        \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request:\n            The :class:`PreparedRequest <PreparedRequest>` object to be sent\n            over the connection.\n        :param verify:\n            Either a boolean, in which case it controls whether we verify the\n            server's TLS certificate, or a string, in which case it must be a\n            path to a CA bundle to use.\n        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.HTTPConnectionPool\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        try:\n            host_params, pool_kwargs = self.build_connection_pool_key_attributes(\n                request,\n                verify,\n                cert,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=request)\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n        else:\n            # Only scheme should be lower case\n            conn = self.poolmanager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n\n        return conn\n\n    def get_connection(\n        self, url: str, proxies: dict[str, str] | None = None\n    ) -> HTTPConnectionPool:\n        \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n        for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n        Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.HTTPConnectionPool\n        \"\"\"\n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        proxy = select_proxy(url, proxies)\n\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_url(url)\n        else:\n            # Only scheme should be lower case\n            parsed = urlparse(url)\n            url = parsed.geturl()\n            conn = self.poolmanager.connection_from_url(url)\n\n        return conn\n\n    def close(self) -> None:\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        for proxy in self.proxy_manager.values():\n            proxy.clear()\n\n    def request_url(\n        self, request: PreparedRequest, proxies: dict[str, str] | None\n    ) -> str:\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        scheme = urlparse(request.url).scheme\n\n        is_proxied_http_request = proxy and scheme != \"https\"\n        using_socks_proxy = False\n        if proxy:\n            proxy_scheme = urlparse(proxy).scheme.lower()\n            using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n        url = request.path_url\n\n        if is_proxied_http_request and not using_socks_proxy:\n            url = urldefragauth(request.url)\n\n        return url\n\n    def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None:\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        pass\n\n    def proxy_headers(self, proxy: str) -> dict[str, str]:\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        headers: dict[str, str] = {}\n        username, password = get_auth_from_url(proxy)\n\n        if username:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return headers\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n\n        assert _is_prepared(request)\n\n        try:\n            conn = self.get_connection_with_tls_context(\n                request, verify, proxies=proxies, cert=cert\n            )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n            stream=stream,\n            timeout=timeout,\n            verify=verify,\n            cert=cert,\n            proxies=proxies,\n        )\n\n        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n\n        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                resolved_timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            resolved_timeout = timeout\n        else:\n            resolved_timeout = TimeoutSauce(connect=timeout, read=timeout)\n\n        try:\n            resp = conn.urlopen(\n                method=request.method,\n                url=url,\n                body=request.body,  # type: ignore[arg-type]  # urllib3 stubs don't accept Iterable[bytes | str]\n                headers=request.headers,  # type: ignore[arg-type]  # urllib3#3072\n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=resolved_timeout,\n                chunked=chunked,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=request)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=request)\n\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=request)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=request)\n\n            if isinstance(e.reason, _SSLError):\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=request)\n\n            raise ConnectionError(e, request=request)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=request)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=request)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=request)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=request)\n            else:\n                raise\n\n        return self.build_response(request, resp)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-a0e3de19d1287dec", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "62fe1998dfc14bc81c452a3da1221c40f2370a5498ff3359fb99b36de88599a1", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 648, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__HTTPAdapter__78e9739d.py", "order": 11, "original_content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "parent_variant_id": "pyint-d7199f8ad572-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L158-L748", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 3, "intermediate_variables_introduced": 6, "statements_augmented": 3}, "unit_kind": "class", "unit_name": "HTTPAdapter", "variant_id": "pyint-f5b678e9739d-I11", "group_id": "py-a0e3de19d1287dec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 740, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-99875982f289-I12", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__: list[str] = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    max_retries: Retry\n    config: dict[str, Any]\n    proxy_manager: dict[str, Any]\n    _pool_connections: int\n    _pool_maxsize: int\n    _pool_block: bool\n    poolmanager: _PoolManager\n\n    def __init__(\n        self,\n        pool_connections: int = DEFAULT_POOLSIZE,\n        pool_maxsize: int = DEFAULT_POOLSIZE,\n        max_retries: int | Retry = DEFAULT_RETRIES,\n        pool_block: bool = DEFAULT_POOLBLOCK,\n    ) -> None:\n        if max_retries == DEFAULT_RETRIES:\n            self.max_retries = Retry(0, read=False)\n        else:\n            self.max_retries = Retry.from_int(max_retries)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = pool_connections\n        self._pool_maxsize = pool_maxsize\n        self._pool_block = pool_block\n\n        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n\n    def __getstate__(self) -> dict[str, Any]:\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        self.proxy_manager = {}\n        self.config = {}\n\n        for attr, value in state.items():\n            setattr(self, attr, value)\n\n        self.init_poolmanager(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def init_poolmanager(\n        self,\n        connections: int,\n        maxsize: int,\n        block: bool = DEFAULT_POOLBLOCK,\n        **pool_kwargs: Any,\n    ) -> None:\n        \"\"\"Initializes a urllib3 PoolManager.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        # save these values for pickling\n        self._pool_connections = connections\n        self._pool_maxsize = maxsize\n        self._pool_block = block\n\n        self.poolmanager = PoolManager(\n            num_pools=connections,\n            maxsize=maxsize,\n            block=block,\n            **pool_kwargs,\n        )\n\n    def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any:\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if proxy in self.proxy_manager:\n            manager = self.proxy_manager[proxy]\n        elif proxy.lower().startswith(\"socks\"):\n            username, password = get_auth_from_url(proxy)\n            manager = self.proxy_manager[proxy] = SOCKSProxyManager(\n                proxy,\n                username=username,\n                password=password,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n        else:\n            proxy_headers = self.proxy_headers(proxy)\n            manager = self.proxy_manager[proxy] = proxy_from_url(\n                proxy,\n                proxy_headers=proxy_headers,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n\n        return manager\n\n    def cert_verify(\n        self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType\n    ) -> None:\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if url.lower().startswith(\"https\") and verify:\n            cert_loc = None\n\n            # Allow self-specified cert location.\n            if verify is not True:\n                cert_loc = verify\n\n            if not cert_loc:\n                cert_loc = DEFAULT_CA_BUNDLE_PATH\n\n            if not cert_loc or not os.path.exists(cert_loc):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {cert_loc}\"\n                )\n\n            conn.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(cert_loc):\n                conn.ca_certs = cert_loc\n            else:\n                conn.ca_cert_dir = cert_loc\n        else:\n            conn.cert_reqs = \"CERT_NONE\"\n            conn.ca_certs = None\n            conn.ca_cert_dir = None\n\n        if cert:\n            if not isinstance(cert, basestring):\n                conn.cert_file = cert[0]\n                conn.key_file = cert[1]\n            else:\n                conn.cert_file = cert\n                conn.key_file = None\n            if conn.cert_file and not os.path.exists(conn.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {conn.cert_file}\"\n                )\n            if conn.key_file and not os.path.exists(conn.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {conn.key_file}\"\n                )\n\n    def build_response(self, req: PreparedRequest, resp: Any) -> Response:\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        assert _is_prepared(req)\n        response = Response()\n\n        # Fallback to None if there's no status_code, for whatever reason.\n        response.status_code = getattr(resp, \"status\", None)  # type: ignore[assignment]\n\n        # Make headers case-insensitive.\n        response.headers = CaseInsensitiveDict(getattr(resp, \"headers\", {}))\n\n        # Set encoding.\n        response.encoding = get_encoding_from_headers(response.headers)\n        response.raw = resp\n        response.reason = response.raw.reason\n\n        if isinstance(req.url, bytes):\n            response.url = req.url.decode(\"utf-8\")\n        else:\n            response.url = req.url\n\n        # Add new cookies from the server.\n        extract_cookies_to_jar(response.cookies, req, resp)\n\n        # Give the Response some context.\n        response.request = req\n        response.connection = self\n\n        return response\n\n    def build_connection_pool_key_attributes(\n        self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None\n    ) -> tuple[dict[str, Any], dict[str, Any]]:\n        \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n\n        This looks at the PreparedRequest, the user-specified verify value,\n        and the value of the cert parameter to determine what PoolKey values\n        to use to select a connection from a given urllib3 Connection Pool.\n\n        The SSL related pool key arguments are not consistently set. As of\n        this writing, use the following to determine what keys may be in that\n        dictionary:\n\n        * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n          default Requests SSL Context\n        * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n          ``\"cert_reqs\"`` will be set\n        * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n          ``\"ca_certs\"`` will be set if the string is not a directory recognized\n          by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n          set.\n        * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n          ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n          be present\n\n        To override these settings, one may subclass this class, call this\n        method and use the above logic to change parameters as desired. For\n        example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n        must both set ``\"ssl_context\"`` and based on what else they require,\n        alter the other keys to ensure the desired behaviour.\n\n        :param request:\n            The PreparedRequest being sent over the connection.\n        :type request:\n            :class:`~requests.models.PreparedRequest`\n        :param verify:\n            Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use.\n        :param cert:\n            (optional) Any user-provided SSL certificate for client\n            authentication (a.k.a., mTLS). This may be a string (i.e., just\n            the path to a file which holds both certificate and key) or a\n            tuple of length 2 with the certificate file path and key file\n            path.\n        :returns:\n            A tuple of two dictionaries. The first is the \"host parameters\"\n            portion of the Pool Key including scheme, hostname, and port. The\n            second is a dictionary of SSLContext related parameters.\n        \"\"\"\n        return _urllib3_request_context(request, verify, cert, self.poolmanager)\n\n    def get_connection_with_tls_context(\n        self,\n        request: PreparedRequest,\n        verify: _t.VerifyType,\n        proxies: dict[str, str] | None = None,\n        cert: _t.CertType = None,\n    ) -> HTTPConnectionPool:\n        \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request:\n            The :class:`PreparedRequest <PreparedRequest>` object to be sent\n            over the connection.\n        :param verify:\n            Either a boolean, in which case it controls whether we verify the\n            server's TLS certificate, or a string, in which case it must be a\n            path to a CA bundle to use.\n        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.HTTPConnectionPool\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        try:\n            host_params, pool_kwargs = self.build_connection_pool_key_attributes(\n                request,\n                verify,\n                cert,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=request)\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n        else:\n            # Only scheme should be lower case\n            conn = self.poolmanager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n\n        return conn\n\n    def get_connection(\n        self, url: str, proxies: dict[str, str] | None = None\n    ) -> HTTPConnectionPool:\n        \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n        for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n        Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.HTTPConnectionPool\n        \"\"\"\n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        proxy = select_proxy(url, proxies)\n\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_url(url)\n        else:\n            # Only scheme should be lower case\n            parsed = urlparse(url)\n            url = parsed.geturl()\n            conn = self.poolmanager.connection_from_url(url)\n\n        return conn\n\n    def close(self) -> None:\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        for proxy in self.proxy_manager.values():\n            proxy.clear()\n\n    def request_url(\n        self, request: PreparedRequest, proxies: dict[str, str] | None\n    ) -> str:\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        scheme = urlparse(request.url).scheme\n\n        is_proxied_http_request = proxy and scheme != \"https\"\n        using_socks_proxy = False\n        if proxy:\n            proxy_scheme = urlparse(proxy).scheme.lower()\n            using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n        url = request.path_url\n\n        if is_proxied_http_request and not using_socks_proxy:\n            url = urldefragauth(request.url)\n\n        return url\n\n    def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None:\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        pass\n\n    def proxy_headers(self, proxy: str) -> dict[str, str]:\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        headers: dict[str, str] = {}\n        username, password = get_auth_from_url(proxy)\n\n        if username:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return headers\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n\n        assert _is_prepared(request)\n\n        try:\n            conn = self.get_connection_with_tls_context(\n                request, verify, proxies=proxies, cert=cert\n            )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n            stream=stream,\n            timeout=timeout,\n            verify=verify,\n            cert=cert,\n            proxies=proxies,\n        )\n\n        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n\n        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                resolved_timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            resolved_timeout = timeout\n        else:\n            resolved_timeout = TimeoutSauce(connect=timeout, read=timeout)\n\n        try:\n            resp = conn.urlopen(\n                method=request.method,\n                url=url,\n                body=request.body,  # type: ignore[arg-type]  # urllib3 stubs don't accept Iterable[bytes | str]\n                headers=request.headers,  # type: ignore[arg-type]  # urllib3#3072\n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=resolved_timeout,\n                chunked=chunked,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=request)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=request)\n\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=request)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=request)\n\n            if isinstance(e.reason, _SSLError):\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=request)\n\n            raise ConnectionError(e, request=request)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=request)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=request)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=request)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=request)\n            else:\n                raise\n\n        return self.build_response(request, resp)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-a0e3de19d1287dec", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 642, "local_path": "data-flow/inline-intermediate-variables/I12__requests__HTTPAdapter__5982f289.py", "order": 12, "original_content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "parent_variant_id": "pyint-d7199f8ad572-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L158-L748", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "HTTPAdapter", "variant_id": "pyint-99875982f289-I12", "group_id": "py-a0e3de19d1287dec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 741, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3684e8e9deb9-I13", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__: list[str] = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    max_retries: Retry\n    config: dict[str, Any]\n    proxy_manager: dict[str, Any]\n    _pool_connections: int\n    _pool_maxsize: int\n    _pool_block: bool\n    poolmanager: _PoolManager\n\n    def __init__(\n        self,\n        pool_connections: int = DEFAULT_POOLSIZE,\n        pool_maxsize: int = DEFAULT_POOLSIZE,\n        max_retries: int | Retry = DEFAULT_RETRIES,\n        pool_block: bool = DEFAULT_POOLBLOCK,\n    ) -> None:\n        if max_retries == DEFAULT_RETRIES:\n            self.max_retries = Retry(0, read=False)\n        else:\n            self.max_retries = Retry.from_int(max_retries)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = pool_connections\n        self._pool_maxsize = pool_maxsize\n        self._pool_block = pool_block\n\n        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n\n    def __getstate__(self) -> dict[str, Any]:\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        self.proxy_manager = {}\n        self.config = {}\n\n        loopIterator = __import__(\"builtins\").iter(state.items())\n        while True:\n            try:\n                attr, value = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            setattr(self, attr, value)\n\n        self.init_poolmanager(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def init_poolmanager(\n        self,\n        connections: int,\n        maxsize: int,\n        block: bool = DEFAULT_POOLBLOCK,\n        **pool_kwargs: Any,\n    ) -> None:\n        \"\"\"Initializes a urllib3 PoolManager.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        # save these values for pickling\n        self._pool_connections = connections\n        self._pool_maxsize = maxsize\n        self._pool_block = block\n\n        self.poolmanager = PoolManager(\n            num_pools=connections,\n            maxsize=maxsize,\n            block=block,\n            **pool_kwargs,\n        )\n\n    def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any:\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if proxy in self.proxy_manager:\n            manager = self.proxy_manager[proxy]\n        elif proxy.lower().startswith(\"socks\"):\n            username, password = get_auth_from_url(proxy)\n            manager = self.proxy_manager[proxy] = SOCKSProxyManager(\n                proxy,\n                username=username,\n                password=password,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n        else:\n            proxy_headers = self.proxy_headers(proxy)\n            manager = self.proxy_manager[proxy] = proxy_from_url(\n                proxy,\n                proxy_headers=proxy_headers,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n\n        return manager\n\n    def cert_verify(\n        self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType\n    ) -> None:\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if url.lower().startswith(\"https\") and verify:\n            cert_loc = None\n\n            # Allow self-specified cert location.\n            if verify is not True:\n                cert_loc = verify\n\n            if not cert_loc:\n                cert_loc = DEFAULT_CA_BUNDLE_PATH\n\n            if not cert_loc or not os.path.exists(cert_loc):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {cert_loc}\"\n                )\n\n            conn.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(cert_loc):\n                conn.ca_certs = cert_loc\n            else:\n                conn.ca_cert_dir = cert_loc\n        else:\n            conn.cert_reqs = \"CERT_NONE\"\n            conn.ca_certs = None\n            conn.ca_cert_dir = None\n\n        if cert:\n            if not isinstance(cert, basestring):\n                conn.cert_file = cert[0]\n                conn.key_file = cert[1]\n            else:\n                conn.cert_file = cert\n                conn.key_file = None\n            if conn.cert_file and not os.path.exists(conn.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {conn.cert_file}\"\n                )\n            if conn.key_file and not os.path.exists(conn.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {conn.key_file}\"\n                )\n\n    def build_response(self, req: PreparedRequest, resp: Any) -> Response:\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        assert _is_prepared(req)\n        response = Response()\n\n        # Fallback to None if there's no status_code, for whatever reason.\n        response.status_code = getattr(resp, \"status\", None)  # type: ignore[assignment]\n\n        # Make headers case-insensitive.\n        response.headers = CaseInsensitiveDict(getattr(resp, \"headers\", {}))\n\n        # Set encoding.\n        response.encoding = get_encoding_from_headers(response.headers)\n        response.raw = resp\n        response.reason = response.raw.reason\n\n        if isinstance(req.url, bytes):\n            response.url = req.url.decode(\"utf-8\")\n        else:\n            response.url = req.url\n\n        # Add new cookies from the server.\n        extract_cookies_to_jar(response.cookies, req, resp)\n\n        # Give the Response some context.\n        response.request = req\n        response.connection = self\n\n        return response\n\n    def build_connection_pool_key_attributes(\n        self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None\n    ) -> tuple[dict[str, Any], dict[str, Any]]:\n        \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n\n        This looks at the PreparedRequest, the user-specified verify value,\n        and the value of the cert parameter to determine what PoolKey values\n        to use to select a connection from a given urllib3 Connection Pool.\n\n        The SSL related pool key arguments are not consistently set. As of\n        this writing, use the following to determine what keys may be in that\n        dictionary:\n\n        * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n          default Requests SSL Context\n        * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n          ``\"cert_reqs\"`` will be set\n        * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n          ``\"ca_certs\"`` will be set if the string is not a directory recognized\n          by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n          set.\n        * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n          ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n          be present\n\n        To override these settings, one may subclass this class, call this\n        method and use the above logic to change parameters as desired. For\n        example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n        must both set ``\"ssl_context\"`` and based on what else they require,\n        alter the other keys to ensure the desired behaviour.\n\n        :param request:\n            The PreparedRequest being sent over the connection.\n        :type request:\n            :class:`~requests.models.PreparedRequest`\n        :param verify:\n            Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use.\n        :param cert:\n            (optional) Any user-provided SSL certificate for client\n            authentication (a.k.a., mTLS). This may be a string (i.e., just\n            the path to a file which holds both certificate and key) or a\n            tuple of length 2 with the certificate file path and key file\n            path.\n        :returns:\n            A tuple of two dictionaries. The first is the \"host parameters\"\n            portion of the Pool Key including scheme, hostname, and port. The\n            second is a dictionary of SSLContext related parameters.\n        \"\"\"\n        return _urllib3_request_context(request, verify, cert, self.poolmanager)\n\n    def get_connection_with_tls_context(\n        self,\n        request: PreparedRequest,\n        verify: _t.VerifyType,\n        proxies: dict[str, str] | None = None,\n        cert: _t.CertType = None,\n    ) -> HTTPConnectionPool:\n        \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n        This should not be called from user code, and is only exposed for use\n        when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request:\n            The :class:`PreparedRequest <PreparedRequest>` object to be sent\n            over the connection.\n        :param verify:\n            Either a boolean, in which case it controls whether we verify the\n            server's TLS certificate, or a string, in which case it must be a\n            path to a CA bundle to use.\n        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.HTTPConnectionPool\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        try:\n            host_params, pool_kwargs = self.build_connection_pool_key_attributes(\n                request,\n                verify,\n                cert,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=request)\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n        else:\n            # Only scheme should be lower case\n            conn = self.poolmanager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n\n        return conn\n\n    def get_connection(\n        self, url: str, proxies: dict[str, str] | None = None\n    ) -> HTTPConnectionPool:\n        \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n        for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n        Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.HTTPConnectionPool\n        \"\"\"\n        warnings.warn(\n            (\n                \"`get_connection` has been deprecated in favor of \"\n                \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n                \"will need to migrate for Requests>=2.32.2. Please see \"\n                \"https://github.com/psf/requests/pull/6710 for more details.\"\n            ),\n            DeprecationWarning,\n        )\n        proxy = select_proxy(url, proxies)\n\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_url(url)\n        else:\n            # Only scheme should be lower case\n            parsed = urlparse(url)\n            url = parsed.geturl()\n            conn = self.poolmanager.connection_from_url(url)\n\n        return conn\n\n    def close(self) -> None:\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        loopIteratorA = __import__(\"builtins\").iter(self.proxy_manager.values())\n        while True:\n            try:\n                proxy = __import__(\"builtins\").next(loopIteratorA)\n            except __import__(\"builtins\").StopIteration:\n                break\n            proxy.clear()\n\n    def request_url(\n        self, request: PreparedRequest, proxies: dict[str, str] | None\n    ) -> str:\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        scheme = urlparse(request.url).scheme\n\n        is_proxied_http_request = proxy and scheme != \"https\"\n        using_socks_proxy = False\n        if proxy:\n            proxy_scheme = urlparse(proxy).scheme.lower()\n            using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n        url = request.path_url\n\n        if is_proxied_http_request and not using_socks_proxy:\n            url = urldefragauth(request.url)\n\n        return url\n\n    def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None:\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        pass\n\n    def proxy_headers(self, proxy: str) -> dict[str, str]:\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        headers: dict[str, str] = {}\n        username, password = get_auth_from_url(proxy)\n\n        if username:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return headers\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n\n        assert _is_prepared(request)\n\n        try:\n            conn = self.get_connection_with_tls_context(\n                request, verify, proxies=proxies, cert=cert\n            )\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n            stream=stream,\n            timeout=timeout,\n            verify=verify,\n            cert=cert,\n            proxies=proxies,\n        )\n\n        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n\n        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                resolved_timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            resolved_timeout = timeout\n        else:\n            resolved_timeout = TimeoutSauce(connect=timeout, read=timeout)\n\n        try:\n            resp = conn.urlopen(\n                method=request.method,\n                url=url,\n                body=request.body,  # type: ignore[arg-type]  # urllib3 stubs don't accept Iterable[bytes | str]\n                headers=request.headers,  # type: ignore[arg-type]  # urllib3#3072\n                redirect=False,\n                assert_same_host=False,\n                preload_content=False,\n                decode_content=False,\n                retries=self.max_retries,\n                timeout=resolved_timeout,\n                chunked=chunked,\n            )\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=request)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=request)\n\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=request)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=request)\n\n            if isinstance(e.reason, _SSLError):\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=request)\n\n            raise ConnectionError(e, request=request)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=request)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=request)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=request)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=request)\n            else:\n                raise\n\n        return self.build_response(request, resp)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-a0e3de19d1287dec", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "2a775f99a4371bee744037c0709bd476dbfd07167a3bef3769f93be9db2c537c", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 652, "local_path": "control-flow/lower-for-to-while/I13__requests__HTTPAdapter__e8e9deb9.py", "order": 13, "original_content_sha256": "ba207db16efcc5536d2685c5150466999b7b38a9d0ad5caf716f11fc0dfa77db", "parent_variant_id": "pyint-d7199f8ad572-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L158-L748", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 2, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 2, "synchronous_for_loops_eligible": 2, "synchronous_for_loops_found": 2}, "unit_kind": "class", "unit_name": "HTTPAdapter", "variant_id": "pyint-3684e8e9deb9-I13", "group_id": "py-a0e3de19d1287dec", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 742, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-555cb46774cb-SRC", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _NumberValidator:\n    bound = attrib()\n    compare_op = attrib()\n    compare_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.compare_func(value, self.bound):\n            msg = f\"'{attr.name}' must be {self.compare_op} {self.bound}: {value}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<Validator for x {self.compare_op} {self.bound}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-a28914734b1370ba", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 25, "local_path": "source-original/SRC__attrs___NumberValidator__b46774cb.py", "order": 0, "original_content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L462-L476", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_NumberValidator", "variant_id": "pyint-555cb46774cb-SRC", "group_id": "py-a28914734b1370ba", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1051, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-58a6b4b00288-I01", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _NumberValidator:\n    bound = attrib()\n    compare_op = attrib()\n    compare_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \n        if not self.compare_func(value, self.bound):\n            msg = f\"'{attr.name}' must be {self.compare_op} {self.bound}: {value}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<Validator for x {self.compare_op} {self.bound}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-a28914734b1370ba", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "c27db53e07873bae9cadce4c9ad746c61e1b52c6d4daf6a72180cef924ca3ae8", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 23, "local_path": "comments/remove-comments/I01__attrs___NumberValidator__b4b00288.py", "order": 1, "original_content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "parent_variant_id": "pyint-555cb46774cb-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L462-L476", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 86, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "_NumberValidator", "variant_id": "pyint-58a6b4b00288-I01", "group_id": "py-a28914734b1370ba", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1052, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-53c1be945bdd-I02", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _NumberValidator:\n    bound = attrib()\n    compare_op = attrib()\n    compare_func = attrib()\n\n    def __call__(self, ins, att, val):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.compare_func(val, self.bound):\n            msg2 = f\"'{att.name}' must be {self.compare_op} {self.bound}: {val}\"\n            raise ValueError(msg2)\n\n    def __repr__(self):\n        return f\"<Validator for x {self.compare_op} {self.bound}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-a28914734b1370ba", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "f88615094ca5f22fa2892ffce6068e03327d4973fa40ddcb80cc91f0d5402a8a", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 25, "local_path": "identifiers/shorten-identifiers/I02__attrs___NumberValidator__be945bdd.py", "order": 2, "original_content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "parent_variant_id": "pyint-555cb46774cb-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L462-L476", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_NumberValidator", "variant_id": "pyint-53c1be945bdd-I02", "group_id": "py-a28914734b1370ba", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1053, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9b915be8ca46-I03", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _NumberValidator:\n    bound = attrib()\n    compare_op = attrib()\n    compare_func = attrib()\n\n    def __call__(self, path, data, event):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.compare_func(event, self.bound):\n            key = f\"'{data.name}' must be {self.compare_op} {self.bound}: {event}\"\n            raise ValueError(key)\n\n    def __repr__(self):\n        return f\"<Validator for x {self.compare_op} {self.bound}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-a28914734b1370ba", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "2c9be0b401882790db4a660555da0ce5198b55c12e4c9f0682015df29f2ed987", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 25, "local_path": "identifiers/mislead-identifiers/I03__attrs___NumberValidator__5be8ca46.py", "order": 3, "original_content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "parent_variant_id": "pyint-555cb46774cb-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L462-L476", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 4, "local_random_pool_selections": 4, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_NumberValidator", "variant_id": "pyint-9b915be8ca46-I03", "group_id": "py-a28914734b1370ba", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1054, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-081adf221478-I04", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _NumberValidator:\n    bound = attrib()\n    compare_op = attrib()\n    compare_func = attrib()\n\n    def __call__(self, a, b, c):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.compare_func(c, self.bound):\n            d = f\"'{b.name}' must be {self.compare_op} {self.bound}: {c}\"\n            raise ValueError(d)\n\n    def __repr__(self):\n        return f\"<Validator for x {self.compare_op} {self.bound}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-a28914734b1370ba", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "5fb59096ed6442a9cd0bc2ed77fe62535a3a4145a86f8ccf57defe71d9583556", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 25, "local_path": "identifiers/garble-identifiers/I04__attrs___NumberValidator__df221478.py", "order": 4, "original_content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "parent_variant_id": "pyint-555cb46774cb-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L462-L476", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_NumberValidator", "variant_id": "pyint-081adf221478-I04", "group_id": "py-a28914734b1370ba", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1055, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-169a4ecb2d28-I05", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _NumberValidator:\n    bound = attrib()\n    compare_op = attrib()\n    compare_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.compare_func(value, self.bound):\n            msg = f\"'{attr.name}' must be {self.compare_op} {self.bound}: {value}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<Validator for x {self.compare_op} {self.bound}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-a28914734b1370ba", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 25, "local_path": "expressions/encode-integer-literals/I05__attrs___NumberValidator__4ecb2d28.py", "order": 5, "original_content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "parent_variant_id": "pyint-555cb46774cb-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L462-L476", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "_NumberValidator", "variant_id": "pyint-169a4ecb2d28-I05", "group_id": "py-a28914734b1370ba", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1056, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-58a950acc281-I06", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _NumberValidator:\n    bound = attrib()\n    compare_op = attrib()\n    compare_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not (not self.compare_func(value, self.bound)):\n            pass\n        else:\n            msg = f\"'{attr.name}' must be {self.compare_op} {self.bound}: {value}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<Validator for x {self.compare_op} {self.bound}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-a28914734b1370ba", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "2475167728dc570a2e10d043fdbe24e5b7a357780b4015539add9b1e4ce7b2a1", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 27, "local_path": "expressions/invert-conditions/I06__attrs___NumberValidator__50acc281.py", "order": 6, "original_content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "parent_variant_id": "pyint-555cb46774cb-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L462-L476", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "_NumberValidator", "variant_id": "pyint-58a950acc281-I06", "group_id": "py-a28914734b1370ba", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1057, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bee71ac193e0-I07", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _NumberValidator:\n    bound = attrib()\n    compare_op = attrib()\n    compare_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if ((0x640d ^ 0x640d) != 0):\n            raise AssertionError()\n        if not self.compare_func(value, self.bound):\n            msg = f\"'{attr.name}' must be {self.compare_op} {self.bound}: {value}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        if ((0x3932 ^ 0x3932) != 0):\n            raise AssertionError()\n        return f\"<Validator for x {self.compare_op} {self.bound}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-a28914734b1370ba", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "0886e441753d791aea8acf67d706b7e76aaafdccdf45175ebcfa07c3adfe393c", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 29, "local_path": "code-injection/insert-dead-branches/I07__attrs___NumberValidator__1ac193e0.py", "order": 7, "original_content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "parent_variant_id": "pyint-555cb46774cb-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L462-L476", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "_NumberValidator", "variant_id": "pyint-bee71ac193e0-I07", "group_id": "py-a28914734b1370ba", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1058, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3837a5704fbf-I08", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _NumberValidator:\n    bound = attrib()\n    compare_op = attrib()\n    compare_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.compare_func(value, self.bound):\n            msg = f\"'{attr.name}' must be {self.compare_op} {self.bound}: {value}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        feature_enabled = False\n        for toggle_count in range(3):\n            feature_enabled = not feature_enabled\n        return f\"<Validator for x {self.compare_op} {self.bound}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-a28914734b1370ba", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "09682c070b725e49816550303e6a99e351f5f63d9f26eade0fe08049b5f96f6b", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 28, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___NumberValidator__a5704fbf.py", "order": 8, "original_content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "parent_variant_id": "pyint-555cb46774cb-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L462-L476", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 7}, "unit_kind": "class", "unit_name": "_NumberValidator", "variant_id": "pyint-3837a5704fbf-I08", "group_id": "py-a28914734b1370ba", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1059, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-04d3aa2d3854-I09", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _NumberValidator:\n    bound = attrib()\n    compare_op = attrib()\n    compare_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        lI0O_550bdd37 = 0x1477\n        lI0O_550bdd37 = (0 if (lI0O_550bdd37 ^ lI0O_550bdd37) == 0 else 1) if (lI0O_550bdd37 & 0) == 0 else 2\n        if not self.compare_func(value, self.bound):\n            msg = f\"'{attr.name}' must be {self.compare_op} {self.bound}: {value}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<Validator for x {self.compare_op} {self.bound}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-a28914734b1370ba", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "70cf79d75302c5604b99052892eefea988d93f70571c5262656b0ee39f34fccf", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 27, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___NumberValidator__aa2d3854.py", "order": 9, "original_content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "parent_variant_id": "pyint-555cb46774cb-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L462-L476", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 8}, "unit_kind": "class", "unit_name": "_NumberValidator", "variant_id": "pyint-04d3aa2d3854-I09", "group_id": "py-a28914734b1370ba", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1060, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f5144ee0ee36-I10", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n@attrs(repr=False, frozen=True, slots=True)\nclass _NumberValidator:\n    bound = attrib()\n    compare_op = attrib()\n    compare_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.compare_func(value, self.bound):\n            msg = f\"'{attr.name}' must be {self.compare_op} {self.bound}: {value}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<Validator for x {self.compare_op} {self.bound}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-a28914734b1370ba", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "73be53e539f54de37fc706c77473ed53570ba3e43d93b3fa5d5d6602a8984b20", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 24, "local_path": "layout/partially-compact-layout/I10__attrs___NumberValidator__4ee0ee36.py", "order": 10, "original_content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "parent_variant_id": "pyint-555cb46774cb-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L462-L476", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 3, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "_NumberValidator", "variant_id": "pyint-f5144ee0ee36-I10", "group_id": "py-a28914734b1370ba", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1061, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8435f95d075f-I11", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _NumberValidator:\n    bound = attrib()\n    compare_op = attrib()\n    compare_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.compare_func(value, self.bound):\n            msg = f\"'{attr.name}' must be {self.compare_op} {self.bound}: {value}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<Validator for x {self.compare_op} {self.bound}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-a28914734b1370ba", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 25, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___NumberValidator__f95d075f.py", "order": 11, "original_content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "parent_variant_id": "pyint-555cb46774cb-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L462-L476", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "_NumberValidator", "variant_id": "pyint-8435f95d075f-I11", "group_id": "py-a28914734b1370ba", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1062, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-df47ebf2ff08-I12", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _NumberValidator:\n    bound = attrib()\n    compare_op = attrib()\n    compare_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.compare_func(value, self.bound):\n            \n            raise ValueError((f\"'{attr.name}' must be {self.compare_op} {self.bound}: {value}\"))\n\n    def __repr__(self):\n        return f\"<Validator for x {self.compare_op} {self.bound}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-a28914734b1370ba", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a359a591ab4196026b84d793de638712881a3b288796b4cc02a8d813fb07549d", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 25, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___NumberValidator__ebf2ff08.py", "order": 12, "original_content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "parent_variant_id": "pyint-555cb46774cb-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L462-L476", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_NumberValidator", "variant_id": "pyint-df47ebf2ff08-I12", "group_id": "py-a28914734b1370ba", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1063, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d65a8a93dd81-I13", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _NumberValidator:\n    bound = attrib()\n    compare_op = attrib()\n    compare_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.compare_func(value, self.bound):\n            msg = f\"'{attr.name}' must be {self.compare_op} {self.bound}: {value}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<Validator for x {self.compare_op} {self.bound}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-a28914734b1370ba", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 25, "local_path": "control-flow/lower-for-to-while/I13__attrs___NumberValidator__8a93dd81.py", "order": 13, "original_content_sha256": "65171f1247d9afd643d7e1831a1af8ef959bc7bbe4633aa491437365a58093e0", "parent_variant_id": "pyint-555cb46774cb-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L462-L476", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "_NumberValidator", "variant_id": "pyint-d65a8a93dd81-I13", "group_id": "py-a28914734b1370ba", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1064, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3e6802a08bd5-SRC", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Converter:\n    \"\"\"\n    Stores a converter callable.\n\n    Allows for the wrapped converter to take additional arguments. The\n    arguments are passed in the order they are documented.\n\n    Args:\n        converter (Callable): A callable that converts the passed value.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument. (default: `False`)\n\n        takes_field (bool):\n            Pass the field definition (an :class:`Attribute`) into the\n            converter as a positional argument. (default: `False`)\n\n    .. versionadded:: 24.1.0\n    \"\"\"\n\n    __slots__ = (\n        \"__call__\",\n        \"_first_param_type\",\n        \"_global_name\",\n        \"converter\",\n        \"takes_field\",\n        \"takes_self\",\n    )\n\n    def __init__(self, converter, *, takes_self=False, takes_field=False):\n        self.converter = converter\n        self.takes_self = takes_self\n        self.takes_field = takes_field\n\n        ex = _AnnotationExtractor(converter)\n        self._first_param_type = ex.get_first_param_type()\n\n        if not (self.takes_self or self.takes_field):\n            self.__call__ = lambda value, _, __: self.converter(value)\n        elif self.takes_self and not self.takes_field:\n            self.__call__ = lambda value, instance, __: self.converter(\n                value, instance\n            )\n        elif not self.takes_self and self.takes_field:\n            self.__call__ = lambda value, __, field: self.converter(\n                value, field\n            )\n        else:\n            self.__call__ = self.converter\n\n        rt = ex.get_return_type()\n        if rt is not None:\n            self.__call__.__annotations__[\"return\"] = rt\n\n    @staticmethod\n    def _get_global_name(attr_name: str) -> str:\n        \"\"\"\n        Return the name that a converter for an attribute name *attr_name*\n        would have.\n        \"\"\"\n        return f\"__attr_converter_{attr_name}\"\n\n    def _fmt_converter_call(self, attr_name: str, value_var: str) -> str:\n        \"\"\"\n        Return a string that calls the converter for an attribute name\n        *attr_name* and the value in variable named *value_var* according to\n        `self.takes_self` and `self.takes_field`.\n        \"\"\"\n        if not (self.takes_self or self.takes_field):\n            return f\"{self._get_global_name(attr_name)}({value_var})\"\n\n        if self.takes_self and self.takes_field:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])\"\n\n        if self.takes_self:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self)\"\n\n        return f\"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])\"\n\n    def __getstate__(self):\n        \"\"\"\n        Return a dict containing only converter and takes_self -- the rest gets\n        computed when loading.\n        \"\"\"\n        return {\n            \"converter\": self.converter,\n            \"takes_self\": self.takes_self,\n            \"takes_field\": self.takes_field,\n        }\n\n    def __setstate__(self, state):\n        \"\"\"\n        Load instance from state.\n        \"\"\"\n        self.__init__(**state)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-a437ac55440699ca", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 125, "local_path": "source-original/SRC__attrs__Converter__02a08bd5.py", "order": 0, "original_content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3142-L3237", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Converter", "variant_id": "pyint-3e6802a08bd5-SRC", "group_id": "py-a437ac55440699ca", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1205, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-af64cc768261-I01", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Converter:\n    \n\n    __slots__ = (\n        \"__call__\",\n        \"_first_param_type\",\n        \"_global_name\",\n        \"converter\",\n        \"takes_field\",\n        \"takes_self\",\n    )\n\n    def __init__(self, converter, *, takes_self=False, takes_field=False):\n        self.converter = converter\n        self.takes_self = takes_self\n        self.takes_field = takes_field\n\n        ex = _AnnotationExtractor(converter)\n        self._first_param_type = ex.get_first_param_type()\n\n        if not (self.takes_self or self.takes_field):\n            self.__call__ = lambda value, _, __: self.converter(value)\n        elif self.takes_self and not self.takes_field:\n            self.__call__ = lambda value, instance, __: self.converter(\n                value, instance\n            )\n        elif not self.takes_self and self.takes_field:\n            self.__call__ = lambda value, __, field: self.converter(\n                value, field\n            )\n        else:\n            self.__call__ = self.converter\n\n        rt = ex.get_return_type()\n        if rt is not None:\n            self.__call__.__annotations__[\"return\"] = rt\n\n    @staticmethod\n    def _get_global_name(attr_name: str) -> str:\n        \n        return f\"__attr_converter_{attr_name}\"\n\n    def _fmt_converter_call(self, attr_name: str, value_var: str) -> str:\n        \n        if not (self.takes_self or self.takes_field):\n            return f\"{self._get_global_name(attr_name)}({value_var})\"\n\n        if self.takes_self and self.takes_field:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])\"\n\n        if self.takes_self:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self)\"\n\n        return f\"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])\"\n\n    def __getstate__(self):\n        \n        return {\n            \"converter\": self.converter,\n            \"takes_self\": self.takes_self,\n            \"takes_field\": self.takes_field,\n        }\n\n    def __setstate__(self, state):\n        \n        self.__init__(**state)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-a437ac55440699ca", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "69947dbc085c19fc850bec71c58cee7a809bf29339ea182e40ae5592500b3ae3", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 95, "local_path": "comments/remove-comments/I01__attrs__Converter__cc768261.py", "order": 1, "original_content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "parent_variant_id": "pyint-3e6802a08bd5-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3142-L3237", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 1117, "comments_removed": 5, "docstrings_removed": 5, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "Converter", "variant_id": "pyint-af64cc768261-I01", "group_id": "py-a437ac55440699ca", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1206, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-848c0ee07c5e-I02", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Converter:\n    \"\"\"\n    Stores a converter callable.\n\n    Allows for the wrapped converter to take additional arguments. The\n    arguments are passed in the order they are documented.\n\n    Args:\n        converter (Callable): A callable that converts the passed value.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument. (default: `False`)\n\n        takes_field (bool):\n            Pass the field definition (an :class:`Attribute`) into the\n            converter as a positional argument. (default: `False`)\n\n    .. versionadded:: 24.1.0\n    \"\"\"\n\n    __slots__ = (\n        \"__call__\",\n        \"_first_param_type\",\n        \"_global_name\",\n        \"converter\",\n        \"takes_field\",\n        \"takes_self\",\n    )\n\n    def __init__(self, con, *, takes=False, takes2=False):\n        self.converter = con\n        self.takes_self = takes\n        self.takes_field = takes2\n\n        ex2 = _AnnotationExtractor(con)\n        self._first_param_type = ex2.get_first_param_type()\n\n        if not (self.takes_self or self.takes_field):\n            self.__call__ = lambda value, _, __: self.converter(value)\n        elif self.takes_self and not self.takes_field:\n            self.__call__ = lambda value, instance, __: self.converter(\n                value, instance\n            )\n        elif not self.takes_self and self.takes_field:\n            self.__call__ = lambda value, __, field: self.converter(\n                value, field\n            )\n        else:\n            self.__call__ = self.converter\n\n        rt2 = ex2.get_return_type()\n        if rt2 is not None:\n            self.__call__.__annotations__[\"return\"] = rt2\n\n    @staticmethod\n    def get(attr: str) -> str:\n        \"\"\"\n        Return the name that a converter for an attribute name *attr_name*\n        would have.\n        \"\"\"\n        return f\"__attr_converter_{attr}\"\n\n    def fmt(self, attr2: str, value2: str) -> str:\n        \"\"\"\n        Return a string that calls the converter for an attribute name\n        *attr_name* and the value in variable named *value_var* according to\n        `self.takes_self` and `self.takes_field`.\n        \"\"\"\n        if not (self.takes_self or self.takes_field):\n            return f\"{self.get(attr2)}({value2})\"\n\n        if self.takes_self and self.takes_field:\n            return f\"{self.get(attr2)}({value2}, self, attr_dict['{attr2}'])\"\n\n        if self.takes_self:\n            return f\"{self.get(attr2)}({value2}, self)\"\n\n        return f\"{self.get(attr2)}({value2}, attr_dict['{attr2}'])\"\n\n    def __getstate__(self):\n        \"\"\"\n        Return a dict containing only converter and takes_self -- the rest gets\n        computed when loading.\n        \"\"\"\n        return {\n            \"converter\": self.converter,\n            \"takes_self\": self.takes_self,\n            \"takes_field\": self.takes_field,\n        }\n\n    def __setstate__(self, sta):\n        \"\"\"\n        Load instance from state.\n        \"\"\"\n        self.__init__(**sta)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-a437ac55440699ca", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b201c87eef04c38e63c3a6d06b77ee56126e34df9d0d070cd653f7b9a27773ce", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 125, "local_path": "identifiers/shorten-identifiers/I02__attrs__Converter__0ee07c5e.py", "order": 2, "original_content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "parent_variant_id": "pyint-3e6802a08bd5-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3142-L3237", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 35, "identifiers_declared": 11}, "unit_kind": "class", "unit_name": "Converter", "variant_id": "pyint-848c0ee07c5e-I02", "group_id": "py-a437ac55440699ca", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1207, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d4f3679c35ea-I03", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Converter:\n    \"\"\"\n    Stores a converter callable.\n\n    Allows for the wrapped converter to take additional arguments. The\n    arguments are passed in the order they are documented.\n\n    Args:\n        converter (Callable): A callable that converts the passed value.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument. (default: `False`)\n\n        takes_field (bool):\n            Pass the field definition (an :class:`Attribute`) into the\n            converter as a positional argument. (default: `False`)\n\n    .. versionadded:: 24.1.0\n    \"\"\"\n\n    __slots__ = (\n        \"__call__\",\n        \"_first_param_type\",\n        \"_global_name\",\n        \"converter\",\n        \"takes_field\",\n        \"takes_self\",\n    )\n\n    def __init__(self, secureKey, *, localCache=False, remoteState=False):\n        self.converter = secureKey\n        self.takes_self = localCache\n        self.takes_field = remoteState\n\n        key = _AnnotationExtractor(secureKey)\n        self._first_param_type = key.get_first_param_type()\n\n        if not (self.takes_self or self.takes_field):\n            self.__call__ = lambda value, _, __: self.converter(value)\n        elif self.takes_self and not self.takes_field:\n            self.__call__ = lambda value, instance, __: self.converter(\n                value, instance\n            )\n        elif not self.takes_self and self.takes_field:\n            self.__call__ = lambda value, __, field: self.converter(\n                value, field\n            )\n        else:\n            self.__call__ = self.converter\n\n        age = key.get_return_type()\n        if age is not None:\n            self.__call__.__annotations__[\"return\"] = age\n\n    @staticmethod\n    def validateMessage(nextBatch: str) -> str:\n        \"\"\"\n        Return the name that a converter for an attribute name *attr_name*\n        would have.\n        \"\"\"\n        return f\"__attr_converter_{nextBatch}\"\n\n    def validateAccount(self, finalUser: str, finalPath: str) -> str:\n        \"\"\"\n        Return a string that calls the converter for an attribute name\n        *attr_name* and the value in variable named *value_var* according to\n        `self.takes_self` and `self.takes_field`.\n        \"\"\"\n        if not (self.takes_self or self.takes_field):\n            return f\"{self.validateMessage(finalUser)}({finalPath})\"\n\n        if self.takes_self and self.takes_field:\n            return f\"{self.validateMessage(finalUser)}({finalPath}, self, attr_dict['{finalUser}'])\"\n\n        if self.takes_self:\n            return f\"{self.validateMessage(finalUser)}({finalPath}, self)\"\n\n        return f\"{self.validateMessage(finalUser)}({finalPath}, attr_dict['{finalUser}'])\"\n\n    def __getstate__(self):\n        \"\"\"\n        Return a dict containing only converter and takes_self -- the rest gets\n        computed when loading.\n        \"\"\"\n        return {\n            \"converter\": self.converter,\n            \"takes_self\": self.takes_self,\n            \"takes_field\": self.takes_field,\n        }\n\n    def __setstate__(self, total):\n        \"\"\"\n        Load instance from state.\n        \"\"\"\n        self.__init__(**total)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-a437ac55440699ca", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b9f3f6c3f2eb164d09b8a23a0c58adb00e096fb88689ccdb1edeae9185a729b0", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 125, "local_path": "identifiers/mislead-identifiers/I03__attrs__Converter__679c35ea.py", "order": 3, "original_content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "parent_variant_id": "pyint-3e6802a08bd5-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3142-L3237", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 35, "identifiers_declared": 11, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 7, "local_random_pool_selections": 9, "local_total_length_difference": 2, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 2, "method_total_length_difference": 5}, "unit_kind": "class", "unit_name": "Converter", "variant_id": "pyint-d4f3679c35ea-I03", "group_id": "py-a437ac55440699ca", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1208, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bc12eb68b117-I04", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Converter:\n    \"\"\"\n    Stores a converter callable.\n\n    Allows for the wrapped converter to take additional arguments. The\n    arguments are passed in the order they are documented.\n\n    Args:\n        converter (Callable): A callable that converts the passed value.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument. (default: `False`)\n\n        takes_field (bool):\n            Pass the field definition (an :class:`Attribute`) into the\n            converter as a positional argument. (default: `False`)\n\n    .. versionadded:: 24.1.0\n    \"\"\"\n\n    __slots__ = (\n        \"__call__\",\n        \"_first_param_type\",\n        \"_global_name\",\n        \"converter\",\n        \"takes_field\",\n        \"takes_self\",\n    )\n\n    def __init__(self, c, *, d=False, e=False):\n        self.converter = c\n        self.takes_self = d\n        self.takes_field = e\n\n        f = _AnnotationExtractor(c)\n        self._first_param_type = f.get_first_param_type()\n\n        if not (self.takes_self or self.takes_field):\n            self.__call__ = lambda value, _, __: self.converter(value)\n        elif self.takes_self and not self.takes_field:\n            self.__call__ = lambda value, instance, __: self.converter(\n                value, instance\n            )\n        elif not self.takes_self and self.takes_field:\n            self.__call__ = lambda value, __, field: self.converter(\n                value, field\n            )\n        else:\n            self.__call__ = self.converter\n\n        g = f.get_return_type()\n        if g is not None:\n            self.__call__.__annotations__[\"return\"] = g\n\n    @staticmethod\n    def a(h: str) -> str:\n        \"\"\"\n        Return the name that a converter for an attribute name *attr_name*\n        would have.\n        \"\"\"\n        return f\"__attr_converter_{h}\"\n\n    def b(self, i: str, j: str) -> str:\n        \"\"\"\n        Return a string that calls the converter for an attribute name\n        *attr_name* and the value in variable named *value_var* according to\n        `self.takes_self` and `self.takes_field`.\n        \"\"\"\n        if not (self.takes_self or self.takes_field):\n            return f\"{self.a(i)}({j})\"\n\n        if self.takes_self and self.takes_field:\n            return f\"{self.a(i)}({j}, self, attr_dict['{i}'])\"\n\n        if self.takes_self:\n            return f\"{self.a(i)}({j}, self)\"\n\n        return f\"{self.a(i)}({j}, attr_dict['{i}'])\"\n\n    def __getstate__(self):\n        \"\"\"\n        Return a dict containing only converter and takes_self -- the rest gets\n        computed when loading.\n        \"\"\"\n        return {\n            \"converter\": self.converter,\n            \"takes_self\": self.takes_self,\n            \"takes_field\": self.takes_field,\n        }\n\n    def __setstate__(self, k):\n        \"\"\"\n        Load instance from state.\n        \"\"\"\n        self.__init__(**k)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-a437ac55440699ca", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "25e656f01c33fc43f8515bbb524e267834ad36ddcf6186e848f5b4aff0d8c67a", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 125, "local_path": "identifiers/garble-identifiers/I04__attrs__Converter__eb68b117.py", "order": 4, "original_content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "parent_variant_id": "pyint-3e6802a08bd5-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3142-L3237", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 35, "identifiers_declared": 11}, "unit_kind": "class", "unit_name": "Converter", "variant_id": "pyint-bc12eb68b117-I04", "group_id": "py-a437ac55440699ca", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1209, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b8a6026d5e12-I05", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Converter:\n    \"\"\"\n    Stores a converter callable.\n\n    Allows for the wrapped converter to take additional arguments. The\n    arguments are passed in the order they are documented.\n\n    Args:\n        converter (Callable): A callable that converts the passed value.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument. (default: `False`)\n\n        takes_field (bool):\n            Pass the field definition (an :class:`Attribute`) into the\n            converter as a positional argument. (default: `False`)\n\n    .. versionadded:: 24.1.0\n    \"\"\"\n\n    __slots__ = (\n        \"__call__\",\n        \"_first_param_type\",\n        \"_global_name\",\n        \"converter\",\n        \"takes_field\",\n        \"takes_self\",\n    )\n\n    def __init__(self, converter, *, takes_self=False, takes_field=False):\n        self.converter = converter\n        self.takes_self = takes_self\n        self.takes_field = takes_field\n\n        ex = _AnnotationExtractor(converter)\n        self._first_param_type = ex.get_first_param_type()\n\n        if not (self.takes_self or self.takes_field):\n            self.__call__ = lambda value, _, __: self.converter(value)\n        elif self.takes_self and not self.takes_field:\n            self.__call__ = lambda value, instance, __: self.converter(\n                value, instance\n            )\n        elif not self.takes_self and self.takes_field:\n            self.__call__ = lambda value, __, field: self.converter(\n                value, field\n            )\n        else:\n            self.__call__ = self.converter\n\n        rt = ex.get_return_type()\n        if rt is not None:\n            self.__call__.__annotations__[\"return\"] = rt\n\n    @staticmethod\n    def _get_global_name(attr_name: str) -> str:\n        \"\"\"\n        Return the name that a converter for an attribute name *attr_name*\n        would have.\n        \"\"\"\n        return f\"__attr_converter_{attr_name}\"\n\n    def _fmt_converter_call(self, attr_name: str, value_var: str) -> str:\n        \"\"\"\n        Return a string that calls the converter for an attribute name\n        *attr_name* and the value in variable named *value_var* according to\n        `self.takes_self` and `self.takes_field`.\n        \"\"\"\n        if not (self.takes_self or self.takes_field):\n            return f\"{self._get_global_name(attr_name)}({value_var})\"\n\n        if self.takes_self and self.takes_field:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])\"\n\n        if self.takes_self:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self)\"\n\n        return f\"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])\"\n\n    def __getstate__(self):\n        \"\"\"\n        Return a dict containing only converter and takes_self -- the rest gets\n        computed when loading.\n        \"\"\"\n        return {\n            \"converter\": self.converter,\n            \"takes_self\": self.takes_self,\n            \"takes_field\": self.takes_field,\n        }\n\n    def __setstate__(self, state):\n        \"\"\"\n        Load instance from state.\n        \"\"\"\n        self.__init__(**state)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-a437ac55440699ca", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 125, "local_path": "expressions/encode-integer-literals/I05__attrs__Converter__026d5e12.py", "order": 5, "original_content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "parent_variant_id": "pyint-3e6802a08bd5-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3142-L3237", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "Converter", "variant_id": "pyint-b8a6026d5e12-I05", "group_id": "py-a437ac55440699ca", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1210, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-38d2e01c1054-I06", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Converter:\n    \"\"\"\n    Stores a converter callable.\n\n    Allows for the wrapped converter to take additional arguments. The\n    arguments are passed in the order they are documented.\n\n    Args:\n        converter (Callable): A callable that converts the passed value.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument. (default: `False`)\n\n        takes_field (bool):\n            Pass the field definition (an :class:`Attribute`) into the\n            converter as a positional argument. (default: `False`)\n\n    .. versionadded:: 24.1.0\n    \"\"\"\n\n    __slots__ = (\n        \"__call__\",\n        \"_first_param_type\",\n        \"_global_name\",\n        \"converter\",\n        \"takes_field\",\n        \"takes_self\",\n    )\n\n    def __init__(self, converter, *, takes_self=False, takes_field=False):\n        self.converter = converter\n        self.takes_self = takes_self\n        self.takes_field = takes_field\n\n        ex = _AnnotationExtractor(converter)\n        self._first_param_type = ex.get_first_param_type()\n\n        if not (self.takes_self or self.takes_field):\n            self.__call__ = lambda value, _, __: self.converter(value)\n        elif self.takes_self and not self.takes_field:\n            self.__call__ = lambda value, instance, __: self.converter(\n                value, instance\n            )\n        elif not self.takes_self and self.takes_field:\n            self.__call__ = lambda value, __, field: self.converter(\n                value, field\n            )\n        else:\n            self.__call__ = self.converter\n\n        rt = ex.get_return_type()\n        if not (rt is not None):\n            pass\n        else:\n            self.__call__.__annotations__[\"return\"] = rt\n\n    @staticmethod\n    def _get_global_name(attr_name: str) -> str:\n        \"\"\"\n        Return the name that a converter for an attribute name *attr_name*\n        would have.\n        \"\"\"\n        return f\"__attr_converter_{attr_name}\"\n\n    def _fmt_converter_call(self, attr_name: str, value_var: str) -> str:\n        \"\"\"\n        Return a string that calls the converter for an attribute name\n        *attr_name* and the value in variable named *value_var* according to\n        `self.takes_self` and `self.takes_field`.\n        \"\"\"\n        if not (not (self.takes_self or self.takes_field)):\n            pass\n        else:\n            return f\"{self._get_global_name(attr_name)}({value_var})\"\n\n        if not (self.takes_self and self.takes_field):\n            pass\n        else:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])\"\n\n        if not (self.takes_self):\n            pass\n        else:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self)\"\n\n        return f\"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])\"\n\n    def __getstate__(self):\n        \"\"\"\n        Return a dict containing only converter and takes_self -- the rest gets\n        computed when loading.\n        \"\"\"\n        return {\n            \"converter\": self.converter,\n            \"takes_self\": self.takes_self,\n            \"takes_field\": self.takes_field,\n        }\n\n    def __setstate__(self, state):\n        \"\"\"\n        Load instance from state.\n        \"\"\"\n        self.__init__(**state)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-a437ac55440699ca", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "d2bc1c1cb8cec923edeeae4bd9e35324db454e1b8ff1ae52f7b08572176dde6c", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 133, "local_path": "expressions/invert-conditions/I06__attrs__Converter__e01c1054.py", "order": 6, "original_content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "parent_variant_id": "pyint-3e6802a08bd5-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3142-L3237", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 4}, "unit_kind": "class", "unit_name": "Converter", "variant_id": "pyint-38d2e01c1054-I06", "group_id": "py-a437ac55440699ca", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1211, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c78b32659a04-I07", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Converter:\n    \"\"\"\n    Stores a converter callable.\n\n    Allows for the wrapped converter to take additional arguments. The\n    arguments are passed in the order they are documented.\n\n    Args:\n        converter (Callable): A callable that converts the passed value.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument. (default: `False`)\n\n        takes_field (bool):\n            Pass the field definition (an :class:`Attribute`) into the\n            converter as a positional argument. (default: `False`)\n\n    .. versionadded:: 24.1.0\n    \"\"\"\n\n    __slots__ = (\n        \"__call__\",\n        \"_first_param_type\",\n        \"_global_name\",\n        \"converter\",\n        \"takes_field\",\n        \"takes_self\",\n    )\n\n    def __init__(self, converter, *, takes_self=False, takes_field=False):\n        if ((0xf42e ^ 0xf42e) != 0):\n            raise AssertionError()\n        self.converter = converter\n        self.takes_self = takes_self\n        self.takes_field = takes_field\n\n        ex = _AnnotationExtractor(converter)\n        self._first_param_type = ex.get_first_param_type()\n\n        if not (self.takes_self or self.takes_field):\n            self.__call__ = lambda value, _, __: self.converter(value)\n        elif self.takes_self and not self.takes_field:\n            self.__call__ = lambda value, instance, __: self.converter(\n                value, instance\n            )\n        elif not self.takes_self and self.takes_field:\n            self.__call__ = lambda value, __, field: self.converter(\n                value, field\n            )\n        else:\n            self.__call__ = self.converter\n\n        rt = ex.get_return_type()\n        if rt is not None:\n            self.__call__.__annotations__[\"return\"] = rt\n\n    @staticmethod\n    def _get_global_name(attr_name: str) -> str:\n        \"\"\"\n        Return the name that a converter for an attribute name *attr_name*\n        would have.\n        \"\"\"\n        if ((0x6240 ^ 0x6240) != 0):\n            raise AssertionError()\n        return f\"__attr_converter_{attr_name}\"\n\n    def _fmt_converter_call(self, attr_name: str, value_var: str) -> str:\n        \"\"\"\n        Return a string that calls the converter for an attribute name\n        *attr_name* and the value in variable named *value_var* according to\n        `self.takes_self` and `self.takes_field`.\n        \"\"\"\n        if ((0x71f ^ 0x71f) != 0):\n            raise AssertionError()\n        if not (self.takes_self or self.takes_field):\n            return f\"{self._get_global_name(attr_name)}({value_var})\"\n\n        if self.takes_self and self.takes_field:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])\"\n\n        if self.takes_self:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self)\"\n\n        return f\"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])\"\n\n    def __getstate__(self):\n        \"\"\"\n        Return a dict containing only converter and takes_self -- the rest gets\n        computed when loading.\n        \"\"\"\n        if ((0xeaa ^ 0xeaa) != 0):\n            raise AssertionError()\n        return {\n            \"converter\": self.converter,\n            \"takes_self\": self.takes_self,\n            \"takes_field\": self.takes_field,\n        }\n\n    def __setstate__(self, state):\n        \"\"\"\n        Load instance from state.\n        \"\"\"\n        if ((0x4bee ^ 0x4bee) != 0):\n            raise AssertionError()\n        self.__init__(**state)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-a437ac55440699ca", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "457c8affc82f8063f862498159bc43b5dd46b07f809fbd35d6610b954f20c1b7", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 135, "local_path": "code-injection/insert-dead-branches/I07__attrs__Converter__32659a04.py", "order": 7, "original_content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "parent_variant_id": "pyint-3e6802a08bd5-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3142-L3237", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 5}, "unit_kind": "class", "unit_name": "Converter", "variant_id": "pyint-c78b32659a04-I07", "group_id": "py-a437ac55440699ca", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1212, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7b384563d721-I08", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Converter:\n    \"\"\"\n    Stores a converter callable.\n\n    Allows for the wrapped converter to take additional arguments. The\n    arguments are passed in the order they are documented.\n\n    Args:\n        converter (Callable): A callable that converts the passed value.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument. (default: `False`)\n\n        takes_field (bool):\n            Pass the field definition (an :class:`Attribute`) into the\n            converter as a positional argument. (default: `False`)\n\n    .. versionadded:: 24.1.0\n    \"\"\"\n\n    __slots__ = (\n        \"__call__\",\n        \"_first_param_type\",\n        \"_global_name\",\n        \"converter\",\n        \"takes_field\",\n        \"takes_self\",\n    )\n\n    def __init__(self, converter, *, takes_self=False, takes_field=False):\n        self.converter = converter\n        self.takes_self = takes_self\n        self.takes_field = takes_field\n\n        ex = _AnnotationExtractor(converter)\n        self._first_param_type = ex.get_first_param_type()\n\n        if not (self.takes_self or self.takes_field):\n            self.__call__ = lambda value, _, __: self.converter(value)\n        elif self.takes_self and not self.takes_field:\n            self.__call__ = lambda value, instance, __: self.converter(\n                value, instance\n            )\n        elif not self.takes_self and self.takes_field:\n            self.__call__ = lambda value, __, field: self.converter(\n                value, field\n            )\n        else:\n            self.__call__ = self.converter\n\n        rt = ex.get_return_type()\n        if rt is not None:\n            self.__call__.__annotations__[\"return\"] = rt\n\n    @staticmethod\n    def _get_global_name(attr_name: str) -> str:\n        \"\"\"\n        Return the name that a converter for an attribute name *attr_name*\n        would have.\n        \"\"\"\n        return f\"__attr_converter_{attr_name}\"\n\n    def _fmt_converter_call(self, attr_name: str, value_var: str) -> str:\n        \"\"\"\n        Return a string that calls the converter for an attribute name\n        *attr_name* and the value in variable named *value_var* according to\n        `self.takes_self` and `self.takes_field`.\n        \"\"\"\n        if not (self.takes_self or self.takes_field):\n            return f\"{self._get_global_name(attr_name)}({value_var})\"\n\n        if self.takes_self and self.takes_field:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])\"\n\n        if self.takes_self:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self)\"\n\n        return f\"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])\"\n\n    def __getstate__(self):\n        \"\"\"\n        Return a dict containing only converter and takes_self -- the rest gets\n        computed when loading.\n        \"\"\"\n        return {\n            \"converter\": self.converter,\n            \"takes_self\": self.takes_self,\n            \"takes_field\": self.takes_field,\n        }\n\n    def __setstate__(self, state):\n        \"\"\"\n        Load instance from state.\n        \"\"\"\n        first_score = 72\n        second_score = 85\n        if first_score > second_score:\n            higher_score = first_score\n        else:\n            higher_score = second_score\n        self.__init__(**state)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-a437ac55440699ca", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "612a19ee5a25e476ac4699428c0535ef1b0c9b85c8ae9d98c1798c3a8b938ac5", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 131, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs__Converter__4563d721.py", "order": 8, "original_content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "parent_variant_id": "pyint-3e6802a08bd5-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3142-L3237", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 3}, "unit_kind": "class", "unit_name": "Converter", "variant_id": "pyint-7b384563d721-I08", "group_id": "py-a437ac55440699ca", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1213, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e42c771752c3-I09", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Converter:\n    \"\"\"\n    Stores a converter callable.\n\n    Allows for the wrapped converter to take additional arguments. The\n    arguments are passed in the order they are documented.\n\n    Args:\n        converter (Callable): A callable that converts the passed value.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument. (default: `False`)\n\n        takes_field (bool):\n            Pass the field definition (an :class:`Attribute`) into the\n            converter as a positional argument. (default: `False`)\n\n    .. versionadded:: 24.1.0\n    \"\"\"\n\n    __slots__ = (\n        \"__call__\",\n        \"_first_param_type\",\n        \"_global_name\",\n        \"converter\",\n        \"takes_field\",\n        \"takes_self\",\n    )\n\n    def __init__(self, converter, *, takes_self=False, takes_field=False):\n        self.converter = converter\n        self.takes_self = takes_self\n        self.takes_field = takes_field\n\n        ex = _AnnotationExtractor(converter)\n        self._first_param_type = ex.get_first_param_type()\n\n        if not (self.takes_self or self.takes_field):\n            self.__call__ = lambda value, _, __: self.converter(value)\n        elif self.takes_self and not self.takes_field:\n            self.__call__ = lambda value, instance, __: self.converter(\n                value, instance\n            )\n        elif not self.takes_self and self.takes_field:\n            self.__call__ = lambda value, __, field: self.converter(\n                value, field\n            )\n        else:\n            self.__call__ = self.converter\n\n        rt = ex.get_return_type()\n        if rt is not None:\n            self.__call__.__annotations__[\"return\"] = rt\n\n    @staticmethod\n    def _get_global_name(attr_name: str) -> str:\n        \"\"\"\n        Return the name that a converter for an attribute name *attr_name*\n        would have.\n        \"\"\"\n        return f\"__attr_converter_{attr_name}\"\n\n    def _fmt_converter_call(self, attr_name: str, value_var: str) -> str:\n        \"\"\"\n        Return a string that calls the converter for an attribute name\n        *attr_name* and the value in variable named *value_var* according to\n        `self.takes_self` and `self.takes_field`.\n        \"\"\"\n        if not (self.takes_self or self.takes_field):\n            return f\"{self._get_global_name(attr_name)}({value_var})\"\n\n        if self.takes_self and self.takes_field:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])\"\n\n        if self.takes_self:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self)\"\n\n        return f\"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])\"\n\n    def __getstate__(self):\n        \"\"\"\n        Return a dict containing only converter and takes_self -- the rest gets\n        computed when loading.\n        \"\"\"\n        return {\n            \"converter\": self.converter,\n            \"takes_self\": self.takes_self,\n            \"takes_field\": self.takes_field,\n        }\n\n    def __setstate__(self, state):\n        \"\"\"\n        Load instance from state.\n        \"\"\"\n        lI0O_247fe2c7 = ((0xc74a ^ 0xc74a) != 0)\n        lI0O_247fe2c7 = not (not lI0O_247fe2c7)\n        self.__init__(**state)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-a437ac55440699ca", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d3f23885061031568b65c0dbb004a1f06fe797eeef8abe544bc7b55af9a91acd", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 127, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs__Converter__771752c3.py", "order": 9, "original_content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "parent_variant_id": "pyint-3e6802a08bd5-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3142-L3237", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 4}, "unit_kind": "class", "unit_name": "Converter", "variant_id": "pyint-e42c771752c3-I09", "group_id": "py-a437ac55440699ca", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1214, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4c3b58458c6f-I10", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (     PY_3_11_PLUS,\n    PY_3_13_PLUS,     _AnnotationExtractor,\n    _get_annotations,     _lazy_is_generator,\n    get_generic_base, )\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,     NotAnAttrsClassError,     UnannotatedAttributeError,\n)\n\nclass Converter:\n    \"\"\"\n    Stores a converter callable.\n\n    Allows for the wrapped converter to take additional arguments. The\n    arguments are passed in the order they are documented.\n    Args:\n        converter (Callable): A callable that converts the passed value.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument. (default: `False`)\n\n        takes_field (bool):\n            Pass the field definition (an :class:`Attribute`) into the\n            converter as a positional argument. (default: `False`)\n\n    .. versionadded:: 24.1.0\n    \"\"\"\n    __slots__ = (\n        \"__call__\",\n        \"_first_param_type\",\n        \"_global_name\",\n        \"converter\",\n        \"takes_field\",\n        \"takes_self\",\n    )\n    def __init__(self, converter, *, takes_self=False, takes_field=False):\n        self.converter = converter\n        self.takes_self = takes_self\n        self.takes_field = takes_field\n\n        ex = _AnnotationExtractor(converter)\n        self._first_param_type = ex.get_first_param_type()\n\n        if not (self.takes_self or self.takes_field):\n            self.__call__ = lambda value, _, __: self.converter(value)\n        elif self.takes_self and not self.takes_field:\n            self.__call__ = lambda value, instance, __: self.converter(\n                value, instance             )\n        elif not self.takes_self and self.takes_field:\n            self.__call__ = lambda value, __, field: self.converter(\n                value, field             )\n        else:\n            self.__call__ = self.converter\n        rt = ex.get_return_type()\n        if rt is not None:\n            self.__call__.__annotations__[\"return\"] = rt\n\n    @staticmethod\n    def _get_global_name(attr_name: str) -> str:\n        \"\"\"\n        Return the name that a converter for an attribute name *attr_name*\n        would have.\n        \"\"\"\n        return f\"__attr_converter_{attr_name}\"\n    def _fmt_converter_call(self, attr_name: str, value_var: str) -> str:\n        \"\"\"\n        Return a string that calls the converter for an attribute name\n        *attr_name* and the value in variable named *value_var* according to\n        `self.takes_self` and `self.takes_field`.\n        \"\"\"\n        if not (self.takes_self or self.takes_field):\n            return f\"{self._get_global_name(attr_name)}({value_var})\"\n\n        if self.takes_self and self.takes_field:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])\"\n        if self.takes_self:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self)\"\n\n        return f\"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])\"\n    def __getstate__(self):\n        \"\"\"\n        Return a dict containing only converter and takes_self -- the rest gets\n        computed when loading.\n        \"\"\"\n        return {\n            \"converter\": self.converter,             \"takes_self\": self.takes_self,\n            \"takes_field\": self.takes_field,         }\n    def __setstate__(self, state):\n        \"\"\"\n        Load instance from state.\n        \"\"\"\n        self.__init__(**state)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-a437ac55440699ca", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "4f22f5af7a158210175825aa2a74cf859fa778f73b4020c63dfbb9ec4dcaf9d0", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 107, "local_path": "layout/partially-compact-layout/I10__attrs__Converter__58458c6f.py", "order": 10, "original_content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "parent_variant_id": "pyint-3e6802a08bd5-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3142-L3237", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 45, "line_break_groups_removed": 18, "line_breaks_removed": 18, "whitespace_characters_removed": 8}, "unit_kind": "class", "unit_name": "Converter", "variant_id": "pyint-4c3b58458c6f-I10", "group_id": "py-a437ac55440699ca", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1215, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-88a4e0553833-I11", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Converter:\n    \"\"\"\n    Stores a converter callable.\n\n    Allows for the wrapped converter to take additional arguments. The\n    arguments are passed in the order they are documented.\n\n    Args:\n        converter (Callable): A callable that converts the passed value.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument. (default: `False`)\n\n        takes_field (bool):\n            Pass the field definition (an :class:`Attribute`) into the\n            converter as a positional argument. (default: `False`)\n\n    .. versionadded:: 24.1.0\n    \"\"\"\n\n    __slots__ = (\n        \"__call__\",\n        \"_first_param_type\",\n        \"_global_name\",\n        \"converter\",\n        \"takes_field\",\n        \"takes_self\",\n    )\n\n    def __init__(self, converter, *, takes_self=False, takes_field=False):\n        self.converter = converter\n        self.takes_self = takes_self\n        self.takes_field = takes_field\n\n        ex = _AnnotationExtractor(converter)\n        self._first_param_type = ex.get_first_param_type()\n\n        if not (self.takes_self or self.takes_field):\n            self.__call__ = lambda value, _, __: self.converter(value)\n        elif self.takes_self and not self.takes_field:\n            self.__call__ = lambda value, instance, __: self.converter(\n                value, instance\n            )\n        elif not self.takes_self and self.takes_field:\n            self.__call__ = lambda value, __, field: self.converter(\n                value, field\n            )\n        else:\n            self.__call__ = self.converter\n\n        rt = ex.get_return_type()\n        if rt is not None:\n            self.__call__.__annotations__[\"return\"] = rt\n\n    @staticmethod\n    def _get_global_name(attr_name: str) -> str:\n        \"\"\"\n        Return the name that a converter for an attribute name *attr_name*\n        would have.\n        \"\"\"\n        return f\"__attr_converter_{attr_name}\"\n\n    def _fmt_converter_call(self, attr_name: str, value_var: str) -> str:\n        \"\"\"\n        Return a string that calls the converter for an attribute name\n        *attr_name* and the value in variable named *value_var* according to\n        `self.takes_self` and `self.takes_field`.\n        \"\"\"\n        if not (self.takes_self or self.takes_field):\n            return f\"{self._get_global_name(attr_name)}({value_var})\"\n\n        if self.takes_self and self.takes_field:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])\"\n\n        if self.takes_self:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self)\"\n\n        return f\"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])\"\n\n    def __getstate__(self):\n        \"\"\"\n        Return a dict containing only converter and takes_self -- the rest gets\n        computed when loading.\n        \"\"\"\n        return {\n            \"converter\": self.converter,\n            \"takes_self\": self.takes_self,\n            \"takes_field\": self.takes_field,\n        }\n\n    def __setstate__(self, state):\n        \"\"\"\n        Load instance from state.\n        \"\"\"\n        self.__init__(**state)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-a437ac55440699ca", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 125, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs__Converter__e0553833.py", "order": 11, "original_content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "parent_variant_id": "pyint-3e6802a08bd5-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3142-L3237", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "Converter", "variant_id": "pyint-88a4e0553833-I11", "group_id": "py-a437ac55440699ca", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1216, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d8cdbb59806a-I12", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Converter:\n    \"\"\"\n    Stores a converter callable.\n\n    Allows for the wrapped converter to take additional arguments. The\n    arguments are passed in the order they are documented.\n\n    Args:\n        converter (Callable): A callable that converts the passed value.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument. (default: `False`)\n\n        takes_field (bool):\n            Pass the field definition (an :class:`Attribute`) into the\n            converter as a positional argument. (default: `False`)\n\n    .. versionadded:: 24.1.0\n    \"\"\"\n\n    __slots__ = (\n        \"__call__\",\n        \"_first_param_type\",\n        \"_global_name\",\n        \"converter\",\n        \"takes_field\",\n        \"takes_self\",\n    )\n\n    def __init__(self, converter, *, takes_self=False, takes_field=False):\n        self.converter = converter\n        self.takes_self = takes_self\n        self.takes_field = takes_field\n\n        ex = _AnnotationExtractor(converter)\n        self._first_param_type = ex.get_first_param_type()\n\n        if not (self.takes_self or self.takes_field):\n            self.__call__ = lambda value, _, __: self.converter(value)\n        elif self.takes_self and not self.takes_field:\n            self.__call__ = lambda value, instance, __: self.converter(\n                value, instance\n            )\n        elif not self.takes_self and self.takes_field:\n            self.__call__ = lambda value, __, field: self.converter(\n                value, field\n            )\n        else:\n            self.__call__ = self.converter\n\n        rt = ex.get_return_type()\n        if rt is not None:\n            self.__call__.__annotations__[\"return\"] = rt\n\n    @staticmethod\n    def _get_global_name(attr_name: str) -> str:\n        \"\"\"\n        Return the name that a converter for an attribute name *attr_name*\n        would have.\n        \"\"\"\n        return f\"__attr_converter_{attr_name}\"\n\n    def _fmt_converter_call(self, attr_name: str, value_var: str) -> str:\n        \"\"\"\n        Return a string that calls the converter for an attribute name\n        *attr_name* and the value in variable named *value_var* according to\n        `self.takes_self` and `self.takes_field`.\n        \"\"\"\n        if not (self.takes_self or self.takes_field):\n            return f\"{self._get_global_name(attr_name)}({value_var})\"\n\n        if self.takes_self and self.takes_field:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])\"\n\n        if self.takes_self:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self)\"\n\n        return f\"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])\"\n\n    def __getstate__(self):\n        \"\"\"\n        Return a dict containing only converter and takes_self -- the rest gets\n        computed when loading.\n        \"\"\"\n        return {\n            \"converter\": self.converter,\n            \"takes_self\": self.takes_self,\n            \"takes_field\": self.takes_field,\n        }\n\n    def __setstate__(self, state):\n        \"\"\"\n        Load instance from state.\n        \"\"\"\n        self.__init__(**state)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-a437ac55440699ca", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 125, "local_path": "data-flow/inline-intermediate-variables/I12__attrs__Converter__bb59806a.py", "order": 12, "original_content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "parent_variant_id": "pyint-3e6802a08bd5-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3142-L3237", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Converter", "variant_id": "pyint-d8cdbb59806a-I12", "group_id": "py-a437ac55440699ca", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1217, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cc6ba1c10797-I13", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Converter:\n    \"\"\"\n    Stores a converter callable.\n\n    Allows for the wrapped converter to take additional arguments. The\n    arguments are passed in the order they are documented.\n\n    Args:\n        converter (Callable): A callable that converts the passed value.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument. (default: `False`)\n\n        takes_field (bool):\n            Pass the field definition (an :class:`Attribute`) into the\n            converter as a positional argument. (default: `False`)\n\n    .. versionadded:: 24.1.0\n    \"\"\"\n\n    __slots__ = (\n        \"__call__\",\n        \"_first_param_type\",\n        \"_global_name\",\n        \"converter\",\n        \"takes_field\",\n        \"takes_self\",\n    )\n\n    def __init__(self, converter, *, takes_self=False, takes_field=False):\n        self.converter = converter\n        self.takes_self = takes_self\n        self.takes_field = takes_field\n\n        ex = _AnnotationExtractor(converter)\n        self._first_param_type = ex.get_first_param_type()\n\n        if not (self.takes_self or self.takes_field):\n            self.__call__ = lambda value, _, __: self.converter(value)\n        elif self.takes_self and not self.takes_field:\n            self.__call__ = lambda value, instance, __: self.converter(\n                value, instance\n            )\n        elif not self.takes_self and self.takes_field:\n            self.__call__ = lambda value, __, field: self.converter(\n                value, field\n            )\n        else:\n            self.__call__ = self.converter\n\n        rt = ex.get_return_type()\n        if rt is not None:\n            self.__call__.__annotations__[\"return\"] = rt\n\n    @staticmethod\n    def _get_global_name(attr_name: str) -> str:\n        \"\"\"\n        Return the name that a converter for an attribute name *attr_name*\n        would have.\n        \"\"\"\n        return f\"__attr_converter_{attr_name}\"\n\n    def _fmt_converter_call(self, attr_name: str, value_var: str) -> str:\n        \"\"\"\n        Return a string that calls the converter for an attribute name\n        *attr_name* and the value in variable named *value_var* according to\n        `self.takes_self` and `self.takes_field`.\n        \"\"\"\n        if not (self.takes_self or self.takes_field):\n            return f\"{self._get_global_name(attr_name)}({value_var})\"\n\n        if self.takes_self and self.takes_field:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])\"\n\n        if self.takes_self:\n            return f\"{self._get_global_name(attr_name)}({value_var}, self)\"\n\n        return f\"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])\"\n\n    def __getstate__(self):\n        \"\"\"\n        Return a dict containing only converter and takes_self -- the rest gets\n        computed when loading.\n        \"\"\"\n        return {\n            \"converter\": self.converter,\n            \"takes_self\": self.takes_self,\n            \"takes_field\": self.takes_field,\n        }\n\n    def __setstate__(self, state):\n        \"\"\"\n        Load instance from state.\n        \"\"\"\n        self.__init__(**state)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-a437ac55440699ca", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 125, "local_path": "control-flow/lower-for-to-while/I13__attrs__Converter__a1c10797.py", "order": 13, "original_content_sha256": "d7e10cfdb0bf3e7968782db4e28b38052239ddc60b3012b9c103e0e22a41d93f", "parent_variant_id": "pyint-3e6802a08bd5-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3142-L3237", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "Converter", "variant_id": "pyint-cc6ba1c10797-I13", "group_id": "py-a437ac55440699ca", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1218, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-877b5604eff7-SRC", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-ad6200d6ecb454e0", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 20, "local_path": "source-original/SRC__requests__HTTPProxyAuth__5604eff7.py", "order": 0, "original_content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L116-L121", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "HTTPProxyAuth", "variant_id": "pyint-877b5604eff7-SRC", "group_id": "py-ad6200d6ecb454e0", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 771, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5d5c88e0b604-I01", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-ad6200d6ecb454e0", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "92ed26cc9c2d56b14802390549fb9093d2df46d73776a73f1342b4770d30c0c7", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 20, "local_path": "comments/remove-comments/I01__requests__HTTPProxyAuth__88e0b604.py", "order": 1, "original_content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "parent_variant_id": "pyint-877b5604eff7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L116-L121", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 67, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "HTTPProxyAuth", "variant_id": "pyint-5d5c88e0b604-I01", "group_id": "py-ad6200d6ecb454e0", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 772, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8428e68ce8fa-I02", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, r2: PreparedRequest) -> PreparedRequest:\n        r2.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r2\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-ad6200d6ecb454e0", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "ac06a06ce76fb70381f7113dfdc729b12412f1d46ce7ba5aee4714f54f88487c", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 20, "local_path": "identifiers/shorten-identifiers/I02__requests__HTTPProxyAuth__e68ce8fa.py", "order": 2, "original_content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "parent_variant_id": "pyint-877b5604eff7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L116-L121", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 3, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "HTTPProxyAuth", "variant_id": "pyint-8428e68ce8fa-I02", "group_id": "py-ad6200d6ecb454e0", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 773, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-40b0df5d0cc5-I03", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, map: PreparedRequest) -> PreparedRequest:\n        map.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return map\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-ad6200d6ecb454e0", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "a7f4338733370c11494c4df0f4d43dc87c72495b4d809ea9622ae481422eb1cc", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 20, "local_path": "identifiers/mislead-identifiers/I03__requests__HTTPProxyAuth__df5d0cc5.py", "order": 3, "original_content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "parent_variant_id": "pyint-877b5604eff7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L116-L121", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 3, "identifiers_declared": 1, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 0, "local_random_pool_selections": 1, "local_total_length_difference": 2, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "HTTPProxyAuth", "variant_id": "pyint-40b0df5d0cc5-I03", "group_id": "py-ad6200d6ecb454e0", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 774, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c8b1c76a1e1b-I04", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, a: PreparedRequest) -> PreparedRequest:\n        a.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return a\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-ad6200d6ecb454e0", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "0c1e35ef53610138e6ff39ba2adbc041c5bf9337353b23880908141a94182153", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 20, "local_path": "identifiers/garble-identifiers/I04__requests__HTTPProxyAuth__c76a1e1b.py", "order": 4, "original_content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "parent_variant_id": "pyint-877b5604eff7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L116-L121", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 3, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "HTTPProxyAuth", "variant_id": "pyint-c8b1c76a1e1b-I04", "group_id": "py-ad6200d6ecb454e0", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 775, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-df041c92f2b5-I05", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-ad6200d6ecb454e0", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 20, "local_path": "expressions/encode-integer-literals/I05__requests__HTTPProxyAuth__1c92f2b5.py", "order": 5, "original_content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "parent_variant_id": "pyint-877b5604eff7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L116-L121", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "HTTPProxyAuth", "variant_id": "pyint-df041c92f2b5-I05", "group_id": "py-ad6200d6ecb454e0", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 776, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-45c1c25a3bfc-I06", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-ad6200d6ecb454e0", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 20, "local_path": "expressions/invert-conditions/I06__requests__HTTPProxyAuth__c25a3bfc.py", "order": 6, "original_content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "parent_variant_id": "pyint-877b5604eff7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L116-L121", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "HTTPProxyAuth", "variant_id": "pyint-45c1c25a3bfc-I06", "group_id": "py-ad6200d6ecb454e0", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 777, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-51972080ace0-I07", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        if ((0x1a65 ^ 0x1a65) != 0):\n            raise AssertionError()\n        r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-ad6200d6ecb454e0", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "164e0b11185ab2a705ee4fc4dea04c767ed8bd6b850f6fab46d6db96d4b2f44a", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 22, "local_path": "code-injection/insert-dead-branches/I07__requests__HTTPProxyAuth__2080ace0.py", "order": 7, "original_content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "parent_variant_id": "pyint-877b5604eff7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L116-L121", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "HTTPProxyAuth", "variant_id": "pyint-51972080ace0-I07", "group_id": "py-ad6200d6ecb454e0", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 778, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-27d6e0ad930b-I08", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        running_total = 0\n        for current_number in range(1, 6):\n            running_total += current_number\n        r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-ad6200d6ecb454e0", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "5c393c63287b316cadb30d2cc961a74e078b6885438a44ccb8fcecc70d3fe5d6", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 23, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__HTTPProxyAuth__e0ad930b.py", "order": 8, "original_content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "parent_variant_id": "pyint-877b5604eff7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L116-L121", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 0}, "unit_kind": "class", "unit_name": "HTTPProxyAuth", "variant_id": "pyint-27d6e0ad930b-I08", "group_id": "py-ad6200d6ecb454e0", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 779, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-afbe838b1233-I09", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        lI0O_52e8e2cb, lI0O_5667c108 = 0, 0\n        while lI0O_5667c108 < 2:\n            lI0O_52e8e2cb ^= (lI0O_5667c108 << 1) ^ 0x7\n            lI0O_5667c108 += 1\n        lI0O_52e8e2cb ^= lI0O_52e8e2cb\n        r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-ad6200d6ecb454e0", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d9498f4dc2a46bbec688a2d9c3b18e537ad2d2ec54054b8637fc880a0f496784", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 25, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__HTTPProxyAuth__838b1233.py", "order": 9, "original_content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "parent_variant_id": "pyint-877b5604eff7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L116-L121", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 2}, "unit_kind": "class", "unit_name": "HTTPProxyAuth", "variant_id": "pyint-afbe838b1233-I09", "group_id": "py-ad6200d6ecb454e0", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 780, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c2bf25a67a1f-I10", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-ad6200d6ecb454e0", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 20, "local_path": "layout/partially-compact-layout/I10__requests__HTTPProxyAuth__25a67a1f.py", "order": 10, "original_content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "parent_variant_id": "pyint-877b5604eff7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L116-L121", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 2, "line_break_groups_removed": 0, "line_breaks_removed": 0, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "HTTPProxyAuth", "variant_id": "pyint-c2bf25a67a1f-I10", "group_id": "py-ad6200d6ecb454e0", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 781, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b51c1223fae8-I11", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-ad6200d6ecb454e0", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 20, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__HTTPProxyAuth__1223fae8.py", "order": 11, "original_content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "parent_variant_id": "pyint-877b5604eff7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L116-L121", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "HTTPProxyAuth", "variant_id": "pyint-b51c1223fae8-I11", "group_id": "py-ad6200d6ecb454e0", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 782, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d140974b8ee0-I12", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-ad6200d6ecb454e0", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 20, "local_path": "data-flow/inline-intermediate-variables/I12__requests__HTTPProxyAuth__974b8ee0.py", "order": 12, "original_content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "parent_variant_id": "pyint-877b5604eff7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L116-L121", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "HTTPProxyAuth", "variant_id": "pyint-d140974b8ee0-I12", "group_id": "py-ad6200d6ecb454e0", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 783, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c5faab6220db-I13", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-ad6200d6ecb454e0", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 20, "local_path": "control-flow/lower-for-to-while/I13__requests__HTTPProxyAuth__ab6220db.py", "order": 13, "original_content_sha256": "2611d0fe04d9e8688086d0ec2b9e22c24772dc48531f4eacdf27eb2cbaa9f750", "parent_variant_id": "pyint-877b5604eff7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L116-L121", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "HTTPProxyAuth", "variant_id": "pyint-c5faab6220db-I13", "group_id": "py-ad6200d6ecb454e0", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 784, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-203033a416af-SRC", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass View:\n    \"\"\"Subclass this class and override :meth:`dispatch_request` to\n    create a generic class-based view. Call :meth:`as_view` to create a\n    view function that creates an instance of the class with the given\n    arguments and calls its ``dispatch_request`` method with any URL\n    variables.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class Hello(View):\n            init_every_request = False\n\n            def dispatch_request(self, name):\n                return f\"Hello, {name}!\"\n\n        app.add_url_rule(\n            \"/hello/<name>\", view_func=Hello.as_view(\"hello\")\n        )\n\n    Set :attr:`methods` on the class to change what methods the view\n    accepts.\n\n    Set :attr:`decorators` on the class to apply a list of decorators to\n    the generated view function. Decorators applied to the class itself\n    will not be applied to the generated view function!\n\n    Set :attr:`init_every_request` to ``False`` for efficiency, unless\n    you need to store request-global data on ``self``.\n    \"\"\"\n\n    #: The methods this view is registered for. Uses the same default\n    #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    methods: t.ClassVar[t.Collection[str] | None] = None\n\n    #: Control whether the ``OPTIONS`` method is handled automatically.\n    #: Uses the same default (``True``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    provide_automatic_options: t.ClassVar[bool | None] = None\n\n    #: A list of decorators to apply, in order, to the generated view\n    #: function. Remember that ``@decorator`` syntax is applied bottom\n    #: to top, so the first decorator in the list would be the bottom\n    #: decorator.\n    #:\n    #: .. versionadded:: 0.8\n    decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []\n\n    #: Create a new instance of this view class for every request by\n    #: default. If a view subclass sets this to ``False``, the same\n    #: instance is used for every request.\n    #:\n    #: A single instance is more efficient, especially if complex setup\n    #: is done during init. However, storing data on ``self`` is no\n    #: longer safe across requests, and :data:`~flask.g` should be used\n    #: instead.\n    #:\n    #: .. versionadded:: 2.2\n    init_every_request: t.ClassVar[bool] = True\n\n    def dispatch_request(self) -> ft.ResponseReturnValue:\n        \"\"\"The actual view function behavior. Subclasses must override\n        this and return a valid response. Any variables from the URL\n        rule are passed as keyword arguments.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def as_view(\n        cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n    ) -> ft.RouteCallable:\n        \"\"\"Convert the class into a view function that can be registered\n        for a route.\n\n        By default, the generated view will create a new instance of the\n        view class for every request and call its\n        :meth:`dispatch_request` method. If the view class sets\n        :attr:`init_every_request` to ``False``, the same instance will\n        be used for every request.\n\n        Except for ``name``, all other arguments passed to this method\n        are forwarded to the view class ``__init__`` method.\n\n        .. versionchanged:: 2.2\n            Added the ``init_every_request`` class attribute.\n        \"\"\"\n        if cls.init_every_request:\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                self = view.view_class(  # type: ignore[attr-defined]\n                    *class_args, **class_kwargs\n                )\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        else:\n            self = cls(*class_args, **class_kwargs)  # pyright: ignore\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        if cls.decorators:\n            view.__name__ = name\n            view.__module__ = cls.__module__\n            for decorator in cls.decorators:\n                view = decorator(view)\n\n        # We attach the view class to the view function for two reasons:\n        # first of all it allows us to easily figure out what class-based\n        # view this thing came from, secondly it's also used for instantiating\n        # the view class so you can actually replace it with something else\n        # for testing purposes and debugging.\n        view.view_class = cls  # type: ignore\n        view.__name__ = name\n        view.__doc__ = cls.__doc__\n        view.__module__ = cls.__module__\n        view.methods = cls.methods  # type: ignore\n        view.provide_automatic_options = cls.provide_automatic_options  # type: ignore\n        return view\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-adb6df588c55e9e9", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 126, "local_path": "source-original/SRC__flask__View__33a416af.py", "order": 0, "original_content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L16-L135", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "View", "variant_id": "pyint-203033a416af-SRC", "group_id": "py-adb6df588c55e9e9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 561, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f15a07e9d32a-I01", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass View:\n    \n\n     \n     \n     \n    methods: t.ClassVar[t.Collection[str] | None] = None\n\n     \n     \n     \n    provide_automatic_options: t.ClassVar[bool | None] = None\n\n     \n     \n     \n     \n     \n     \n    decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []\n\n     \n     \n     \n     \n     \n     \n     \n     \n     \n     \n    init_every_request: t.ClassVar[bool] = True\n\n    def dispatch_request(self) -> ft.ResponseReturnValue:\n        \n        raise NotImplementedError()\n\n    @classmethod\n    def as_view(\n        cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n    ) -> ft.RouteCallable:\n        \n        if cls.init_every_request:\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                self = view.view_class(   \n                    *class_args, **class_kwargs\n                )\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)   \n\n        else:\n            self = cls(*class_args, **class_kwargs)   \n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)   \n\n        if cls.decorators:\n            view.__name__ = name\n            view.__module__ = cls.__module__\n            for decorator in cls.decorators:\n                view = decorator(view)\n\n         \n         \n         \n         \n         \n        view.view_class = cls   \n        view.__name__ = name\n        view.__doc__ = cls.__doc__\n        view.__module__ = cls.__module__\n        view.methods = cls.methods   \n        view.provide_automatic_options = cls.provide_automatic_options   \n        return view\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-adb6df588c55e9e9", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "45323f63ad6f3cea3e86f4e1a6ef000671884b91a1442cfcbf59f4ec081c085a", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 80, "local_path": "comments/remove-comments/I01__flask__View__07e9d32a.py", "order": 1, "original_content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "parent_variant_id": "pyint-203033a416af-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L16-L135", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 3193, "comments_removed": 37, "docstrings_removed": 3, "line_comments_removed": 34}, "unit_kind": "class", "unit_name": "View", "variant_id": "pyint-f15a07e9d32a-I01", "group_id": "py-adb6df588c55e9e9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 562, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-784fcf2c7e09-I02", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass View:\n    \"\"\"Subclass this class and override :meth:`dispatch_request` to\n    create a generic class-based view. Call :meth:`as_view` to create a\n    view function that creates an instance of the class with the given\n    arguments and calls its ``dispatch_request`` method with any URL\n    variables.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class Hello(View):\n            init_every_request = False\n\n            def dispatch_request(self, name):\n                return f\"Hello, {name}!\"\n\n        app.add_url_rule(\n            \"/hello/<name>\", view_func=Hello.as_view(\"hello\")\n        )\n\n    Set :attr:`methods` on the class to change what methods the view\n    accepts.\n\n    Set :attr:`decorators` on the class to apply a list of decorators to\n    the generated view function. Decorators applied to the class itself\n    will not be applied to the generated view function!\n\n    Set :attr:`init_every_request` to ``False`` for efficiency, unless\n    you need to store request-global data on ``self``.\n    \"\"\"\n\n    #: The methods this view is registered for. Uses the same default\n    #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    methods: t.ClassVar[t.Collection[str] | None] = None\n\n    #: Control whether the ``OPTIONS`` method is handled automatically.\n    #: Uses the same default (``True``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    provide_automatic_options: t.ClassVar[bool | None] = None\n\n    #: A list of decorators to apply, in order, to the generated view\n    #: function. Remember that ``@decorator`` syntax is applied bottom\n    #: to top, so the first decorator in the list would be the bottom\n    #: decorator.\n    #:\n    #: .. versionadded:: 0.8\n    decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []\n\n    #: Create a new instance of this view class for every request by\n    #: default. If a view subclass sets this to ``False``, the same\n    #: instance is used for every request.\n    #:\n    #: A single instance is more efficient, especially if complex setup\n    #: is done during init. However, storing data on ``self`` is no\n    #: longer safe across requests, and :data:`~flask.g` should be used\n    #: instead.\n    #:\n    #: .. versionadded:: 2.2\n    init_every_request: t.ClassVar[bool] = True\n\n    def dispatch(self) -> ft.ResponseReturnValue:\n        \"\"\"The actual view function behavior. Subclasses must override\n        this and return a valid response. Any variables from the URL\n        rule are passed as keyword arguments.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def as2(\n        cls, nam: str, *class2: t.Any, **class3: t.Any\n    ) -> ft.RouteCallable:\n        \"\"\"Convert the class into a view function that can be registered\n        for a route.\n\n        By default, the generated view will create a new instance of the\n        view class for every request and call its\n        :meth:`dispatch_request` method. If the view class sets\n        :attr:`init_every_request` to ``False``, the same instance will\n        be used for every request.\n\n        Except for ``name``, all other arguments passed to this method\n        are forwarded to the view class ``__init__`` method.\n\n        .. versionchanged:: 2.2\n            Added the ``init_every_request`` class attribute.\n        \"\"\"\n        if cls.init_every_request:\n\n            def view(**kwa: t.Any) -> ft.ResponseReturnValue:\n                sel2 = view.view_class(  # type: ignore[attr-defined]\n                    *class_args, **class_kwargs\n                )\n                return current_app.ensure_sync(sel2.dispatch)(**kwa)  # type: ignore[no-any-return]\n\n        else:\n            sel = cls(*class2, **class3)  # pyright: ignore\n\n            def view(**kwa2: t.Any) -> ft.ResponseReturnValue:\n                return current_app.ensure_sync(self.dispatch)(**kwa2)  # type: ignore[no-any-return]\n\n        if cls.decorators:\n            vie.__name__ = nam\n            vie.__module__ = cls.__module__\n            for dec in cls.decorators:\n                vie = dec(vie)\n\n        # We attach the view class to the view function for two reasons:\n        # first of all it allows us to easily figure out what class-based\n        # view this thing came from, secondly it's also used for instantiating\n        # the view class so you can actually replace it with something else\n        # for testing purposes and debugging.\n        vie.view_class = cls  # type: ignore\n        vie.__name__ = nam\n        vie.__doc__ = cls.__doc__\n        vie.__module__ = cls.__module__\n        vie.methods = cls.methods  # type: ignore\n        vie.provide_automatic_options = cls.provide_automatic_options  # type: ignore\n        return vie\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-adb6df588c55e9e9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "bcf575a48b5e7d168924c77324cbb1395765e3b148aecceda465e81d67a40515", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 126, "local_path": "identifiers/shorten-identifiers/I02__flask__View__cf2c7e09.py", "order": 2, "original_content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "parent_variant_id": "pyint-203033a416af-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L16-L135", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 31, "identifiers_declared": 11}, "unit_kind": "class", "unit_name": "View", "variant_id": "pyint-784fcf2c7e09-I02", "group_id": "py-adb6df588c55e9e9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 563, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-68615458b1fb-I03", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass View:\n    \"\"\"Subclass this class and override :meth:`dispatch_request` to\n    create a generic class-based view. Call :meth:`as_view` to create a\n    view function that creates an instance of the class with the given\n    arguments and calls its ``dispatch_request`` method with any URL\n    variables.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class Hello(View):\n            init_every_request = False\n\n            def dispatch_request(self, name):\n                return f\"Hello, {name}!\"\n\n        app.add_url_rule(\n            \"/hello/<name>\", view_func=Hello.as_view(\"hello\")\n        )\n\n    Set :attr:`methods` on the class to change what methods the view\n    accepts.\n\n    Set :attr:`decorators` on the class to apply a list of decorators to\n    the generated view function. Decorators applied to the class itself\n    will not be applied to the generated view function!\n\n    Set :attr:`init_every_request` to ``False`` for efficiency, unless\n    you need to store request-global data on ``self``.\n    \"\"\"\n\n    #: The methods this view is registered for. Uses the same default\n    #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    methods: t.ClassVar[t.Collection[str] | None] = None\n\n    #: Control whether the ``OPTIONS`` method is handled automatically.\n    #: Uses the same default (``True``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    provide_automatic_options: t.ClassVar[bool | None] = None\n\n    #: A list of decorators to apply, in order, to the generated view\n    #: function. Remember that ``@decorator`` syntax is applied bottom\n    #: to top, so the first decorator in the list would be the bottom\n    #: decorator.\n    #:\n    #: .. versionadded:: 0.8\n    decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []\n\n    #: Create a new instance of this view class for every request by\n    #: default. If a view subclass sets this to ``False``, the same\n    #: instance is used for every request.\n    #:\n    #: A single instance is more efficient, especially if complex setup\n    #: is done during init. However, storing data on ``self`` is no\n    #: longer safe across requests, and :data:`~flask.g` should be used\n    #: instead.\n    #:\n    #: .. versionadded:: 2.2\n    init_every_request: t.ClassVar[bool] = True\n\n    def validateAddress(self) -> ft.ResponseReturnValue:\n        \"\"\"The actual view function behavior. Subclasses must override\n        this and return a valid response. Any variables from the URL\n        rule are passed as keyword arguments.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def refresh(\n        cls, step: str, *finalCount: t.Any, **secureClient: t.Any\n    ) -> ft.RouteCallable:\n        \"\"\"Convert the class into a view function that can be registered\n        for a route.\n\n        By default, the generated view will create a new instance of the\n        view class for every request and call its\n        :meth:`dispatch_request` method. If the view class sets\n        :attr:`init_every_request` to ``False``, the same instance will\n        be used for every request.\n\n        Except for ``name``, all other arguments passed to this method\n        are forwarded to the view class ``__init__`` method.\n\n        .. versionchanged:: 2.2\n            Added the ``init_every_request`` class attribute.\n        \"\"\"\n        if cls.init_every_request:\n\n            def view(**status: t.Any) -> ft.ResponseReturnValue:\n                date = view.view_class(  # type: ignore[attr-defined]\n                    *class_args, **class_kwargs\n                )\n                return current_app.ensure_sync(date.validateAddress)(**status)  # type: ignore[no-any-return]\n\n        else:\n            date = cls(*finalCount, **secureClient)  # pyright: ignore\n\n            def view(**result: t.Any) -> ft.ResponseReturnValue:\n                return current_app.ensure_sync(self.validateAddress)(**result)  # type: ignore[no-any-return]\n\n        if cls.decorators:\n            data.__name__ = step\n            data.__module__ = cls.__module__\n            for finalPath in cls.decorators:\n                data = finalPath(data)\n\n        # We attach the view class to the view function for two reasons:\n        # first of all it allows us to easily figure out what class-based\n        # view this thing came from, secondly it's also used for instantiating\n        # the view class so you can actually replace it with something else\n        # for testing purposes and debugging.\n        data.view_class = cls  # type: ignore\n        data.__name__ = step\n        data.__doc__ = cls.__doc__\n        data.__module__ = cls.__module__\n        data.methods = cls.methods  # type: ignore\n        data.provide_automatic_options = cls.provide_automatic_options  # type: ignore\n        return data\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-adb6df588c55e9e9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "07202e9a513f78e98c8845750bd647723070d102606d1b7b428c633cbd647b99", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 126, "local_path": "identifiers/mislead-identifiers/I03__flask__View__5458b1fb.py", "order": 3, "original_content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "parent_variant_id": "pyint-203033a416af-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L16-L135", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 31, "identifiers_declared": 11, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 9, "local_random_pool_selections": 9, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 2, "method_total_length_difference": 1}, "unit_kind": "class", "unit_name": "View", "variant_id": "pyint-68615458b1fb-I03", "group_id": "py-adb6df588c55e9e9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 564, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-62bd1b788eef-I04", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass View:\n    \"\"\"Subclass this class and override :meth:`dispatch_request` to\n    create a generic class-based view. Call :meth:`as_view` to create a\n    view function that creates an instance of the class with the given\n    arguments and calls its ``dispatch_request`` method with any URL\n    variables.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class Hello(View):\n            init_every_request = False\n\n            def dispatch_request(self, name):\n                return f\"Hello, {name}!\"\n\n        app.add_url_rule(\n            \"/hello/<name>\", view_func=Hello.as_view(\"hello\")\n        )\n\n    Set :attr:`methods` on the class to change what methods the view\n    accepts.\n\n    Set :attr:`decorators` on the class to apply a list of decorators to\n    the generated view function. Decorators applied to the class itself\n    will not be applied to the generated view function!\n\n    Set :attr:`init_every_request` to ``False`` for efficiency, unless\n    you need to store request-global data on ``self``.\n    \"\"\"\n\n    #: The methods this view is registered for. Uses the same default\n    #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    methods: t.ClassVar[t.Collection[str] | None] = None\n\n    #: Control whether the ``OPTIONS`` method is handled automatically.\n    #: Uses the same default (``True``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    provide_automatic_options: t.ClassVar[bool | None] = None\n\n    #: A list of decorators to apply, in order, to the generated view\n    #: function. Remember that ``@decorator`` syntax is applied bottom\n    #: to top, so the first decorator in the list would be the bottom\n    #: decorator.\n    #:\n    #: .. versionadded:: 0.8\n    decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []\n\n    #: Create a new instance of this view class for every request by\n    #: default. If a view subclass sets this to ``False``, the same\n    #: instance is used for every request.\n    #:\n    #: A single instance is more efficient, especially if complex setup\n    #: is done during init. However, storing data on ``self`` is no\n    #: longer safe across requests, and :data:`~flask.g` should be used\n    #: instead.\n    #:\n    #: .. versionadded:: 2.2\n    init_every_request: t.ClassVar[bool] = True\n\n    def a(self) -> ft.ResponseReturnValue:\n        \"\"\"The actual view function behavior. Subclasses must override\n        this and return a valid response. Any variables from the URL\n        rule are passed as keyword arguments.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def b(\n        cls, c: str, *d: t.Any, **e: t.Any\n    ) -> ft.RouteCallable:\n        \"\"\"Convert the class into a view function that can be registered\n        for a route.\n\n        By default, the generated view will create a new instance of the\n        view class for every request and call its\n        :meth:`dispatch_request` method. If the view class sets\n        :attr:`init_every_request` to ``False``, the same instance will\n        be used for every request.\n\n        Except for ``name``, all other arguments passed to this method\n        are forwarded to the view class ``__init__`` method.\n\n        .. versionchanged:: 2.2\n            Added the ``init_every_request`` class attribute.\n        \"\"\"\n        if cls.init_every_request:\n\n            def view(**i: t.Any) -> ft.ResponseReturnValue:\n                j = view.view_class(  # type: ignore[attr-defined]\n                    *class_args, **class_kwargs\n                )\n                return current_app.ensure_sync(j.a)(**i)  # type: ignore[no-any-return]\n\n        else:\n            f = cls(*d, **e)  # pyright: ignore\n\n            def view(**k: t.Any) -> ft.ResponseReturnValue:\n                return current_app.ensure_sync(self.a)(**k)  # type: ignore[no-any-return]\n\n        if cls.decorators:\n            h.__name__ = c\n            h.__module__ = cls.__module__\n            for g in cls.decorators:\n                h = g(h)\n\n        # We attach the view class to the view function for two reasons:\n        # first of all it allows us to easily figure out what class-based\n        # view this thing came from, secondly it's also used for instantiating\n        # the view class so you can actually replace it with something else\n        # for testing purposes and debugging.\n        h.view_class = cls  # type: ignore\n        h.__name__ = c\n        h.__doc__ = cls.__doc__\n        h.__module__ = cls.__module__\n        h.methods = cls.methods  # type: ignore\n        h.provide_automatic_options = cls.provide_automatic_options  # type: ignore\n        return h\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-adb6df588c55e9e9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "ba83b59f963c2269bde7caf4fed38c93b490c7f0e26e358fea3307ff4a12f715", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 126, "local_path": "identifiers/garble-identifiers/I04__flask__View__1b788eef.py", "order": 4, "original_content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "parent_variant_id": "pyint-203033a416af-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L16-L135", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 31, "identifiers_declared": 11}, "unit_kind": "class", "unit_name": "View", "variant_id": "pyint-62bd1b788eef-I04", "group_id": "py-adb6df588c55e9e9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 565, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ebc9a7c1a5fd-I05", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass View:\n    \"\"\"Subclass this class and override :meth:`dispatch_request` to\n    create a generic class-based view. Call :meth:`as_view` to create a\n    view function that creates an instance of the class with the given\n    arguments and calls its ``dispatch_request`` method with any URL\n    variables.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class Hello(View):\n            init_every_request = False\n\n            def dispatch_request(self, name):\n                return f\"Hello, {name}!\"\n\n        app.add_url_rule(\n            \"/hello/<name>\", view_func=Hello.as_view(\"hello\")\n        )\n\n    Set :attr:`methods` on the class to change what methods the view\n    accepts.\n\n    Set :attr:`decorators` on the class to apply a list of decorators to\n    the generated view function. Decorators applied to the class itself\n    will not be applied to the generated view function!\n\n    Set :attr:`init_every_request` to ``False`` for efficiency, unless\n    you need to store request-global data on ``self``.\n    \"\"\"\n\n    #: The methods this view is registered for. Uses the same default\n    #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    methods: t.ClassVar[t.Collection[str] | None] = None\n\n    #: Control whether the ``OPTIONS`` method is handled automatically.\n    #: Uses the same default (``True``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    provide_automatic_options: t.ClassVar[bool | None] = None\n\n    #: A list of decorators to apply, in order, to the generated view\n    #: function. Remember that ``@decorator`` syntax is applied bottom\n    #: to top, so the first decorator in the list would be the bottom\n    #: decorator.\n    #:\n    #: .. versionadded:: 0.8\n    decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []\n\n    #: Create a new instance of this view class for every request by\n    #: default. If a view subclass sets this to ``False``, the same\n    #: instance is used for every request.\n    #:\n    #: A single instance is more efficient, especially if complex setup\n    #: is done during init. However, storing data on ``self`` is no\n    #: longer safe across requests, and :data:`~flask.g` should be used\n    #: instead.\n    #:\n    #: .. versionadded:: 2.2\n    init_every_request: t.ClassVar[bool] = True\n\n    def dispatch_request(self) -> ft.ResponseReturnValue:\n        \"\"\"The actual view function behavior. Subclasses must override\n        this and return a valid response. Any variables from the URL\n        rule are passed as keyword arguments.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def as_view(\n        cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n    ) -> ft.RouteCallable:\n        \"\"\"Convert the class into a view function that can be registered\n        for a route.\n\n        By default, the generated view will create a new instance of the\n        view class for every request and call its\n        :meth:`dispatch_request` method. If the view class sets\n        :attr:`init_every_request` to ``False``, the same instance will\n        be used for every request.\n\n        Except for ``name``, all other arguments passed to this method\n        are forwarded to the view class ``__init__`` method.\n\n        .. versionchanged:: 2.2\n            Added the ``init_every_request`` class attribute.\n        \"\"\"\n        if cls.init_every_request:\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                self = view.view_class(  # type: ignore[attr-defined]\n                    *class_args, **class_kwargs\n                )\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        else:\n            self = cls(*class_args, **class_kwargs)  # pyright: ignore\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        if cls.decorators:\n            view.__name__ = name\n            view.__module__ = cls.__module__\n            for decorator in cls.decorators:\n                view = decorator(view)\n\n        # We attach the view class to the view function for two reasons:\n        # first of all it allows us to easily figure out what class-based\n        # view this thing came from, secondly it's also used for instantiating\n        # the view class so you can actually replace it with something else\n        # for testing purposes and debugging.\n        view.view_class = cls  # type: ignore\n        view.__name__ = name\n        view.__doc__ = cls.__doc__\n        view.__module__ = cls.__module__\n        view.methods = cls.methods  # type: ignore\n        view.provide_automatic_options = cls.provide_automatic_options  # type: ignore\n        return view\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-adb6df588c55e9e9", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 126, "local_path": "expressions/encode-integer-literals/I05__flask__View__a7c1a5fd.py", "order": 5, "original_content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "parent_variant_id": "pyint-203033a416af-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L16-L135", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "View", "variant_id": "pyint-ebc9a7c1a5fd-I05", "group_id": "py-adb6df588c55e9e9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 566, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-55d5054808f0-I06", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass View:\n    \"\"\"Subclass this class and override :meth:`dispatch_request` to\n    create a generic class-based view. Call :meth:`as_view` to create a\n    view function that creates an instance of the class with the given\n    arguments and calls its ``dispatch_request`` method with any URL\n    variables.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class Hello(View):\n            init_every_request = False\n\n            def dispatch_request(self, name):\n                return f\"Hello, {name}!\"\n\n        app.add_url_rule(\n            \"/hello/<name>\", view_func=Hello.as_view(\"hello\")\n        )\n\n    Set :attr:`methods` on the class to change what methods the view\n    accepts.\n\n    Set :attr:`decorators` on the class to apply a list of decorators to\n    the generated view function. Decorators applied to the class itself\n    will not be applied to the generated view function!\n\n    Set :attr:`init_every_request` to ``False`` for efficiency, unless\n    you need to store request-global data on ``self``.\n    \"\"\"\n\n    #: The methods this view is registered for. Uses the same default\n    #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    methods: t.ClassVar[t.Collection[str] | None] = None\n\n    #: Control whether the ``OPTIONS`` method is handled automatically.\n    #: Uses the same default (``True``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    provide_automatic_options: t.ClassVar[bool | None] = None\n\n    #: A list of decorators to apply, in order, to the generated view\n    #: function. Remember that ``@decorator`` syntax is applied bottom\n    #: to top, so the first decorator in the list would be the bottom\n    #: decorator.\n    #:\n    #: .. versionadded:: 0.8\n    decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []\n\n    #: Create a new instance of this view class for every request by\n    #: default. If a view subclass sets this to ``False``, the same\n    #: instance is used for every request.\n    #:\n    #: A single instance is more efficient, especially if complex setup\n    #: is done during init. However, storing data on ``self`` is no\n    #: longer safe across requests, and :data:`~flask.g` should be used\n    #: instead.\n    #:\n    #: .. versionadded:: 2.2\n    init_every_request: t.ClassVar[bool] = True\n\n    def dispatch_request(self) -> ft.ResponseReturnValue:\n        \"\"\"The actual view function behavior. Subclasses must override\n        this and return a valid response. Any variables from the URL\n        rule are passed as keyword arguments.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def as_view(\n        cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n    ) -> ft.RouteCallable:\n        \"\"\"Convert the class into a view function that can be registered\n        for a route.\n\n        By default, the generated view will create a new instance of the\n        view class for every request and call its\n        :meth:`dispatch_request` method. If the view class sets\n        :attr:`init_every_request` to ``False``, the same instance will\n        be used for every request.\n\n        Except for ``name``, all other arguments passed to this method\n        are forwarded to the view class ``__init__`` method.\n\n        .. versionchanged:: 2.2\n            Added the ``init_every_request`` class attribute.\n        \"\"\"\n        if not (cls.init_every_request):\n            self = cls(*class_args, **class_kwargs)  # pyright: ignore\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n        else:\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                self = view.view_class(  # type: ignore[attr-defined]\n                    *class_args, **class_kwargs\n                )\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]  # type: ignore[no-any-return]\n\n        if not (cls.decorators):\n            pass\n        else:\n            view.__name__ = name\n            view.__module__ = cls.__module__\n            for decorator in cls.decorators:\n                view = decorator(view)\n\n        # We attach the view class to the view function for two reasons:\n        # first of all it allows us to easily figure out what class-based\n        # view this thing came from, secondly it's also used for instantiating\n        # the view class so you can actually replace it with something else\n        # for testing purposes and debugging.\n        view.view_class = cls  # type: ignore\n        view.__name__ = name\n        view.__doc__ = cls.__doc__\n        view.__module__ = cls.__module__\n        view.methods = cls.methods  # type: ignore\n        view.provide_automatic_options = cls.provide_automatic_options  # type: ignore\n        return view\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-adb6df588c55e9e9", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "a42b49bc35f14f227076a3f2f2e0c6fcbc5d5c1905f2f554b595c57a2929fd9c", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 127, "local_path": "expressions/invert-conditions/I06__flask__View__054808f0.py", "order": 6, "original_content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "parent_variant_id": "pyint-203033a416af-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L16-L135", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 2}, "unit_kind": "class", "unit_name": "View", "variant_id": "pyint-55d5054808f0-I06", "group_id": "py-adb6df588c55e9e9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 567, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-60c7c66acc86-I07", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass View:\n    \"\"\"Subclass this class and override :meth:`dispatch_request` to\n    create a generic class-based view. Call :meth:`as_view` to create a\n    view function that creates an instance of the class with the given\n    arguments and calls its ``dispatch_request`` method with any URL\n    variables.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class Hello(View):\n            init_every_request = False\n\n            def dispatch_request(self, name):\n                return f\"Hello, {name}!\"\n\n        app.add_url_rule(\n            \"/hello/<name>\", view_func=Hello.as_view(\"hello\")\n        )\n\n    Set :attr:`methods` on the class to change what methods the view\n    accepts.\n\n    Set :attr:`decorators` on the class to apply a list of decorators to\n    the generated view function. Decorators applied to the class itself\n    will not be applied to the generated view function!\n\n    Set :attr:`init_every_request` to ``False`` for efficiency, unless\n    you need to store request-global data on ``self``.\n    \"\"\"\n\n    #: The methods this view is registered for. Uses the same default\n    #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    methods: t.ClassVar[t.Collection[str] | None] = None\n\n    #: Control whether the ``OPTIONS`` method is handled automatically.\n    #: Uses the same default (``True``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    provide_automatic_options: t.ClassVar[bool | None] = None\n\n    #: A list of decorators to apply, in order, to the generated view\n    #: function. Remember that ``@decorator`` syntax is applied bottom\n    #: to top, so the first decorator in the list would be the bottom\n    #: decorator.\n    #:\n    #: .. versionadded:: 0.8\n    decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []\n\n    #: Create a new instance of this view class for every request by\n    #: default. If a view subclass sets this to ``False``, the same\n    #: instance is used for every request.\n    #:\n    #: A single instance is more efficient, especially if complex setup\n    #: is done during init. However, storing data on ``self`` is no\n    #: longer safe across requests, and :data:`~flask.g` should be used\n    #: instead.\n    #:\n    #: .. versionadded:: 2.2\n    init_every_request: t.ClassVar[bool] = True\n\n    def dispatch_request(self) -> ft.ResponseReturnValue:\n        \"\"\"The actual view function behavior. Subclasses must override\n        this and return a valid response. Any variables from the URL\n        rule are passed as keyword arguments.\n        \"\"\"\n        if ((0xbd21 ^ 0xbd21) != 0):\n            raise AssertionError()\n        raise NotImplementedError()\n\n    @classmethod\n    def as_view(\n        cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n    ) -> ft.RouteCallable:\n        \"\"\"Convert the class into a view function that can be registered\n        for a route.\n\n        By default, the generated view will create a new instance of the\n        view class for every request and call its\n        :meth:`dispatch_request` method. If the view class sets\n        :attr:`init_every_request` to ``False``, the same instance will\n        be used for every request.\n\n        Except for ``name``, all other arguments passed to this method\n        are forwarded to the view class ``__init__`` method.\n\n        .. versionchanged:: 2.2\n            Added the ``init_every_request`` class attribute.\n        \"\"\"\n        if ((0xf0d4 ^ 0xf0d4) != 0):\n            raise AssertionError()\n        if cls.init_every_request:\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                if ((0xfa49 ^ 0xfa49) != 0):\n                    raise AssertionError()\n                self = view.view_class(  # type: ignore[attr-defined]\n                    *class_args, **class_kwargs\n                )\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        else:\n            self = cls(*class_args, **class_kwargs)  # pyright: ignore\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                if ((0x46a2 ^ 0x46a2) != 0):\n                    raise AssertionError()\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        if cls.decorators:\n            view.__name__ = name\n            view.__module__ = cls.__module__\n            for decorator in cls.decorators:\n                view = decorator(view)\n\n        # We attach the view class to the view function for two reasons:\n        # first of all it allows us to easily figure out what class-based\n        # view this thing came from, secondly it's also used for instantiating\n        # the view class so you can actually replace it with something else\n        # for testing purposes and debugging.\n        view.view_class = cls  # type: ignore\n        view.__name__ = name\n        view.__doc__ = cls.__doc__\n        view.__module__ = cls.__module__\n        view.methods = cls.methods  # type: ignore\n        view.provide_automatic_options = cls.provide_automatic_options  # type: ignore\n        return view\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-adb6df588c55e9e9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "ea79157382d38ba0a732708203797eeca55d806c9e54af8a987b599a609b4579", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 134, "local_path": "code-injection/insert-dead-branches/I07__flask__View__c66acc86.py", "order": 7, "original_content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "parent_variant_id": "pyint-203033a416af-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L16-L135", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 4}, "unit_kind": "class", "unit_name": "View", "variant_id": "pyint-60c7c66acc86-I07", "group_id": "py-adb6df588c55e9e9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 568, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4b7ddd80e522-I08", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass View:\n    \"\"\"Subclass this class and override :meth:`dispatch_request` to\n    create a generic class-based view. Call :meth:`as_view` to create a\n    view function that creates an instance of the class with the given\n    arguments and calls its ``dispatch_request`` method with any URL\n    variables.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class Hello(View):\n            init_every_request = False\n\n            def dispatch_request(self, name):\n                return f\"Hello, {name}!\"\n\n        app.add_url_rule(\n            \"/hello/<name>\", view_func=Hello.as_view(\"hello\")\n        )\n\n    Set :attr:`methods` on the class to change what methods the view\n    accepts.\n\n    Set :attr:`decorators` on the class to apply a list of decorators to\n    the generated view function. Decorators applied to the class itself\n    will not be applied to the generated view function!\n\n    Set :attr:`init_every_request` to ``False`` for efficiency, unless\n    you need to store request-global data on ``self``.\n    \"\"\"\n\n    #: The methods this view is registered for. Uses the same default\n    #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    methods: t.ClassVar[t.Collection[str] | None] = None\n\n    #: Control whether the ``OPTIONS`` method is handled automatically.\n    #: Uses the same default (``True``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    provide_automatic_options: t.ClassVar[bool | None] = None\n\n    #: A list of decorators to apply, in order, to the generated view\n    #: function. Remember that ``@decorator`` syntax is applied bottom\n    #: to top, so the first decorator in the list would be the bottom\n    #: decorator.\n    #:\n    #: .. versionadded:: 0.8\n    decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []\n\n    #: Create a new instance of this view class for every request by\n    #: default. If a view subclass sets this to ``False``, the same\n    #: instance is used for every request.\n    #:\n    #: A single instance is more efficient, especially if complex setup\n    #: is done during init. However, storing data on ``self`` is no\n    #: longer safe across requests, and :data:`~flask.g` should be used\n    #: instead.\n    #:\n    #: .. versionadded:: 2.2\n    init_every_request: t.ClassVar[bool] = True\n\n    def dispatch_request(self) -> ft.ResponseReturnValue:\n        \"\"\"The actual view function behavior. Subclasses must override\n        this and return a valid response. Any variables from the URL\n        rule are passed as keyword arguments.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def as_view(\n        cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n    ) -> ft.RouteCallable:\n        \"\"\"Convert the class into a view function that can be registered\n        for a route.\n\n        By default, the generated view will create a new instance of the\n        view class for every request and call its\n        :meth:`dispatch_request` method. If the view class sets\n        :attr:`init_every_request` to ``False``, the same instance will\n        be used for every request.\n\n        Except for ``name``, all other arguments passed to this method\n        are forwarded to the view class ``__init__`` method.\n\n        .. versionchanged:: 2.2\n            Added the ``init_every_request`` class attribute.\n        \"\"\"\n        if cls.init_every_request:\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                factorial = 1\n                for current_factor in range(2, 5):\n                    factorial *= current_factor\n                self = view.view_class(  # type: ignore[attr-defined]\n                    *class_args, **class_kwargs\n                )\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        else:\n            self = cls(*class_args, **class_kwargs)  # pyright: ignore\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        if cls.decorators:\n            view.__name__ = name\n            view.__module__ = cls.__module__\n            for decorator in cls.decorators:\n                view = decorator(view)\n\n        # We attach the view class to the view function for two reasons:\n        # first of all it allows us to easily figure out what class-based\n        # view this thing came from, secondly it's also used for instantiating\n        # the view class so you can actually replace it with something else\n        # for testing purposes and debugging.\n        view.view_class = cls  # type: ignore\n        view.__name__ = name\n        view.__doc__ = cls.__doc__\n        view.__module__ = cls.__module__\n        view.methods = cls.methods  # type: ignore\n        view.provide_automatic_options = cls.provide_automatic_options  # type: ignore\n        return view\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-adb6df588c55e9e9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "f167fabab923b9945290e747b21d2579a129f9416f33d7e2f3719ffbdd3cc592", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 129, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__View__dd80e522.py", "order": 8, "original_content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "parent_variant_id": "pyint-203033a416af-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L16-L135", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 6}, "unit_kind": "class", "unit_name": "View", "variant_id": "pyint-4b7ddd80e522-I08", "group_id": "py-adb6df588c55e9e9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 569, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6d38461c0fd0-I09", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass View:\n    \"\"\"Subclass this class and override :meth:`dispatch_request` to\n    create a generic class-based view. Call :meth:`as_view` to create a\n    view function that creates an instance of the class with the given\n    arguments and calls its ``dispatch_request`` method with any URL\n    variables.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class Hello(View):\n            init_every_request = False\n\n            def dispatch_request(self, name):\n                return f\"Hello, {name}!\"\n\n        app.add_url_rule(\n            \"/hello/<name>\", view_func=Hello.as_view(\"hello\")\n        )\n\n    Set :attr:`methods` on the class to change what methods the view\n    accepts.\n\n    Set :attr:`decorators` on the class to apply a list of decorators to\n    the generated view function. Decorators applied to the class itself\n    will not be applied to the generated view function!\n\n    Set :attr:`init_every_request` to ``False`` for efficiency, unless\n    you need to store request-global data on ``self``.\n    \"\"\"\n\n    #: The methods this view is registered for. Uses the same default\n    #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    methods: t.ClassVar[t.Collection[str] | None] = None\n\n    #: Control whether the ``OPTIONS`` method is handled automatically.\n    #: Uses the same default (``True``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    provide_automatic_options: t.ClassVar[bool | None] = None\n\n    #: A list of decorators to apply, in order, to the generated view\n    #: function. Remember that ``@decorator`` syntax is applied bottom\n    #: to top, so the first decorator in the list would be the bottom\n    #: decorator.\n    #:\n    #: .. versionadded:: 0.8\n    decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []\n\n    #: Create a new instance of this view class for every request by\n    #: default. If a view subclass sets this to ``False``, the same\n    #: instance is used for every request.\n    #:\n    #: A single instance is more efficient, especially if complex setup\n    #: is done during init. However, storing data on ``self`` is no\n    #: longer safe across requests, and :data:`~flask.g` should be used\n    #: instead.\n    #:\n    #: .. versionadded:: 2.2\n    init_every_request: t.ClassVar[bool] = True\n\n    def dispatch_request(self) -> ft.ResponseReturnValue:\n        \"\"\"The actual view function behavior. Subclasses must override\n        this and return a valid response. Any variables from the URL\n        rule are passed as keyword arguments.\n        \"\"\"\n        lI0O_c98fde3d = 0x26cc\n        lI0O_c98fde3d = (0 if (lI0O_c98fde3d ^ lI0O_c98fde3d) == 0 else 1) if (lI0O_c98fde3d & 0) == 0 else 2\n        raise NotImplementedError()\n\n    @classmethod\n    def as_view(\n        cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n    ) -> ft.RouteCallable:\n        \"\"\"Convert the class into a view function that can be registered\n        for a route.\n\n        By default, the generated view will create a new instance of the\n        view class for every request and call its\n        :meth:`dispatch_request` method. If the view class sets\n        :attr:`init_every_request` to ``False``, the same instance will\n        be used for every request.\n\n        Except for ``name``, all other arguments passed to this method\n        are forwarded to the view class ``__init__`` method.\n\n        .. versionchanged:: 2.2\n            Added the ``init_every_request`` class attribute.\n        \"\"\"\n        if cls.init_every_request:\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                self = view.view_class(  # type: ignore[attr-defined]\n                    *class_args, **class_kwargs\n                )\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        else:\n            self = cls(*class_args, **class_kwargs)  # pyright: ignore\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        if cls.decorators:\n            view.__name__ = name\n            view.__module__ = cls.__module__\n            for decorator in cls.decorators:\n                view = decorator(view)\n\n        # We attach the view class to the view function for two reasons:\n        # first of all it allows us to easily figure out what class-based\n        # view this thing came from, secondly it's also used for instantiating\n        # the view class so you can actually replace it with something else\n        # for testing purposes and debugging.\n        view.view_class = cls  # type: ignore\n        view.__name__ = name\n        view.__doc__ = cls.__doc__\n        view.__module__ = cls.__module__\n        view.methods = cls.methods  # type: ignore\n        view.provide_automatic_options = cls.provide_automatic_options  # type: ignore\n        return view\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-adb6df588c55e9e9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "9c3b5534aab5a9cd34aafd0325967f86716baefae875cf3d6e7f372d006ddd73", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 128, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__View__461c0fd0.py", "order": 9, "original_content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "parent_variant_id": "pyint-203033a416af-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L16-L135", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 8}, "unit_kind": "class", "unit_name": "View", "variant_id": "pyint-6d38461c0fd0-I09", "group_id": "py-adb6df588c55e9e9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 570, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3139ee945c70-I10", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass View:\n    \"\"\"Subclass this class and override :meth:`dispatch_request` to\n    create a generic class-based view. Call :meth:`as_view` to create a\n    view function that creates an instance of the class with the given\n    arguments and calls its ``dispatch_request`` method with any URL\n    variables.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class Hello(View):\n            init_every_request = False\n            def dispatch_request(self, name):\n                return f\"Hello, {name}!\"\n        app.add_url_rule(\n            \"/hello/<name>\", view_func=Hello.as_view(\"hello\")\n        )\n    Set :attr:`methods` on the class to change what methods the view\n    accepts.\n\n    Set :attr:`decorators` on the class to apply a list of decorators to\n    the generated view function. Decorators applied to the class itself\n    will not be applied to the generated view function!\n    Set :attr:`init_every_request` to ``False`` for efficiency, unless\n    you need to store request-global data on ``self``.\n    \"\"\"\n    #: The methods this view is registered for. Uses the same default\n    #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    methods: t.ClassVar[t.Collection[str] | None] = None\n\n    #: Control whether the ``OPTIONS`` method is handled automatically.\n    #: Uses the same default (``True``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    provide_automatic_options: t.ClassVar[bool | None] = None\n\n    #: A list of decorators to apply, in order, to the generated view\n    #: function. Remember that ``@decorator`` syntax is applied bottom\n    #: to top, so the first decorator in the list would be the bottom\n    #: decorator.\n    #:\n    #: .. versionadded:: 0.8\n    decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []\n    #: Create a new instance of this view class for every request by\n    #: default. If a view subclass sets this to ``False``, the same\n    #: instance is used for every request.\n    #:\n    #: A single instance is more efficient, especially if complex setup\n    #: is done during init. However, storing data on ``self`` is no\n    #: longer safe across requests, and :data:`~flask.g` should be used\n    #: instead.\n    #:\n    #: .. versionadded:: 2.2\n    init_every_request: t.ClassVar[bool] = True\n    def dispatch_request(self) -> ft.ResponseReturnValue:\n        \"\"\"The actual view function behavior. Subclasses must override\n        this and return a valid response. Any variables from the URL\n        rule are passed as keyword arguments.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def as_view(\n        cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n    ) -> ft.RouteCallable:\n        \"\"\"Convert the class into a view function that can be registered\n        for a route.\n\n        By default, the generated view will create a new instance of the\n        view class for every request and call its\n        :meth:`dispatch_request` method. If the view class sets\n        :attr:`init_every_request` to ``False``, the same instance will\n        be used for every request.\n\n        Except for ``name``, all other arguments passed to this method\n        are forwarded to the view class ``__init__`` method.\n\n        .. versionchanged:: 2.2\n            Added the ``init_every_request`` class attribute.\n        \"\"\"\n        if cls.init_every_request:\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                self = view.view_class(  # type: ignore[attr-defined]\n                    *class_args, **class_kwargs                 )\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        else:\n            self = cls(*class_args, **class_kwargs)  # pyright: ignore\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        if cls.decorators:\n            view.__name__ = name\n            view.__module__ = cls.__module__\n            for decorator in cls.decorators:\n                view = decorator(view)\n        # We attach the view class to the view function for two reasons:\n        # first of all it allows us to easily figure out what class-based\n        # view this thing came from, secondly it's also used for instantiating\n        # the view class so you can actually replace it with something else\n        # for testing purposes and debugging.\n        view.view_class = cls  # type: ignore\n        view.__name__ = name\n        view.__doc__ = cls.__doc__\n        view.__module__ = cls.__module__\n        view.methods = cls.methods  # type: ignore\n        view.provide_automatic_options = cls.provide_automatic_options  # type: ignore\n        return view\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-adb6df588c55e9e9", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "586804d98973ede3a909c333083d4e6bf544aa6a0c2ce2a46026d149f7d7cf15", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 116, "local_path": "layout/partially-compact-layout/I10__flask__View__ee945c70.py", "order": 10, "original_content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "parent_variant_id": "pyint-203033a416af-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L16-L135", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 26, "line_break_groups_removed": 10, "line_breaks_removed": 10, "whitespace_characters_removed": 9}, "unit_kind": "class", "unit_name": "View", "variant_id": "pyint-3139ee945c70-I10", "group_id": "py-adb6df588c55e9e9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 571, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-51028bef1232-I11", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass View:\n    \"\"\"Subclass this class and override :meth:`dispatch_request` to\n    create a generic class-based view. Call :meth:`as_view` to create a\n    view function that creates an instance of the class with the given\n    arguments and calls its ``dispatch_request`` method with any URL\n    variables.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class Hello(View):\n            init_every_request = False\n\n            def dispatch_request(self, name):\n                return f\"Hello, {name}!\"\n\n        app.add_url_rule(\n            \"/hello/<name>\", view_func=Hello.as_view(\"hello\")\n        )\n\n    Set :attr:`methods` on the class to change what methods the view\n    accepts.\n\n    Set :attr:`decorators` on the class to apply a list of decorators to\n    the generated view function. Decorators applied to the class itself\n    will not be applied to the generated view function!\n\n    Set :attr:`init_every_request` to ``False`` for efficiency, unless\n    you need to store request-global data on ``self``.\n    \"\"\"\n\n    #: The methods this view is registered for. Uses the same default\n    #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    methods: t.ClassVar[t.Collection[str] | None] = None\n\n    #: Control whether the ``OPTIONS`` method is handled automatically.\n    #: Uses the same default (``True``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    provide_automatic_options: t.ClassVar[bool | None] = None\n\n    #: A list of decorators to apply, in order, to the generated view\n    #: function. Remember that ``@decorator`` syntax is applied bottom\n    #: to top, so the first decorator in the list would be the bottom\n    #: decorator.\n    #:\n    #: .. versionadded:: 0.8\n    decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []\n\n    #: Create a new instance of this view class for every request by\n    #: default. If a view subclass sets this to ``False``, the same\n    #: instance is used for every request.\n    #:\n    #: A single instance is more efficient, especially if complex setup\n    #: is done during init. However, storing data on ``self`` is no\n    #: longer safe across requests, and :data:`~flask.g` should be used\n    #: instead.\n    #:\n    #: .. versionadded:: 2.2\n    init_every_request: t.ClassVar[bool] = True\n\n    def dispatch_request(self) -> ft.ResponseReturnValue:\n        \"\"\"The actual view function behavior. Subclasses must override\n        this and return a valid response. Any variables from the URL\n        rule are passed as keyword arguments.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def as_view(\n        cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n    ) -> ft.RouteCallable:\n        \"\"\"Convert the class into a view function that can be registered\n        for a route.\n\n        By default, the generated view will create a new instance of the\n        view class for every request and call its\n        :meth:`dispatch_request` method. If the view class sets\n        :attr:`init_every_request` to ``False``, the same instance will\n        be used for every request.\n\n        Except for ``name``, all other arguments passed to this method\n        are forwarded to the view class ``__init__`` method.\n\n        .. versionchanged:: 2.2\n            Added the ``init_every_request`` class attribute.\n        \"\"\"\n        if cls.init_every_request:\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                self = view.view_class(  # type: ignore[attr-defined]\n                    *class_args, **class_kwargs\n                )\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        else:\n            self = cls(*class_args, **class_kwargs)  # pyright: ignore\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        if cls.decorators:\n            view.__name__ = name\n            view.__module__ = cls.__module__\n            for decorator in cls.decorators:\n                view = decorator(view)\n\n        # We attach the view class to the view function for two reasons:\n        # first of all it allows us to easily figure out what class-based\n        # view this thing came from, secondly it's also used for instantiating\n        # the view class so you can actually replace it with something else\n        # for testing purposes and debugging.\n        view.view_class = cls  # type: ignore\n        view.__name__ = name\n        view.__doc__ = cls.__doc__\n        view.__module__ = cls.__module__\n        view.methods = cls.methods  # type: ignore\n        view.provide_automatic_options = cls.provide_automatic_options  # type: ignore\n        return view\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-adb6df588c55e9e9", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 126, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__View__8bef1232.py", "order": 11, "original_content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "parent_variant_id": "pyint-203033a416af-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L16-L135", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "View", "variant_id": "pyint-51028bef1232-I11", "group_id": "py-adb6df588c55e9e9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 572, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f1c66b57ce26-I12", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass View:\n    \"\"\"Subclass this class and override :meth:`dispatch_request` to\n    create a generic class-based view. Call :meth:`as_view` to create a\n    view function that creates an instance of the class with the given\n    arguments and calls its ``dispatch_request`` method with any URL\n    variables.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class Hello(View):\n            init_every_request = False\n\n            def dispatch_request(self, name):\n                return f\"Hello, {name}!\"\n\n        app.add_url_rule(\n            \"/hello/<name>\", view_func=Hello.as_view(\"hello\")\n        )\n\n    Set :attr:`methods` on the class to change what methods the view\n    accepts.\n\n    Set :attr:`decorators` on the class to apply a list of decorators to\n    the generated view function. Decorators applied to the class itself\n    will not be applied to the generated view function!\n\n    Set :attr:`init_every_request` to ``False`` for efficiency, unless\n    you need to store request-global data on ``self``.\n    \"\"\"\n\n    #: The methods this view is registered for. Uses the same default\n    #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    methods: t.ClassVar[t.Collection[str] | None] = None\n\n    #: Control whether the ``OPTIONS`` method is handled automatically.\n    #: Uses the same default (``True``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    provide_automatic_options: t.ClassVar[bool | None] = None\n\n    #: A list of decorators to apply, in order, to the generated view\n    #: function. Remember that ``@decorator`` syntax is applied bottom\n    #: to top, so the first decorator in the list would be the bottom\n    #: decorator.\n    #:\n    #: .. versionadded:: 0.8\n    decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []\n\n    #: Create a new instance of this view class for every request by\n    #: default. If a view subclass sets this to ``False``, the same\n    #: instance is used for every request.\n    #:\n    #: A single instance is more efficient, especially if complex setup\n    #: is done during init. However, storing data on ``self`` is no\n    #: longer safe across requests, and :data:`~flask.g` should be used\n    #: instead.\n    #:\n    #: .. versionadded:: 2.2\n    init_every_request: t.ClassVar[bool] = True\n\n    def dispatch_request(self) -> ft.ResponseReturnValue:\n        \"\"\"The actual view function behavior. Subclasses must override\n        this and return a valid response. Any variables from the URL\n        rule are passed as keyword arguments.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def as_view(\n        cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n    ) -> ft.RouteCallable:\n        \"\"\"Convert the class into a view function that can be registered\n        for a route.\n\n        By default, the generated view will create a new instance of the\n        view class for every request and call its\n        :meth:`dispatch_request` method. If the view class sets\n        :attr:`init_every_request` to ``False``, the same instance will\n        be used for every request.\n\n        Except for ``name``, all other arguments passed to this method\n        are forwarded to the view class ``__init__`` method.\n\n        .. versionchanged:: 2.2\n            Added the ``init_every_request`` class attribute.\n        \"\"\"\n        if cls.init_every_request:\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                \n                return current_app.ensure_sync((view.view_class(  # type: ignore[attr-defined]\n                    *class_args, **class_kwargs\n                )).dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        else:\n            self = cls(*class_args, **class_kwargs)  # pyright: ignore\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        if cls.decorators:\n            view.__name__ = name\n            view.__module__ = cls.__module__\n            for decorator in cls.decorators:\n                view = decorator(view)\n\n        # We attach the view class to the view function for two reasons:\n        # first of all it allows us to easily figure out what class-based\n        # view this thing came from, secondly it's also used for instantiating\n        # the view class so you can actually replace it with something else\n        # for testing purposes and debugging.\n        view.view_class = cls  # type: ignore\n        view.__name__ = name\n        view.__doc__ = cls.__doc__\n        view.__module__ = cls.__module__\n        view.methods = cls.methods  # type: ignore\n        view.provide_automatic_options = cls.provide_automatic_options  # type: ignore\n        return view\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-adb6df588c55e9e9", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "05093962b8d16edd72229c442488a27c6cd0fd0054bde4b508d254c5721cde9d", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 126, "local_path": "data-flow/inline-intermediate-variables/I12__flask__View__6b57ce26.py", "order": 12, "original_content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "parent_variant_id": "pyint-203033a416af-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L16-L135", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "View", "variant_id": "pyint-f1c66b57ce26-I12", "group_id": "py-adb6df588c55e9e9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 573, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c5769bc33c9f-I13", "source": "from __future__ import annotations\nimport typing as t\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\nclass View:\n    \"\"\"Subclass this class and override :meth:`dispatch_request` to\n    create a generic class-based view. Call :meth:`as_view` to create a\n    view function that creates an instance of the class with the given\n    arguments and calls its ``dispatch_request`` method with any URL\n    variables.\n\n    See :doc:`views` for a detailed guide.\n\n    .. code-block:: python\n\n        class Hello(View):\n            init_every_request = False\n\n            def dispatch_request(self, name):\n                return f\"Hello, {name}!\"\n\n        app.add_url_rule(\n            \"/hello/<name>\", view_func=Hello.as_view(\"hello\")\n        )\n\n    Set :attr:`methods` on the class to change what methods the view\n    accepts.\n\n    Set :attr:`decorators` on the class to apply a list of decorators to\n    the generated view function. Decorators applied to the class itself\n    will not be applied to the generated view function!\n\n    Set :attr:`init_every_request` to ``False`` for efficiency, unless\n    you need to store request-global data on ``self``.\n    \"\"\"\n\n    #: The methods this view is registered for. Uses the same default\n    #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    methods: t.ClassVar[t.Collection[str] | None] = None\n\n    #: Control whether the ``OPTIONS`` method is handled automatically.\n    #: Uses the same default (``True``) as ``route`` and\n    #: ``add_url_rule`` by default.\n    provide_automatic_options: t.ClassVar[bool | None] = None\n\n    #: A list of decorators to apply, in order, to the generated view\n    #: function. Remember that ``@decorator`` syntax is applied bottom\n    #: to top, so the first decorator in the list would be the bottom\n    #: decorator.\n    #:\n    #: .. versionadded:: 0.8\n    decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []\n\n    #: Create a new instance of this view class for every request by\n    #: default. If a view subclass sets this to ``False``, the same\n    #: instance is used for every request.\n    #:\n    #: A single instance is more efficient, especially if complex setup\n    #: is done during init. However, storing data on ``self`` is no\n    #: longer safe across requests, and :data:`~flask.g` should be used\n    #: instead.\n    #:\n    #: .. versionadded:: 2.2\n    init_every_request: t.ClassVar[bool] = True\n\n    def dispatch_request(self) -> ft.ResponseReturnValue:\n        \"\"\"The actual view function behavior. Subclasses must override\n        this and return a valid response. Any variables from the URL\n        rule are passed as keyword arguments.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def as_view(\n        cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n    ) -> ft.RouteCallable:\n        \"\"\"Convert the class into a view function that can be registered\n        for a route.\n\n        By default, the generated view will create a new instance of the\n        view class for every request and call its\n        :meth:`dispatch_request` method. If the view class sets\n        :attr:`init_every_request` to ``False``, the same instance will\n        be used for every request.\n\n        Except for ``name``, all other arguments passed to this method\n        are forwarded to the view class ``__init__`` method.\n\n        .. versionchanged:: 2.2\n            Added the ``init_every_request`` class attribute.\n        \"\"\"\n        if cls.init_every_request:\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                self = view.view_class(  # type: ignore[attr-defined]\n                    *class_args, **class_kwargs\n                )\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        else:\n            self = cls(*class_args, **class_kwargs)  # pyright: ignore\n\n            def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n                return current_app.ensure_sync(self.dispatch_request)(**kwargs)  # type: ignore[no-any-return]\n\n        if cls.decorators:\n            view.__name__ = name\n            view.__module__ = cls.__module__\n            loopIterator = __import__(\"builtins\").iter(cls.decorators)\n            while True:\n                try:\n                    decorator = __import__(\"builtins\").next(loopIterator)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                view = decorator(view)\n\n        # We attach the view class to the view function for two reasons:\n        # first of all it allows us to easily figure out what class-based\n        # view this thing came from, secondly it's also used for instantiating\n        # the view class so you can actually replace it with something else\n        # for testing purposes and debugging.\n        view.view_class = cls  # type: ignore\n        view.__name__ = name\n        view.__doc__ = cls.__doc__\n        view.__module__ = cls.__module__\n        view.methods = cls.methods  # type: ignore\n        view.provide_automatic_options = cls.provide_automatic_options  # type: ignore\n        return view\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-adb6df588c55e9e9", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "742b2d166d75d6d1235a3c67cdf40e02b4fa2c25d2869c8f3936f9a15f347894", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 131, "local_path": "control-flow/lower-for-to-while/I13__flask__View__9bc33c9f.py", "order": 13, "original_content_sha256": "d190e87cd0ab117a4ea2e6f4df33395c3fceb7f81d2da05a420689d42a3c3d4c", "parent_variant_id": "pyint-203033a416af-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/views.py#L16-L135", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 1, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 1, "synchronous_for_loops_eligible": 1, "synchronous_for_loops_found": 1}, "unit_kind": "class", "unit_name": "View", "variant_id": "pyint-c5769bc33c9f-I13", "group_id": "py-adb6df588c55e9e9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 574, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8725f82ffcfc-SRC", "source": "from django.apps import AppConfig\nfrom django.contrib.contenttypes.checks import (\n    check_generic_foreign_keys,\n    check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\nclass ContentTypesConfig(AppConfig):\n    default_auto_field = \"django.db.models.AutoField\"\n    name = \"django.contrib.contenttypes\"\n    verbose_name = _(\"Content Types\")\n\n    def ready(self):\n        pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)\n        post_migrate.connect(create_contenttypes)\n        checks.register(check_generic_foreign_keys, checks.Tags.models)\n        checks.register(check_model_name_lengths, checks.Tags.models)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-af4c9eb0b8bbb644", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 20, "local_path": "source-original/SRC__django__ContentTypesConfig__f82ffcfc.py", "order": 0, "original_content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/contenttypes/apps.py#L13-L22", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "ContentTypesConfig", "variant_id": "pyint-8725f82ffcfc-SRC", "group_id": "py-af4c9eb0b8bbb644", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 85, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b0f0a03876f9-I01", "source": "from django.apps import AppConfig\nfrom django.contrib.contenttypes.checks import (\n    check_generic_foreign_keys,\n    check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\nclass ContentTypesConfig(AppConfig):\n    default_auto_field = \"django.db.models.AutoField\"\n    name = \"django.contrib.contenttypes\"\n    verbose_name = _(\"Content Types\")\n\n    def ready(self):\n        pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)\n        post_migrate.connect(create_contenttypes)\n        checks.register(check_generic_foreign_keys, checks.Tags.models)\n        checks.register(check_model_name_lengths, checks.Tags.models)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-af4c9eb0b8bbb644", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 20, "local_path": "comments/remove-comments/I01__django__ContentTypesConfig__a03876f9.py", "order": 1, "original_content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "parent_variant_id": "pyint-8725f82ffcfc-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/contenttypes/apps.py#L13-L22", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "ContentTypesConfig", "variant_id": "pyint-b0f0a03876f9-I01", "group_id": "py-af4c9eb0b8bbb644", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 86, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f5b9641e4c08-I02", "source": "from django.apps import AppConfig\nfrom django.contrib.contenttypes.checks import (\n    check_generic_foreign_keys,\n    check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\nclass ContentTypesConfig(AppConfig):\n    default_auto_field = \"django.db.models.AutoField\"\n    name = \"django.contrib.contenttypes\"\n    verbose_name = _(\"Content Types\")\n\n    def rea(self):\n        pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)\n        post_migrate.connect(create_contenttypes)\n        checks.register(check_generic_foreign_keys, checks.Tags.models)\n        checks.register(check_model_name_lengths, checks.Tags.models)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-af4c9eb0b8bbb644", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "6f3fce3d0d64324ea9dca83daaf21c83f491223e0a80fc3e60147595d2a3c52f", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 20, "local_path": "identifiers/shorten-identifiers/I02__django__ContentTypesConfig__641e4c08.py", "order": 2, "original_content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "parent_variant_id": "pyint-8725f82ffcfc-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/contenttypes/apps.py#L13-L22", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "ContentTypesConfig", "variant_id": "pyint-f5b9641e4c08-I02", "group_id": "py-af4c9eb0b8bbb644", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 87, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fc975ca57f2a-I03", "source": "from django.apps import AppConfig\nfrom django.contrib.contenttypes.checks import (\n    check_generic_foreign_keys,\n    check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\nclass ContentTypesConfig(AppConfig):\n    default_auto_field = \"django.db.models.AutoField\"\n    name = \"django.contrib.contenttypes\"\n    verbose_name = _(\"Content Types\")\n\n    def reset(self):\n        pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)\n        post_migrate.connect(create_contenttypes)\n        checks.register(check_generic_foreign_keys, checks.Tags.models)\n        checks.register(check_model_name_lengths, checks.Tags.models)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-af4c9eb0b8bbb644", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d9e5980046a1d03223773c1caa3cfbd0040e22063fe83e5ad1e448ea221870f5", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 20, "local_path": "identifiers/mislead-identifiers/I03__django__ContentTypesConfig__5ca57f2a.py", "order": 3, "original_content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "parent_variant_id": "pyint-8725f82ffcfc-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/contenttypes/apps.py#L13-L22", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 0, "local_random_pool_selections": 0, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "ContentTypesConfig", "variant_id": "pyint-fc975ca57f2a-I03", "group_id": "py-af4c9eb0b8bbb644", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 88, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a1b949b85a9a-I04", "source": "from django.apps import AppConfig\nfrom django.contrib.contenttypes.checks import (\n    check_generic_foreign_keys,\n    check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\nclass ContentTypesConfig(AppConfig):\n    default_auto_field = \"django.db.models.AutoField\"\n    name = \"django.contrib.contenttypes\"\n    verbose_name = _(\"Content Types\")\n\n    def a(self):\n        pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)\n        post_migrate.connect(create_contenttypes)\n        checks.register(check_generic_foreign_keys, checks.Tags.models)\n        checks.register(check_model_name_lengths, checks.Tags.models)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-af4c9eb0b8bbb644", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "980e39fc4741dc3f1b990b9770c25e078540d2011579c50898448bf8581a25be", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 20, "local_path": "identifiers/garble-identifiers/I04__django__ContentTypesConfig__49b85a9a.py", "order": 4, "original_content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "parent_variant_id": "pyint-8725f82ffcfc-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/contenttypes/apps.py#L13-L22", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 1, "identifiers_declared": 1}, "unit_kind": "class", "unit_name": "ContentTypesConfig", "variant_id": "pyint-a1b949b85a9a-I04", "group_id": "py-af4c9eb0b8bbb644", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 89, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a91844509cc4-I05", "source": "from django.apps import AppConfig\nfrom django.contrib.contenttypes.checks import (\n    check_generic_foreign_keys,\n    check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\nclass ContentTypesConfig(AppConfig):\n    default_auto_field = \"django.db.models.AutoField\"\n    name = \"django.contrib.contenttypes\"\n    verbose_name = _(\"Content Types\")\n\n    def ready(self):\n        pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)\n        post_migrate.connect(create_contenttypes)\n        checks.register(check_generic_foreign_keys, checks.Tags.models)\n        checks.register(check_model_name_lengths, checks.Tags.models)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-af4c9eb0b8bbb644", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 20, "local_path": "expressions/encode-integer-literals/I05__django__ContentTypesConfig__44509cc4.py", "order": 5, "original_content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "parent_variant_id": "pyint-8725f82ffcfc-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/contenttypes/apps.py#L13-L22", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "ContentTypesConfig", "variant_id": "pyint-a91844509cc4-I05", "group_id": "py-af4c9eb0b8bbb644", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 90, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f470e7f395d4-I06", "source": "from django.apps import AppConfig\nfrom django.contrib.contenttypes.checks import (\n    check_generic_foreign_keys,\n    check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\nclass ContentTypesConfig(AppConfig):\n    default_auto_field = \"django.db.models.AutoField\"\n    name = \"django.contrib.contenttypes\"\n    verbose_name = _(\"Content Types\")\n\n    def ready(self):\n        pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)\n        post_migrate.connect(create_contenttypes)\n        checks.register(check_generic_foreign_keys, checks.Tags.models)\n        checks.register(check_model_name_lengths, checks.Tags.models)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-af4c9eb0b8bbb644", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 20, "local_path": "expressions/invert-conditions/I06__django__ContentTypesConfig__e7f395d4.py", "order": 6, "original_content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "parent_variant_id": "pyint-8725f82ffcfc-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/contenttypes/apps.py#L13-L22", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "ContentTypesConfig", "variant_id": "pyint-f470e7f395d4-I06", "group_id": "py-af4c9eb0b8bbb644", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 91, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b6fe823725cf-I07", "source": "from django.apps import AppConfig\nfrom django.contrib.contenttypes.checks import (\n    check_generic_foreign_keys,\n    check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\nclass ContentTypesConfig(AppConfig):\n    default_auto_field = \"django.db.models.AutoField\"\n    name = \"django.contrib.contenttypes\"\n    verbose_name = _(\"Content Types\")\n\n    def ready(self):\n        if ((0xd636 ^ 0xd636) != 0):\n            raise AssertionError()\n        pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)\n        post_migrate.connect(create_contenttypes)\n        checks.register(check_generic_foreign_keys, checks.Tags.models)\n        checks.register(check_model_name_lengths, checks.Tags.models)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-af4c9eb0b8bbb644", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "a963bfc319bbe45c3d28eced30156b0c6b9590196ff49c38c0b73a35ca08b26e", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 22, "local_path": "code-injection/insert-dead-branches/I07__django__ContentTypesConfig__823725cf.py", "order": 7, "original_content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "parent_variant_id": "pyint-8725f82ffcfc-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/contenttypes/apps.py#L13-L22", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 1}, "unit_kind": "class", "unit_name": "ContentTypesConfig", "variant_id": "pyint-b6fe823725cf-I07", "group_id": "py-af4c9eb0b8bbb644", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 92, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2cabdce36f79-I08", "source": "from django.apps import AppConfig\nfrom django.contrib.contenttypes.checks import (\n    check_generic_foreign_keys,\n    check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\nclass ContentTypesConfig(AppConfig):\n    default_auto_field = \"django.db.models.AutoField\"\n    name = \"django.contrib.contenttypes\"\n    verbose_name = _(\"Content Types\")\n\n    def ready(self):\n        first_score = 72\n        second_score = 85\n        if first_score > second_score:\n            higher_score = first_score\n        else:\n            higher_score = second_score\n        pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)\n        post_migrate.connect(create_contenttypes)\n        checks.register(check_generic_foreign_keys, checks.Tags.models)\n        checks.register(check_model_name_lengths, checks.Tags.models)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-af4c9eb0b8bbb644", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "ecc8257545949762ee1067fe8b3eb6a823240803655ee4dd68e22d0c9b80936d", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 26, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__ContentTypesConfig__dce36f79.py", "order": 8, "original_content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "parent_variant_id": "pyint-8725f82ffcfc-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/contenttypes/apps.py#L13-L22", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 3}, "unit_kind": "class", "unit_name": "ContentTypesConfig", "variant_id": "pyint-2cabdce36f79-I08", "group_id": "py-af4c9eb0b8bbb644", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 93, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f67ca814f1a9-I09", "source": "from django.apps import AppConfig\nfrom django.contrib.contenttypes.checks import (\n    check_generic_foreign_keys,\n    check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\nclass ContentTypesConfig(AppConfig):\n    default_auto_field = \"django.db.models.AutoField\"\n    name = \"django.contrib.contenttypes\"\n    verbose_name = _(\"Content Types\")\n\n    def ready(self):\n        lI0O_b697dccd = 0x11ba\n        lI0O_b697dccd = ((lI0O_b697dccd ^ 0x11ba) | 0) & -1\n        if (lI0O_b697dccd & 1) == 1:\n            lI0O_b697dccd ^= lI0O_b697dccd\n        pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)\n        post_migrate.connect(create_contenttypes)\n        checks.register(check_generic_foreign_keys, checks.Tags.models)\n        checks.register(check_model_name_lengths, checks.Tags.models)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-af4c9eb0b8bbb644", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "6b858b37ff4d237695cb5287ac114c8722cd72bb19356101ba60dc5584a11b91", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 24, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__ContentTypesConfig__a814f1a9.py", "order": 9, "original_content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "parent_variant_id": "pyint-8725f82ffcfc-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/contenttypes/apps.py#L13-L22", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 0}, "unit_kind": "class", "unit_name": "ContentTypesConfig", "variant_id": "pyint-f67ca814f1a9-I09", "group_id": "py-af4c9eb0b8bbb644", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 94, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0c9bfb321073-I10", "source": "from django.apps import AppConfig\nfrom django.contrib.contenttypes.checks import (     check_generic_foreign_keys,\n    check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\nclass ContentTypesConfig(AppConfig):\n    default_auto_field = \"django.db.models.AutoField\"\n    name = \"django.contrib.contenttypes\"\n    verbose_name = _(\"Content Types\")\n    def ready(self):\n        pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)\n        post_migrate.connect(create_contenttypes)\n        checks.register(check_generic_foreign_keys, checks.Tags.models)\n        checks.register(check_model_name_lengths, checks.Tags.models)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-af4c9eb0b8bbb644", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "c22aad3ad053396b24af0aa4f90c45941c99e919a15d908115d4e1ad256cdc59", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 18, "local_path": "layout/partially-compact-layout/I10__django__ContentTypesConfig__fb321073.py", "order": 10, "original_content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "parent_variant_id": "pyint-8725f82ffcfc-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/contenttypes/apps.py#L13-L22", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 5, "line_break_groups_removed": 2, "line_breaks_removed": 2, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "ContentTypesConfig", "variant_id": "pyint-0c9bfb321073-I10", "group_id": "py-af4c9eb0b8bbb644", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 95, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-19e92b5c90ca-I11", "source": "from django.apps import AppConfig\nfrom django.contrib.contenttypes.checks import (\n    check_generic_foreign_keys,\n    check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\nclass ContentTypesConfig(AppConfig):\n    default_auto_field = \"django.db.models.AutoField\"\n    name = \"django.contrib.contenttypes\"\n    verbose_name = _(\"Content Types\")\n\n    def ready(self):\n        pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)\n        post_migrate.connect(create_contenttypes)\n        checks.register(check_generic_foreign_keys, checks.Tags.models)\n        checks.register(check_model_name_lengths, checks.Tags.models)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-af4c9eb0b8bbb644", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 20, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__ContentTypesConfig__2b5c90ca.py", "order": 11, "original_content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "parent_variant_id": "pyint-8725f82ffcfc-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/contenttypes/apps.py#L13-L22", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "ContentTypesConfig", "variant_id": "pyint-19e92b5c90ca-I11", "group_id": "py-af4c9eb0b8bbb644", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 96, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d653da083303-I12", "source": "from django.apps import AppConfig\nfrom django.contrib.contenttypes.checks import (\n    check_generic_foreign_keys,\n    check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\nclass ContentTypesConfig(AppConfig):\n    default_auto_field = \"django.db.models.AutoField\"\n    name = \"django.contrib.contenttypes\"\n    verbose_name = _(\"Content Types\")\n\n    def ready(self):\n        pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)\n        post_migrate.connect(create_contenttypes)\n        checks.register(check_generic_foreign_keys, checks.Tags.models)\n        checks.register(check_model_name_lengths, checks.Tags.models)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-af4c9eb0b8bbb644", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 20, "local_path": "data-flow/inline-intermediate-variables/I12__django__ContentTypesConfig__da083303.py", "order": 12, "original_content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "parent_variant_id": "pyint-8725f82ffcfc-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/contenttypes/apps.py#L13-L22", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "ContentTypesConfig", "variant_id": "pyint-d653da083303-I12", "group_id": "py-af4c9eb0b8bbb644", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 97, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-97486e162b1c-I13", "source": "from django.apps import AppConfig\nfrom django.contrib.contenttypes.checks import (\n    check_generic_foreign_keys,\n    check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\nclass ContentTypesConfig(AppConfig):\n    default_auto_field = \"django.db.models.AutoField\"\n    name = \"django.contrib.contenttypes\"\n    verbose_name = _(\"Content Types\")\n\n    def ready(self):\n        pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)\n        post_migrate.connect(create_contenttypes)\n        checks.register(check_generic_foreign_keys, checks.Tags.models)\n        checks.register(check_model_name_lengths, checks.Tags.models)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-af4c9eb0b8bbb644", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 20, "local_path": "control-flow/lower-for-to-while/I13__django__ContentTypesConfig__6e162b1c.py", "order": 13, "original_content_sha256": "7b87286a0beb5d09246046b9acdc81e75a20bb6bcd845495a16d82f9bb34dfe5", "parent_variant_id": "pyint-8725f82ffcfc-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/contenttypes/apps.py#L13-L22", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "ContentTypesConfig", "variant_id": "pyint-97486e162b1c-I13", "group_id": "py-af4c9eb0b8bbb644", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 98, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1c145a4ace99-SRC", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass ClassProps:\n    \"\"\"\n    Effective class properties as derived from parameters to `attr.s()` or\n    `define()` decorators.\n\n    This is the same data structure that *attrs* uses internally to decide how\n    to construct the final class.\n\n    Warning:\n\n        This feature is currently **experimental** and is not covered by our\n        strict backwards-compatibility guarantees.\n\n\n    Attributes:\n        is_exception (bool):\n            Whether the class is treated as an exception class.\n\n        is_slotted (bool):\n            Whether the class is `slotted <slotted classes>`.\n\n        has_weakref_slot (bool):\n            Whether the class has a slot for weak references.\n\n        is_frozen (bool):\n            Whether the class is frozen.\n\n        kw_only (KeywordOnly):\n            Whether / how the class enforces keyword-only arguments on the\n            ``__init__`` method.\n\n        collected_fields_by_mro (bool):\n            Whether the class fields were collected by method resolution order.\n            That is, correctly but unlike `dataclasses`.\n\n        added_init (bool):\n            Whether the class has an *attrs*-generated ``__init__`` method.\n\n        added_repr (bool):\n            Whether the class has an *attrs*-generated ``__repr__`` method.\n\n        added_eq (bool):\n            Whether the class has *attrs*-generated equality methods.\n\n        added_ordering (bool):\n            Whether the class has *attrs*-generated ordering methods.\n\n        hashability (Hashability): How `hashable <hashing>` the class is.\n\n        added_match_args (bool):\n            Whether the class supports positional `match <match>` over its\n            fields.\n\n        added_str (bool):\n            Whether the class has an *attrs*-generated ``__str__`` method.\n\n        added_pickling (bool):\n            Whether the class has *attrs*-generated ``__getstate__`` and\n            ``__setstate__`` methods for `pickle`.\n\n        on_setattr_hook (Callable[[Any, Attribute[Any], Any], Any] | None):\n            The class's ``__setattr__`` hook.\n\n        field_transformer (Callable[[Attribute[Any]], Attribute[Any]] | None):\n            The class's `field transformers <transform-fields>`.\n\n    .. versionadded:: 25.4.0\n    \"\"\"\n\n    class Hashability(enum.Enum):\n        \"\"\"\n        The hashability of a class.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        HASHABLE = \"hashable\"\n        \"\"\"Write a ``__hash__``.\"\"\"\n        HASHABLE_CACHED = \"hashable_cache\"\n        \"\"\"Write a ``__hash__`` and cache the hash.\"\"\"\n        UNHASHABLE = \"unhashable\"\n        \"\"\"Set ``__hash__`` to ``None``.\"\"\"\n        LEAVE_ALONE = \"leave_alone\"\n        \"\"\"Don't touch ``__hash__``.\"\"\"\n\n    class KeywordOnly(enum.Enum):\n        \"\"\"\n        How attributes should be treated regarding keyword-only parameters.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        NO = \"no\"\n        \"\"\"Attributes are not keyword-only.\"\"\"\n        YES = \"yes\"\n        \"\"\"Attributes in current class without kw_only=False are keyword-only.\"\"\"\n        FORCE = \"force\"\n        \"\"\"All attributes are keyword-only.\"\"\"\n\n    __slots__ = (  # noqa: RUF023 -- order matters for __init__\n        \"is_exception\",\n        \"is_slotted\",\n        \"has_weakref_slot\",\n        \"is_frozen\",\n        \"kw_only\",\n        \"collected_fields_by_mro\",\n        \"added_init\",\n        \"added_repr\",\n        \"added_eq\",\n        \"added_ordering\",\n        \"hashability\",\n        \"added_match_args\",\n        \"added_str\",\n        \"added_pickling\",\n        \"on_setattr_hook\",\n        \"field_transformer\",\n    )\n\n    def __init__(\n        self,\n        is_exception,\n        is_slotted,\n        has_weakref_slot,\n        is_frozen,\n        kw_only,\n        collected_fields_by_mro,\n        added_init,\n        added_repr,\n        added_eq,\n        added_ordering,\n        hashability,\n        added_match_args,\n        added_str,\n        added_pickling,\n        on_setattr_hook,\n        field_transformer,\n    ):\n        self.is_exception = is_exception\n        self.is_slotted = is_slotted\n        self.has_weakref_slot = has_weakref_slot\n        self.is_frozen = is_frozen\n        self.kw_only = kw_only\n        self.collected_fields_by_mro = collected_fields_by_mro\n        self.added_init = added_init\n        self.added_repr = added_repr\n        self.added_eq = added_eq\n        self.added_ordering = added_ordering\n        self.hashability = hashability\n        self.added_match_args = added_match_args\n        self.added_str = added_str\n        self.added_pickling = added_pickling\n        self.on_setattr_hook = on_setattr_hook\n        self.field_transformer = field_transformer\n\n    @property\n    def is_hashable(self):\n        return (\n            self.hashability is ClassProps.Hashability.HASHABLE\n            or self.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-b34fc4b00b9cff5b", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 189, "local_path": "source-original/SRC__attrs__ClassProps__5a4ace99.py", "order": 0, "original_content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2902-L3061", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "ClassProps", "variant_id": "pyint-1c145a4ace99-SRC", "group_id": "py-b34fc4b00b9cff5b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1107, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-72b67f997500-I01", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass ClassProps:\n    \n\n    class Hashability(enum.Enum):\n        \n\n        HASHABLE = \"hashable\"\n        \"\"\"Write a ``__hash__``.\"\"\"\n        HASHABLE_CACHED = \"hashable_cache\"\n        \"\"\"Write a ``__hash__`` and cache the hash.\"\"\"\n        UNHASHABLE = \"unhashable\"\n        \"\"\"Set ``__hash__`` to ``None``.\"\"\"\n        LEAVE_ALONE = \"leave_alone\"\n        \"\"\"Don't touch ``__hash__``.\"\"\"\n\n    class KeywordOnly(enum.Enum):\n        \n\n        NO = \"no\"\n        \"\"\"Attributes are not keyword-only.\"\"\"\n        YES = \"yes\"\n        \"\"\"Attributes in current class without kw_only=False are keyword-only.\"\"\"\n        FORCE = \"force\"\n        \"\"\"All attributes are keyword-only.\"\"\"\n\n    __slots__ = (   \n        \"is_exception\",\n        \"is_slotted\",\n        \"has_weakref_slot\",\n        \"is_frozen\",\n        \"kw_only\",\n        \"collected_fields_by_mro\",\n        \"added_init\",\n        \"added_repr\",\n        \"added_eq\",\n        \"added_ordering\",\n        \"hashability\",\n        \"added_match_args\",\n        \"added_str\",\n        \"added_pickling\",\n        \"on_setattr_hook\",\n        \"field_transformer\",\n    )\n\n    def __init__(\n        self,\n        is_exception,\n        is_slotted,\n        has_weakref_slot,\n        is_frozen,\n        kw_only,\n        collected_fields_by_mro,\n        added_init,\n        added_repr,\n        added_eq,\n        added_ordering,\n        hashability,\n        added_match_args,\n        added_str,\n        added_pickling,\n        on_setattr_hook,\n        field_transformer,\n    ):\n        self.is_exception = is_exception\n        self.is_slotted = is_slotted\n        self.has_weakref_slot = has_weakref_slot\n        self.is_frozen = is_frozen\n        self.kw_only = kw_only\n        self.collected_fields_by_mro = collected_fields_by_mro\n        self.added_init = added_init\n        self.added_repr = added_repr\n        self.added_eq = added_eq\n        self.added_ordering = added_ordering\n        self.hashability = hashability\n        self.added_match_args = added_match_args\n        self.added_str = added_str\n        self.added_pickling = added_pickling\n        self.on_setattr_hook = on_setattr_hook\n        self.field_transformer = field_transformer\n\n    @property\n    def is_hashable(self):\n        return (\n            self.hashability is ClassProps.Hashability.HASHABLE\n            or self.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-b34fc4b00b9cff5b", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "c6461172547afbaca3d21eeaa4aaaa76c7be307f5535f6c69c9f42d31d6f6069", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 115, "local_path": "comments/remove-comments/I01__attrs__ClassProps__7f997500.py", "order": 1, "original_content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "parent_variant_id": "pyint-1c145a4ace99-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2902-L3061", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 2472, "comments_removed": 4, "docstrings_removed": 3, "line_comments_removed": 1}, "unit_kind": "class", "unit_name": "ClassProps", "variant_id": "pyint-72b67f997500-I01", "group_id": "py-b34fc4b00b9cff5b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1108, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-66c9d3ff9c93-I02", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass ClassProps:\n    \"\"\"\n    Effective class properties as derived from parameters to `attr.s()` or\n    `define()` decorators.\n\n    This is the same data structure that *attrs* uses internally to decide how\n    to construct the final class.\n\n    Warning:\n\n        This feature is currently **experimental** and is not covered by our\n        strict backwards-compatibility guarantees.\n\n\n    Attributes:\n        is_exception (bool):\n            Whether the class is treated as an exception class.\n\n        is_slotted (bool):\n            Whether the class is `slotted <slotted classes>`.\n\n        has_weakref_slot (bool):\n            Whether the class has a slot for weak references.\n\n        is_frozen (bool):\n            Whether the class is frozen.\n\n        kw_only (KeywordOnly):\n            Whether / how the class enforces keyword-only arguments on the\n            ``__init__`` method.\n\n        collected_fields_by_mro (bool):\n            Whether the class fields were collected by method resolution order.\n            That is, correctly but unlike `dataclasses`.\n\n        added_init (bool):\n            Whether the class has an *attrs*-generated ``__init__`` method.\n\n        added_repr (bool):\n            Whether the class has an *attrs*-generated ``__repr__`` method.\n\n        added_eq (bool):\n            Whether the class has *attrs*-generated equality methods.\n\n        added_ordering (bool):\n            Whether the class has *attrs*-generated ordering methods.\n\n        hashability (Hashability): How `hashable <hashing>` the class is.\n\n        added_match_args (bool):\n            Whether the class supports positional `match <match>` over its\n            fields.\n\n        added_str (bool):\n            Whether the class has an *attrs*-generated ``__str__`` method.\n\n        added_pickling (bool):\n            Whether the class has *attrs*-generated ``__getstate__`` and\n            ``__setstate__`` methods for `pickle`.\n\n        on_setattr_hook (Callable[[Any, Attribute[Any], Any], Any] | None):\n            The class's ``__setattr__`` hook.\n\n        field_transformer (Callable[[Attribute[Any]], Attribute[Any]] | None):\n            The class's `field transformers <transform-fields>`.\n\n    .. versionadded:: 25.4.0\n    \"\"\"\n\n    class Hashability(enum.Enum):\n        \"\"\"\n        The hashability of a class.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        HASHABLE = \"hashable\"\n        \"\"\"Write a ``__hash__``.\"\"\"\n        HASHABLE_CACHED = \"hashable_cache\"\n        \"\"\"Write a ``__hash__`` and cache the hash.\"\"\"\n        UNHASHABLE = \"unhashable\"\n        \"\"\"Set ``__hash__`` to ``None``.\"\"\"\n        LEAVE_ALONE = \"leave_alone\"\n        \"\"\"Don't touch ``__hash__``.\"\"\"\n\n    class KeywordOnly(enum.Enum):\n        \"\"\"\n        How attributes should be treated regarding keyword-only parameters.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        NO = \"no\"\n        \"\"\"Attributes are not keyword-only.\"\"\"\n        YES = \"yes\"\n        \"\"\"Attributes in current class without kw_only=False are keyword-only.\"\"\"\n        FORCE = \"force\"\n        \"\"\"All attributes are keyword-only.\"\"\"\n\n    __slots__ = (  # noqa: RUF023 -- order matters for __init__\n        \"is_exception\",\n        \"is_slotted\",\n        \"has_weakref_slot\",\n        \"is_frozen\",\n        \"kw_only\",\n        \"collected_fields_by_mro\",\n        \"added_init\",\n        \"added_repr\",\n        \"added_eq\",\n        \"added_ordering\",\n        \"hashability\",\n        \"added_match_args\",\n        \"added_str\",\n        \"added_pickling\",\n        \"on_setattr_hook\",\n        \"field_transformer\",\n    )\n\n    def __init__(\n        self,\n        is3,\n        is4,\n        has,\n        is5,\n        kw,\n        collected,\n        added,\n        added2,\n        added3,\n        added4,\n        has2,\n        added5,\n        added6,\n        added7,\n        on,\n        field,\n    ):\n        self.is_exception = is3\n        self.is_slotted = is4\n        self.has_weakref_slot = has\n        self.is_frozen = is5\n        self.kw_only = kw\n        self.collected_fields_by_mro = collected\n        self.added_init = added\n        self.added_repr = added2\n        self.added_eq = added3\n        self.added_ordering = added4\n        self.hashability = has2\n        self.added_match_args = added5\n        self.added_str = added6\n        self.added_pickling = added7\n        self.on_setattr_hook = on\n        self.field_transformer = field\n\n    @property\n    def is2(self):\n        return (\n            self.hashability is ClassProps.Hashability.HASHABLE\n            or self.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-b34fc4b00b9cff5b", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "2254e20edf17195488457d62f259f082009e38dea660546c486aace7506f9420", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 189, "local_path": "identifiers/shorten-identifiers/I02__attrs__ClassProps__d3ff9c93.py", "order": 2, "original_content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "parent_variant_id": "pyint-1c145a4ace99-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2902-L3061", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 33, "identifiers_declared": 17}, "unit_kind": "class", "unit_name": "ClassProps", "variant_id": "pyint-66c9d3ff9c93-I02", "group_id": "py-b34fc4b00b9cff5b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1109, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7e5ef0b951d7-I03", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass ClassProps:\n    \"\"\"\n    Effective class properties as derived from parameters to `attr.s()` or\n    `define()` decorators.\n\n    This is the same data structure that *attrs* uses internally to decide how\n    to construct the final class.\n\n    Warning:\n\n        This feature is currently **experimental** and is not covered by our\n        strict backwards-compatibility guarantees.\n\n\n    Attributes:\n        is_exception (bool):\n            Whether the class is treated as an exception class.\n\n        is_slotted (bool):\n            Whether the class is `slotted <slotted classes>`.\n\n        has_weakref_slot (bool):\n            Whether the class has a slot for weak references.\n\n        is_frozen (bool):\n            Whether the class is frozen.\n\n        kw_only (KeywordOnly):\n            Whether / how the class enforces keyword-only arguments on the\n            ``__init__`` method.\n\n        collected_fields_by_mro (bool):\n            Whether the class fields were collected by method resolution order.\n            That is, correctly but unlike `dataclasses`.\n\n        added_init (bool):\n            Whether the class has an *attrs*-generated ``__init__`` method.\n\n        added_repr (bool):\n            Whether the class has an *attrs*-generated ``__repr__`` method.\n\n        added_eq (bool):\n            Whether the class has *attrs*-generated equality methods.\n\n        added_ordering (bool):\n            Whether the class has *attrs*-generated ordering methods.\n\n        hashability (Hashability): How `hashable <hashing>` the class is.\n\n        added_match_args (bool):\n            Whether the class supports positional `match <match>` over its\n            fields.\n\n        added_str (bool):\n            Whether the class has an *attrs*-generated ``__str__`` method.\n\n        added_pickling (bool):\n            Whether the class has *attrs*-generated ``__getstate__`` and\n            ``__setstate__`` methods for `pickle`.\n\n        on_setattr_hook (Callable[[Any, Attribute[Any], Any], Any] | None):\n            The class's ``__setattr__`` hook.\n\n        field_transformer (Callable[[Attribute[Any]], Attribute[Any]] | None):\n            The class's `field transformers <transform-fields>`.\n\n    .. versionadded:: 25.4.0\n    \"\"\"\n\n    class Hashability(enum.Enum):\n        \"\"\"\n        The hashability of a class.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        HASHABLE = \"hashable\"\n        \"\"\"Write a ``__hash__``.\"\"\"\n        HASHABLE_CACHED = \"hashable_cache\"\n        \"\"\"Write a ``__hash__`` and cache the hash.\"\"\"\n        UNHASHABLE = \"unhashable\"\n        \"\"\"Set ``__hash__`` to ``None``.\"\"\"\n        LEAVE_ALONE = \"leave_alone\"\n        \"\"\"Don't touch ``__hash__``.\"\"\"\n\n    class KeywordOnly(enum.Enum):\n        \"\"\"\n        How attributes should be treated regarding keyword-only parameters.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        NO = \"no\"\n        \"\"\"Attributes are not keyword-only.\"\"\"\n        YES = \"yes\"\n        \"\"\"Attributes in current class without kw_only=False are keyword-only.\"\"\"\n        FORCE = \"force\"\n        \"\"\"All attributes are keyword-only.\"\"\"\n\n    __slots__ = (  # noqa: RUF023 -- order matters for __init__\n        \"is_exception\",\n        \"is_slotted\",\n        \"has_weakref_slot\",\n        \"is_frozen\",\n        \"kw_only\",\n        \"collected_fields_by_mro\",\n        \"added_init\",\n        \"added_repr\",\n        \"added_eq\",\n        \"added_ordering\",\n        \"hashability\",\n        \"added_match_args\",\n        \"added_str\",\n        \"added_pickling\",\n        \"on_setattr_hook\",\n        \"field_transformer\",\n    )\n\n    def __init__(\n        self,\n        primaryScore,\n        finalCache,\n        primaryAccount,\n        tempValue,\n        version,\n        currentAccount,\n        activePath,\n        remoteNode,\n        document,\n        primaryAddress,\n        backupBatch,\n        defaultBalance,\n        reference,\n        pendingSession,\n        primaryMessage,\n        defaultAccount,\n    ):\n        self.is_exception = primaryScore\n        self.is_slotted = finalCache\n        self.has_weakref_slot = primaryAccount\n        self.is_frozen = tempValue\n        self.kw_only = version\n        self.collected_fields_by_mro = currentAccount\n        self.added_init = activePath\n        self.added_repr = remoteNode\n        self.added_eq = document\n        self.added_ordering = primaryAddress\n        self.hashability = backupBatch\n        self.added_match_args = defaultBalance\n        self.added_str = reference\n        self.added_pickling = pendingSession\n        self.on_setattr_hook = primaryMessage\n        self.field_transformer = defaultAccount\n\n    @property\n    def removeScore(self):\n        return (\n            self.hashability is ClassProps.Hashability.HASHABLE\n            or self.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-b34fc4b00b9cff5b", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "42e30e57d8044664f93e562ac404272d458d097617a38c285d604a86807c6887", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 189, "local_path": "identifiers/mislead-identifiers/I03__attrs__ClassProps__f0b951d7.py", "order": 3, "original_content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "parent_variant_id": "pyint-1c145a4ace99-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2902-L3061", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 33, "identifiers_declared": 17, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 11, "local_random_pool_selections": 16, "local_total_length_difference": 17, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "ClassProps", "variant_id": "pyint-7e5ef0b951d7-I03", "group_id": "py-b34fc4b00b9cff5b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1110, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cac60587cee2-I04", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass ClassProps:\n    \"\"\"\n    Effective class properties as derived from parameters to `attr.s()` or\n    `define()` decorators.\n\n    This is the same data structure that *attrs* uses internally to decide how\n    to construct the final class.\n\n    Warning:\n\n        This feature is currently **experimental** and is not covered by our\n        strict backwards-compatibility guarantees.\n\n\n    Attributes:\n        is_exception (bool):\n            Whether the class is treated as an exception class.\n\n        is_slotted (bool):\n            Whether the class is `slotted <slotted classes>`.\n\n        has_weakref_slot (bool):\n            Whether the class has a slot for weak references.\n\n        is_frozen (bool):\n            Whether the class is frozen.\n\n        kw_only (KeywordOnly):\n            Whether / how the class enforces keyword-only arguments on the\n            ``__init__`` method.\n\n        collected_fields_by_mro (bool):\n            Whether the class fields were collected by method resolution order.\n            That is, correctly but unlike `dataclasses`.\n\n        added_init (bool):\n            Whether the class has an *attrs*-generated ``__init__`` method.\n\n        added_repr (bool):\n            Whether the class has an *attrs*-generated ``__repr__`` method.\n\n        added_eq (bool):\n            Whether the class has *attrs*-generated equality methods.\n\n        added_ordering (bool):\n            Whether the class has *attrs*-generated ordering methods.\n\n        hashability (Hashability): How `hashable <hashing>` the class is.\n\n        added_match_args (bool):\n            Whether the class supports positional `match <match>` over its\n            fields.\n\n        added_str (bool):\n            Whether the class has an *attrs*-generated ``__str__`` method.\n\n        added_pickling (bool):\n            Whether the class has *attrs*-generated ``__getstate__`` and\n            ``__setstate__`` methods for `pickle`.\n\n        on_setattr_hook (Callable[[Any, Attribute[Any], Any], Any] | None):\n            The class's ``__setattr__`` hook.\n\n        field_transformer (Callable[[Attribute[Any]], Attribute[Any]] | None):\n            The class's `field transformers <transform-fields>`.\n\n    .. versionadded:: 25.4.0\n    \"\"\"\n\n    class Hashability(enum.Enum):\n        \"\"\"\n        The hashability of a class.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        HASHABLE = \"hashable\"\n        \"\"\"Write a ``__hash__``.\"\"\"\n        HASHABLE_CACHED = \"hashable_cache\"\n        \"\"\"Write a ``__hash__`` and cache the hash.\"\"\"\n        UNHASHABLE = \"unhashable\"\n        \"\"\"Set ``__hash__`` to ``None``.\"\"\"\n        LEAVE_ALONE = \"leave_alone\"\n        \"\"\"Don't touch ``__hash__``.\"\"\"\n\n    class KeywordOnly(enum.Enum):\n        \"\"\"\n        How attributes should be treated regarding keyword-only parameters.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        NO = \"no\"\n        \"\"\"Attributes are not keyword-only.\"\"\"\n        YES = \"yes\"\n        \"\"\"Attributes in current class without kw_only=False are keyword-only.\"\"\"\n        FORCE = \"force\"\n        \"\"\"All attributes are keyword-only.\"\"\"\n\n    __slots__ = (  # noqa: RUF023 -- order matters for __init__\n        \"is_exception\",\n        \"is_slotted\",\n        \"has_weakref_slot\",\n        \"is_frozen\",\n        \"kw_only\",\n        \"collected_fields_by_mro\",\n        \"added_init\",\n        \"added_repr\",\n        \"added_eq\",\n        \"added_ordering\",\n        \"hashability\",\n        \"added_match_args\",\n        \"added_str\",\n        \"added_pickling\",\n        \"on_setattr_hook\",\n        \"field_transformer\",\n    )\n\n    def __init__(\n        self,\n        b,\n        c,\n        d,\n        e,\n        f,\n        g,\n        h,\n        i,\n        j,\n        k,\n        l,\n        m,\n        n,\n        o,\n        p,\n        q,\n    ):\n        self.is_exception = b\n        self.is_slotted = c\n        self.has_weakref_slot = d\n        self.is_frozen = e\n        self.kw_only = f\n        self.collected_fields_by_mro = g\n        self.added_init = h\n        self.added_repr = i\n        self.added_eq = j\n        self.added_ordering = k\n        self.hashability = l\n        self.added_match_args = m\n        self.added_str = n\n        self.added_pickling = o\n        self.on_setattr_hook = p\n        self.field_transformer = q\n\n    @property\n    def a(self):\n        return (\n            self.hashability is ClassProps.Hashability.HASHABLE\n            or self.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-b34fc4b00b9cff5b", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "68152bf2d537c29e8077d98ae1f6c9399fc241de48862261398ba0b07f6035ea", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 189, "local_path": "identifiers/garble-identifiers/I04__attrs__ClassProps__0587cee2.py", "order": 4, "original_content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "parent_variant_id": "pyint-1c145a4ace99-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2902-L3061", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 33, "identifiers_declared": 17}, "unit_kind": "class", "unit_name": "ClassProps", "variant_id": "pyint-cac60587cee2-I04", "group_id": "py-b34fc4b00b9cff5b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1111, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-732f72fd8c84-I05", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass ClassProps:\n    \"\"\"\n    Effective class properties as derived from parameters to `attr.s()` or\n    `define()` decorators.\n\n    This is the same data structure that *attrs* uses internally to decide how\n    to construct the final class.\n\n    Warning:\n\n        This feature is currently **experimental** and is not covered by our\n        strict backwards-compatibility guarantees.\n\n\n    Attributes:\n        is_exception (bool):\n            Whether the class is treated as an exception class.\n\n        is_slotted (bool):\n            Whether the class is `slotted <slotted classes>`.\n\n        has_weakref_slot (bool):\n            Whether the class has a slot for weak references.\n\n        is_frozen (bool):\n            Whether the class is frozen.\n\n        kw_only (KeywordOnly):\n            Whether / how the class enforces keyword-only arguments on the\n            ``__init__`` method.\n\n        collected_fields_by_mro (bool):\n            Whether the class fields were collected by method resolution order.\n            That is, correctly but unlike `dataclasses`.\n\n        added_init (bool):\n            Whether the class has an *attrs*-generated ``__init__`` method.\n\n        added_repr (bool):\n            Whether the class has an *attrs*-generated ``__repr__`` method.\n\n        added_eq (bool):\n            Whether the class has *attrs*-generated equality methods.\n\n        added_ordering (bool):\n            Whether the class has *attrs*-generated ordering methods.\n\n        hashability (Hashability): How `hashable <hashing>` the class is.\n\n        added_match_args (bool):\n            Whether the class supports positional `match <match>` over its\n            fields.\n\n        added_str (bool):\n            Whether the class has an *attrs*-generated ``__str__`` method.\n\n        added_pickling (bool):\n            Whether the class has *attrs*-generated ``__getstate__`` and\n            ``__setstate__`` methods for `pickle`.\n\n        on_setattr_hook (Callable[[Any, Attribute[Any], Any], Any] | None):\n            The class's ``__setattr__`` hook.\n\n        field_transformer (Callable[[Attribute[Any]], Attribute[Any]] | None):\n            The class's `field transformers <transform-fields>`.\n\n    .. versionadded:: 25.4.0\n    \"\"\"\n\n    class Hashability(enum.Enum):\n        \"\"\"\n        The hashability of a class.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        HASHABLE = \"hashable\"\n        \"\"\"Write a ``__hash__``.\"\"\"\n        HASHABLE_CACHED = \"hashable_cache\"\n        \"\"\"Write a ``__hash__`` and cache the hash.\"\"\"\n        UNHASHABLE = \"unhashable\"\n        \"\"\"Set ``__hash__`` to ``None``.\"\"\"\n        LEAVE_ALONE = \"leave_alone\"\n        \"\"\"Don't touch ``__hash__``.\"\"\"\n\n    class KeywordOnly(enum.Enum):\n        \"\"\"\n        How attributes should be treated regarding keyword-only parameters.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        NO = \"no\"\n        \"\"\"Attributes are not keyword-only.\"\"\"\n        YES = \"yes\"\n        \"\"\"Attributes in current class without kw_only=False are keyword-only.\"\"\"\n        FORCE = \"force\"\n        \"\"\"All attributes are keyword-only.\"\"\"\n\n    __slots__ = (  # noqa: RUF023 -- order matters for __init__\n        \"is_exception\",\n        \"is_slotted\",\n        \"has_weakref_slot\",\n        \"is_frozen\",\n        \"kw_only\",\n        \"collected_fields_by_mro\",\n        \"added_init\",\n        \"added_repr\",\n        \"added_eq\",\n        \"added_ordering\",\n        \"hashability\",\n        \"added_match_args\",\n        \"added_str\",\n        \"added_pickling\",\n        \"on_setattr_hook\",\n        \"field_transformer\",\n    )\n\n    def __init__(\n        self,\n        is_exception,\n        is_slotted,\n        has_weakref_slot,\n        is_frozen,\n        kw_only,\n        collected_fields_by_mro,\n        added_init,\n        added_repr,\n        added_eq,\n        added_ordering,\n        hashability,\n        added_match_args,\n        added_str,\n        added_pickling,\n        on_setattr_hook,\n        field_transformer,\n    ):\n        self.is_exception = is_exception\n        self.is_slotted = is_slotted\n        self.has_weakref_slot = has_weakref_slot\n        self.is_frozen = is_frozen\n        self.kw_only = kw_only\n        self.collected_fields_by_mro = collected_fields_by_mro\n        self.added_init = added_init\n        self.added_repr = added_repr\n        self.added_eq = added_eq\n        self.added_ordering = added_ordering\n        self.hashability = hashability\n        self.added_match_args = added_match_args\n        self.added_str = added_str\n        self.added_pickling = added_pickling\n        self.on_setattr_hook = on_setattr_hook\n        self.field_transformer = field_transformer\n\n    @property\n    def is_hashable(self):\n        return (\n            self.hashability is ClassProps.Hashability.HASHABLE\n            or self.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-b34fc4b00b9cff5b", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 189, "local_path": "expressions/encode-integer-literals/I05__attrs__ClassProps__72fd8c84.py", "order": 5, "original_content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "parent_variant_id": "pyint-1c145a4ace99-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2902-L3061", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "ClassProps", "variant_id": "pyint-732f72fd8c84-I05", "group_id": "py-b34fc4b00b9cff5b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1112, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-45b0b7ba4b70-I06", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass ClassProps:\n    \"\"\"\n    Effective class properties as derived from parameters to `attr.s()` or\n    `define()` decorators.\n\n    This is the same data structure that *attrs* uses internally to decide how\n    to construct the final class.\n\n    Warning:\n\n        This feature is currently **experimental** and is not covered by our\n        strict backwards-compatibility guarantees.\n\n\n    Attributes:\n        is_exception (bool):\n            Whether the class is treated as an exception class.\n\n        is_slotted (bool):\n            Whether the class is `slotted <slotted classes>`.\n\n        has_weakref_slot (bool):\n            Whether the class has a slot for weak references.\n\n        is_frozen (bool):\n            Whether the class is frozen.\n\n        kw_only (KeywordOnly):\n            Whether / how the class enforces keyword-only arguments on the\n            ``__init__`` method.\n\n        collected_fields_by_mro (bool):\n            Whether the class fields were collected by method resolution order.\n            That is, correctly but unlike `dataclasses`.\n\n        added_init (bool):\n            Whether the class has an *attrs*-generated ``__init__`` method.\n\n        added_repr (bool):\n            Whether the class has an *attrs*-generated ``__repr__`` method.\n\n        added_eq (bool):\n            Whether the class has *attrs*-generated equality methods.\n\n        added_ordering (bool):\n            Whether the class has *attrs*-generated ordering methods.\n\n        hashability (Hashability): How `hashable <hashing>` the class is.\n\n        added_match_args (bool):\n            Whether the class supports positional `match <match>` over its\n            fields.\n\n        added_str (bool):\n            Whether the class has an *attrs*-generated ``__str__`` method.\n\n        added_pickling (bool):\n            Whether the class has *attrs*-generated ``__getstate__`` and\n            ``__setstate__`` methods for `pickle`.\n\n        on_setattr_hook (Callable[[Any, Attribute[Any], Any], Any] | None):\n            The class's ``__setattr__`` hook.\n\n        field_transformer (Callable[[Attribute[Any]], Attribute[Any]] | None):\n            The class's `field transformers <transform-fields>`.\n\n    .. versionadded:: 25.4.0\n    \"\"\"\n\n    class Hashability(enum.Enum):\n        \"\"\"\n        The hashability of a class.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        HASHABLE = \"hashable\"\n        \"\"\"Write a ``__hash__``.\"\"\"\n        HASHABLE_CACHED = \"hashable_cache\"\n        \"\"\"Write a ``__hash__`` and cache the hash.\"\"\"\n        UNHASHABLE = \"unhashable\"\n        \"\"\"Set ``__hash__`` to ``None``.\"\"\"\n        LEAVE_ALONE = \"leave_alone\"\n        \"\"\"Don't touch ``__hash__``.\"\"\"\n\n    class KeywordOnly(enum.Enum):\n        \"\"\"\n        How attributes should be treated regarding keyword-only parameters.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        NO = \"no\"\n        \"\"\"Attributes are not keyword-only.\"\"\"\n        YES = \"yes\"\n        \"\"\"Attributes in current class without kw_only=False are keyword-only.\"\"\"\n        FORCE = \"force\"\n        \"\"\"All attributes are keyword-only.\"\"\"\n\n    __slots__ = (  # noqa: RUF023 -- order matters for __init__\n        \"is_exception\",\n        \"is_slotted\",\n        \"has_weakref_slot\",\n        \"is_frozen\",\n        \"kw_only\",\n        \"collected_fields_by_mro\",\n        \"added_init\",\n        \"added_repr\",\n        \"added_eq\",\n        \"added_ordering\",\n        \"hashability\",\n        \"added_match_args\",\n        \"added_str\",\n        \"added_pickling\",\n        \"on_setattr_hook\",\n        \"field_transformer\",\n    )\n\n    def __init__(\n        self,\n        is_exception,\n        is_slotted,\n        has_weakref_slot,\n        is_frozen,\n        kw_only,\n        collected_fields_by_mro,\n        added_init,\n        added_repr,\n        added_eq,\n        added_ordering,\n        hashability,\n        added_match_args,\n        added_str,\n        added_pickling,\n        on_setattr_hook,\n        field_transformer,\n    ):\n        self.is_exception = is_exception\n        self.is_slotted = is_slotted\n        self.has_weakref_slot = has_weakref_slot\n        self.is_frozen = is_frozen\n        self.kw_only = kw_only\n        self.collected_fields_by_mro = collected_fields_by_mro\n        self.added_init = added_init\n        self.added_repr = added_repr\n        self.added_eq = added_eq\n        self.added_ordering = added_ordering\n        self.hashability = hashability\n        self.added_match_args = added_match_args\n        self.added_str = added_str\n        self.added_pickling = added_pickling\n        self.on_setattr_hook = on_setattr_hook\n        self.field_transformer = field_transformer\n\n    @property\n    def is_hashable(self):\n        return (\n            self.hashability is ClassProps.Hashability.HASHABLE\n            or self.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-b34fc4b00b9cff5b", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 189, "local_path": "expressions/invert-conditions/I06__attrs__ClassProps__b7ba4b70.py", "order": 6, "original_content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "parent_variant_id": "pyint-1c145a4ace99-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2902-L3061", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "ClassProps", "variant_id": "pyint-45b0b7ba4b70-I06", "group_id": "py-b34fc4b00b9cff5b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1113, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-db385912f015-I07", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass ClassProps:\n    \"\"\"\n    Effective class properties as derived from parameters to `attr.s()` or\n    `define()` decorators.\n\n    This is the same data structure that *attrs* uses internally to decide how\n    to construct the final class.\n\n    Warning:\n\n        This feature is currently **experimental** and is not covered by our\n        strict backwards-compatibility guarantees.\n\n\n    Attributes:\n        is_exception (bool):\n            Whether the class is treated as an exception class.\n\n        is_slotted (bool):\n            Whether the class is `slotted <slotted classes>`.\n\n        has_weakref_slot (bool):\n            Whether the class has a slot for weak references.\n\n        is_frozen (bool):\n            Whether the class is frozen.\n\n        kw_only (KeywordOnly):\n            Whether / how the class enforces keyword-only arguments on the\n            ``__init__`` method.\n\n        collected_fields_by_mro (bool):\n            Whether the class fields were collected by method resolution order.\n            That is, correctly but unlike `dataclasses`.\n\n        added_init (bool):\n            Whether the class has an *attrs*-generated ``__init__`` method.\n\n        added_repr (bool):\n            Whether the class has an *attrs*-generated ``__repr__`` method.\n\n        added_eq (bool):\n            Whether the class has *attrs*-generated equality methods.\n\n        added_ordering (bool):\n            Whether the class has *attrs*-generated ordering methods.\n\n        hashability (Hashability): How `hashable <hashing>` the class is.\n\n        added_match_args (bool):\n            Whether the class supports positional `match <match>` over its\n            fields.\n\n        added_str (bool):\n            Whether the class has an *attrs*-generated ``__str__`` method.\n\n        added_pickling (bool):\n            Whether the class has *attrs*-generated ``__getstate__`` and\n            ``__setstate__`` methods for `pickle`.\n\n        on_setattr_hook (Callable[[Any, Attribute[Any], Any], Any] | None):\n            The class's ``__setattr__`` hook.\n\n        field_transformer (Callable[[Attribute[Any]], Attribute[Any]] | None):\n            The class's `field transformers <transform-fields>`.\n\n    .. versionadded:: 25.4.0\n    \"\"\"\n\n    class Hashability(enum.Enum):\n        \"\"\"\n        The hashability of a class.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        HASHABLE = \"hashable\"\n        \"\"\"Write a ``__hash__``.\"\"\"\n        HASHABLE_CACHED = \"hashable_cache\"\n        \"\"\"Write a ``__hash__`` and cache the hash.\"\"\"\n        UNHASHABLE = \"unhashable\"\n        \"\"\"Set ``__hash__`` to ``None``.\"\"\"\n        LEAVE_ALONE = \"leave_alone\"\n        \"\"\"Don't touch ``__hash__``.\"\"\"\n\n    class KeywordOnly(enum.Enum):\n        \"\"\"\n        How attributes should be treated regarding keyword-only parameters.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        NO = \"no\"\n        \"\"\"Attributes are not keyword-only.\"\"\"\n        YES = \"yes\"\n        \"\"\"Attributes in current class without kw_only=False are keyword-only.\"\"\"\n        FORCE = \"force\"\n        \"\"\"All attributes are keyword-only.\"\"\"\n\n    __slots__ = (  # noqa: RUF023 -- order matters for __init__\n        \"is_exception\",\n        \"is_slotted\",\n        \"has_weakref_slot\",\n        \"is_frozen\",\n        \"kw_only\",\n        \"collected_fields_by_mro\",\n        \"added_init\",\n        \"added_repr\",\n        \"added_eq\",\n        \"added_ordering\",\n        \"hashability\",\n        \"added_match_args\",\n        \"added_str\",\n        \"added_pickling\",\n        \"on_setattr_hook\",\n        \"field_transformer\",\n    )\n\n    def __init__(\n        self,\n        is_exception,\n        is_slotted,\n        has_weakref_slot,\n        is_frozen,\n        kw_only,\n        collected_fields_by_mro,\n        added_init,\n        added_repr,\n        added_eq,\n        added_ordering,\n        hashability,\n        added_match_args,\n        added_str,\n        added_pickling,\n        on_setattr_hook,\n        field_transformer,\n    ):\n        if ((0x9dbb ^ 0x9dbb) != 0):\n            raise AssertionError()\n        self.is_exception = is_exception\n        self.is_slotted = is_slotted\n        self.has_weakref_slot = has_weakref_slot\n        self.is_frozen = is_frozen\n        self.kw_only = kw_only\n        self.collected_fields_by_mro = collected_fields_by_mro\n        self.added_init = added_init\n        self.added_repr = added_repr\n        self.added_eq = added_eq\n        self.added_ordering = added_ordering\n        self.hashability = hashability\n        self.added_match_args = added_match_args\n        self.added_str = added_str\n        self.added_pickling = added_pickling\n        self.on_setattr_hook = on_setattr_hook\n        self.field_transformer = field_transformer\n\n    @property\n    def is_hashable(self):\n        if ((0x5507 ^ 0x5507) != 0):\n            raise AssertionError()\n        return (\n            self.hashability is ClassProps.Hashability.HASHABLE\n            or self.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-b34fc4b00b9cff5b", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "cb2841f0e2ecb2c5b43ecb504477d0a1c0b0ac031c100a9268005901d9f25b46", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 193, "local_path": "code-injection/insert-dead-branches/I07__attrs__ClassProps__5912f015.py", "order": 7, "original_content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "parent_variant_id": "pyint-1c145a4ace99-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2902-L3061", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "ClassProps", "variant_id": "pyint-db385912f015-I07", "group_id": "py-b34fc4b00b9cff5b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1114, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a263266385a0-I08", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass ClassProps:\n    \"\"\"\n    Effective class properties as derived from parameters to `attr.s()` or\n    `define()` decorators.\n\n    This is the same data structure that *attrs* uses internally to decide how\n    to construct the final class.\n\n    Warning:\n\n        This feature is currently **experimental** and is not covered by our\n        strict backwards-compatibility guarantees.\n\n\n    Attributes:\n        is_exception (bool):\n            Whether the class is treated as an exception class.\n\n        is_slotted (bool):\n            Whether the class is `slotted <slotted classes>`.\n\n        has_weakref_slot (bool):\n            Whether the class has a slot for weak references.\n\n        is_frozen (bool):\n            Whether the class is frozen.\n\n        kw_only (KeywordOnly):\n            Whether / how the class enforces keyword-only arguments on the\n            ``__init__`` method.\n\n        collected_fields_by_mro (bool):\n            Whether the class fields were collected by method resolution order.\n            That is, correctly but unlike `dataclasses`.\n\n        added_init (bool):\n            Whether the class has an *attrs*-generated ``__init__`` method.\n\n        added_repr (bool):\n            Whether the class has an *attrs*-generated ``__repr__`` method.\n\n        added_eq (bool):\n            Whether the class has *attrs*-generated equality methods.\n\n        added_ordering (bool):\n            Whether the class has *attrs*-generated ordering methods.\n\n        hashability (Hashability): How `hashable <hashing>` the class is.\n\n        added_match_args (bool):\n            Whether the class supports positional `match <match>` over its\n            fields.\n\n        added_str (bool):\n            Whether the class has an *attrs*-generated ``__str__`` method.\n\n        added_pickling (bool):\n            Whether the class has *attrs*-generated ``__getstate__`` and\n            ``__setstate__`` methods for `pickle`.\n\n        on_setattr_hook (Callable[[Any, Attribute[Any], Any], Any] | None):\n            The class's ``__setattr__`` hook.\n\n        field_transformer (Callable[[Attribute[Any]], Attribute[Any]] | None):\n            The class's `field transformers <transform-fields>`.\n\n    .. versionadded:: 25.4.0\n    \"\"\"\n\n    class Hashability(enum.Enum):\n        \"\"\"\n        The hashability of a class.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        HASHABLE = \"hashable\"\n        \"\"\"Write a ``__hash__``.\"\"\"\n        HASHABLE_CACHED = \"hashable_cache\"\n        \"\"\"Write a ``__hash__`` and cache the hash.\"\"\"\n        UNHASHABLE = \"unhashable\"\n        \"\"\"Set ``__hash__`` to ``None``.\"\"\"\n        LEAVE_ALONE = \"leave_alone\"\n        \"\"\"Don't touch ``__hash__``.\"\"\"\n\n    class KeywordOnly(enum.Enum):\n        \"\"\"\n        How attributes should be treated regarding keyword-only parameters.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        NO = \"no\"\n        \"\"\"Attributes are not keyword-only.\"\"\"\n        YES = \"yes\"\n        \"\"\"Attributes in current class without kw_only=False are keyword-only.\"\"\"\n        FORCE = \"force\"\n        \"\"\"All attributes are keyword-only.\"\"\"\n\n    __slots__ = (  # noqa: RUF023 -- order matters for __init__\n        \"is_exception\",\n        \"is_slotted\",\n        \"has_weakref_slot\",\n        \"is_frozen\",\n        \"kw_only\",\n        \"collected_fields_by_mro\",\n        \"added_init\",\n        \"added_repr\",\n        \"added_eq\",\n        \"added_ordering\",\n        \"hashability\",\n        \"added_match_args\",\n        \"added_str\",\n        \"added_pickling\",\n        \"on_setattr_hook\",\n        \"field_transformer\",\n    )\n\n    def __init__(\n        self,\n        is_exception,\n        is_slotted,\n        has_weakref_slot,\n        is_frozen,\n        kw_only,\n        collected_fields_by_mro,\n        added_init,\n        added_repr,\n        added_eq,\n        added_ordering,\n        hashability,\n        added_match_args,\n        added_str,\n        added_pickling,\n        on_setattr_hook,\n        field_transformer,\n    ):\n        self.is_exception = is_exception\n        self.is_slotted = is_slotted\n        self.has_weakref_slot = has_weakref_slot\n        self.is_frozen = is_frozen\n        self.kw_only = kw_only\n        self.collected_fields_by_mro = collected_fields_by_mro\n        self.added_init = added_init\n        self.added_repr = added_repr\n        self.added_eq = added_eq\n        self.added_ordering = added_ordering\n        self.hashability = hashability\n        self.added_match_args = added_match_args\n        self.added_str = added_str\n        self.added_pickling = added_pickling\n        self.on_setattr_hook = on_setattr_hook\n        self.field_transformer = field_transformer\n\n    @property\n    def is_hashable(self):\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        return (\n            self.hashability is ClassProps.Hashability.HASHABLE\n            or self.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-b34fc4b00b9cff5b", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "6e67381c31df5b2e693a83b96545522661bf8144d019a7e9fed99cda78ab2a84", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 194, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs__ClassProps__266385a0.py", "order": 8, "original_content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "parent_variant_id": "pyint-1c145a4ace99-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2902-L3061", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "ClassProps", "variant_id": "pyint-a263266385a0-I08", "group_id": "py-b34fc4b00b9cff5b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1115, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-881ac436fade-I09", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass ClassProps:\n    \"\"\"\n    Effective class properties as derived from parameters to `attr.s()` or\n    `define()` decorators.\n\n    This is the same data structure that *attrs* uses internally to decide how\n    to construct the final class.\n\n    Warning:\n\n        This feature is currently **experimental** and is not covered by our\n        strict backwards-compatibility guarantees.\n\n\n    Attributes:\n        is_exception (bool):\n            Whether the class is treated as an exception class.\n\n        is_slotted (bool):\n            Whether the class is `slotted <slotted classes>`.\n\n        has_weakref_slot (bool):\n            Whether the class has a slot for weak references.\n\n        is_frozen (bool):\n            Whether the class is frozen.\n\n        kw_only (KeywordOnly):\n            Whether / how the class enforces keyword-only arguments on the\n            ``__init__`` method.\n\n        collected_fields_by_mro (bool):\n            Whether the class fields were collected by method resolution order.\n            That is, correctly but unlike `dataclasses`.\n\n        added_init (bool):\n            Whether the class has an *attrs*-generated ``__init__`` method.\n\n        added_repr (bool):\n            Whether the class has an *attrs*-generated ``__repr__`` method.\n\n        added_eq (bool):\n            Whether the class has *attrs*-generated equality methods.\n\n        added_ordering (bool):\n            Whether the class has *attrs*-generated ordering methods.\n\n        hashability (Hashability): How `hashable <hashing>` the class is.\n\n        added_match_args (bool):\n            Whether the class supports positional `match <match>` over its\n            fields.\n\n        added_str (bool):\n            Whether the class has an *attrs*-generated ``__str__`` method.\n\n        added_pickling (bool):\n            Whether the class has *attrs*-generated ``__getstate__`` and\n            ``__setstate__`` methods for `pickle`.\n\n        on_setattr_hook (Callable[[Any, Attribute[Any], Any], Any] | None):\n            The class's ``__setattr__`` hook.\n\n        field_transformer (Callable[[Attribute[Any]], Attribute[Any]] | None):\n            The class's `field transformers <transform-fields>`.\n\n    .. versionadded:: 25.4.0\n    \"\"\"\n\n    class Hashability(enum.Enum):\n        \"\"\"\n        The hashability of a class.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        HASHABLE = \"hashable\"\n        \"\"\"Write a ``__hash__``.\"\"\"\n        HASHABLE_CACHED = \"hashable_cache\"\n        \"\"\"Write a ``__hash__`` and cache the hash.\"\"\"\n        UNHASHABLE = \"unhashable\"\n        \"\"\"Set ``__hash__`` to ``None``.\"\"\"\n        LEAVE_ALONE = \"leave_alone\"\n        \"\"\"Don't touch ``__hash__``.\"\"\"\n\n    class KeywordOnly(enum.Enum):\n        \"\"\"\n        How attributes should be treated regarding keyword-only parameters.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        NO = \"no\"\n        \"\"\"Attributes are not keyword-only.\"\"\"\n        YES = \"yes\"\n        \"\"\"Attributes in current class without kw_only=False are keyword-only.\"\"\"\n        FORCE = \"force\"\n        \"\"\"All attributes are keyword-only.\"\"\"\n\n    __slots__ = (  # noqa: RUF023 -- order matters for __init__\n        \"is_exception\",\n        \"is_slotted\",\n        \"has_weakref_slot\",\n        \"is_frozen\",\n        \"kw_only\",\n        \"collected_fields_by_mro\",\n        \"added_init\",\n        \"added_repr\",\n        \"added_eq\",\n        \"added_ordering\",\n        \"hashability\",\n        \"added_match_args\",\n        \"added_str\",\n        \"added_pickling\",\n        \"on_setattr_hook\",\n        \"field_transformer\",\n    )\n\n    def __init__(\n        self,\n        is_exception,\n        is_slotted,\n        has_weakref_slot,\n        is_frozen,\n        kw_only,\n        collected_fields_by_mro,\n        added_init,\n        added_repr,\n        added_eq,\n        added_ordering,\n        hashability,\n        added_match_args,\n        added_str,\n        added_pickling,\n        on_setattr_hook,\n        field_transformer,\n    ):\n        self.is_exception = is_exception\n        self.is_slotted = is_slotted\n        self.has_weakref_slot = has_weakref_slot\n        self.is_frozen = is_frozen\n        self.kw_only = kw_only\n        self.collected_fields_by_mro = collected_fields_by_mro\n        self.added_init = added_init\n        self.added_repr = added_repr\n        self.added_eq = added_eq\n        self.added_ordering = added_ordering\n        self.hashability = hashability\n        self.added_match_args = added_match_args\n        self.added_str = added_str\n        self.added_pickling = added_pickling\n        self.on_setattr_hook = on_setattr_hook\n        self.field_transformer = field_transformer\n\n    @property\n    def is_hashable(self):\n        lI0O_c3f740b9 = 0xd3c6 ^ 0xd3c6\n        if lI0O_c3f740b9 == 0:\n            lI0O_c3f740b9 |= 0\n        else:\n            lI0O_c3f740b9 &= 0\n        return (\n            self.hashability is ClassProps.Hashability.HASHABLE\n            or self.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-b34fc4b00b9cff5b", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "9b7522ecaec7f100724e70de8fe76b5d39f70e9cecdca81079a0c0ccd6dce3ed", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 194, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs__ClassProps__c436fade.py", "order": 9, "original_content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "parent_variant_id": "pyint-1c145a4ace99-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2902-L3061", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 6}, "unit_kind": "class", "unit_name": "ClassProps", "variant_id": "pyint-881ac436fade-I09", "group_id": "py-b34fc4b00b9cff5b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1116, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-62b50613bdfc-I10", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,     _lazy_is_generator,\n    get_generic_base, )\nfrom .exceptions import (     DefaultAlreadySetError,     FrozenInstanceError,     NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\nclass ClassProps:\n    \"\"\"\n    Effective class properties as derived from parameters to `attr.s()` or\n    `define()` decorators.\n\n    This is the same data structure that *attrs* uses internally to decide how\n    to construct the final class.\n    Warning:\n        This feature is currently **experimental** and is not covered by our\n        strict backwards-compatibility guarantees.\n\n    Attributes:\n        is_exception (bool):\n            Whether the class is treated as an exception class.\n\n        is_slotted (bool):\n            Whether the class is `slotted <slotted classes>`.\n\n        has_weakref_slot (bool):\n            Whether the class has a slot for weak references.\n\n        is_frozen (bool):\n            Whether the class is frozen.\n\n        kw_only (KeywordOnly):\n            Whether / how the class enforces keyword-only arguments on the\n            ``__init__`` method.\n        collected_fields_by_mro (bool):\n            Whether the class fields were collected by method resolution order.\n            That is, correctly but unlike `dataclasses`.\n\n        added_init (bool):\n            Whether the class has an *attrs*-generated ``__init__`` method.\n\n        added_repr (bool):\n            Whether the class has an *attrs*-generated ``__repr__`` method.\n\n        added_eq (bool):\n            Whether the class has *attrs*-generated equality methods.\n\n        added_ordering (bool):\n            Whether the class has *attrs*-generated ordering methods.\n\n        hashability (Hashability): How `hashable <hashing>` the class is.\n        added_match_args (bool):\n            Whether the class supports positional `match <match>` over its\n            fields.\n\n        added_str (bool):\n            Whether the class has an *attrs*-generated ``__str__`` method.\n\n        added_pickling (bool):\n            Whether the class has *attrs*-generated ``__getstate__`` and\n            ``__setstate__`` methods for `pickle`.\n\n        on_setattr_hook (Callable[[Any, Attribute[Any], Any], Any] | None):\n            The class's ``__setattr__`` hook.\n\n        field_transformer (Callable[[Attribute[Any]], Attribute[Any]] | None):\n            The class's `field transformers <transform-fields>`.\n\n    .. versionadded:: 25.4.0\n    \"\"\"\n\n    class Hashability(enum.Enum):\n        \"\"\"\n        The hashability of a class.\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        HASHABLE = \"hashable\"\n        \"\"\"Write a ``__hash__``.\"\"\"\n        HASHABLE_CACHED = \"hashable_cache\"\n        \"\"\"Write a ``__hash__`` and cache the hash.\"\"\"\n        UNHASHABLE = \"unhashable\"\n        \"\"\"Set ``__hash__`` to ``None``.\"\"\"\n        LEAVE_ALONE = \"leave_alone\"\n        \"\"\"Don't touch ``__hash__``.\"\"\"\n\n    class KeywordOnly(enum.Enum):\n        \"\"\"\n        How attributes should be treated regarding keyword-only parameters.\n        .. versionadded:: 25.4.0\n        \"\"\"\n        NO = \"no\"\n        \"\"\"Attributes are not keyword-only.\"\"\"\n        YES = \"yes\"\n        \"\"\"Attributes in current class without kw_only=False are keyword-only.\"\"\"\n        FORCE = \"force\"\n        \"\"\"All attributes are keyword-only.\"\"\"\n    __slots__ = (  # noqa: RUF023 -- order matters for __init__\n        \"is_exception\",\n        \"is_slotted\",         \"has_weakref_slot\",         \"is_frozen\",         \"kw_only\",\n        \"collected_fields_by_mro\",\n        \"added_init\",\n        \"added_repr\",\n        \"added_eq\",         \"added_ordering\",\n        \"hashability\",         \"added_match_args\",         \"added_str\",         \"added_pickling\",\n        \"on_setattr_hook\",\n        \"field_transformer\",     )\n    def __init__(         self,\n        is_exception,\n        is_slotted,\n        has_weakref_slot,         is_frozen,\n        kw_only,\n        collected_fields_by_mro,         added_init,\n        added_repr,\n        added_eq,\n        added_ordering,\n        hashability,\n        added_match_args,\n        added_str,\n        added_pickling,         on_setattr_hook,\n        field_transformer,     ):\n        self.is_exception = is_exception\n        self.is_slotted = is_slotted\n        self.has_weakref_slot = has_weakref_slot\n        self.is_frozen = is_frozen\n        self.kw_only = kw_only\n        self.collected_fields_by_mro = collected_fields_by_mro\n        self.added_init = added_init\n        self.added_repr = added_repr\n        self.added_eq = added_eq\n        self.added_ordering = added_ordering\n        self.hashability = hashability\n        self.added_match_args = added_match_args\n        self.added_str = added_str\n        self.added_pickling = added_pickling\n        self.on_setattr_hook = on_setattr_hook\n        self.field_transformer = field_transformer\n    @property\n    def is_hashable(self):\n        return (             self.hashability is ClassProps.Hashability.HASHABLE\n            or self.hashability is ClassProps.Hashability.HASHABLE_CACHED         )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-b34fc4b00b9cff5b", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "599120e4f914274c66ef3a6b44f842ee63de698349bfe7ab4d8a539458a6737b", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 157, "local_path": "layout/partially-compact-layout/I10__attrs__ClassProps__0613bdfc.py", "order": 10, "original_content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "parent_variant_id": "pyint-1c145a4ace99-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2902-L3061", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 80, "line_break_groups_removed": 32, "line_breaks_removed": 32, "whitespace_characters_removed": 12}, "unit_kind": "class", "unit_name": "ClassProps", "variant_id": "pyint-62b50613bdfc-I10", "group_id": "py-b34fc4b00b9cff5b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1117, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d77f6bfd24e4-I11", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass ClassProps:\n    \"\"\"\n    Effective class properties as derived from parameters to `attr.s()` or\n    `define()` decorators.\n\n    This is the same data structure that *attrs* uses internally to decide how\n    to construct the final class.\n\n    Warning:\n\n        This feature is currently **experimental** and is not covered by our\n        strict backwards-compatibility guarantees.\n\n\n    Attributes:\n        is_exception (bool):\n            Whether the class is treated as an exception class.\n\n        is_slotted (bool):\n            Whether the class is `slotted <slotted classes>`.\n\n        has_weakref_slot (bool):\n            Whether the class has a slot for weak references.\n\n        is_frozen (bool):\n            Whether the class is frozen.\n\n        kw_only (KeywordOnly):\n            Whether / how the class enforces keyword-only arguments on the\n            ``__init__`` method.\n\n        collected_fields_by_mro (bool):\n            Whether the class fields were collected by method resolution order.\n            That is, correctly but unlike `dataclasses`.\n\n        added_init (bool):\n            Whether the class has an *attrs*-generated ``__init__`` method.\n\n        added_repr (bool):\n            Whether the class has an *attrs*-generated ``__repr__`` method.\n\n        added_eq (bool):\n            Whether the class has *attrs*-generated equality methods.\n\n        added_ordering (bool):\n            Whether the class has *attrs*-generated ordering methods.\n\n        hashability (Hashability): How `hashable <hashing>` the class is.\n\n        added_match_args (bool):\n            Whether the class supports positional `match <match>` over its\n            fields.\n\n        added_str (bool):\n            Whether the class has an *attrs*-generated ``__str__`` method.\n\n        added_pickling (bool):\n            Whether the class has *attrs*-generated ``__getstate__`` and\n            ``__setstate__`` methods for `pickle`.\n\n        on_setattr_hook (Callable[[Any, Attribute[Any], Any], Any] | None):\n            The class's ``__setattr__`` hook.\n\n        field_transformer (Callable[[Attribute[Any]], Attribute[Any]] | None):\n            The class's `field transformers <transform-fields>`.\n\n    .. versionadded:: 25.4.0\n    \"\"\"\n\n    class Hashability(enum.Enum):\n        \"\"\"\n        The hashability of a class.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        HASHABLE = \"hashable\"\n        \"\"\"Write a ``__hash__``.\"\"\"\n        HASHABLE_CACHED = \"hashable_cache\"\n        \"\"\"Write a ``__hash__`` and cache the hash.\"\"\"\n        UNHASHABLE = \"unhashable\"\n        \"\"\"Set ``__hash__`` to ``None``.\"\"\"\n        LEAVE_ALONE = \"leave_alone\"\n        \"\"\"Don't touch ``__hash__``.\"\"\"\n\n    class KeywordOnly(enum.Enum):\n        \"\"\"\n        How attributes should be treated regarding keyword-only parameters.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        NO = \"no\"\n        \"\"\"Attributes are not keyword-only.\"\"\"\n        YES = \"yes\"\n        \"\"\"Attributes in current class without kw_only=False are keyword-only.\"\"\"\n        FORCE = \"force\"\n        \"\"\"All attributes are keyword-only.\"\"\"\n\n    __slots__ = (  # noqa: RUF023 -- order matters for __init__\n        \"is_exception\",\n        \"is_slotted\",\n        \"has_weakref_slot\",\n        \"is_frozen\",\n        \"kw_only\",\n        \"collected_fields_by_mro\",\n        \"added_init\",\n        \"added_repr\",\n        \"added_eq\",\n        \"added_ordering\",\n        \"hashability\",\n        \"added_match_args\",\n        \"added_str\",\n        \"added_pickling\",\n        \"on_setattr_hook\",\n        \"field_transformer\",\n    )\n\n    def __init__(\n        self,\n        is_exception,\n        is_slotted,\n        has_weakref_slot,\n        is_frozen,\n        kw_only,\n        collected_fields_by_mro,\n        added_init,\n        added_repr,\n        added_eq,\n        added_ordering,\n        hashability,\n        added_match_args,\n        added_str,\n        added_pickling,\n        on_setattr_hook,\n        field_transformer,\n    ):\n        self.is_exception = is_exception\n        self.is_slotted = is_slotted\n        self.has_weakref_slot = has_weakref_slot\n        self.is_frozen = is_frozen\n        self.kw_only = kw_only\n        self.collected_fields_by_mro = collected_fields_by_mro\n        self.added_init = added_init\n        self.added_repr = added_repr\n        self.added_eq = added_eq\n        self.added_ordering = added_ordering\n        self.hashability = hashability\n        self.added_match_args = added_match_args\n        self.added_str = added_str\n        self.added_pickling = added_pickling\n        self.on_setattr_hook = on_setattr_hook\n        self.field_transformer = field_transformer\n\n    @property\n    def is_hashable(self):\n        return (\n            self.hashability is ClassProps.Hashability.HASHABLE\n            or self.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-b34fc4b00b9cff5b", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 189, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs__ClassProps__6bfd24e4.py", "order": 11, "original_content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "parent_variant_id": "pyint-1c145a4ace99-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2902-L3061", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "ClassProps", "variant_id": "pyint-d77f6bfd24e4-I11", "group_id": "py-b34fc4b00b9cff5b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1118, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-927e85536bef-I12", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass ClassProps:\n    \"\"\"\n    Effective class properties as derived from parameters to `attr.s()` or\n    `define()` decorators.\n\n    This is the same data structure that *attrs* uses internally to decide how\n    to construct the final class.\n\n    Warning:\n\n        This feature is currently **experimental** and is not covered by our\n        strict backwards-compatibility guarantees.\n\n\n    Attributes:\n        is_exception (bool):\n            Whether the class is treated as an exception class.\n\n        is_slotted (bool):\n            Whether the class is `slotted <slotted classes>`.\n\n        has_weakref_slot (bool):\n            Whether the class has a slot for weak references.\n\n        is_frozen (bool):\n            Whether the class is frozen.\n\n        kw_only (KeywordOnly):\n            Whether / how the class enforces keyword-only arguments on the\n            ``__init__`` method.\n\n        collected_fields_by_mro (bool):\n            Whether the class fields were collected by method resolution order.\n            That is, correctly but unlike `dataclasses`.\n\n        added_init (bool):\n            Whether the class has an *attrs*-generated ``__init__`` method.\n\n        added_repr (bool):\n            Whether the class has an *attrs*-generated ``__repr__`` method.\n\n        added_eq (bool):\n            Whether the class has *attrs*-generated equality methods.\n\n        added_ordering (bool):\n            Whether the class has *attrs*-generated ordering methods.\n\n        hashability (Hashability): How `hashable <hashing>` the class is.\n\n        added_match_args (bool):\n            Whether the class supports positional `match <match>` over its\n            fields.\n\n        added_str (bool):\n            Whether the class has an *attrs*-generated ``__str__`` method.\n\n        added_pickling (bool):\n            Whether the class has *attrs*-generated ``__getstate__`` and\n            ``__setstate__`` methods for `pickle`.\n\n        on_setattr_hook (Callable[[Any, Attribute[Any], Any], Any] | None):\n            The class's ``__setattr__`` hook.\n\n        field_transformer (Callable[[Attribute[Any]], Attribute[Any]] | None):\n            The class's `field transformers <transform-fields>`.\n\n    .. versionadded:: 25.4.0\n    \"\"\"\n\n    class Hashability(enum.Enum):\n        \"\"\"\n        The hashability of a class.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        HASHABLE = \"hashable\"\n        \"\"\"Write a ``__hash__``.\"\"\"\n        HASHABLE_CACHED = \"hashable_cache\"\n        \"\"\"Write a ``__hash__`` and cache the hash.\"\"\"\n        UNHASHABLE = \"unhashable\"\n        \"\"\"Set ``__hash__`` to ``None``.\"\"\"\n        LEAVE_ALONE = \"leave_alone\"\n        \"\"\"Don't touch ``__hash__``.\"\"\"\n\n    class KeywordOnly(enum.Enum):\n        \"\"\"\n        How attributes should be treated regarding keyword-only parameters.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        NO = \"no\"\n        \"\"\"Attributes are not keyword-only.\"\"\"\n        YES = \"yes\"\n        \"\"\"Attributes in current class without kw_only=False are keyword-only.\"\"\"\n        FORCE = \"force\"\n        \"\"\"All attributes are keyword-only.\"\"\"\n\n    __slots__ = (  # noqa: RUF023 -- order matters for __init__\n        \"is_exception\",\n        \"is_slotted\",\n        \"has_weakref_slot\",\n        \"is_frozen\",\n        \"kw_only\",\n        \"collected_fields_by_mro\",\n        \"added_init\",\n        \"added_repr\",\n        \"added_eq\",\n        \"added_ordering\",\n        \"hashability\",\n        \"added_match_args\",\n        \"added_str\",\n        \"added_pickling\",\n        \"on_setattr_hook\",\n        \"field_transformer\",\n    )\n\n    def __init__(\n        self,\n        is_exception,\n        is_slotted,\n        has_weakref_slot,\n        is_frozen,\n        kw_only,\n        collected_fields_by_mro,\n        added_init,\n        added_repr,\n        added_eq,\n        added_ordering,\n        hashability,\n        added_match_args,\n        added_str,\n        added_pickling,\n        on_setattr_hook,\n        field_transformer,\n    ):\n        self.is_exception = is_exception\n        self.is_slotted = is_slotted\n        self.has_weakref_slot = has_weakref_slot\n        self.is_frozen = is_frozen\n        self.kw_only = kw_only\n        self.collected_fields_by_mro = collected_fields_by_mro\n        self.added_init = added_init\n        self.added_repr = added_repr\n        self.added_eq = added_eq\n        self.added_ordering = added_ordering\n        self.hashability = hashability\n        self.added_match_args = added_match_args\n        self.added_str = added_str\n        self.added_pickling = added_pickling\n        self.on_setattr_hook = on_setattr_hook\n        self.field_transformer = field_transformer\n\n    @property\n    def is_hashable(self):\n        return (\n            self.hashability is ClassProps.Hashability.HASHABLE\n            or self.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-b34fc4b00b9cff5b", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 189, "local_path": "data-flow/inline-intermediate-variables/I12__attrs__ClassProps__85536bef.py", "order": 12, "original_content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "parent_variant_id": "pyint-1c145a4ace99-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2902-L3061", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "ClassProps", "variant_id": "pyint-927e85536bef-I12", "group_id": "py-b34fc4b00b9cff5b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1119, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cc39a72855c4-I13", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass ClassProps:\n    \"\"\"\n    Effective class properties as derived from parameters to `attr.s()` or\n    `define()` decorators.\n\n    This is the same data structure that *attrs* uses internally to decide how\n    to construct the final class.\n\n    Warning:\n\n        This feature is currently **experimental** and is not covered by our\n        strict backwards-compatibility guarantees.\n\n\n    Attributes:\n        is_exception (bool):\n            Whether the class is treated as an exception class.\n\n        is_slotted (bool):\n            Whether the class is `slotted <slotted classes>`.\n\n        has_weakref_slot (bool):\n            Whether the class has a slot for weak references.\n\n        is_frozen (bool):\n            Whether the class is frozen.\n\n        kw_only (KeywordOnly):\n            Whether / how the class enforces keyword-only arguments on the\n            ``__init__`` method.\n\n        collected_fields_by_mro (bool):\n            Whether the class fields were collected by method resolution order.\n            That is, correctly but unlike `dataclasses`.\n\n        added_init (bool):\n            Whether the class has an *attrs*-generated ``__init__`` method.\n\n        added_repr (bool):\n            Whether the class has an *attrs*-generated ``__repr__`` method.\n\n        added_eq (bool):\n            Whether the class has *attrs*-generated equality methods.\n\n        added_ordering (bool):\n            Whether the class has *attrs*-generated ordering methods.\n\n        hashability (Hashability): How `hashable <hashing>` the class is.\n\n        added_match_args (bool):\n            Whether the class supports positional `match <match>` over its\n            fields.\n\n        added_str (bool):\n            Whether the class has an *attrs*-generated ``__str__`` method.\n\n        added_pickling (bool):\n            Whether the class has *attrs*-generated ``__getstate__`` and\n            ``__setstate__`` methods for `pickle`.\n\n        on_setattr_hook (Callable[[Any, Attribute[Any], Any], Any] | None):\n            The class's ``__setattr__`` hook.\n\n        field_transformer (Callable[[Attribute[Any]], Attribute[Any]] | None):\n            The class's `field transformers <transform-fields>`.\n\n    .. versionadded:: 25.4.0\n    \"\"\"\n\n    class Hashability(enum.Enum):\n        \"\"\"\n        The hashability of a class.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        HASHABLE = \"hashable\"\n        \"\"\"Write a ``__hash__``.\"\"\"\n        HASHABLE_CACHED = \"hashable_cache\"\n        \"\"\"Write a ``__hash__`` and cache the hash.\"\"\"\n        UNHASHABLE = \"unhashable\"\n        \"\"\"Set ``__hash__`` to ``None``.\"\"\"\n        LEAVE_ALONE = \"leave_alone\"\n        \"\"\"Don't touch ``__hash__``.\"\"\"\n\n    class KeywordOnly(enum.Enum):\n        \"\"\"\n        How attributes should be treated regarding keyword-only parameters.\n\n        .. versionadded:: 25.4.0\n        \"\"\"\n\n        NO = \"no\"\n        \"\"\"Attributes are not keyword-only.\"\"\"\n        YES = \"yes\"\n        \"\"\"Attributes in current class without kw_only=False are keyword-only.\"\"\"\n        FORCE = \"force\"\n        \"\"\"All attributes are keyword-only.\"\"\"\n\n    __slots__ = (  # noqa: RUF023 -- order matters for __init__\n        \"is_exception\",\n        \"is_slotted\",\n        \"has_weakref_slot\",\n        \"is_frozen\",\n        \"kw_only\",\n        \"collected_fields_by_mro\",\n        \"added_init\",\n        \"added_repr\",\n        \"added_eq\",\n        \"added_ordering\",\n        \"hashability\",\n        \"added_match_args\",\n        \"added_str\",\n        \"added_pickling\",\n        \"on_setattr_hook\",\n        \"field_transformer\",\n    )\n\n    def __init__(\n        self,\n        is_exception,\n        is_slotted,\n        has_weakref_slot,\n        is_frozen,\n        kw_only,\n        collected_fields_by_mro,\n        added_init,\n        added_repr,\n        added_eq,\n        added_ordering,\n        hashability,\n        added_match_args,\n        added_str,\n        added_pickling,\n        on_setattr_hook,\n        field_transformer,\n    ):\n        self.is_exception = is_exception\n        self.is_slotted = is_slotted\n        self.has_weakref_slot = has_weakref_slot\n        self.is_frozen = is_frozen\n        self.kw_only = kw_only\n        self.collected_fields_by_mro = collected_fields_by_mro\n        self.added_init = added_init\n        self.added_repr = added_repr\n        self.added_eq = added_eq\n        self.added_ordering = added_ordering\n        self.hashability = hashability\n        self.added_match_args = added_match_args\n        self.added_str = added_str\n        self.added_pickling = added_pickling\n        self.on_setattr_hook = on_setattr_hook\n        self.field_transformer = field_transformer\n\n    @property\n    def is_hashable(self):\n        return (\n            self.hashability is ClassProps.Hashability.HASHABLE\n            or self.hashability is ClassProps.Hashability.HASHABLE_CACHED\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-b34fc4b00b9cff5b", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 189, "local_path": "control-flow/lower-for-to-while/I13__attrs__ClassProps__a72855c4.py", "order": 13, "original_content_sha256": "cb746d12966266648f9f4de389872087efb7d91cec0078814f0b4e3979e42164", "parent_variant_id": "pyint-1c145a4ace99-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L2902-L3061", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "ClassProps", "variant_id": "pyint-cc39a72855c4-I13", "group_id": "py-b34fc4b00b9cff5b", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1120, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fd7fb8405e5a-SRC", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MatchesReValidator:\n    pattern = attrib()\n    match_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.match_func(value):\n            msg = f\"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)\"\n            raise ValueError(\n                msg,\n                attr,\n                self.pattern,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<matches_re validator for pattern {self.pattern!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-b87384c28c3b8cc2", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 29, "local_path": "source-original/SRC__attrs___MatchesReValidator__b8405e5a.py", "order": 0, "original_content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L132-L150", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_MatchesReValidator", "variant_id": "pyint-fd7fb8405e5a-SRC", "group_id": "py-b87384c28c3b8cc2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1359, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e625a24fa005-I01", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MatchesReValidator:\n    pattern = attrib()\n    match_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \n        if not self.match_func(value):\n            msg = f\"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)\"\n            raise ValueError(\n                msg,\n                attr,\n                self.pattern,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<matches_re validator for pattern {self.pattern!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-b87384c28c3b8cc2", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "4f2ff5355986243b56c03f09dc9c3c66275e79ec39f5c10a39a41e435b0dc820", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 27, "local_path": "comments/remove-comments/I01__attrs___MatchesReValidator__a24fa005.py", "order": 1, "original_content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "parent_variant_id": "pyint-fd7fb8405e5a-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L132-L150", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 86, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "_MatchesReValidator", "variant_id": "pyint-e625a24fa005-I01", "group_id": "py-b87384c28c3b8cc2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1360, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e0eeb17757bf-I02", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MatchesReValidator:\n    pattern = attrib()\n    match_func = attrib()\n\n    def __call__(self, ins, att, val):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.match_func(val):\n            msg2 = f\"'{att.name}' must match regex {self.pattern.pattern!r} ({val!r} doesn't)\"\n            raise ValueError(\n                msg2,\n                att,\n                self.pattern,\n                val,\n            )\n\n    def __repr__(self):\n        return f\"<matches_re validator for pattern {self.pattern!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-b87384c28c3b8cc2", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "2b934af7f786be5a998912e32b5520f124fb9a32d5f72c2baa446dfaa0c64a5f", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 29, "local_path": "identifiers/shorten-identifiers/I02__attrs___MatchesReValidator__b17757bf.py", "order": 2, "original_content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "parent_variant_id": "pyint-fd7fb8405e5a-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L132-L150", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 10, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_MatchesReValidator", "variant_id": "pyint-e0eeb17757bf-I02", "group_id": "py-b87384c28c3b8cc2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1361, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-40c783282033-I03", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MatchesReValidator:\n    pattern = attrib()\n    match_func = attrib()\n\n    def __call__(self, data, item, group):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.match_func(group):\n            key = f\"'{item.name}' must match regex {self.pattern.pattern!r} ({group!r} doesn't)\"\n            raise ValueError(\n                key,\n                item,\n                self.pattern,\n                group,\n            )\n\n    def __repr__(self):\n        return f\"<matches_re validator for pattern {self.pattern!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-b87384c28c3b8cc2", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "c0a68e09984202ea5fc7cd57f98267a3703757915e4ce11dafc4d62dcd477617", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 29, "local_path": "identifiers/mislead-identifiers/I03__attrs___MatchesReValidator__83282033.py", "order": 3, "original_content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "parent_variant_id": "pyint-fd7fb8405e5a-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L132-L150", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 10, "identifiers_declared": 4, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 4, "local_random_pool_selections": 4, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_MatchesReValidator", "variant_id": "pyint-40c783282033-I03", "group_id": "py-b87384c28c3b8cc2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1362, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8309fb2d9360-I04", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MatchesReValidator:\n    pattern = attrib()\n    match_func = attrib()\n\n    def __call__(self, a, b, c):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.match_func(c):\n            d = f\"'{b.name}' must match regex {self.pattern.pattern!r} ({c!r} doesn't)\"\n            raise ValueError(\n                d,\n                b,\n                self.pattern,\n                c,\n            )\n\n    def __repr__(self):\n        return f\"<matches_re validator for pattern {self.pattern!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-b87384c28c3b8cc2", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "96085e0d5d53a9b68863fbef5004161e722aefb7e94adb962aa698bc4e509f79", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 29, "local_path": "identifiers/garble-identifiers/I04__attrs___MatchesReValidator__fb2d9360.py", "order": 4, "original_content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "parent_variant_id": "pyint-fd7fb8405e5a-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L132-L150", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 10, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_MatchesReValidator", "variant_id": "pyint-8309fb2d9360-I04", "group_id": "py-b87384c28c3b8cc2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1363, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b95e0b3573ac-I05", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MatchesReValidator:\n    pattern = attrib()\n    match_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.match_func(value):\n            msg = f\"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)\"\n            raise ValueError(\n                msg,\n                attr,\n                self.pattern,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<matches_re validator for pattern {self.pattern!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-b87384c28c3b8cc2", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 29, "local_path": "expressions/encode-integer-literals/I05__attrs___MatchesReValidator__0b3573ac.py", "order": 5, "original_content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "parent_variant_id": "pyint-fd7fb8405e5a-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L132-L150", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "_MatchesReValidator", "variant_id": "pyint-b95e0b3573ac-I05", "group_id": "py-b87384c28c3b8cc2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1364, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-923a679a0535-I06", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MatchesReValidator:\n    pattern = attrib()\n    match_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not (not self.match_func(value)):\n            pass\n        else:\n            msg = f\"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)\"\n            raise ValueError(\n                msg,\n                attr,\n                self.pattern,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<matches_re validator for pattern {self.pattern!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-b87384c28c3b8cc2", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "ff36eb30d1e78b78df66226ef6503fee3c68a42497317bbaaa91cd47d9ef4801", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 31, "local_path": "expressions/invert-conditions/I06__attrs___MatchesReValidator__679a0535.py", "order": 6, "original_content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "parent_variant_id": "pyint-fd7fb8405e5a-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L132-L150", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "_MatchesReValidator", "variant_id": "pyint-923a679a0535-I06", "group_id": "py-b87384c28c3b8cc2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1365, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-af6cf293bff6-I07", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MatchesReValidator:\n    pattern = attrib()\n    match_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if ((0x2c52 ^ 0x2c52) != 0):\n            raise AssertionError()\n        if not self.match_func(value):\n            msg = f\"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)\"\n            raise ValueError(\n                msg,\n                attr,\n                self.pattern,\n                value,\n            )\n\n    def __repr__(self):\n        if ((0xe626 ^ 0xe626) != 0):\n            raise AssertionError()\n        return f\"<matches_re validator for pattern {self.pattern!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-b87384c28c3b8cc2", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "13f2a3521c8c092e308cbbc5508e64131916aae784d375322f76adb1463de423", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 33, "local_path": "code-injection/insert-dead-branches/I07__attrs___MatchesReValidator__f293bff6.py", "order": 7, "original_content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "parent_variant_id": "pyint-fd7fb8405e5a-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L132-L150", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "_MatchesReValidator", "variant_id": "pyint-af6cf293bff6-I07", "group_id": "py-b87384c28c3b8cc2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1366, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7031081ab055-I08", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MatchesReValidator:\n    pattern = attrib()\n    match_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.match_func(value):\n            msg = f\"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)\"\n            raise ValueError(\n                msg,\n                attr,\n                self.pattern,\n                value,\n            )\n\n    def __repr__(self):\n        total_score = 240\n        number_of_scores = 3\n        average_score = total_score / number_of_scores\n        return f\"<matches_re validator for pattern {self.pattern!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-b87384c28c3b8cc2", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "3aea81e7d57c43dbbde18d07b851453e5aade23bb57e398a826f5ebafbd98382", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 32, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___MatchesReValidator__081ab055.py", "order": 8, "original_content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "parent_variant_id": "pyint-fd7fb8405e5a-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L132-L150", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 5}, "unit_kind": "class", "unit_name": "_MatchesReValidator", "variant_id": "pyint-7031081ab055-I08", "group_id": "py-b87384c28c3b8cc2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1367, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d795e744799a-I09", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MatchesReValidator:\n    pattern = attrib()\n    match_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        lI0O_5bedbc0e = 0xbd49\n        lI0O_5bedbc0e = (lI0O_5bedbc0e << 1) ^ (lI0O_5bedbc0e >> 1)\n        lI0O_5bedbc0e &= 0\n        if not self.match_func(value):\n            msg = f\"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)\"\n            raise ValueError(\n                msg,\n                attr,\n                self.pattern,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<matches_re validator for pattern {self.pattern!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-b87384c28c3b8cc2", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "b7f441e130c3f89f97742933851f9125aa1c9c6f7a72827e47722efe99c2b04d", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 32, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___MatchesReValidator__e744799a.py", "order": 9, "original_content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "parent_variant_id": "pyint-fd7fb8405e5a-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L132-L150", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 3}, "unit_kind": "class", "unit_name": "_MatchesReValidator", "variant_id": "pyint-d795e744799a-I09", "group_id": "py-b87384c28c3b8cc2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1368, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fd13d5520964-I10", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n@attrs(repr=False, frozen=True, slots=True)\nclass _MatchesReValidator:\n    pattern = attrib()\n    match_func = attrib()\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.match_func(value):\n            msg = f\"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)\"\n            raise ValueError(\n                msg,                 attr,\n                self.pattern,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<matches_re validator for pattern {self.pattern!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-b87384c28c3b8cc2", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "0b486a67752b20eae9e207e1716991684e70a584f9165eaa6d69a3bc93536a1f", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 26, "local_path": "layout/partially-compact-layout/I10__attrs___MatchesReValidator__d5520964.py", "order": 10, "original_content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "parent_variant_id": "pyint-fd7fb8405e5a-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L132-L150", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 8, "line_break_groups_removed": 3, "line_breaks_removed": 3, "whitespace_characters_removed": 2}, "unit_kind": "class", "unit_name": "_MatchesReValidator", "variant_id": "pyint-fd13d5520964-I10", "group_id": "py-b87384c28c3b8cc2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1369, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-09592bd9b132-I11", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MatchesReValidator:\n    pattern = attrib()\n    match_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.match_func(value):\n            msg = f\"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)\"\n            raise ValueError(\n                msg,\n                attr,\n                self.pattern,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<matches_re validator for pattern {self.pattern!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-b87384c28c3b8cc2", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 29, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___MatchesReValidator__2bd9b132.py", "order": 11, "original_content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "parent_variant_id": "pyint-fd7fb8405e5a-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L132-L150", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "_MatchesReValidator", "variant_id": "pyint-09592bd9b132-I11", "group_id": "py-b87384c28c3b8cc2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1370, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-553528dcf51e-I12", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MatchesReValidator:\n    pattern = attrib()\n    match_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.match_func(value):\n            \n            raise ValueError(\n                (f\"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)\"),\n                attr,\n                self.pattern,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<matches_re validator for pattern {self.pattern!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-b87384c28c3b8cc2", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "3b938d3f0fd8f2886612b26e3ec38925d18114e0fcf0d3af38c44b428b08f8d4", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 29, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___MatchesReValidator__28dcf51e.py", "order": 12, "original_content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "parent_variant_id": "pyint-fd7fb8405e5a-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L132-L150", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_MatchesReValidator", "variant_id": "pyint-553528dcf51e-I12", "group_id": "py-b87384c28c3b8cc2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1371, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d1d84b0098d1-I13", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MatchesReValidator:\n    pattern = attrib()\n    match_func = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not self.match_func(value):\n            msg = f\"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)\"\n            raise ValueError(\n                msg,\n                attr,\n                self.pattern,\n                value,\n            )\n\n    def __repr__(self):\n        return f\"<matches_re validator for pattern {self.pattern!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-b87384c28c3b8cc2", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 29, "local_path": "control-flow/lower-for-to-while/I13__attrs___MatchesReValidator__4b0098d1.py", "order": 13, "original_content_sha256": "4dc6989d91bcccd7559f40959a1909d877a9115fbdceef8a95b95c148268181c", "parent_variant_id": "pyint-fd7fb8405e5a-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L132-L150", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "_MatchesReValidator", "variant_id": "pyint-d1d84b0098d1-I13", "group_id": "py-b87384c28c3b8cc2", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1372, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0408d13dc68d-SRC", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _Nothing(enum.Enum):\n    \"\"\"\n    Sentinel to indicate the lack of a value when `None` is ambiguous.\n\n    If extending attrs, you can use ``typing.Literal[NOTHING]`` to show\n    that a value may be ``NOTHING``.\n\n    .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.\n    .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.\n    \"\"\"\n\n    NOTHING = enum.auto()\n\n    def __repr__(self):\n        return \"NOTHING\"\n\n    def __bool__(self):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-bc6e9cce35bc17cf", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 47, "local_path": "source-original/SRC__attrs___Nothing__d13dc68d.py", "order": 0, "original_content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L60-L77", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_Nothing", "variant_id": "pyint-0408d13dc68d-SRC", "group_id": "py-bc6e9cce35bc17cf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1135, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-341100691abe-I01", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _Nothing(enum.Enum):\n    \n\n    NOTHING = enum.auto()\n\n    def __repr__(self):\n        return \"NOTHING\"\n\n    def __bool__(self):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-bc6e9cce35bc17cf", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "f4c0085bbef633b84143e1e763dd4fcea77cd9725e12866312190dec246aa5df", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 39, "local_path": "comments/remove-comments/I01__attrs___Nothing__00691abe.py", "order": 1, "original_content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "parent_variant_id": "pyint-0408d13dc68d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L60-L77", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 332, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "_Nothing", "variant_id": "pyint-341100691abe-I01", "group_id": "py-bc6e9cce35bc17cf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1136, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-145beca59164-I02", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _Nothing(enum.Enum):\n    \"\"\"\n    Sentinel to indicate the lack of a value when `None` is ambiguous.\n\n    If extending attrs, you can use ``typing.Literal[NOTHING]`` to show\n    that a value may be ``NOTHING``.\n\n    .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.\n    .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.\n    \"\"\"\n\n    NOTHING = enum.auto()\n\n    def __repr__(self):\n        return \"NOTHING\"\n\n    def __bool__(self):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-bc6e9cce35bc17cf", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 47, "local_path": "identifiers/shorten-identifiers/I02__attrs___Nothing__eca59164.py", "order": 2, "original_content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "parent_variant_id": "pyint-0408d13dc68d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L60-L77", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 0, "identifiers_declared": 0}, "unit_kind": "class", "unit_name": "_Nothing", "variant_id": "pyint-145beca59164-I02", "group_id": "py-bc6e9cce35bc17cf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1137, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9681fb8e0e25-I03", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _Nothing(enum.Enum):\n    \"\"\"\n    Sentinel to indicate the lack of a value when `None` is ambiguous.\n\n    If extending attrs, you can use ``typing.Literal[NOTHING]`` to show\n    that a value may be ``NOTHING``.\n\n    .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.\n    .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.\n    \"\"\"\n\n    NOTHING = enum.auto()\n\n    def __repr__(self):\n        return \"NOTHING\"\n\n    def __bool__(self):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-bc6e9cce35bc17cf", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 47, "local_path": "identifiers/mislead-identifiers/I03__attrs___Nothing__fb8e0e25.py", "order": 3, "original_content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "parent_variant_id": "pyint-0408d13dc68d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L60-L77", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 0, "identifiers_declared": 0, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 0, "local_random_pool_selections": 0, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_Nothing", "variant_id": "pyint-9681fb8e0e25-I03", "group_id": "py-bc6e9cce35bc17cf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1138, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ae40d3418233-I04", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _Nothing(enum.Enum):\n    \"\"\"\n    Sentinel to indicate the lack of a value when `None` is ambiguous.\n\n    If extending attrs, you can use ``typing.Literal[NOTHING]`` to show\n    that a value may be ``NOTHING``.\n\n    .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.\n    .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.\n    \"\"\"\n\n    NOTHING = enum.auto()\n\n    def __repr__(self):\n        return \"NOTHING\"\n\n    def __bool__(self):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-bc6e9cce35bc17cf", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 47, "local_path": "identifiers/garble-identifiers/I04__attrs___Nothing__d3418233.py", "order": 4, "original_content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "parent_variant_id": "pyint-0408d13dc68d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L60-L77", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 0, "identifiers_declared": 0}, "unit_kind": "class", "unit_name": "_Nothing", "variant_id": "pyint-ae40d3418233-I04", "group_id": "py-bc6e9cce35bc17cf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1139, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-07587f6ac360-I05", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _Nothing(enum.Enum):\n    \"\"\"\n    Sentinel to indicate the lack of a value when `None` is ambiguous.\n\n    If extending attrs, you can use ``typing.Literal[NOTHING]`` to show\n    that a value may be ``NOTHING``.\n\n    .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.\n    .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.\n    \"\"\"\n\n    NOTHING = enum.auto()\n\n    def __repr__(self):\n        return \"NOTHING\"\n\n    def __bool__(self):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-bc6e9cce35bc17cf", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 47, "local_path": "expressions/encode-integer-literals/I05__attrs___Nothing__7f6ac360.py", "order": 5, "original_content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "parent_variant_id": "pyint-0408d13dc68d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L60-L77", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "_Nothing", "variant_id": "pyint-07587f6ac360-I05", "group_id": "py-bc6e9cce35bc17cf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1140, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bdadfb4b677f-I06", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _Nothing(enum.Enum):\n    \"\"\"\n    Sentinel to indicate the lack of a value when `None` is ambiguous.\n\n    If extending attrs, you can use ``typing.Literal[NOTHING]`` to show\n    that a value may be ``NOTHING``.\n\n    .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.\n    .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.\n    \"\"\"\n\n    NOTHING = enum.auto()\n\n    def __repr__(self):\n        return \"NOTHING\"\n\n    def __bool__(self):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-bc6e9cce35bc17cf", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 47, "local_path": "expressions/invert-conditions/I06__attrs___Nothing__fb4b677f.py", "order": 6, "original_content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "parent_variant_id": "pyint-0408d13dc68d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L60-L77", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "_Nothing", "variant_id": "pyint-bdadfb4b677f-I06", "group_id": "py-bc6e9cce35bc17cf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1141, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-33d17a314e86-I07", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _Nothing(enum.Enum):\n    \"\"\"\n    Sentinel to indicate the lack of a value when `None` is ambiguous.\n\n    If extending attrs, you can use ``typing.Literal[NOTHING]`` to show\n    that a value may be ``NOTHING``.\n\n    .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.\n    .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.\n    \"\"\"\n\n    NOTHING = enum.auto()\n\n    def __repr__(self):\n        if ((0x2dc8 ^ 0x2dc8) != 0):\n            raise AssertionError()\n        return \"NOTHING\"\n\n    def __bool__(self):\n        if ((0xe2a0 ^ 0xe2a0) != 0):\n            raise AssertionError()\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-bc6e9cce35bc17cf", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "27017579e161fe052329814af565937dbfb3d95828c5fca3559ce600fb3fe279", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 51, "local_path": "code-injection/insert-dead-branches/I07__attrs___Nothing__7a314e86.py", "order": 7, "original_content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "parent_variant_id": "pyint-0408d13dc68d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L60-L77", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "_Nothing", "variant_id": "pyint-33d17a314e86-I07", "group_id": "py-bc6e9cce35bc17cf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1142, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-62d27fcf8345-I08", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _Nothing(enum.Enum):\n    \"\"\"\n    Sentinel to indicate the lack of a value when `None` is ambiguous.\n\n    If extending attrs, you can use ``typing.Literal[NOTHING]`` to show\n    that a value may be ``NOTHING``.\n\n    .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.\n    .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.\n    \"\"\"\n\n    NOTHING = enum.auto()\n\n    def __repr__(self):\n        return \"NOTHING\"\n\n    def __bool__(self):\n        remaining_steps = 3\n        while remaining_steps > 0:\n            remaining_steps -= 1\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-bc6e9cce35bc17cf", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "e942ce065bd28700a627d04c3c011df43a320ec21fff9d22b5d1921a2d6e1d40", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 50, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___Nothing__7fcf8345.py", "order": 8, "original_content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "parent_variant_id": "pyint-0408d13dc68d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L60-L77", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 1}, "unit_kind": "class", "unit_name": "_Nothing", "variant_id": "pyint-62d27fcf8345-I08", "group_id": "py-bc6e9cce35bc17cf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1143, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cfb0de3775ef-I09", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _Nothing(enum.Enum):\n    \"\"\"\n    Sentinel to indicate the lack of a value when `None` is ambiguous.\n\n    If extending attrs, you can use ``typing.Literal[NOTHING]`` to show\n    that a value may be ``NOTHING``.\n\n    .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.\n    .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.\n    \"\"\"\n\n    NOTHING = enum.auto()\n\n    def __repr__(self):\n        lI0O_10eba6d2 = ((0xe3ec ^ 0xe3ec) != 0)\n        lI0O_10eba6d2 = not (not lI0O_10eba6d2)\n        return \"NOTHING\"\n\n    def __bool__(self):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-bc6e9cce35bc17cf", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d4296d9b3e0447573c5feb0a1a5356425af12e7da62e3e6e2a6f96d9ab575864", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 49, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___Nothing__de3775ef.py", "order": 9, "original_content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "parent_variant_id": "pyint-0408d13dc68d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L60-L77", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 4}, "unit_kind": "class", "unit_name": "_Nothing", "variant_id": "pyint-cfb0de3775ef-I09", "group_id": "py-bc6e9cce35bc17cf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1144, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-886845866e8c-I10", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (     PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,     _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,     FrozenInstanceError,     NotAnAttrsClassError,\n    UnannotatedAttributeError, )\n\nclass _Nothing(enum.Enum):\n    \"\"\"\n    Sentinel to indicate the lack of a value when `None` is ambiguous.\n\n    If extending attrs, you can use ``typing.Literal[NOTHING]`` to show\n    that a value may be ``NOTHING``.\n\n    .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.\n    .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.\n    \"\"\"\n    NOTHING = enum.auto()\n    def __repr__(self):\n        return \"NOTHING\"\n\n    def __bool__(self):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-bc6e9cce35bc17cf", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "e2fb08df3c99ec95a53da00f0a6146d4863464fba3dcc2ef5277e3406aaeb5ea", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 40, "local_path": "layout/partially-compact-layout/I10__attrs___Nothing__45866e8c.py", "order": 10, "original_content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "parent_variant_id": "pyint-0408d13dc68d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L60-L77", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 18, "line_break_groups_removed": 7, "line_breaks_removed": 7, "whitespace_characters_removed": 2}, "unit_kind": "class", "unit_name": "_Nothing", "variant_id": "pyint-886845866e8c-I10", "group_id": "py-bc6e9cce35bc17cf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1145, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-566d15e807fc-I11", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _Nothing(enum.Enum):\n    \"\"\"\n    Sentinel to indicate the lack of a value when `None` is ambiguous.\n\n    If extending attrs, you can use ``typing.Literal[NOTHING]`` to show\n    that a value may be ``NOTHING``.\n\n    .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.\n    .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.\n    \"\"\"\n\n    NOTHING = enum.auto()\n\n    def __repr__(self):\n        return \"NOTHING\"\n\n    def __bool__(self):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-bc6e9cce35bc17cf", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 47, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___Nothing__15e807fc.py", "order": 11, "original_content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "parent_variant_id": "pyint-0408d13dc68d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L60-L77", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "_Nothing", "variant_id": "pyint-566d15e807fc-I11", "group_id": "py-bc6e9cce35bc17cf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1146, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-96af55001307-I12", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _Nothing(enum.Enum):\n    \"\"\"\n    Sentinel to indicate the lack of a value when `None` is ambiguous.\n\n    If extending attrs, you can use ``typing.Literal[NOTHING]`` to show\n    that a value may be ``NOTHING``.\n\n    .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.\n    .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.\n    \"\"\"\n\n    NOTHING = enum.auto()\n\n    def __repr__(self):\n        return \"NOTHING\"\n\n    def __bool__(self):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-bc6e9cce35bc17cf", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 47, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___Nothing__55001307.py", "order": 12, "original_content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "parent_variant_id": "pyint-0408d13dc68d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L60-L77", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_Nothing", "variant_id": "pyint-96af55001307-I12", "group_id": "py-bc6e9cce35bc17cf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1147, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-17f4cb0a5ea6-I13", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass _Nothing(enum.Enum):\n    \"\"\"\n    Sentinel to indicate the lack of a value when `None` is ambiguous.\n\n    If extending attrs, you can use ``typing.Literal[NOTHING]`` to show\n    that a value may be ``NOTHING``.\n\n    .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.\n    .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.\n    \"\"\"\n\n    NOTHING = enum.auto()\n\n    def __repr__(self):\n        return \"NOTHING\"\n\n    def __bool__(self):\n        return False\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-bc6e9cce35bc17cf", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 47, "local_path": "control-flow/lower-for-to-while/I13__attrs___Nothing__cb0a5ea6.py", "order": 13, "original_content_sha256": "511c54bdde2dab70f0144b8a36fc9cc163fd9f8ea98de4e7ea2fdcaaa3a9c5c7", "parent_variant_id": "pyint-0408d13dc68d-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L60-L77", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "_Nothing", "variant_id": "pyint-17f4cb0a5ea6-I13", "group_id": "py-bc6e9cce35bc17cf", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1148, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a811d88731a4-SRC", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _DeepIterable:\n    member_validator = attrib(validator=is_callable())\n    iterable_validator = attrib(\n        default=None, validator=optional(is_callable())\n    )\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if self.iterable_validator is not None:\n            self.iterable_validator(inst, attr, value)\n\n        for member in value:\n            self.member_validator(inst, attr, member)\n\n    def __repr__(self):\n        iterable_identifier = (\n            \"\"\n            if self.iterable_validator is None\n            else f\" {self.iterable_validator!r}\"\n        )\n        return (\n            f\"<deep_iterable validator for{iterable_identifier}\"\n            f\" iterables of {self.member_validator!r}>\"\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-bc8b8040d3957534", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 36, "local_path": "source-original/SRC__attrs___DeepIterable__d88731a4.py", "order": 0, "original_content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L334-L359", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_DeepIterable", "variant_id": "pyint-a811d88731a4-SRC", "group_id": "py-bc8b8040d3957534", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1065, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1afd7de48f1b-I01", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _DeepIterable:\n    member_validator = attrib(validator=is_callable())\n    iterable_validator = attrib(\n        default=None, validator=optional(is_callable())\n    )\n\n    def __call__(self, inst, attr, value):\n        \n        if self.iterable_validator is not None:\n            self.iterable_validator(inst, attr, value)\n\n        for member in value:\n            self.member_validator(inst, attr, member)\n\n    def __repr__(self):\n        iterable_identifier = (\n            \"\"\n            if self.iterable_validator is None\n            else f\" {self.iterable_validator!r}\"\n        )\n        return (\n            f\"<deep_iterable validator for{iterable_identifier}\"\n            f\" iterables of {self.member_validator!r}>\"\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-bc8b8040d3957534", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "df17d380665d80735b9cb414f40c32046816cca669a47d29e1d1f1cfc27ae5ff", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 34, "local_path": "comments/remove-comments/I01__attrs___DeepIterable__7de48f1b.py", "order": 1, "original_content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "parent_variant_id": "pyint-a811d88731a4-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L334-L359", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 86, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "_DeepIterable", "variant_id": "pyint-1afd7de48f1b-I01", "group_id": "py-bc8b8040d3957534", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1066, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-75a2d53ec61a-I02", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _DeepIterable:\n    member_validator = attrib(validator=is_callable())\n    iterable_validator = attrib(\n        default=None, validator=optional(is_callable())\n    )\n\n    def __call__(self, ins, att, val):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if self.iterable_validator is not None:\n            self.iterable_validator(ins, att, val)\n\n        for mem in val:\n            self.member_validator(ins, att, mem)\n\n    def __repr__(self):\n        iterable = (\n            \"\"\n            if self.iterable_validator is None\n            else f\" {self.iterable_validator!r}\"\n        )\n        return (\n            f\"<deep_iterable validator for{iterable}\"\n            f\" iterables of {self.member_validator!r}>\"\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-bc8b8040d3957534", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "170b942492f08477e077561565fa45231f1f039ce25a331323b141272b35c93f", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 36, "local_path": "identifiers/shorten-identifiers/I02__attrs___DeepIterable__d53ec61a.py", "order": 2, "original_content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "parent_variant_id": "pyint-a811d88731a4-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L334-L359", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 13, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "_DeepIterable", "variant_id": "pyint-75a2d53ec61a-I02", "group_id": "py-bc8b8040d3957534", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1067, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-beb0b5022b2f-I03", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _DeepIterable:\n    member_validator = attrib(validator=is_callable())\n    iterable_validator = attrib(\n        default=None, validator=optional(is_callable())\n    )\n\n    def __call__(self, node, path, count):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if self.iterable_validator is not None:\n            self.iterable_validator(node, path, count)\n\n        for status in count:\n            self.member_validator(node, path, status)\n\n    def __repr__(self):\n        defaultBalance = (\n            \"\"\n            if self.iterable_validator is None\n            else f\" {self.iterable_validator!r}\"\n        )\n        return (\n            f\"<deep_iterable validator for{defaultBalance}\"\n            f\" iterables of {self.member_validator!r}>\"\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-bc8b8040d3957534", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "c2d66ba9046abe164d8edd2a2384a6492636f902afd20da72d1ed69c12a3b9eb", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 36, "local_path": "identifiers/mislead-identifiers/I03__attrs___DeepIterable__b5022b2f.py", "order": 3, "original_content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "parent_variant_id": "pyint-a811d88731a4-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L334-L359", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 13, "identifiers_declared": 5, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 4, "local_random_pool_selections": 5, "local_total_length_difference": 5, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_DeepIterable", "variant_id": "pyint-beb0b5022b2f-I03", "group_id": "py-bc8b8040d3957534", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1068, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-734fb4ce2fbd-I04", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _DeepIterable:\n    member_validator = attrib(validator=is_callable())\n    iterable_validator = attrib(\n        default=None, validator=optional(is_callable())\n    )\n\n    def __call__(self, a, b, c):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if self.iterable_validator is not None:\n            self.iterable_validator(a, b, c)\n\n        for d in c:\n            self.member_validator(a, b, d)\n\n    def __repr__(self):\n        e = (\n            \"\"\n            if self.iterable_validator is None\n            else f\" {self.iterable_validator!r}\"\n        )\n        return (\n            f\"<deep_iterable validator for{e}\"\n            f\" iterables of {self.member_validator!r}>\"\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-bc8b8040d3957534", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "365845537ae44ffa72810dc70fd94843fe0fb9006032bb8e244df3e3b2289084", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 36, "local_path": "identifiers/garble-identifiers/I04__attrs___DeepIterable__b4ce2fbd.py", "order": 4, "original_content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "parent_variant_id": "pyint-a811d88731a4-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L334-L359", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 13, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "_DeepIterable", "variant_id": "pyint-734fb4ce2fbd-I04", "group_id": "py-bc8b8040d3957534", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1069, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c236b24c4374-I05", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _DeepIterable:\n    member_validator = attrib(validator=is_callable())\n    iterable_validator = attrib(\n        default=None, validator=optional(is_callable())\n    )\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if self.iterable_validator is not None:\n            self.iterable_validator(inst, attr, value)\n\n        for member in value:\n            self.member_validator(inst, attr, member)\n\n    def __repr__(self):\n        iterable_identifier = (\n            \"\"\n            if self.iterable_validator is None\n            else f\" {self.iterable_validator!r}\"\n        )\n        return (\n            f\"<deep_iterable validator for{iterable_identifier}\"\n            f\" iterables of {self.member_validator!r}>\"\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-bc8b8040d3957534", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 36, "local_path": "expressions/encode-integer-literals/I05__attrs___DeepIterable__b24c4374.py", "order": 5, "original_content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "parent_variant_id": "pyint-a811d88731a4-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L334-L359", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "_DeepIterable", "variant_id": "pyint-c236b24c4374-I05", "group_id": "py-bc8b8040d3957534", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1070, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ba216cc7b52f-I06", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _DeepIterable:\n    member_validator = attrib(validator=is_callable())\n    iterable_validator = attrib(\n        default=None, validator=optional(is_callable())\n    )\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not (self.iterable_validator is not None):\n            pass\n        else:\n            self.iterable_validator(inst, attr, value)\n\n        for member in value:\n            self.member_validator(inst, attr, member)\n\n    def __repr__(self):\n        iterable_identifier = (\n            \"\"\n            if self.iterable_validator is None\n            else f\" {self.iterable_validator!r}\"\n        )\n        return (\n            f\"<deep_iterable validator for{iterable_identifier}\"\n            f\" iterables of {self.member_validator!r}>\"\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-bc8b8040d3957534", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "e82ffaf5153453b9b59b0b7175b6d3cc70a0cbb195da41ed5cd3ade54af909a1", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 38, "local_path": "expressions/invert-conditions/I06__attrs___DeepIterable__6cc7b52f.py", "order": 6, "original_content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "parent_variant_id": "pyint-a811d88731a4-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L334-L359", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "_DeepIterable", "variant_id": "pyint-ba216cc7b52f-I06", "group_id": "py-bc8b8040d3957534", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1071, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-da94f07fbd47-I07", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _DeepIterable:\n    member_validator = attrib(validator=is_callable())\n    iterable_validator = attrib(\n        default=None, validator=optional(is_callable())\n    )\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if ((0x79ec ^ 0x79ec) != 0):\n            raise AssertionError()\n        if self.iterable_validator is not None:\n            self.iterable_validator(inst, attr, value)\n\n        for member in value:\n            self.member_validator(inst, attr, member)\n\n    def __repr__(self):\n        if ((0xbcfa ^ 0xbcfa) != 0):\n            raise AssertionError()\n        iterable_identifier = (\n            \"\"\n            if self.iterable_validator is None\n            else f\" {self.iterable_validator!r}\"\n        )\n        return (\n            f\"<deep_iterable validator for{iterable_identifier}\"\n            f\" iterables of {self.member_validator!r}>\"\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-bc8b8040d3957534", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "3f7e32c5a58dff49962fa34bb47478832b31b758d81f426c0b9d0f8fe77ed501", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 40, "local_path": "code-injection/insert-dead-branches/I07__attrs___DeepIterable__f07fbd47.py", "order": 7, "original_content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "parent_variant_id": "pyint-a811d88731a4-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L334-L359", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "_DeepIterable", "variant_id": "pyint-da94f07fbd47-I07", "group_id": "py-bc8b8040d3957534", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1072, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-23ba6e612caf-I08", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _DeepIterable:\n    member_validator = attrib(validator=is_callable())\n    iterable_validator = attrib(\n        default=None, validator=optional(is_callable())\n    )\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if self.iterable_validator is not None:\n            self.iterable_validator(inst, attr, value)\n\n        for member in value:\n            self.member_validator(inst, attr, member)\n\n    def __repr__(self):\n        previous_number = 0\n        current_number = 1\n        for sequence_step in range(4):\n            next_number = previous_number + current_number\n            previous_number = current_number\n            current_number = next_number\n        iterable_identifier = (\n            \"\"\n            if self.iterable_validator is None\n            else f\" {self.iterable_validator!r}\"\n        )\n        return (\n            f\"<deep_iterable validator for{iterable_identifier}\"\n            f\" iterables of {self.member_validator!r}>\"\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-bc8b8040d3957534", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "ed48936be560cdc7517470d80fc65049039d34736a288cfb3377dfd30e6f4bf9", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 42, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___DeepIterable__6e612caf.py", "order": 8, "original_content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "parent_variant_id": "pyint-a811d88731a4-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L334-L359", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 8}, "unit_kind": "class", "unit_name": "_DeepIterable", "variant_id": "pyint-23ba6e612caf-I08", "group_id": "py-bc8b8040d3957534", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1073, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9850d931e0e9-I09", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _DeepIterable:\n    member_validator = attrib(validator=is_callable())\n    iterable_validator = attrib(\n        default=None, validator=optional(is_callable())\n    )\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if self.iterable_validator is not None:\n            self.iterable_validator(inst, attr, value)\n\n        for member in value:\n            self.member_validator(inst, attr, member)\n\n    def __repr__(self):\n        lI0O_4e9278cf = 0x4797 ^ 0x4797\n        if lI0O_4e9278cf != 0:\n            if ((lI0O_4e9278cf | 1) & 1) == 0:\n                lI0O_4e9278cf += 1\n            else:\n                lI0O_4e9278cf -= 1\n        iterable_identifier = (\n            \"\"\n            if self.iterable_validator is None\n            else f\" {self.iterable_validator!r}\"\n        )\n        return (\n            f\"<deep_iterable validator for{iterable_identifier}\"\n            f\" iterables of {self.member_validator!r}>\"\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-bc8b8040d3957534", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "ed3d6dad23b4da1d5c4e7a5e45f6ba94df8d01b8afdf83e8440b14a7a771f5c1", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 42, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___DeepIterable__d931e0e9.py", "order": 9, "original_content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "parent_variant_id": "pyint-a811d88731a4-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L334-L359", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 5}, "unit_kind": "class", "unit_name": "_DeepIterable", "variant_id": "pyint-9850d931e0e9-I09", "group_id": "py-bc8b8040d3957534", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1074, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d350ff545b54-I10", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _DeepIterable:\n    member_validator = attrib(validator=is_callable())\n    iterable_validator = attrib(         default=None, validator=optional(is_callable())\n    )\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if self.iterable_validator is not None:\n            self.iterable_validator(inst, attr, value)\n        for member in value:\n            self.member_validator(inst, attr, member)\n    def __repr__(self):\n        iterable_identifier = (\n            \"\"\n            if self.iterable_validator is None\n            else f\" {self.iterable_validator!r}\"\n        )\n        return (             f\"<deep_iterable validator for{iterable_identifier}\"\n            f\" iterables of {self.member_validator!r}>\"\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-bc8b8040d3957534", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "8c2d9c2096f630cd047c4bf397e9eafbc3931acc390d6b78423733dc3b13ca57", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 31, "local_path": "layout/partially-compact-layout/I10__attrs___DeepIterable__ff545b54.py", "order": 10, "original_content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "parent_variant_id": "pyint-a811d88731a4-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L334-L359", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 13, "line_break_groups_removed": 5, "line_breaks_removed": 5, "whitespace_characters_removed": 3}, "unit_kind": "class", "unit_name": "_DeepIterable", "variant_id": "pyint-d350ff545b54-I10", "group_id": "py-bc8b8040d3957534", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1075, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4c90b995c19f-I11", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _DeepIterable:\n    member_validator = attrib(validator=is_callable())\n    iterable_validator = attrib(\n        default=None, validator=optional(is_callable())\n    )\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if self.iterable_validator is not None:\n            self.iterable_validator(inst, attr, value)\n\n        for member in value:\n            self.member_validator(inst, attr, member)\n\n    def __repr__(self):\n        iterable_identifier = (\n            \"\"\n            if self.iterable_validator is None\n            else f\" {self.iterable_validator!r}\"\n        )\n        return (\n            f\"<deep_iterable validator for{iterable_identifier}\"\n            f\" iterables of {self.member_validator!r}>\"\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-bc8b8040d3957534", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 36, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___DeepIterable__b995c19f.py", "order": 11, "original_content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "parent_variant_id": "pyint-a811d88731a4-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L334-L359", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "_DeepIterable", "variant_id": "pyint-4c90b995c19f-I11", "group_id": "py-bc8b8040d3957534", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1076, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-92df7fddb91c-I12", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _DeepIterable:\n    member_validator = attrib(validator=is_callable())\n    iterable_validator = attrib(\n        default=None, validator=optional(is_callable())\n    )\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if self.iterable_validator is not None:\n            self.iterable_validator(inst, attr, value)\n\n        for member in value:\n            self.member_validator(inst, attr, member)\n\n    def __repr__(self):\n        iterable_identifier = (\n            \"\"\n            if self.iterable_validator is None\n            else f\" {self.iterable_validator!r}\"\n        )\n        return (\n            f\"<deep_iterable validator for{iterable_identifier}\"\n            f\" iterables of {self.member_validator!r}>\"\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-bc8b8040d3957534", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 36, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___DeepIterable__7fddb91c.py", "order": 12, "original_content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "parent_variant_id": "pyint-a811d88731a4-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L334-L359", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_DeepIterable", "variant_id": "pyint-92df7fddb91c-I12", "group_id": "py-bc8b8040d3957534", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1077, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a982da214d28-I13", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _DeepIterable:\n    member_validator = attrib(validator=is_callable())\n    iterable_validator = attrib(\n        default=None, validator=optional(is_callable())\n    )\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if self.iterable_validator is not None:\n            self.iterable_validator(inst, attr, value)\n\n        loopIterator = __import__(\"builtins\").iter(value)\n        while True:\n            try:\n                member = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            self.member_validator(inst, attr, member)\n\n    def __repr__(self):\n        iterable_identifier = (\n            \"\"\n            if self.iterable_validator is None\n            else f\" {self.iterable_validator!r}\"\n        )\n        return (\n            f\"<deep_iterable validator for{iterable_identifier}\"\n            f\" iterables of {self.member_validator!r}>\"\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-bc8b8040d3957534", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f7ed4cae4b6108b41d0b85594227efea9c4eda22e0ad62335d10783b1dac32e9", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 41, "local_path": "control-flow/lower-for-to-while/I13__attrs___DeepIterable__da214d28.py", "order": 13, "original_content_sha256": "801a505191d934e0d0b70a662eb117a81e31624c6d1540c7d890a538cee8859d", "parent_variant_id": "pyint-a811d88731a4-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L334-L359", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 1, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 1, "synchronous_for_loops_eligible": 1, "synchronous_for_loops_found": 1}, "unit_kind": "class", "unit_name": "_DeepIterable", "variant_id": "pyint-a982da214d28-I13", "group_id": "py-bc8b8040d3957534", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1078, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2643cf679ba3-SRC", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass LookupDict(dict[str, _VT]):\n    \"\"\"Dictionary lookup object.\"\"\"\n\n    name: Any\n\n    def __init__(self, name: Any = None) -> None:\n        self.name = name\n        super().__init__()\n\n    def __repr__(self) -> str:\n        return f\"<lookup '{self.name}'>\"\n\n    def __getattr__(self, key: str) -> _VT | None:\n        # We need this for type checkers to infer typing\n        # on attribute access with status_codes.py\n        if key in self.__dict__:\n            return self.__dict__[key]\n        else:\n            raise AttributeError(\n                f\"'{type(self).__name__}' object has no attribute '{key}'\"\n            )\n\n    def __getitem__(self, key: str) -> _VT | None:  # type: ignore[override]\n        # We allow fall-through here, so values default to None\n\n        return self.__dict__.get(key, None)\n\n    @overload\n    def get(self, key: str, default: None = None) -> _VT | None: ...\n\n    @overload\n    def get(self, key: str, default: _D | _VT) -> _D | _VT: ...\n\n    def get(self, key: str, default: _D | None = None) -> _VT | _D | None:\n        return self.__dict__.get(key, default)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-c513e8958c87dbb4", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 41, "local_path": "source-original/SRC__requests__LookupDict__cf679ba3.py", "order": 0, "original_content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L96-L130", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "LookupDict", "variant_id": "pyint-2643cf679ba3-SRC", "group_id": "py-c513e8958c87dbb4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 953, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b6b7f861c72c-I01", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass LookupDict(dict[str, _VT]):\n    \n\n    name: Any\n\n    def __init__(self, name: Any = None) -> None:\n        self.name = name\n        super().__init__()\n\n    def __repr__(self) -> str:\n        return f\"<lookup '{self.name}'>\"\n\n    def __getattr__(self, key: str) -> _VT | None:\n         \n         \n        if key in self.__dict__:\n            return self.__dict__[key]\n        else:\n            raise AttributeError(\n                f\"'{type(self).__name__}' object has no attribute '{key}'\"\n            )\n\n    def __getitem__(self, key: str) -> _VT | None:   \n         \n\n        return self.__dict__.get(key, None)\n\n    @overload\n    def get(self, key: str, default: None = None) -> _VT | None: ...\n\n    @overload\n    def get(self, key: str, default: _D | _VT) -> _D | _VT: ...\n\n    def get(self, key: str, default: _D | None = None) -> _VT | _D | None:\n        return self.__dict__.get(key, default)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-c513e8958c87dbb4", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "3367e42f25507490b98bfac4adcca3f2d6e188d73bb4228f574e5d0d8f91963d", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 41, "local_path": "comments/remove-comments/I01__requests__LookupDict__f861c72c.py", "order": 1, "original_content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "parent_variant_id": "pyint-2643cf679ba3-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L96-L130", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 196, "comments_removed": 5, "docstrings_removed": 1, "line_comments_removed": 4}, "unit_kind": "class", "unit_name": "LookupDict", "variant_id": "pyint-b6b7f861c72c-I01", "group_id": "py-c513e8958c87dbb4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 954, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dd3eb2d95411-I02", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass LookupDict(dict[str, _VT]):\n    \"\"\"Dictionary lookup object.\"\"\"\n\n    name: Any\n\n    def __init__(self, nam: Any = None) -> None:\n        self.name = nam\n        super().__init__()\n\n    def __repr__(self) -> str:\n        return f\"<lookup '{self.name}'>\"\n\n    def __getattr__(self, key2: str) -> _VT | None:\n        # We need this for type checkers to infer typing\n        # on attribute access with status_codes.py\n        if key2 in self.__dict__:\n            return self.__dict__[key2]\n        else:\n            raise AttributeError(\n                f\"'{type(self).__name__}' object has no attribute '{key2}'\"\n            )\n\n    def __getitem__(self, key3: str) -> _VT | None:  # type: ignore[override]\n        # We allow fall-through here, so values default to None\n\n        return self.__dict__.get(key3, None)\n\n    @overload\n    def get4(self, key4: str, def2: None = None) -> _VT | None: ...\n\n    @overload\n    def get4(self, key5: str, def3: _D | _VT) -> _D | _VT: ...\n\n    def get4(self, key6: str, def4: _D | None = None) -> _VT | _D | None:\n        return self.__dict__.get(key6, def4)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-c513e8958c87dbb4", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "4d24e7605ed46a62ae9d1a67d95854e0a20d03844351555c1207c72c5aa4681b", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 41, "local_path": "identifiers/shorten-identifiers/I02__requests__LookupDict__b2d95411.py", "order": 2, "original_content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "parent_variant_id": "pyint-2643cf679ba3-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L96-L130", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 19, "identifiers_declared": 12}, "unit_kind": "class", "unit_name": "LookupDict", "variant_id": "pyint-dd3eb2d95411-I02", "group_id": "py-c513e8958c87dbb4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 955, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f1c6136d21dd-I03", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass LookupDict(dict[str, _VT]):\n    \"\"\"Dictionary lookup object.\"\"\"\n\n    name: Any\n\n    def __init__(self, item: Any = None) -> None:\n        self.name = item\n        super().__init__()\n\n    def __repr__(self) -> str:\n        return f\"<lookup '{self.name}'>\"\n\n    def __getattr__(self, map: str) -> _VT | None:\n        # We need this for type checkers to infer typing\n        # on attribute access with status_codes.py\n        if map in self.__dict__:\n            return self.__dict__[map]\n        else:\n            raise AttributeError(\n                f\"'{type(self).__name__}' object has no attribute '{map}'\"\n            )\n\n    def __getitem__(self, map: str) -> _VT | None:  # type: ignore[override]\n        # We allow fall-through here, so values default to None\n\n        return self.__dict__.get(map, None)\n\n    @overload\n    def emit(self, age: str, context: None = None) -> _VT | None: ...\n\n    @overload\n    def emit(self, map: str, nextKey: _D | _VT) -> _D | _VT: ...\n\n    def emit(self, map: str, invoice: _D | None = None) -> _VT | _D | None:\n        return self.__dict__.get(map, invoice)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-c513e8958c87dbb4", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b6e80ec76bbdabd70d187f79050add67d39ccd1c6cf462acbf0de73051b19a1d", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 41, "local_path": "identifiers/mislead-identifiers/I03__requests__LookupDict__136d21dd.py", "order": 3, "original_content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "parent_variant_id": "pyint-2643cf679ba3-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L96-L130", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 19, "identifiers_declared": 12, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 9, "local_random_pool_selections": 9, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 2, "method_exact_length_matches": 0, "method_random_pool_selections": 3, "method_total_length_difference": 1}, "unit_kind": "class", "unit_name": "LookupDict", "variant_id": "pyint-f1c6136d21dd-I03", "group_id": "py-c513e8958c87dbb4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 956, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-247d8ec494e4-I04", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass LookupDict(dict[str, _VT]):\n    \"\"\"Dictionary lookup object.\"\"\"\n\n    name: Any\n\n    def __init__(self, d: Any = None) -> None:\n        self.name = d\n        super().__init__()\n\n    def __repr__(self) -> str:\n        return f\"<lookup '{self.name}'>\"\n\n    def __getattr__(self, e: str) -> _VT | None:\n        # We need this for type checkers to infer typing\n        # on attribute access with status_codes.py\n        if e in self.__dict__:\n            return self.__dict__[e]\n        else:\n            raise AttributeError(\n                f\"'{type(self).__name__}' object has no attribute '{e}'\"\n            )\n\n    def __getitem__(self, f: str) -> _VT | None:  # type: ignore[override]\n        # We allow fall-through here, so values default to None\n\n        return self.__dict__.get(f, None)\n\n    @overload\n    def c(self, g: str, h: None = None) -> _VT | None: ...\n\n    @overload\n    def c(self, i: str, j: _D | _VT) -> _D | _VT: ...\n\n    def c(self, k: str, l: _D | None = None) -> _VT | _D | None:\n        return self.__dict__.get(k, l)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-c513e8958c87dbb4", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "c9e01e13a61525903bbfafd157a6ea4f771996664fb1d007017d47c68b81c57f", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 41, "local_path": "identifiers/garble-identifiers/I04__requests__LookupDict__8ec494e4.py", "order": 4, "original_content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "parent_variant_id": "pyint-2643cf679ba3-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L96-L130", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 19, "identifiers_declared": 12}, "unit_kind": "class", "unit_name": "LookupDict", "variant_id": "pyint-247d8ec494e4-I04", "group_id": "py-c513e8958c87dbb4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 957, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2ac18024ca6b-I05", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass LookupDict(dict[str, _VT]):\n    \"\"\"Dictionary lookup object.\"\"\"\n\n    name: Any\n\n    def __init__(self, name: Any = None) -> None:\n        self.name = name\n        super().__init__()\n\n    def __repr__(self) -> str:\n        return f\"<lookup '{self.name}'>\"\n\n    def __getattr__(self, key: str) -> _VT | None:\n        # We need this for type checkers to infer typing\n        # on attribute access with status_codes.py\n        if key in self.__dict__:\n            return self.__dict__[key]\n        else:\n            raise AttributeError(\n                f\"'{type(self).__name__}' object has no attribute '{key}'\"\n            )\n\n    def __getitem__(self, key: str) -> _VT | None:  # type: ignore[override]\n        # We allow fall-through here, so values default to None\n\n        return self.__dict__.get(key, None)\n\n    @overload\n    def get(self, key: str, default: None = None) -> _VT | None: ...\n\n    @overload\n    def get(self, key: str, default: _D | _VT) -> _D | _VT: ...\n\n    def get(self, key: str, default: _D | None = None) -> _VT | _D | None:\n        return self.__dict__.get(key, default)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-c513e8958c87dbb4", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 41, "local_path": "expressions/encode-integer-literals/I05__requests__LookupDict__8024ca6b.py", "order": 5, "original_content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "parent_variant_id": "pyint-2643cf679ba3-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L96-L130", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "LookupDict", "variant_id": "pyint-2ac18024ca6b-I05", "group_id": "py-c513e8958c87dbb4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 958, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8d0f875179a3-I06", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass LookupDict(dict[str, _VT]):\n    \"\"\"Dictionary lookup object.\"\"\"\n\n    name: Any\n\n    def __init__(self, name: Any = None) -> None:\n        self.name = name\n        super().__init__()\n\n    def __repr__(self) -> str:\n        return f\"<lookup '{self.name}'>\"\n\n    def __getattr__(self, key: str) -> _VT | None:\n        # We need this for type checkers to infer typing\n        # on attribute access with status_codes.py\n        if not (key in self.__dict__):\n            raise AttributeError(\n                f\"'{type(self).__name__}' object has no attribute '{key}'\"\n            )\n        else:\n            return self.__dict__[key]\n\n    def __getitem__(self, key: str) -> _VT | None:  # type: ignore[override]\n        # We allow fall-through here, so values default to None\n\n        return self.__dict__.get(key, None)\n\n    @overload\n    def get(self, key: str, default: None = None) -> _VT | None: ...\n\n    @overload\n    def get(self, key: str, default: _D | _VT) -> _D | _VT: ...\n\n    def get(self, key: str, default: _D | None = None) -> _VT | _D | None:\n        return self.__dict__.get(key, default)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-c513e8958c87dbb4", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "51dbce8a03d9a34f14f5527eb841f3df8c5848ec4faafe68950bdc0e657094ef", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 41, "local_path": "expressions/invert-conditions/I06__requests__LookupDict__875179a3.py", "order": 6, "original_content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "parent_variant_id": "pyint-2643cf679ba3-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L96-L130", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "LookupDict", "variant_id": "pyint-8d0f875179a3-I06", "group_id": "py-c513e8958c87dbb4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 959, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f7356cc75179-I07", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass LookupDict(dict[str, _VT]):\n    \"\"\"Dictionary lookup object.\"\"\"\n\n    name: Any\n\n    def __init__(self, name: Any = None) -> None:\n        if ((0x7216 ^ 0x7216) != 0):\n            raise AssertionError()\n        self.name = name\n        super().__init__()\n\n    def __repr__(self) -> str:\n        if ((0x3aa2 ^ 0x3aa2) != 0):\n            raise AssertionError()\n        return f\"<lookup '{self.name}'>\"\n\n    def __getattr__(self, key: str) -> _VT | None:\n        # We need this for type checkers to infer typing\n        # on attribute access with status_codes.py\n        if ((0xcd01 ^ 0xcd01) != 0):\n            raise AssertionError()\n        if key in self.__dict__:\n            return self.__dict__[key]\n        else:\n            raise AttributeError(\n                f\"'{type(self).__name__}' object has no attribute '{key}'\"\n            )\n\n    def __getitem__(self, key: str) -> _VT | None:  # type: ignore[override]\n        # We allow fall-through here, so values default to None\n\n        if ((0x7510 ^ 0x7510) != 0):\n            raise AssertionError()\n        return self.__dict__.get(key, None)\n\n    @overload\n    def get(self, key: str, default: None = None) -> _VT | None: ...\n\n    @overload\n    def get(self, key: str, default: _D | _VT) -> _D | _VT: ...\n\n    def get(self, key: str, default: _D | None = None) -> _VT | _D | None:\n        if ((0x8f39 ^ 0x8f39) != 0):\n            raise AssertionError()\n        return self.__dict__.get(key, default)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-c513e8958c87dbb4", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "59c07e7d166f3dbd6ae4cda7495c6b44b4d19f840f10a00e4fc88fb246d15a64", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 51, "local_path": "code-injection/insert-dead-branches/I07__requests__LookupDict__6cc75179.py", "order": 7, "original_content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "parent_variant_id": "pyint-2643cf679ba3-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L96-L130", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 5}, "unit_kind": "class", "unit_name": "LookupDict", "variant_id": "pyint-f7356cc75179-I07", "group_id": "py-c513e8958c87dbb4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 960, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-709d7d5ba093-I08", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass LookupDict(dict[str, _VT]):\n    \"\"\"Dictionary lookup object.\"\"\"\n\n    name: Any\n\n    def __init__(self, name: Any = None) -> None:\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        self.name = name\n        super().__init__()\n\n    def __repr__(self) -> str:\n        return f\"<lookup '{self.name}'>\"\n\n    def __getattr__(self, key: str) -> _VT | None:\n        # We need this for type checkers to infer typing\n        # on attribute access with status_codes.py\n        if key in self.__dict__:\n            return self.__dict__[key]\n        else:\n            raise AttributeError(\n                f\"'{type(self).__name__}' object has no attribute '{key}'\"\n            )\n\n    def __getitem__(self, key: str) -> _VT | None:  # type: ignore[override]\n        # We allow fall-through here, so values default to None\n\n        return self.__dict__.get(key, None)\n\n    @overload\n    def get(self, key: str, default: None = None) -> _VT | None: ...\n\n    @overload\n    def get(self, key: str, default: _D | _VT) -> _D | _VT: ...\n\n    def get(self, key: str, default: _D | None = None) -> _VT | _D | None:\n        return self.__dict__.get(key, default)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-c513e8958c87dbb4", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d6105d356fa47edb87e0a415e93921ad536c9723cc19c3e12d4ef9253ee7f8b7", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 46, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__LookupDict__7d5ba093.py", "order": 8, "original_content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "parent_variant_id": "pyint-2643cf679ba3-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L96-L130", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "LookupDict", "variant_id": "pyint-709d7d5ba093-I08", "group_id": "py-c513e8958c87dbb4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 961, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d86bcf3a3f06-I09", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass LookupDict(dict[str, _VT]):\n    \"\"\"Dictionary lookup object.\"\"\"\n\n    name: Any\n\n    def __init__(self, name: Any = None) -> None:\n        self.name = name\n        super().__init__()\n\n    def __repr__(self) -> str:\n        return f\"<lookup '{self.name}'>\"\n\n    def __getattr__(self, key: str) -> _VT | None:\n        # We need this for type checkers to infer typing\n        # on attribute access with status_codes.py\n        lI0O_0b09dc52 = 0x1d6b\n        lI0O_0b09dc52 = ((lI0O_0b09dc52 ^ 0x1d6b) | 0) & -1\n        if (lI0O_0b09dc52 & 1) == 1:\n            lI0O_0b09dc52 ^= lI0O_0b09dc52\n        if key in self.__dict__:\n            return self.__dict__[key]\n        else:\n            raise AttributeError(\n                f\"'{type(self).__name__}' object has no attribute '{key}'\"\n            )\n\n    def __getitem__(self, key: str) -> _VT | None:  # type: ignore[override]\n        # We allow fall-through here, so values default to None\n\n        return self.__dict__.get(key, None)\n\n    @overload\n    def get(self, key: str, default: None = None) -> _VT | None: ...\n\n    @overload\n    def get(self, key: str, default: _D | _VT) -> _D | _VT: ...\n\n    def get(self, key: str, default: _D | None = None) -> _VT | _D | None:\n        return self.__dict__.get(key, default)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-c513e8958c87dbb4", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "e62b17e7966d64b80f2d6e5b5b15bf54bf6bd19a4d1f45709774ba9779dbfebd", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 45, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__LookupDict__cf3a3f06.py", "order": 9, "original_content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "parent_variant_id": "pyint-2643cf679ba3-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L96-L130", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 0}, "unit_kind": "class", "unit_name": "LookupDict", "variant_id": "pyint-d86bcf3a3f06-I09", "group_id": "py-c513e8958c87dbb4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 962, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6d287e9910a8-I10", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass LookupDict(dict[str, _VT]):\n    \"\"\"Dictionary lookup object.\"\"\"\n    name: Any\n\n    def __init__(self, name: Any = None) -> None:\n        self.name = name\n        super().__init__()\n\n    def __repr__(self) -> str:\n        return f\"<lookup '{self.name}'>\"\n\n    def __getattr__(self, key: str) -> _VT | None:\n        # We need this for type checkers to infer typing\n        # on attribute access with status_codes.py\n        if key in self.__dict__:\n            return self.__dict__[key]\n        else:\n            raise AttributeError(                 f\"'{type(self).__name__}' object has no attribute '{key}'\"\n            )\n    def __getitem__(self, key: str) -> _VT | None:  # type: ignore[override]\n        # We allow fall-through here, so values default to None\n        return self.__dict__.get(key, None)\n\n    @overload\n    def get(self, key: str, default: None = None) -> _VT | None: ...\n\n    @overload\n    def get(self, key: str, default: _D | _VT) -> _D | _VT: ...\n\n    def get(self, key: str, default: _D | None = None) -> _VT | _D | None:\n        return self.__dict__.get(key, default)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-c513e8958c87dbb4", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "d26d1426b49ff8fde5bad3bdd8db64acaa5eb628e5502002fdf30aac2a0824ee", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 37, "local_path": "layout/partially-compact-layout/I10__requests__LookupDict__7e9910a8.py", "order": 10, "original_content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "parent_variant_id": "pyint-2643cf679ba3-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L96-L130", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 12, "line_break_groups_removed": 4, "line_breaks_removed": 4, "whitespace_characters_removed": 3}, "unit_kind": "class", "unit_name": "LookupDict", "variant_id": "pyint-6d287e9910a8-I10", "group_id": "py-c513e8958c87dbb4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 963, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0d5113964424-I11", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass LookupDict(dict[str, _VT]):\n    \"\"\"Dictionary lookup object.\"\"\"\n\n    name: Any\n\n    def __init__(self, name: Any = None) -> None:\n        self.name = name\n        super().__init__()\n\n    def __repr__(self) -> str:\n        return f\"<lookup '{self.name}'>\"\n\n    def __getattr__(self, key: str) -> _VT | None:\n        # We need this for type checkers to infer typing\n        # on attribute access with status_codes.py\n        if key in self.__dict__:\n            return self.__dict__[key]\n        else:\n            raise AttributeError(\n                f\"'{type(self).__name__}' object has no attribute '{key}'\"\n            )\n\n    def __getitem__(self, key: str) -> _VT | None:  # type: ignore[override]\n        # We allow fall-through here, so values default to None\n\n        return self.__dict__.get(key, None)\n\n    @overload\n    def get(self, key: str, default: None = None) -> _VT | None: ...\n\n    @overload\n    def get(self, key: str, default: _D | _VT) -> _D | _VT: ...\n\n    def get(self, key: str, default: _D | None = None) -> _VT | _D | None:\n        return self.__dict__.get(key, default)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-c513e8958c87dbb4", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 41, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__LookupDict__13964424.py", "order": 11, "original_content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "parent_variant_id": "pyint-2643cf679ba3-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L96-L130", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "LookupDict", "variant_id": "pyint-0d5113964424-I11", "group_id": "py-c513e8958c87dbb4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 964, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-94ad14218745-I12", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass LookupDict(dict[str, _VT]):\n    \"\"\"Dictionary lookup object.\"\"\"\n\n    name: Any\n\n    def __init__(self, name: Any = None) -> None:\n        self.name = name\n        super().__init__()\n\n    def __repr__(self) -> str:\n        return f\"<lookup '{self.name}'>\"\n\n    def __getattr__(self, key: str) -> _VT | None:\n        # We need this for type checkers to infer typing\n        # on attribute access with status_codes.py\n        if key in self.__dict__:\n            return self.__dict__[key]\n        else:\n            raise AttributeError(\n                f\"'{type(self).__name__}' object has no attribute '{key}'\"\n            )\n\n    def __getitem__(self, key: str) -> _VT | None:  # type: ignore[override]\n        # We allow fall-through here, so values default to None\n\n        return self.__dict__.get(key, None)\n\n    @overload\n    def get(self, key: str, default: None = None) -> _VT | None: ...\n\n    @overload\n    def get(self, key: str, default: _D | _VT) -> _D | _VT: ...\n\n    def get(self, key: str, default: _D | None = None) -> _VT | _D | None:\n        return self.__dict__.get(key, default)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-c513e8958c87dbb4", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 41, "local_path": "data-flow/inline-intermediate-variables/I12__requests__LookupDict__14218745.py", "order": 12, "original_content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "parent_variant_id": "pyint-2643cf679ba3-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L96-L130", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "LookupDict", "variant_id": "pyint-94ad14218745-I12", "group_id": "py-c513e8958c87dbb4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 965, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ee897172cdc8-I13", "source": "from __future__ import annotations\nfrom collections import OrderedDict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom .compat import MutableMapping\n\nclass LookupDict(dict[str, _VT]):\n    \"\"\"Dictionary lookup object.\"\"\"\n\n    name: Any\n\n    def __init__(self, name: Any = None) -> None:\n        self.name = name\n        super().__init__()\n\n    def __repr__(self) -> str:\n        return f\"<lookup '{self.name}'>\"\n\n    def __getattr__(self, key: str) -> _VT | None:\n        # We need this for type checkers to infer typing\n        # on attribute access with status_codes.py\n        if key in self.__dict__:\n            return self.__dict__[key]\n        else:\n            raise AttributeError(\n                f\"'{type(self).__name__}' object has no attribute '{key}'\"\n            )\n\n    def __getitem__(self, key: str) -> _VT | None:  # type: ignore[override]\n        # We allow fall-through here, so values default to None\n\n        return self.__dict__.get(key, None)\n\n    @overload\n    def get(self, key: str, default: None = None) -> _VT | None: ...\n\n    @overload\n    def get(self, key: str, default: _D | _VT) -> _D | _VT: ...\n\n    def get(self, key: str, default: _D | None = None) -> _VT | _D | None:\n        return self.__dict__.get(key, default)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-c513e8958c87dbb4", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 41, "local_path": "control-flow/lower-for-to-while/I13__requests__LookupDict__7172cdc8.py", "order": 13, "original_content_sha256": "f912b8c1048ddea2631271139f6ae6bf00ca83c1ff44a983c9ae409786957700", "parent_variant_id": "pyint-2643cf679ba3-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/structures.py#L96-L130", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "LookupDict", "variant_id": "pyint-ee897172cdc8-I13", "group_id": "py-c513e8958c87dbb4", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 966, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-939f88f49b68-SRC", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        raise NotImplementedError\n\n    def close(self) -> None:\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        raise NotImplementedError\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-c63e591dfb8a9356", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 85, "local_path": "source-original/SRC__requests__BaseAdapter__88f49b68.py", "order": 0, "original_content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L122-L155", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "BaseAdapter", "variant_id": "pyint-939f88f49b68-SRC", "group_id": "py-c63e591dfb8a9356", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 925, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ba6ef54631c0-I01", "source": "from __future__ import annotations\nimport os.path\nimport socket   \nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass BaseAdapter:\n    \n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \n        raise NotImplementedError\n\n    def close(self) -> None:\n        \n        raise NotImplementedError\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-c63e591dfb8a9356", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "73b012d25840971546924931150b68f091d58a1fc89302057c1d74acf695adbd", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 72, "local_path": "comments/remove-comments/I01__requests__BaseAdapter__f54631c0.py", "order": 1, "original_content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "parent_variant_id": "pyint-939f88f49b68-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L122-L155", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 923, "comments_removed": 4, "docstrings_removed": 3, "line_comments_removed": 1}, "unit_kind": "class", "unit_name": "BaseAdapter", "variant_id": "pyint-ba6ef54631c0-I01", "group_id": "py-c63e591dfb8a9356", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 926, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-752dca2b4957-I02", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def sen(\n        self,\n        req: PreparedRequest,\n        str2: bool = False,\n        tim: _t.TimeoutType = None,\n        ver: _t.VerifyType = True,\n        cer: _t.CertType = None,\n        pro: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        raise NotImplementedError\n\n    def clo(self) -> None:\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        raise NotImplementedError\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-c63e591dfb8a9356", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "5c6dd9fe23a49b206e89067f53f3b3968132b2f034aa5aa2dcae709118837b88", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 85, "local_path": "identifiers/shorten-identifiers/I02__requests__BaseAdapter__ca2b4957.py", "order": 2, "original_content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "parent_variant_id": "pyint-939f88f49b68-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L122-L155", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 8}, "unit_kind": "class", "unit_name": "BaseAdapter", "variant_id": "pyint-752dca2b4957-I02", "group_id": "py-c63e591dfb8a9356", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 927, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4bdf396f2be7-I03", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def sort(\n        self,\n        summary: PreparedRequest,\n        config: bool = False,\n        address: _t.TimeoutType = None,\n        source: _t.VerifyType = True,\n        date: _t.CertType = None,\n        channel: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        raise NotImplementedError\n\n    def write(self) -> None:\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        raise NotImplementedError\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-c63e591dfb8a9356", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "6e1c4ac81ea9adcbb92543c7462fb162e2042db17efcf6c4c9d42d7a89b6bcb7", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 85, "local_path": "identifiers/mislead-identifiers/I03__requests__BaseAdapter__396f2be7.py", "order": 3, "original_content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "parent_variant_id": "pyint-939f88f49b68-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L122-L155", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 8, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 6, "local_random_pool_selections": 6, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 2, "method_random_pool_selections": 2, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "BaseAdapter", "variant_id": "pyint-4bdf396f2be7-I03", "group_id": "py-c63e591dfb8a9356", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 928, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-211985934c18-I04", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def a(\n        self,\n        c: PreparedRequest,\n        d: bool = False,\n        e: _t.TimeoutType = None,\n        f: _t.VerifyType = True,\n        g: _t.CertType = None,\n        h: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        raise NotImplementedError\n\n    def b(self) -> None:\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        raise NotImplementedError\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-c63e591dfb8a9356", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "2fdef31e4708125b4e71e21f9dee2a1c77df8e1646e9458bb02198faea0b682d", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 85, "local_path": "identifiers/garble-identifiers/I04__requests__BaseAdapter__85934c18.py", "order": 4, "original_content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "parent_variant_id": "pyint-939f88f49b68-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L122-L155", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 8}, "unit_kind": "class", "unit_name": "BaseAdapter", "variant_id": "pyint-211985934c18-I04", "group_id": "py-c63e591dfb8a9356", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 929, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cc94dfe3b57f-I05", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        raise NotImplementedError\n\n    def close(self) -> None:\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        raise NotImplementedError\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-c63e591dfb8a9356", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 85, "local_path": "expressions/encode-integer-literals/I05__requests__BaseAdapter__dfe3b57f.py", "order": 5, "original_content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "parent_variant_id": "pyint-939f88f49b68-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L122-L155", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "BaseAdapter", "variant_id": "pyint-cc94dfe3b57f-I05", "group_id": "py-c63e591dfb8a9356", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 930, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b95f3c241e8c-I06", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        raise NotImplementedError\n\n    def close(self) -> None:\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        raise NotImplementedError\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-c63e591dfb8a9356", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 85, "local_path": "expressions/invert-conditions/I06__requests__BaseAdapter__3c241e8c.py", "order": 6, "original_content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "parent_variant_id": "pyint-939f88f49b68-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L122-L155", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "BaseAdapter", "variant_id": "pyint-b95f3c241e8c-I06", "group_id": "py-c63e591dfb8a9356", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 931, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-39bfb32c9106-I07", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n\n    def __init__(self) -> None:\n        if ((0xdbe4 ^ 0xdbe4) != 0):\n            raise AssertionError()\n        super().__init__()\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        if ((0xcb27 ^ 0xcb27) != 0):\n            raise AssertionError()\n        raise NotImplementedError\n\n    def close(self) -> None:\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        if ((0x2fb9 ^ 0x2fb9) != 0):\n            raise AssertionError()\n        raise NotImplementedError\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-c63e591dfb8a9356", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "e9f5cadcaeeeea7d0fb3b9d5e06c1dd1a041cb2d6c9ea3522a9b55536e00f558", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 91, "local_path": "code-injection/insert-dead-branches/I07__requests__BaseAdapter__b32c9106.py", "order": 7, "original_content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "parent_variant_id": "pyint-939f88f49b68-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L122-L155", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 3}, "unit_kind": "class", "unit_name": "BaseAdapter", "variant_id": "pyint-39bfb32c9106-I07", "group_id": "py-c63e591dfb8a9356", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 932, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-00108635d51b-I08", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        raise NotImplementedError\n\n    def close(self) -> None:\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        remaining_steps = 3\n        while remaining_steps > 0:\n            remaining_steps -= 1\n        raise NotImplementedError\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-c63e591dfb8a9356", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "ebd369669d9ea68c898c788633cc3af6fe6359333b87df61b62824cb2bdba80f", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 88, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__BaseAdapter__8635d51b.py", "order": 8, "original_content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "parent_variant_id": "pyint-939f88f49b68-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L122-L155", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 1}, "unit_kind": "class", "unit_name": "BaseAdapter", "variant_id": "pyint-00108635d51b-I08", "group_id": "py-c63e591dfb8a9356", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 933, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e428f69abf66-I09", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        raise NotImplementedError\n\n    def close(self) -> None:\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        lI0O_e104235e = 0xfb3c ^ 0xfb3c\n        if lI0O_e104235e == 0:\n            lI0O_e104235e |= 0\n        else:\n            lI0O_e104235e &= 0\n        raise NotImplementedError\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-c63e591dfb8a9356", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "98a94eac6e34db59bcfcc3a5b4a439e9e9e8f460162364ab607d0399d7c00d27", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 90, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__BaseAdapter__f69abf66.py", "order": 9, "original_content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "parent_variant_id": "pyint-939f88f49b68-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L122-L155", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 6}, "unit_kind": "class", "unit_name": "BaseAdapter", "variant_id": "pyint-e428f69abf66-I09", "group_id": "py-c63e591dfb8a9356", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 934, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-645b5dfdcf94-I10", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,     ConnectTimeoutError,\n    LocationValueError,     MaxRetryError,\n    NewConnectionError,     ProtocolError,\n    ReadTimeoutError,\n    ResponseError, )\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,     InvalidProxyURL,\n    InvalidSchema,     InvalidURL,     ProxyError,\n    ReadTimeout,     RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,     get_encoding_from_headers,\n    prepend_scheme_if_needed,     select_proxy,     urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n    def __init__(self) -> None:\n        super().__init__()\n\n    def send(         self,         request: PreparedRequest,         stream: bool = False,\n        timeout: _t.TimeoutType = None,         verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        raise NotImplementedError\n\n    def close(self) -> None:\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        raise NotImplementedError\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-c63e591dfb8a9356", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "25f687d86ef83735a9d44b572f68f5e391c5fc837b3123d041a99335cb1ce879", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 69, "local_path": "layout/partially-compact-layout/I10__requests__BaseAdapter__5dfdcf94.py", "order": 10, "original_content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "parent_variant_id": "pyint-939f88f49b68-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L122-L155", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 40, "line_break_groups_removed": 16, "line_breaks_removed": 16, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "BaseAdapter", "variant_id": "pyint-645b5dfdcf94-I10", "group_id": "py-c63e591dfb8a9356", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 935, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-22237fa598b7-I11", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        raise NotImplementedError\n\n    def close(self) -> None:\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        raise NotImplementedError\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-c63e591dfb8a9356", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 85, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__BaseAdapter__7fa598b7.py", "order": 11, "original_content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "parent_variant_id": "pyint-939f88f49b68-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L122-L155", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "BaseAdapter", "variant_id": "pyint-22237fa598b7-I11", "group_id": "py-c63e591dfb8a9356", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 936, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8dcd4c6602fe-I12", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        raise NotImplementedError\n\n    def close(self) -> None:\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        raise NotImplementedError\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-c63e591dfb8a9356", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 85, "local_path": "data-flow/inline-intermediate-variables/I12__requests__BaseAdapter__4c6602fe.py", "order": 12, "original_content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "parent_variant_id": "pyint-939f88f49b68-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L122-L155", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "BaseAdapter", "variant_id": "pyint-8dcd4c6602fe-I12", "group_id": "py-c63e591dfb8a9356", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 937, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f3a00a483519-I13", "source": "from __future__ import annotations\nimport os.path\nimport socket  # noqa: F401\nimport typing\nimport warnings\nfrom typing import Any\nfrom urllib3.exceptions import (\n    ClosedPoolError,\n    ConnectTimeoutError,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom urllib3.exceptions import HTTPError as _HTTPError\nfrom urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom urllib3.exceptions import ProxyError as _ProxyError\nfrom urllib3.exceptions import SSLError as _SSLError\nfrom urllib3.poolmanager import PoolManager, proxy_from_url\nfrom urllib3.util import Timeout as TimeoutSauce\nfrom urllib3.util import parse_url\nfrom urllib3.util.retry import Retry\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\nfrom ._types import is_prepared as _is_prepared\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: _t.TimeoutType = None,\n        verify: _t.VerifyType = True,\n        cert: _t.CertType = None,\n        proxies: dict[str, str] | None = None,\n    ) -> Response:\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        raise NotImplementedError\n\n    def close(self) -> None:\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        raise NotImplementedError\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-c63e591dfb8a9356", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 85, "local_path": "control-flow/lower-for-to-while/I13__requests__BaseAdapter__0a483519.py", "order": 13, "original_content_sha256": "d8b485558fced5600a957f69fbaf66ada1c5e9177d13b8c98c85e19258938778", "parent_variant_id": "pyint-939f88f49b68-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/adapters.py#L122-L155", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "BaseAdapter", "variant_id": "pyint-f3a00a483519-I13", "group_id": "py-c63e591dfb8a9356", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 938, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1068ff3e3ef5-SRC", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        CompatJSONDecodeError.__init__(self, *args)\n        InvalidJSONError.__init__(self, *self.args, **kwargs)\n\n    def __reduce__(self) -> tuple[Any, ...] | str:\n        \"\"\"\n        The __reduce__ method called when pickling the object must\n        be the one from the JSONDecodeError (be it json/simplejson)\n        as it expects all the arguments for instantiation, not just\n        one like the IOError, and the MRO would by default call the\n        __reduce__ method from the IOError due to the inheritance order.\n        \"\"\"\n        return CompatJSONDecodeError.__reduce__(self)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-ca4cfcb3db717ff7", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 27, "local_path": "source-original/SRC__requests__JSONDecodeError__ff3e3ef5.py", "order": 0, "original_content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L42-L63", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "JSONDecodeError", "variant_id": "pyint-1068ff3e3ef5-SRC", "group_id": "py-ca4cfcb3db717ff7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 827, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cc99054c29af-I01", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \n        CompatJSONDecodeError.__init__(self, *args)\n        InvalidJSONError.__init__(self, *self.args, **kwargs)\n\n    def __reduce__(self) -> tuple[Any, ...] | str:\n        \n        return CompatJSONDecodeError.__reduce__(self)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-ca4cfcb3db717ff7", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "0f84088dd695aaecb9dcdf92e060fd1a94921d99fbbc475437c2c52752540d33", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 16, "local_path": "comments/remove-comments/I01__requests__JSONDecodeError__054c29af.py", "order": 1, "original_content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "parent_variant_id": "pyint-1068ff3e3ef5-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L42-L63", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 675, "comments_removed": 3, "docstrings_removed": 3, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "JSONDecodeError", "variant_id": "pyint-cc99054c29af-I01", "group_id": "py-ca4cfcb3db717ff7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 828, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-94e4f84b54a4-I02", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *arg: Any, **kwa: Any) -> None:\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        CompatJSONDecodeError.__init__(self, *arg)\n        InvalidJSONError.__init__(self, *self.args, **kwa)\n\n    def __reduce__(self) -> tuple[Any, ...] | str:\n        \"\"\"\n        The __reduce__ method called when pickling the object must\n        be the one from the JSONDecodeError (be it json/simplejson)\n        as it expects all the arguments for instantiation, not just\n        one like the IOError, and the MRO would by default call the\n        __reduce__ method from the IOError due to the inheritance order.\n        \"\"\"\n        return CompatJSONDecodeError.__reduce__(self)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-ca4cfcb3db717ff7", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "189eda3ebe9ca15460c32fdefda4d03d3133ad70d643bc5ccc55555fcfeaf968", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 27, "local_path": "identifiers/shorten-identifiers/I02__requests__JSONDecodeError__f84b54a4.py", "order": 2, "original_content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "parent_variant_id": "pyint-1068ff3e3ef5-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L42-L63", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 4, "identifiers_declared": 2}, "unit_kind": "class", "unit_name": "JSONDecodeError", "variant_id": "pyint-94e4f84b54a4-I02", "group_id": "py-ca4cfcb3db717ff7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 829, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dad8049c64d1-I03", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *step: Any, **amount: Any) -> None:\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        CompatJSONDecodeError.__init__(self, *step)\n        InvalidJSONError.__init__(self, *self.args, **amount)\n\n    def __reduce__(self) -> tuple[Any, ...] | str:\n        \"\"\"\n        The __reduce__ method called when pickling the object must\n        be the one from the JSONDecodeError (be it json/simplejson)\n        as it expects all the arguments for instantiation, not just\n        one like the IOError, and the MRO would by default call the\n        __reduce__ method from the IOError due to the inheritance order.\n        \"\"\"\n        return CompatJSONDecodeError.__reduce__(self)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-ca4cfcb3db717ff7", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "1dd2a2ecee0076fe18ead7992db0640302455ab7f12b6852108b7f4e917fbaae", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 27, "local_path": "identifiers/mislead-identifiers/I03__requests__JSONDecodeError__049c64d1.py", "order": 3, "original_content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "parent_variant_id": "pyint-1068ff3e3ef5-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L42-L63", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 4, "identifiers_declared": 2, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 2, "local_random_pool_selections": 2, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "JSONDecodeError", "variant_id": "pyint-dad8049c64d1-I03", "group_id": "py-ca4cfcb3db717ff7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 830, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-51cf84a2d865-I04", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *a: Any, **b: Any) -> None:\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        CompatJSONDecodeError.__init__(self, *a)\n        InvalidJSONError.__init__(self, *self.args, **b)\n\n    def __reduce__(self) -> tuple[Any, ...] | str:\n        \"\"\"\n        The __reduce__ method called when pickling the object must\n        be the one from the JSONDecodeError (be it json/simplejson)\n        as it expects all the arguments for instantiation, not just\n        one like the IOError, and the MRO would by default call the\n        __reduce__ method from the IOError due to the inheritance order.\n        \"\"\"\n        return CompatJSONDecodeError.__reduce__(self)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-ca4cfcb3db717ff7", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "87b9194d378939c455cd34a866d5173647ca1e8a0c243f4ffc4ca1c4a8a78faf", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 27, "local_path": "identifiers/garble-identifiers/I04__requests__JSONDecodeError__84a2d865.py", "order": 4, "original_content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "parent_variant_id": "pyint-1068ff3e3ef5-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L42-L63", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 4, "identifiers_declared": 2}, "unit_kind": "class", "unit_name": "JSONDecodeError", "variant_id": "pyint-51cf84a2d865-I04", "group_id": "py-ca4cfcb3db717ff7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 831, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1e7073676e63-I05", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        CompatJSONDecodeError.__init__(self, *args)\n        InvalidJSONError.__init__(self, *self.args, **kwargs)\n\n    def __reduce__(self) -> tuple[Any, ...] | str:\n        \"\"\"\n        The __reduce__ method called when pickling the object must\n        be the one from the JSONDecodeError (be it json/simplejson)\n        as it expects all the arguments for instantiation, not just\n        one like the IOError, and the MRO would by default call the\n        __reduce__ method from the IOError due to the inheritance order.\n        \"\"\"\n        return CompatJSONDecodeError.__reduce__(self)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-ca4cfcb3db717ff7", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 27, "local_path": "expressions/encode-integer-literals/I05__requests__JSONDecodeError__73676e63.py", "order": 5, "original_content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "parent_variant_id": "pyint-1068ff3e3ef5-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L42-L63", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "JSONDecodeError", "variant_id": "pyint-1e7073676e63-I05", "group_id": "py-ca4cfcb3db717ff7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 832, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e790d9fefd8c-I06", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        CompatJSONDecodeError.__init__(self, *args)\n        InvalidJSONError.__init__(self, *self.args, **kwargs)\n\n    def __reduce__(self) -> tuple[Any, ...] | str:\n        \"\"\"\n        The __reduce__ method called when pickling the object must\n        be the one from the JSONDecodeError (be it json/simplejson)\n        as it expects all the arguments for instantiation, not just\n        one like the IOError, and the MRO would by default call the\n        __reduce__ method from the IOError due to the inheritance order.\n        \"\"\"\n        return CompatJSONDecodeError.__reduce__(self)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-ca4cfcb3db717ff7", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 27, "local_path": "expressions/invert-conditions/I06__requests__JSONDecodeError__d9fefd8c.py", "order": 6, "original_content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "parent_variant_id": "pyint-1068ff3e3ef5-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L42-L63", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "JSONDecodeError", "variant_id": "pyint-e790d9fefd8c-I06", "group_id": "py-ca4cfcb3db717ff7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 833, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5cc4f5d41576-I07", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        if ((0x4f1 ^ 0x4f1) != 0):\n            raise AssertionError()\n        CompatJSONDecodeError.__init__(self, *args)\n        InvalidJSONError.__init__(self, *self.args, **kwargs)\n\n    def __reduce__(self) -> tuple[Any, ...] | str:\n        \"\"\"\n        The __reduce__ method called when pickling the object must\n        be the one from the JSONDecodeError (be it json/simplejson)\n        as it expects all the arguments for instantiation, not just\n        one like the IOError, and the MRO would by default call the\n        __reduce__ method from the IOError due to the inheritance order.\n        \"\"\"\n        if ((0x2a78 ^ 0x2a78) != 0):\n            raise AssertionError()\n        return CompatJSONDecodeError.__reduce__(self)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-ca4cfcb3db717ff7", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "5d68ec51bf4896d8e0c7ad88b65e5ecc04b39d094995ec9eaca908ccd1a21772", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 31, "local_path": "code-injection/insert-dead-branches/I07__requests__JSONDecodeError__f5d41576.py", "order": 7, "original_content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "parent_variant_id": "pyint-1068ff3e3ef5-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L42-L63", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "JSONDecodeError", "variant_id": "pyint-5cc4f5d41576-I07", "group_id": "py-ca4cfcb3db717ff7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 834, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-403d4e0be826-I08", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        CompatJSONDecodeError.__init__(self, *args)\n        InvalidJSONError.__init__(self, *self.args, **kwargs)\n\n    def __reduce__(self) -> tuple[Any, ...] | str:\n        \"\"\"\n        The __reduce__ method called when pickling the object must\n        be the one from the JSONDecodeError (be it json/simplejson)\n        as it expects all the arguments for instantiation, not just\n        one like the IOError, and the MRO would by default call the\n        __reduce__ method from the IOError due to the inheritance order.\n        \"\"\"\n        return CompatJSONDecodeError.__reduce__(self)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-ca4cfcb3db717ff7", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "ef48c16d17a63656030386e6b92dc69780a960d2771100d63a3540be3a3d08ec", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 32, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__JSONDecodeError__4e0be826.py", "order": 8, "original_content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "parent_variant_id": "pyint-1068ff3e3ef5-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L42-L63", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "JSONDecodeError", "variant_id": "pyint-403d4e0be826-I08", "group_id": "py-ca4cfcb3db717ff7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 835, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-00337c3dcbfd-I09", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        lI0O_919d6db4 = 0xe8ae ^ 0xe8ae\n        if lI0O_919d6db4 != 0:\n            if ((lI0O_919d6db4 | 1) & 1) == 0:\n                lI0O_919d6db4 += 1\n            else:\n                lI0O_919d6db4 -= 1\n        CompatJSONDecodeError.__init__(self, *args)\n        InvalidJSONError.__init__(self, *self.args, **kwargs)\n\n    def __reduce__(self) -> tuple[Any, ...] | str:\n        \"\"\"\n        The __reduce__ method called when pickling the object must\n        be the one from the JSONDecodeError (be it json/simplejson)\n        as it expects all the arguments for instantiation, not just\n        one like the IOError, and the MRO would by default call the\n        __reduce__ method from the IOError due to the inheritance order.\n        \"\"\"\n        return CompatJSONDecodeError.__reduce__(self)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-ca4cfcb3db717ff7", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "20607f42899cbdc63af4e9b310f8f1bd70aef32db5ee1e972a2e3971992f3205", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 33, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__JSONDecodeError__7c3dcbfd.py", "order": 9, "original_content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "parent_variant_id": "pyint-1068ff3e3ef5-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L42-L63", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 5}, "unit_kind": "class", "unit_name": "JSONDecodeError", "variant_id": "pyint-00337c3dcbfd-I09", "group_id": "py-ca4cfcb3db717ff7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 836, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ed41d9585699-I10", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        CompatJSONDecodeError.__init__(self, *args)\n        InvalidJSONError.__init__(self, *self.args, **kwargs)\n\n    def __reduce__(self) -> tuple[Any, ...] | str:\n        \"\"\"\n        The __reduce__ method called when pickling the object must\n        be the one from the JSONDecodeError (be it json/simplejson)\n        as it expects all the arguments for instantiation, not just\n        one like the IOError, and the MRO would by default call the\n        __reduce__ method from the IOError due to the inheritance order.\n        \"\"\"\n        return CompatJSONDecodeError.__reduce__(self)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-ca4cfcb3db717ff7", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "83accb14614911b522f357ad7609a267e31d3b7012e7ba67f19694301c29e974", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 26, "local_path": "layout/partially-compact-layout/I10__requests__JSONDecodeError__d9585699.py", "order": 10, "original_content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "parent_variant_id": "pyint-1068ff3e3ef5-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L42-L63", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 3, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "JSONDecodeError", "variant_id": "pyint-ed41d9585699-I10", "group_id": "py-ca4cfcb3db717ff7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 837, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-706eab1780b0-I11", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        CompatJSONDecodeError.__init__(self, *args)\n        InvalidJSONError.__init__(self, *self.args, **kwargs)\n\n    def __reduce__(self) -> tuple[Any, ...] | str:\n        \"\"\"\n        The __reduce__ method called when pickling the object must\n        be the one from the JSONDecodeError (be it json/simplejson)\n        as it expects all the arguments for instantiation, not just\n        one like the IOError, and the MRO would by default call the\n        __reduce__ method from the IOError due to the inheritance order.\n        \"\"\"\n        return CompatJSONDecodeError.__reduce__(self)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-ca4cfcb3db717ff7", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 27, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__JSONDecodeError__ab1780b0.py", "order": 11, "original_content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "parent_variant_id": "pyint-1068ff3e3ef5-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L42-L63", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "JSONDecodeError", "variant_id": "pyint-706eab1780b0-I11", "group_id": "py-ca4cfcb3db717ff7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 838, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ac46bb26f46b-I12", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        CompatJSONDecodeError.__init__(self, *args)\n        InvalidJSONError.__init__(self, *self.args, **kwargs)\n\n    def __reduce__(self) -> tuple[Any, ...] | str:\n        \"\"\"\n        The __reduce__ method called when pickling the object must\n        be the one from the JSONDecodeError (be it json/simplejson)\n        as it expects all the arguments for instantiation, not just\n        one like the IOError, and the MRO would by default call the\n        __reduce__ method from the IOError due to the inheritance order.\n        \"\"\"\n        return CompatJSONDecodeError.__reduce__(self)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-ca4cfcb3db717ff7", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 27, "local_path": "data-flow/inline-intermediate-variables/I12__requests__JSONDecodeError__bb26f46b.py", "order": 12, "original_content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "parent_variant_id": "pyint-1068ff3e3ef5-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L42-L63", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "JSONDecodeError", "variant_id": "pyint-ac46bb26f46b-I12", "group_id": "py-ca4cfcb3db717ff7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 839, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f7df5b81b056-I13", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        CompatJSONDecodeError.__init__(self, *args)\n        InvalidJSONError.__init__(self, *self.args, **kwargs)\n\n    def __reduce__(self) -> tuple[Any, ...] | str:\n        \"\"\"\n        The __reduce__ method called when pickling the object must\n        be the one from the JSONDecodeError (be it json/simplejson)\n        as it expects all the arguments for instantiation, not just\n        one like the IOError, and the MRO would by default call the\n        __reduce__ method from the IOError due to the inheritance order.\n        \"\"\"\n        return CompatJSONDecodeError.__reduce__(self)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-ca4cfcb3db717ff7", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 27, "local_path": "control-flow/lower-for-to-while/I13__requests__JSONDecodeError__5b81b056.py", "order": 13, "original_content_sha256": "a7cc0096a2e5b36e972cdaaae18398e91b7da073fae84dc3077b096c78150829", "parent_variant_id": "pyint-1068ff3e3ef5-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L42-L63", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "JSONDecodeError", "variant_id": "pyint-f7df5b81b056-I13", "group_id": "py-ca4cfcb3db717ff7", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 840, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5a558e70f330-SRC", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-cf673b9f89b7a95e", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 43, "local_path": "source-original/SRC__requests__HTTPBasicAuth__8e70f330.py", "order": 0, "original_content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L85-L113", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "HTTPBasicAuth", "variant_id": "pyint-5a558e70f330-SRC", "group_id": "py-cf673b9f89b7a95e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 939, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a6b98ad9a0a6-I01", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPBasicAuth(AuthBase):\n    \n\n    username: bytes | str\n    password: bytes | str\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-cf673b9f89b7a95e", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "b8f58afb17a68019f7d1c594f766064399762b72816238b2af1fb0cbf60ed59f", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 43, "local_path": "comments/remove-comments/I01__requests__HTTPBasicAuth__8ad9a0a6.py", "order": 1, "original_content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "parent_variant_id": "pyint-5a558e70f330-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L85-L113", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 69, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "HTTPBasicAuth", "variant_id": "pyint-a6b98ad9a0a6-I01", "group_id": "py-cf673b9f89b7a95e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 940, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f5d853759509-I02", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n\n    @overload\n    def __init__(self, use: str, pas: str) -> None: ...\n    @overload\n    def __init__(self, use2: bytes, pas2: bytes) -> None: ...\n\n    def __init__(self, use3: bytes | str, pas3: bytes | str) -> None:\n        self.username = use3\n        self.password = pas3\n\n    def __eq__(self, oth: object) -> bool:\n        return all(\n            [\n                self.username == getattr(oth, \"username\", None),\n                self.password == getattr(oth, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, oth2: Any) -> bool:\n        return not self == oth2\n\n    def __call__(self, r2: PreparedRequest) -> PreparedRequest:\n        r2.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r2\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-cf673b9f89b7a95e", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "9cbddd309a3853d028b1b5a18538dd74888fc24850057e62038cc8de63394ee7", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 43, "local_path": "identifiers/shorten-identifiers/I02__requests__HTTPBasicAuth__53759509.py", "order": 2, "original_content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "parent_variant_id": "pyint-5a558e70f330-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L85-L113", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 16, "identifiers_declared": 9}, "unit_kind": "class", "unit_name": "HTTPBasicAuth", "variant_id": "pyint-f5d853759509-I02", "group_id": "py-cf673b9f89b7a95e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 941, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-957ee07bd07b-I03", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n\n    @overload\n    def __init__(self, nextNode: str, nextData: str) -> None: ...\n    @overload\n    def __init__(self, nextPath: bytes, location: bytes) -> None: ...\n\n    def __init__(self, localKey: bytes | str, finalKey: bytes | str) -> None:\n        self.username = localKey\n        self.password = finalKey\n\n    def __eq__(self, value: object) -> bool:\n        return all(\n            [\n                self.username == getattr(value, \"username\", None),\n                self.password == getattr(value, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, score: Any) -> bool:\n        return not self == score\n\n    def __call__(self, age: PreparedRequest) -> PreparedRequest:\n        age.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return age\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-cf673b9f89b7a95e", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "a30a70cd91459ec100cbe178a4a29a3717c284adab444ef2c6b71039747279b8", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 43, "local_path": "identifiers/mislead-identifiers/I03__requests__HTTPBasicAuth__e07bd07b.py", "order": 3, "original_content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "parent_variant_id": "pyint-5a558e70f330-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L85-L113", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 16, "identifiers_declared": 9, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 8, "local_random_pool_selections": 9, "local_total_length_difference": 2, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "HTTPBasicAuth", "variant_id": "pyint-957ee07bd07b-I03", "group_id": "py-cf673b9f89b7a95e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 942, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d702ad3bb762-I04", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n\n    @overload\n    def __init__(self, a: str, b: str) -> None: ...\n    @overload\n    def __init__(self, c: bytes, d: bytes) -> None: ...\n\n    def __init__(self, e: bytes | str, f: bytes | str) -> None:\n        self.username = e\n        self.password = f\n\n    def __eq__(self, g: object) -> bool:\n        return all(\n            [\n                self.username == getattr(g, \"username\", None),\n                self.password == getattr(g, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, h: Any) -> bool:\n        return not self == h\n\n    def __call__(self, i: PreparedRequest) -> PreparedRequest:\n        i.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return i\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-cf673b9f89b7a95e", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "105bed23a3667d3003325855b6ab60dfb8bde984490b3fb17ba9c619e7df35fd", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 43, "local_path": "identifiers/garble-identifiers/I04__requests__HTTPBasicAuth__ad3bb762.py", "order": 4, "original_content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "parent_variant_id": "pyint-5a558e70f330-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L85-L113", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 16, "identifiers_declared": 9}, "unit_kind": "class", "unit_name": "HTTPBasicAuth", "variant_id": "pyint-d702ad3bb762-I04", "group_id": "py-cf673b9f89b7a95e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 943, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-57dc65f71d9b-I05", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-cf673b9f89b7a95e", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 43, "local_path": "expressions/encode-integer-literals/I05__requests__HTTPBasicAuth__65f71d9b.py", "order": 5, "original_content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "parent_variant_id": "pyint-5a558e70f330-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L85-L113", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "HTTPBasicAuth", "variant_id": "pyint-57dc65f71d9b-I05", "group_id": "py-cf673b9f89b7a95e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 944, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4cd49b4d7f02-I06", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-cf673b9f89b7a95e", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 43, "local_path": "expressions/invert-conditions/I06__requests__HTTPBasicAuth__9b4d7f02.py", "order": 6, "original_content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "parent_variant_id": "pyint-5a558e70f330-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L85-L113", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "HTTPBasicAuth", "variant_id": "pyint-4cd49b4d7f02-I06", "group_id": "py-cf673b9f89b7a95e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 945, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-67828e5ce3e6-I07", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        if ((0xd78a ^ 0xd78a) != 0):\n            raise AssertionError()\n        self.username = username\n        self.password = password\n\n    def __eq__(self, other: object) -> bool:\n        if ((0x12e6 ^ 0x12e6) != 0):\n            raise AssertionError()\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        if ((0x6e7a ^ 0x6e7a) != 0):\n            raise AssertionError()\n        return not self == other\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        if ((0x46cf ^ 0x46cf) != 0):\n            raise AssertionError()\n        r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-cf673b9f89b7a95e", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "6404f56046a7504b3d92aa913f8a267a6d9d0cddabb0b1048305c50d46f94cda", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 51, "local_path": "code-injection/insert-dead-branches/I07__requests__HTTPBasicAuth__8e5ce3e6.py", "order": 7, "original_content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "parent_variant_id": "pyint-5a558e70f330-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L85-L113", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 4}, "unit_kind": "class", "unit_name": "HTTPBasicAuth", "variant_id": "pyint-67828e5ce3e6-I07", "group_id": "py-cf673b9f89b7a95e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 946, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-11d20ea1dd23-I08", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n\n    def __eq__(self, other: object) -> bool:\n        even_number_count = 0\n        for candidate_number in range(6):\n            if candidate_number % 2 == 0:\n                even_number_count += 1\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-cf673b9f89b7a95e", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "70a0f9b7b7161a3cf3e5620f2624725801bd34c1495e848853359bafa4d7dc9f", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 47, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__HTTPBasicAuth__0ea1dd23.py", "order": 8, "original_content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "parent_variant_id": "pyint-5a558e70f330-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L85-L113", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 4, "readable_template_index": 2}, "unit_kind": "class", "unit_name": "HTTPBasicAuth", "variant_id": "pyint-11d20ea1dd23-I08", "group_id": "py-cf673b9f89b7a95e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 947, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0b66faa37b05-I09", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        lI0O_4110c615, lI0O_7d784c5a = 0xbccf, ~0xbccf\n        lI0O_4110c615 = (lI0O_4110c615 & lI0O_7d784c5a) | (lI0O_4110c615 ^ lI0O_4110c615)\n        lI0O_7d784c5a ^= lI0O_7d784c5a\n        return not self == other\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-cf673b9f89b7a95e", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "4438a5c2c64559760aac0f3125783f8caa08910d30066ad1746804e0707d09b0", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 46, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__HTTPBasicAuth__faa37b05.py", "order": 9, "original_content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "parent_variant_id": "pyint-5a558e70f330-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L85-L113", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 9}, "unit_kind": "class", "unit_name": "HTTPBasicAuth", "variant_id": "pyint-0b66faa37b05-I09", "group_id": "py-cf673b9f89b7a95e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 948, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d0ea7d89a5bc-I10", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n    def __eq__(self, other: object) -> bool:\n        return all(             [\n                self.username == getattr(other, \"username\", None),                 self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-cf673b9f89b7a95e", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "0645e0bc3bbfff5f897e492e61d80a62aaea0c2e43edd3d76cb1d97ef428f55e", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 39, "local_path": "layout/partially-compact-layout/I10__requests__HTTPBasicAuth__7d89a5bc.py", "order": 10, "original_content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "parent_variant_id": "pyint-5a558e70f330-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L85-L113", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 12, "line_break_groups_removed": 4, "line_breaks_removed": 4, "whitespace_characters_removed": 2}, "unit_kind": "class", "unit_name": "HTTPBasicAuth", "variant_id": "pyint-d0ea7d89a5bc-I10", "group_id": "py-cf673b9f89b7a95e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 949, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-04608ec99dda-I11", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-cf673b9f89b7a95e", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 43, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__HTTPBasicAuth__8ec99dda.py", "order": 11, "original_content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "parent_variant_id": "pyint-5a558e70f330-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L85-L113", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "HTTPBasicAuth", "variant_id": "pyint-04608ec99dda-I11", "group_id": "py-cf673b9f89b7a95e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 950, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-df5bfbb14f73-I12", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-cf673b9f89b7a95e", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 43, "local_path": "data-flow/inline-intermediate-variables/I12__requests__HTTPBasicAuth__fbb14f73.py", "order": 12, "original_content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "parent_variant_id": "pyint-5a558e70f330-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L85-L113", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "HTTPBasicAuth", "variant_id": "pyint-df5bfbb14f73-I12", "group_id": "py-cf673b9f89b7a95e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 951, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dcc9ec17347b-I13", "source": "from __future__ import annotations\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\nfrom typing import TYPE_CHECKING, Any, Final, cast, overload\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    username: bytes | str\n    password: bytes | str\n\n    @overload\n    def __init__(self, username: str, password: str) -> None: ...\n    @overload\n    def __init__(self, username: bytes, password: bytes) -> None: ...\n\n    def __init__(self, username: bytes | str, password: bytes | str) -> None:\n        self.username = username\n        self.password = password\n\n    def __eq__(self, other: object) -> bool:\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other: Any) -> bool:\n        return not self == other\n\n    def __call__(self, r: PreparedRequest) -> PreparedRequest:\n        r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-cf673b9f89b7a95e", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 43, "local_path": "control-flow/lower-for-to-while/I13__requests__HTTPBasicAuth__ec17347b.py", "order": 13, "original_content_sha256": "5b3282ea71cdf7a57c0ff0f829fd09cfdb023866d349d72bb0a9c8174a721c80", "parent_variant_id": "pyint-5a558e70f330-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/auth.py#L85-L113", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "HTTPBasicAuth", "variant_id": "pyint-dcc9ec17347b-I13", "group_id": "py-cf673b9f89b7a95e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 952, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-616ceda7294f-SRC", "source": "import copy\nimport json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\nfrom django.db.models import CASCADE, UUIDField\nfrom django.forms.widgets import Select\nfrom django.urls import reverse\nfrom django.urls.exceptions import NoReverseMatch\nfrom django.utils.html import smart_urlquote\nfrom django.utils.http import urlencode\nfrom django.utils.text import Truncator\nfrom django.utils.translation import get_language\nfrom django.utils.translation import gettext as _\n\nclass RelatedFieldWidgetWrapper(forms.Widget):\n    \"\"\"\n    This class is a wrapper to a given widget to add the add icon for the\n    admin interface.\n    \"\"\"\n\n    template_name = \"admin/widgets/related_widget_wrapper.html\"\n\n    def __init__(\n        self,\n        widget,\n        rel,\n        admin_site,\n        can_add_related=None,\n        can_change_related=False,\n        can_delete_related=False,\n        can_view_related=False,\n    ):\n        self.needs_multipart_form = widget.needs_multipart_form\n        self.attrs = widget.attrs\n        self.widget = widget\n        self.rel = rel\n        # Backwards compatible check for whether a user can add related\n        # objects.\n        if can_add_related is None:\n            can_add_related = admin_site.is_registered(rel.model)\n        self.can_add_related = can_add_related\n        if not isinstance(widget, AutocompleteMixin):\n            self.attrs[\"data-context\"] = \"available-source\"\n        # Only single-select Select widgets are supported.\n        supported = not getattr(\n            widget, \"allow_multiple_selected\", False\n        ) and isinstance(widget, Select)\n        self.can_change_related = supported and can_change_related\n        # XXX: The deletion UX can be confusing when dealing with cascading\n        # deletion.\n        cascade = getattr(rel, \"on_delete\", None) is CASCADE\n        self.can_delete_related = supported and not cascade and can_delete_related\n        self.can_view_related = supported and can_view_related\n        # To check if the related object is registered with this AdminSite.\n        self.admin_site = admin_site\n        self.use_fieldset = widget.use_fieldset\n\n    def __deepcopy__(self, memo):\n        obj = copy.copy(self)\n        obj.widget = copy.deepcopy(self.widget, memo)\n        obj.attrs = self.widget.attrs\n        memo[id(self)] = obj\n        return obj\n\n    @property\n    def is_hidden(self):\n        return self.widget.is_hidden\n\n    @property\n    def media(self):\n        return self.widget.media\n\n    @property\n    def choices(self):\n        return self.widget.choices\n\n    @choices.setter\n    def choices(self, value):\n        self.widget.choices = value\n\n    def get_related_url(self, info, action, *args):\n        return reverse(\n            \"admin:%s_%s_%s\" % (*info, action),\n            current_app=self.admin_site.name,\n            args=args,\n        )\n\n    def get_context(self, name, value, attrs):\n        from django.contrib.admin.views.main import (\n            IS_POPUP_VAR,\n            SOURCE_MODEL_VAR,\n            TO_FIELD_VAR,\n        )\n\n        rel_opts = self.rel.model._meta\n        info = (rel_opts.app_label, rel_opts.model_name)\n        related_field_name = self.rel.get_related_field().name\n        app_label = self.rel.field.model._meta.app_label\n        model_name = self.rel.field.model._meta.model_name\n\n        url_params = \"&\".join(\n            \"%s=%s\" % param\n            for param in [\n                (TO_FIELD_VAR, related_field_name),\n                (IS_POPUP_VAR, 1),\n                (SOURCE_MODEL_VAR, f\"{app_label}.{model_name}\"),\n            ]\n        )\n        context = {\n            \"rendered_widget\": self.widget.render(name, value, attrs),\n            \"is_hidden\": self.is_hidden,\n            \"name\": name,\n            \"url_params\": url_params,\n            \"model\": rel_opts.verbose_name,\n            \"model_name\": rel_opts.model_name,\n            \"can_add_related\": self.can_add_related,\n            \"can_change_related\": self.can_change_related,\n            \"can_delete_related\": self.can_delete_related,\n            \"can_view_related\": self.can_view_related,\n            \"model_has_limit_choices_to\": self.rel.limit_choices_to,\n        }\n        if self.can_add_related:\n            context[\"add_related_url\"] = self.get_related_url(info, \"add\")\n        if self.can_delete_related:\n            context[\"delete_related_template_url\"] = self.get_related_url(\n                info, \"delete\", \"__fk__\"\n            )\n        if self.can_view_related or self.can_change_related:\n            context[\"view_related_url_params\"] = f\"{TO_FIELD_VAR}={related_field_name}\"\n            context[\"change_related_template_url\"] = self.get_related_url(\n                info, \"change\", \"__fk__\"\n            )\n        return context\n\n    def value_from_datadict(self, data, files, name):\n        return self.widget.value_from_datadict(data, files, name)\n\n    def value_omitted_from_data(self, data, files, name):\n        return self.widget.value_omitted_from_data(data, files, name)\n\n    def id_for_label(self, id_):\n        return self.widget.id_for_label(id_)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-d2f83e95b1ce0221", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 144, "local_path": "source-original/SRC__django__RelatedFieldWidgetWrapper__eda7294f.py", "order": 0, "original_content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/admin/widgets.py#L264-L391", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "RelatedFieldWidgetWrapper", "variant_id": "pyint-616ceda7294f-SRC", "group_id": "py-d2f83e95b1ce0221", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 99, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d0b4cf6406f0-I01", "source": "import copy\nimport json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\nfrom django.db.models import CASCADE, UUIDField\nfrom django.forms.widgets import Select\nfrom django.urls import reverse\nfrom django.urls.exceptions import NoReverseMatch\nfrom django.utils.html import smart_urlquote\nfrom django.utils.http import urlencode\nfrom django.utils.text import Truncator\nfrom django.utils.translation import get_language\nfrom django.utils.translation import gettext as _\n\nclass RelatedFieldWidgetWrapper(forms.Widget):\n    \n\n    template_name = \"admin/widgets/related_widget_wrapper.html\"\n\n    def __init__(\n        self,\n        widget,\n        rel,\n        admin_site,\n        can_add_related=None,\n        can_change_related=False,\n        can_delete_related=False,\n        can_view_related=False,\n    ):\n        self.needs_multipart_form = widget.needs_multipart_form\n        self.attrs = widget.attrs\n        self.widget = widget\n        self.rel = rel\n         \n         \n        if can_add_related is None:\n            can_add_related = admin_site.is_registered(rel.model)\n        self.can_add_related = can_add_related\n        if not isinstance(widget, AutocompleteMixin):\n            self.attrs[\"data-context\"] = \"available-source\"\n         \n        supported = not getattr(\n            widget, \"allow_multiple_selected\", False\n        ) and isinstance(widget, Select)\n        self.can_change_related = supported and can_change_related\n         \n         \n        cascade = getattr(rel, \"on_delete\", None) is CASCADE\n        self.can_delete_related = supported and not cascade and can_delete_related\n        self.can_view_related = supported and can_view_related\n         \n        self.admin_site = admin_site\n        self.use_fieldset = widget.use_fieldset\n\n    def __deepcopy__(self, memo):\n        obj = copy.copy(self)\n        obj.widget = copy.deepcopy(self.widget, memo)\n        obj.attrs = self.widget.attrs\n        memo[id(self)] = obj\n        return obj\n\n    @property\n    def is_hidden(self):\n        return self.widget.is_hidden\n\n    @property\n    def media(self):\n        return self.widget.media\n\n    @property\n    def choices(self):\n        return self.widget.choices\n\n    @choices.setter\n    def choices(self, value):\n        self.widget.choices = value\n\n    def get_related_url(self, info, action, *args):\n        return reverse(\n            \"admin:%s_%s_%s\" % (*info, action),\n            current_app=self.admin_site.name,\n            args=args,\n        )\n\n    def get_context(self, name, value, attrs):\n        from django.contrib.admin.views.main import (\n            IS_POPUP_VAR,\n            SOURCE_MODEL_VAR,\n            TO_FIELD_VAR,\n        )\n\n        rel_opts = self.rel.model._meta\n        info = (rel_opts.app_label, rel_opts.model_name)\n        related_field_name = self.rel.get_related_field().name\n        app_label = self.rel.field.model._meta.app_label\n        model_name = self.rel.field.model._meta.model_name\n\n        url_params = \"&\".join(\n            \"%s=%s\" % param\n            for param in [\n                (TO_FIELD_VAR, related_field_name),\n                (IS_POPUP_VAR, 1),\n                (SOURCE_MODEL_VAR, f\"{app_label}.{model_name}\"),\n            ]\n        )\n        context = {\n            \"rendered_widget\": self.widget.render(name, value, attrs),\n            \"is_hidden\": self.is_hidden,\n            \"name\": name,\n            \"url_params\": url_params,\n            \"model\": rel_opts.verbose_name,\n            \"model_name\": rel_opts.model_name,\n            \"can_add_related\": self.can_add_related,\n            \"can_change_related\": self.can_change_related,\n            \"can_delete_related\": self.can_delete_related,\n            \"can_view_related\": self.can_view_related,\n            \"model_has_limit_choices_to\": self.rel.limit_choices_to,\n        }\n        if self.can_add_related:\n            context[\"add_related_url\"] = self.get_related_url(info, \"add\")\n        if self.can_delete_related:\n            context[\"delete_related_template_url\"] = self.get_related_url(\n                info, \"delete\", \"__fk__\"\n            )\n        if self.can_view_related or self.can_change_related:\n            context[\"view_related_url_params\"] = f\"{TO_FIELD_VAR}={related_field_name}\"\n            context[\"change_related_template_url\"] = self.get_related_url(\n                info, \"change\", \"__fk__\"\n            )\n        return context\n\n    def value_from_datadict(self, data, files, name):\n        return self.widget.value_from_datadict(data, files, name)\n\n    def value_omitted_from_data(self, data, files, name):\n        return self.widget.value_omitted_from_data(data, files, name)\n\n    def id_for_label(self, id_):\n        return self.widget.id_for_label(id_)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-d2f83e95b1ce0221", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "426fe14f2d5e93b8f836217109f0044aa1802ec5cf5b6767cb344e327c31503e", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 141, "local_path": "comments/remove-comments/I01__django__RelatedFieldWidgetWrapper__cf6406f0.py", "order": 1, "original_content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "parent_variant_id": "pyint-616ceda7294f-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/admin/widgets.py#L264-L391", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 368, "comments_removed": 7, "docstrings_removed": 1, "line_comments_removed": 6}, "unit_kind": "class", "unit_name": "RelatedFieldWidgetWrapper", "variant_id": "pyint-d0b4cf6406f0-I01", "group_id": "py-d2f83e95b1ce0221", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 100, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dae92ba1d776-I02", "source": "import copy\nimport json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\nfrom django.db.models import CASCADE, UUIDField\nfrom django.forms.widgets import Select\nfrom django.urls import reverse\nfrom django.urls.exceptions import NoReverseMatch\nfrom django.utils.html import smart_urlquote\nfrom django.utils.http import urlencode\nfrom django.utils.text import Truncator\nfrom django.utils.translation import get_language\nfrom django.utils.translation import gettext as _\n\nclass RelatedFieldWidgetWrapper(forms.Widget):\n    \"\"\"\n    This class is a wrapper to a given widget to add the add icon for the\n    admin interface.\n    \"\"\"\n\n    template_name = \"admin/widgets/related_widget_wrapper.html\"\n\n    def __init__(\n        self,\n        wid,\n        rel2,\n        admin,\n        can=None,\n        can2=False,\n        can3=False,\n        can4=False,\n    ):\n        self.needs_multipart_form = wid.needs_multipart_form\n        self.attrs = wid.attrs\n        self.widget = wid\n        self.rel = rel2\n        # Backwards compatible check for whether a user can add related\n        # objects.\n        if can is None:\n            can = admin.is_registered(rel2.model)\n        self.can_add_related = can\n        if not isinstance(wid, AutocompleteMixin):\n            self.attrs[\"data-context\"] = \"available-source\"\n        # Only single-select Select widgets are supported.\n        sup = not getattr(\n            wid, \"allow_multiple_selected\", False\n        ) and isinstance(wid, Select)\n        self.can_change_related = sup and can2\n        # XXX: The deletion UX can be confusing when dealing with cascading\n        # deletion.\n        cas = getattr(rel2, \"on_delete\", None) is CASCADE\n        self.can_delete_related = sup and not cas and can3\n        self.can_view_related = sup and can4\n        # To check if the related object is registered with this AdminSite.\n        self.admin_site = admin\n        self.use_fieldset = wid.use_fieldset\n\n    def __deepcopy__(self, mem):\n        obj2 = copy.copy(self)\n        obj2.widget = copy.deepcopy(self.widget, mem)\n        obj2.attrs = self.widget.attrs\n        mem[id(self)] = obj2\n        return obj2\n\n    @property\n    def is2(self):\n        return self.widget.is_hidden\n\n    @property\n    def med(self):\n        return self.widget.media\n\n    @property\n    def cho2(self):\n        return self.widget.choices\n\n    @choices.setter\n    def cho2(self, val):\n        self.widget.choices = val\n\n    def get(self, inf, act, *arg):\n        return reverse(\n            \"admin:%s_%s_%s\" % (*inf, act),\n            current_app=self.admin_site.name,\n            args=arg,\n        )\n\n    def get2(self, nam, val2, att):\n        from django.contrib.admin.views.main import (\n            IS_POPUP_VAR,\n            SOURCE_MODEL_VAR,\n            TO_FIELD_VAR,\n        )\n\n        rel3 = self.rel.model._meta\n        inf2 = (rel3.app_label, rel3.model_name)\n        related = self.rel.get_related_field().name\n        app = self.rel.field.model._meta.app_label\n        model2 = self.rel.field.model._meta.model_name\n\n        url = \"&\".join(\n            \"%s=%s\" % par\n            for par in [\n                (TO_FIELD_VAR, related),\n                (IS_POPUP_VAR, 1),\n                (SOURCE_MODEL_VAR, f\"{app}.{model2}\"),\n            ]\n        )\n        con = {\n            \"rendered_widget\": self.widget.render(nam, val2, att),\n            \"is_hidden\": self.is2,\n            \"name\": nam,\n            \"url_params\": url,\n            \"model\": rel3.verbose_name,\n            \"model_name\": rel3.model_name,\n            \"can_add_related\": self.can_add_related,\n            \"can_change_related\": self.can_change_related,\n            \"can_delete_related\": self.can_delete_related,\n            \"can_view_related\": self.can_view_related,\n            \"model_has_limit_choices_to\": self.rel.limit_choices_to,\n        }\n        if self.can_add_related:\n            con[\"add_related_url\"] = self.get(inf2, \"add\")\n        if self.can_delete_related:\n            con[\"delete_related_template_url\"] = self.get(\n                inf2, \"delete\", \"__fk__\"\n            )\n        if self.can_view_related or self.can_change_related:\n            con[\"view_related_url_params\"] = f\"{TO_FIELD_VAR}={related}\"\n            con[\"change_related_template_url\"] = self.get(\n                inf2, \"change\", \"__fk__\"\n            )\n        return con\n\n    def value2(self, dat, fil, nam2):\n        return self.widget.value_from_datadict(dat, fil, nam2)\n\n    def value3(self, dat2, fil2, nam3):\n        return self.widget.value_omitted_from_data(dat2, fil2, nam3)\n\n    def id2(self, id3):\n        return self.widget.id_for_label(id3)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-d2f83e95b1ce0221", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "2d9782487eb4cf00f0d8079198e849f834446a9d22e09936ef28ab85fa20ae9b", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 144, "local_path": "identifiers/shorten-identifiers/I02__django__RelatedFieldWidgetWrapper__2ba1d776.py", "order": 2, "original_content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "parent_variant_id": "pyint-616ceda7294f-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/admin/widgets.py#L264-L391", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 107, "identifiers_declared": 42}, "unit_kind": "class", "unit_name": "RelatedFieldWidgetWrapper", "variant_id": "pyint-dae92ba1d776-I02", "group_id": "py-d2f83e95b1ce0221", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 101, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6c805c328974-I03", "source": "import copy\nimport json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\nfrom django.db.models import CASCADE, UUIDField\nfrom django.forms.widgets import Select\nfrom django.urls import reverse\nfrom django.urls.exceptions import NoReverseMatch\nfrom django.utils.html import smart_urlquote\nfrom django.utils.http import urlencode\nfrom django.utils.text import Truncator\nfrom django.utils.translation import get_language\nfrom django.utils.translation import gettext as _\n\nclass RelatedFieldWidgetWrapper(forms.Widget):\n    \"\"\"\n    This class is a wrapper to a given widget to add the add icon for the\n    admin interface.\n    \"\"\"\n\n    template_name = \"admin/widgets/related_widget_wrapper.html\"\n\n    def __init__(\n        self,\n        record,\n        map,\n        cachedUser,\n        primaryAccount=None,\n        currentSession=False,\n        currentMessage=False,\n        currentRequest=False,\n    ):\n        self.needs_multipart_form = record.needs_multipart_form\n        self.attrs = record.attrs\n        self.widget = record\n        self.rel = map\n        # Backwards compatible check for whether a user can add related\n        # objects.\n        if primaryAccount is None:\n            primaryAccount = cachedUser.is_registered(map.model)\n        self.can_add_related = primaryAccount\n        if not isinstance(record, AutocompleteMixin):\n            self.attrs[\"data-context\"] = \"available-source\"\n        # Only single-select Select widgets are supported.\n        finalItem = not getattr(\n            record, \"allow_multiple_selected\", False\n        ) and isinstance(record, Select)\n        self.can_change_related = finalItem and currentSession\n        # XXX: The deletion UX can be confusing when dealing with cascading\n        # deletion.\n        context = getattr(map, \"on_delete\", None) is CASCADE\n        self.can_delete_related = finalItem and not context and currentMessage\n        self.can_view_related = finalItem and currentRequest\n        # To check if the related object is registered with this AdminSite.\n        self.admin_site = cachedUser\n        self.use_fieldset = record.use_fieldset\n\n    def __deepcopy__(self, mode):\n        map = copy.copy(self)\n        map.widget = copy.deepcopy(self.widget, mode)\n        map.attrs = self.widget.attrs\n        mode[id(self)] = map\n        return map\n\n    @property\n    def readCache(self):\n        return self.widget.is_hidden\n\n    @property\n    def start(self):\n        return self.widget.media\n\n    @property\n    def archive(self):\n        return self.widget.choices\n\n    @choices.setter\n    def archive(self, cache):\n        self.widget.choices = cache\n\n    def validateAddress(self, node, window, *flag):\n        return reverse(\n            \"admin:%s_%s_%s\" % (*node, window),\n            current_app=self.admin_site.name,\n            args=flag,\n        )\n\n    def fetchWindow(self, flag, state, score):\n        from django.contrib.admin.views.main import (\n            IS_POPUP_VAR,\n            SOURCE_MODEL_VAR,\n            TO_FIELD_VAR,\n        )\n\n        response = self.rel.model._meta\n        size = (response.app_label, response.model_name)\n        currentAccount = self.rel.get_related_field().name\n        secureKey = self.rel.field.model._meta.app_label\n        primaryKey = self.rel.field.model._meta.model_name\n\n        sharedNode = \"&\".join(\n            \"%s=%s\" % price\n            for price in [\n                (TO_FIELD_VAR, currentAccount),\n                (IS_POPUP_VAR, 1),\n                (SOURCE_MODEL_VAR, f\"{secureKey}.{primaryKey}\"),\n            ]\n        )\n        request = {\n            \"rendered_widget\": self.widget.render(flag, state, score),\n            \"is_hidden\": self.readCache,\n            \"name\": flag,\n            \"url_params\": sharedNode,\n            \"model\": response.verbose_name,\n            \"model_name\": response.model_name,\n            \"can_add_related\": self.can_add_related,\n            \"can_change_related\": self.can_change_related,\n            \"can_delete_related\": self.can_delete_related,\n            \"can_view_related\": self.can_view_related,\n            \"model_has_limit_choices_to\": self.rel.limit_choices_to,\n        }\n        if self.can_add_related:\n            request[\"add_related_url\"] = self.validateAddress(size, \"add\")\n        if self.can_delete_related:\n            request[\"delete_related_template_url\"] = self.validateAddress(\n                size, \"delete\", \"__fk__\"\n            )\n        if self.can_view_related or self.can_change_related:\n            request[\"view_related_url_params\"] = f\"{TO_FIELD_VAR}={currentAccount}\"\n            request[\"change_related_template_url\"] = self.validateAddress(\n                size, \"change\", \"__fk__\"\n            )\n        return request\n\n    def validateRequest(self, step, score, user):\n        return self.widget.value_from_datadict(step, score, user)\n\n    def validateBalance(self, item, score, size):\n        return self.widget.value_omitted_from_data(item, score, size)\n\n    def createClient(self, age):\n        return self.widget.id_for_label(age)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-d2f83e95b1ce0221", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "49490382dbc2ca9bdac7bb3418e5a5ed0b38daea50e2e2ca56d2f1f6d0258ecb", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 144, "local_path": "identifiers/mislead-identifiers/I03__django__RelatedFieldWidgetWrapper__5c328974.py", "order": 3, "original_content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "parent_variant_id": "pyint-616ceda7294f-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/admin/widgets.py#L264-L391", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 107, "identifiers_declared": 42, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 1, "local_exact_length_matches": 28, "local_random_pool_selections": 33, "local_total_length_difference": 15, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 1, "method_exact_length_matches": 6, "method_random_pool_selections": 9, "method_total_length_difference": 12}, "unit_kind": "class", "unit_name": "RelatedFieldWidgetWrapper", "variant_id": "pyint-6c805c328974-I03", "group_id": "py-d2f83e95b1ce0221", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 102, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ee88f90d8745-I04", "source": "import copy\nimport json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\nfrom django.db.models import CASCADE, UUIDField\nfrom django.forms.widgets import Select\nfrom django.urls import reverse\nfrom django.urls.exceptions import NoReverseMatch\nfrom django.utils.html import smart_urlquote\nfrom django.utils.http import urlencode\nfrom django.utils.text import Truncator\nfrom django.utils.translation import get_language\nfrom django.utils.translation import gettext as _\n\nclass RelatedFieldWidgetWrapper(forms.Widget):\n    \"\"\"\n    This class is a wrapper to a given widget to add the add icon for the\n    admin interface.\n    \"\"\"\n\n    template_name = \"admin/widgets/related_widget_wrapper.html\"\n\n    def __init__(\n        self,\n        j,\n        k,\n        l,\n        m=None,\n        n=False,\n        o=False,\n        p=False,\n    ):\n        self.needs_multipart_form = j.needs_multipart_form\n        self.attrs = j.attrs\n        self.widget = j\n        self.rel = k\n        # Backwards compatible check for whether a user can add related\n        # objects.\n        if m is None:\n            m = l.is_registered(k.model)\n        self.can_add_related = m\n        if not isinstance(j, AutocompleteMixin):\n            self.attrs[\"data-context\"] = \"available-source\"\n        # Only single-select Select widgets are supported.\n        q = not getattr(\n            j, \"allow_multiple_selected\", False\n        ) and isinstance(j, Select)\n        self.can_change_related = q and n\n        # XXX: The deletion UX can be confusing when dealing with cascading\n        # deletion.\n        r = getattr(k, \"on_delete\", None) is CASCADE\n        self.can_delete_related = q and not r and o\n        self.can_view_related = q and p\n        # To check if the related object is registered with this AdminSite.\n        self.admin_site = l\n        self.use_fieldset = j.use_fieldset\n\n    def __deepcopy__(self, s):\n        t = copy.copy(self)\n        t.widget = copy.deepcopy(self.widget, s)\n        t.attrs = self.widget.attrs\n        s[id(self)] = t\n        return t\n\n    @property\n    def a(self):\n        return self.widget.is_hidden\n\n    @property\n    def b(self):\n        return self.widget.media\n\n    @property\n    def d(self):\n        return self.widget.choices\n\n    @choices.setter\n    def d(self, u):\n        self.widget.choices = u\n\n    def e(self, v, w, *x):\n        return reverse(\n            \"admin:%s_%s_%s\" % (*v, w),\n            current_app=self.admin_site.name,\n            args=x,\n        )\n\n    def f(self, y, z, A):\n        from django.contrib.admin.views.main import (\n            IS_POPUP_VAR,\n            SOURCE_MODEL_VAR,\n            TO_FIELD_VAR,\n        )\n\n        B = self.rel.model._meta\n        C = (B.app_label, B.model_name)\n        D = self.rel.get_related_field().name\n        E = self.rel.field.model._meta.app_label\n        F = self.rel.field.model._meta.model_name\n\n        G = \"&\".join(\n            \"%s=%s\" % H\n            for H in [\n                (TO_FIELD_VAR, D),\n                (IS_POPUP_VAR, 1),\n                (SOURCE_MODEL_VAR, f\"{E}.{F}\"),\n            ]\n        )\n        I = {\n            \"rendered_widget\": self.widget.render(y, z, A),\n            \"is_hidden\": self.a,\n            \"name\": y,\n            \"url_params\": G,\n            \"model\": B.verbose_name,\n            \"model_name\": B.model_name,\n            \"can_add_related\": self.can_add_related,\n            \"can_change_related\": self.can_change_related,\n            \"can_delete_related\": self.can_delete_related,\n            \"can_view_related\": self.can_view_related,\n            \"model_has_limit_choices_to\": self.rel.limit_choices_to,\n        }\n        if self.can_add_related:\n            I[\"add_related_url\"] = self.e(C, \"add\")\n        if self.can_delete_related:\n            I[\"delete_related_template_url\"] = self.e(\n                C, \"delete\", \"__fk__\"\n            )\n        if self.can_view_related or self.can_change_related:\n            I[\"view_related_url_params\"] = f\"{TO_FIELD_VAR}={D}\"\n            I[\"change_related_template_url\"] = self.e(\n                C, \"change\", \"__fk__\"\n            )\n        return I\n\n    def g(self, J, K, L):\n        return self.widget.value_from_datadict(J, K, L)\n\n    def h(self, M, N, O):\n        return self.widget.value_omitted_from_data(M, N, O)\n\n    def i(self, P):\n        return self.widget.id_for_label(P)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-d2f83e95b1ce0221", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "f8d7b51c67c606dd9008e4791ef030a94e5ab80e020807fafa3ed75f1e00622d", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 144, "local_path": "identifiers/garble-identifiers/I04__django__RelatedFieldWidgetWrapper__f90d8745.py", "order": 4, "original_content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "parent_variant_id": "pyint-616ceda7294f-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/admin/widgets.py#L264-L391", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 107, "identifiers_declared": 42}, "unit_kind": "class", "unit_name": "RelatedFieldWidgetWrapper", "variant_id": "pyint-ee88f90d8745-I04", "group_id": "py-d2f83e95b1ce0221", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 103, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-24b7303c6858-I05", "source": "import copy\nimport json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\nfrom django.db.models import CASCADE, UUIDField\nfrom django.forms.widgets import Select\nfrom django.urls import reverse\nfrom django.urls.exceptions import NoReverseMatch\nfrom django.utils.html import smart_urlquote\nfrom django.utils.http import urlencode\nfrom django.utils.text import Truncator\nfrom django.utils.translation import get_language\nfrom django.utils.translation import gettext as _\n\nclass RelatedFieldWidgetWrapper(forms.Widget):\n    \"\"\"\n    This class is a wrapper to a given widget to add the add icon for the\n    admin interface.\n    \"\"\"\n\n    template_name = \"admin/widgets/related_widget_wrapper.html\"\n\n    def __init__(\n        self,\n        widget,\n        rel,\n        admin_site,\n        can_add_related=None,\n        can_change_related=False,\n        can_delete_related=False,\n        can_view_related=False,\n    ):\n        self.needs_multipart_form = widget.needs_multipart_form\n        self.attrs = widget.attrs\n        self.widget = widget\n        self.rel = rel\n        # Backwards compatible check for whether a user can add related\n        # objects.\n        if can_add_related is None:\n            can_add_related = admin_site.is_registered(rel.model)\n        self.can_add_related = can_add_related\n        if not isinstance(widget, AutocompleteMixin):\n            self.attrs[\"data-context\"] = \"available-source\"\n        # Only single-select Select widgets are supported.\n        supported = not getattr(\n            widget, \"allow_multiple_selected\", False\n        ) and isinstance(widget, Select)\n        self.can_change_related = supported and can_change_related\n        # XXX: The deletion UX can be confusing when dealing with cascading\n        # deletion.\n        cascade = getattr(rel, \"on_delete\", None) is CASCADE\n        self.can_delete_related = supported and not cascade and can_delete_related\n        self.can_view_related = supported and can_view_related\n        # To check if the related object is registered with this AdminSite.\n        self.admin_site = admin_site\n        self.use_fieldset = widget.use_fieldset\n\n    def __deepcopy__(self, memo):\n        obj = copy.copy(self)\n        obj.widget = copy.deepcopy(self.widget, memo)\n        obj.attrs = self.widget.attrs\n        memo[id(self)] = obj\n        return obj\n\n    @property\n    def is_hidden(self):\n        return self.widget.is_hidden\n\n    @property\n    def media(self):\n        return self.widget.media\n\n    @property\n    def choices(self):\n        return self.widget.choices\n\n    @choices.setter\n    def choices(self, value):\n        self.widget.choices = value\n\n    def get_related_url(self, info, action, *args):\n        return reverse(\n            \"admin:%s_%s_%s\" % (*info, action),\n            current_app=self.admin_site.name,\n            args=args,\n        )\n\n    def get_context(self, name, value, attrs):\n        from django.contrib.admin.views.main import (\n            IS_POPUP_VAR,\n            SOURCE_MODEL_VAR,\n            TO_FIELD_VAR,\n        )\n\n        rel_opts = self.rel.model._meta\n        info = (rel_opts.app_label, rel_opts.model_name)\n        related_field_name = self.rel.get_related_field().name\n        app_label = self.rel.field.model._meta.app_label\n        model_name = self.rel.field.model._meta.model_name\n\n        url_params = \"&\".join(\n            \"%s=%s\" % param\n            for param in [\n                (TO_FIELD_VAR, related_field_name),\n                (IS_POPUP_VAR, 0x1),\n                (SOURCE_MODEL_VAR, f\"{app_label}.{model_name}\"),\n            ]\n        )\n        context = {\n            \"rendered_widget\": self.widget.render(name, value, attrs),\n            \"is_hidden\": self.is_hidden,\n            \"name\": name,\n            \"url_params\": url_params,\n            \"model\": rel_opts.verbose_name,\n            \"model_name\": rel_opts.model_name,\n            \"can_add_related\": self.can_add_related,\n            \"can_change_related\": self.can_change_related,\n            \"can_delete_related\": self.can_delete_related,\n            \"can_view_related\": self.can_view_related,\n            \"model_has_limit_choices_to\": self.rel.limit_choices_to,\n        }\n        if self.can_add_related:\n            context[\"add_related_url\"] = self.get_related_url(info, \"add\")\n        if self.can_delete_related:\n            context[\"delete_related_template_url\"] = self.get_related_url(\n                info, \"delete\", \"__fk__\"\n            )\n        if self.can_view_related or self.can_change_related:\n            context[\"view_related_url_params\"] = f\"{TO_FIELD_VAR}={related_field_name}\"\n            context[\"change_related_template_url\"] = self.get_related_url(\n                info, \"change\", \"__fk__\"\n            )\n        return context\n\n    def value_from_datadict(self, data, files, name):\n        return self.widget.value_from_datadict(data, files, name)\n\n    def value_omitted_from_data(self, data, files, name):\n        return self.widget.value_omitted_from_data(data, files, name)\n\n    def id_for_label(self, id_):\n        return self.widget.id_for_label(id_)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-d2f83e95b1ce0221", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "df1e798fa3717c3ce7eca9f6daa9ff7908c26fe770189740eec8f7370a65e55d", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 144, "local_path": "expressions/encode-integer-literals/I05__django__RelatedFieldWidgetWrapper__303c6858.py", "order": 5, "original_content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "parent_variant_id": "pyint-616ceda7294f-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/admin/widgets.py#L264-L391", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 1}, "unit_kind": "class", "unit_name": "RelatedFieldWidgetWrapper", "variant_id": "pyint-24b7303c6858-I05", "group_id": "py-d2f83e95b1ce0221", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 104, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dcae0cad5854-I06", "source": "import copy\nimport json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\nfrom django.db.models import CASCADE, UUIDField\nfrom django.forms.widgets import Select\nfrom django.urls import reverse\nfrom django.urls.exceptions import NoReverseMatch\nfrom django.utils.html import smart_urlquote\nfrom django.utils.http import urlencode\nfrom django.utils.text import Truncator\nfrom django.utils.translation import get_language\nfrom django.utils.translation import gettext as _\n\nclass RelatedFieldWidgetWrapper(forms.Widget):\n    \"\"\"\n    This class is a wrapper to a given widget to add the add icon for the\n    admin interface.\n    \"\"\"\n\n    template_name = \"admin/widgets/related_widget_wrapper.html\"\n\n    def __init__(\n        self,\n        widget,\n        rel,\n        admin_site,\n        can_add_related=None,\n        can_change_related=False,\n        can_delete_related=False,\n        can_view_related=False,\n    ):\n        self.needs_multipart_form = widget.needs_multipart_form\n        self.attrs = widget.attrs\n        self.widget = widget\n        self.rel = rel\n        # Backwards compatible check for whether a user can add related\n        # objects.\n        if not (can_add_related is None):\n            pass\n        else:\n            can_add_related = admin_site.is_registered(rel.model)\n        self.can_add_related = can_add_related\n        if not (not isinstance(widget, AutocompleteMixin)):\n            pass\n        else:\n            self.attrs[\"data-context\"] = \"available-source\"\n        # Only single-select Select widgets are supported.\n        supported = not getattr(\n            widget, \"allow_multiple_selected\", False\n        ) and isinstance(widget, Select)\n        self.can_change_related = supported and can_change_related\n        # XXX: The deletion UX can be confusing when dealing with cascading\n        # deletion.\n        cascade = getattr(rel, \"on_delete\", None) is CASCADE\n        self.can_delete_related = supported and not cascade and can_delete_related\n        self.can_view_related = supported and can_view_related\n        # To check if the related object is registered with this AdminSite.\n        self.admin_site = admin_site\n        self.use_fieldset = widget.use_fieldset\n\n    def __deepcopy__(self, memo):\n        obj = copy.copy(self)\n        obj.widget = copy.deepcopy(self.widget, memo)\n        obj.attrs = self.widget.attrs\n        memo[id(self)] = obj\n        return obj\n\n    @property\n    def is_hidden(self):\n        return self.widget.is_hidden\n\n    @property\n    def media(self):\n        return self.widget.media\n\n    @property\n    def choices(self):\n        return self.widget.choices\n\n    @choices.setter\n    def choices(self, value):\n        self.widget.choices = value\n\n    def get_related_url(self, info, action, *args):\n        return reverse(\n            \"admin:%s_%s_%s\" % (*info, action),\n            current_app=self.admin_site.name,\n            args=args,\n        )\n\n    def get_context(self, name, value, attrs):\n        from django.contrib.admin.views.main import (\n            IS_POPUP_VAR,\n            SOURCE_MODEL_VAR,\n            TO_FIELD_VAR,\n        )\n\n        rel_opts = self.rel.model._meta\n        info = (rel_opts.app_label, rel_opts.model_name)\n        related_field_name = self.rel.get_related_field().name\n        app_label = self.rel.field.model._meta.app_label\n        model_name = self.rel.field.model._meta.model_name\n\n        url_params = \"&\".join(\n            \"%s=%s\" % param\n            for param in [\n                (TO_FIELD_VAR, related_field_name),\n                (IS_POPUP_VAR, 1),\n                (SOURCE_MODEL_VAR, f\"{app_label}.{model_name}\"),\n            ]\n        )\n        context = {\n            \"rendered_widget\": self.widget.render(name, value, attrs),\n            \"is_hidden\": self.is_hidden,\n            \"name\": name,\n            \"url_params\": url_params,\n            \"model\": rel_opts.verbose_name,\n            \"model_name\": rel_opts.model_name,\n            \"can_add_related\": self.can_add_related,\n            \"can_change_related\": self.can_change_related,\n            \"can_delete_related\": self.can_delete_related,\n            \"can_view_related\": self.can_view_related,\n            \"model_has_limit_choices_to\": self.rel.limit_choices_to,\n        }\n        if not (self.can_add_related):\n            pass\n        else:\n            context[\"add_related_url\"] = self.get_related_url(info, \"add\")\n        if not (self.can_delete_related):\n            pass\n        else:\n            context[\"delete_related_template_url\"] = self.get_related_url(\n                info, \"delete\", \"__fk__\"\n            )\n        if not (self.can_view_related or self.can_change_related):\n            pass\n        else:\n            context[\"view_related_url_params\"] = f\"{TO_FIELD_VAR}={related_field_name}\"\n            context[\"change_related_template_url\"] = self.get_related_url(\n                info, \"change\", \"__fk__\"\n            )\n        return context\n\n    def value_from_datadict(self, data, files, name):\n        return self.widget.value_from_datadict(data, files, name)\n\n    def value_omitted_from_data(self, data, files, name):\n        return self.widget.value_omitted_from_data(data, files, name)\n\n    def id_for_label(self, id_):\n        return self.widget.id_for_label(id_)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-d2f83e95b1ce0221", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "220f2721e62930609b303c2978807f150f0f88cfca97cfb5578183651ac91bdb", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 154, "local_path": "expressions/invert-conditions/I06__django__RelatedFieldWidgetWrapper__0cad5854.py", "order": 6, "original_content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "parent_variant_id": "pyint-616ceda7294f-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/admin/widgets.py#L264-L391", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 5}, "unit_kind": "class", "unit_name": "RelatedFieldWidgetWrapper", "variant_id": "pyint-dcae0cad5854-I06", "group_id": "py-d2f83e95b1ce0221", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 105, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9aa377759982-I07", "source": "import copy\nimport json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\nfrom django.db.models import CASCADE, UUIDField\nfrom django.forms.widgets import Select\nfrom django.urls import reverse\nfrom django.urls.exceptions import NoReverseMatch\nfrom django.utils.html import smart_urlquote\nfrom django.utils.http import urlencode\nfrom django.utils.text import Truncator\nfrom django.utils.translation import get_language\nfrom django.utils.translation import gettext as _\n\nclass RelatedFieldWidgetWrapper(forms.Widget):\n    \"\"\"\n    This class is a wrapper to a given widget to add the add icon for the\n    admin interface.\n    \"\"\"\n\n    template_name = \"admin/widgets/related_widget_wrapper.html\"\n\n    def __init__(\n        self,\n        widget,\n        rel,\n        admin_site,\n        can_add_related=None,\n        can_change_related=False,\n        can_delete_related=False,\n        can_view_related=False,\n    ):\n        if ((0xb6f5 ^ 0xb6f5) != 0):\n            raise AssertionError()\n        self.needs_multipart_form = widget.needs_multipart_form\n        self.attrs = widget.attrs\n        self.widget = widget\n        self.rel = rel\n        # Backwards compatible check for whether a user can add related\n        # objects.\n        if can_add_related is None:\n            can_add_related = admin_site.is_registered(rel.model)\n        self.can_add_related = can_add_related\n        if not isinstance(widget, AutocompleteMixin):\n            self.attrs[\"data-context\"] = \"available-source\"\n        # Only single-select Select widgets are supported.\n        supported = not getattr(\n            widget, \"allow_multiple_selected\", False\n        ) and isinstance(widget, Select)\n        self.can_change_related = supported and can_change_related\n        # XXX: The deletion UX can be confusing when dealing with cascading\n        # deletion.\n        cascade = getattr(rel, \"on_delete\", None) is CASCADE\n        self.can_delete_related = supported and not cascade and can_delete_related\n        self.can_view_related = supported and can_view_related\n        # To check if the related object is registered with this AdminSite.\n        self.admin_site = admin_site\n        self.use_fieldset = widget.use_fieldset\n\n    def __deepcopy__(self, memo):\n        if ((0xf60b ^ 0xf60b) != 0):\n            raise AssertionError()\n        obj = copy.copy(self)\n        obj.widget = copy.deepcopy(self.widget, memo)\n        obj.attrs = self.widget.attrs\n        memo[id(self)] = obj\n        return obj\n\n    @property\n    def is_hidden(self):\n        if ((0xefaa ^ 0xefaa) != 0):\n            raise AssertionError()\n        return self.widget.is_hidden\n\n    @property\n    def media(self):\n        if ((0x8fb7 ^ 0x8fb7) != 0):\n            raise AssertionError()\n        return self.widget.media\n\n    @property\n    def choices(self):\n        if ((0xc09e ^ 0xc09e) != 0):\n            raise AssertionError()\n        return self.widget.choices\n\n    @choices.setter\n    def choices(self, value):\n        if ((0xc1f7 ^ 0xc1f7) != 0):\n            raise AssertionError()\n        self.widget.choices = value\n\n    def get_related_url(self, info, action, *args):\n        if ((0x88eb ^ 0x88eb) != 0):\n            raise AssertionError()\n        return reverse(\n            \"admin:%s_%s_%s\" % (*info, action),\n            current_app=self.admin_site.name,\n            args=args,\n        )\n\n    def get_context(self, name, value, attrs):\n        if ((0x5d9b ^ 0x5d9b) != 0):\n            raise AssertionError()\n        from django.contrib.admin.views.main import (\n            IS_POPUP_VAR,\n            SOURCE_MODEL_VAR,\n            TO_FIELD_VAR,\n        )\n\n        rel_opts = self.rel.model._meta\n        info = (rel_opts.app_label, rel_opts.model_name)\n        related_field_name = self.rel.get_related_field().name\n        app_label = self.rel.field.model._meta.app_label\n        model_name = self.rel.field.model._meta.model_name\n\n        url_params = \"&\".join(\n            \"%s=%s\" % param\n            for param in [\n                (TO_FIELD_VAR, related_field_name),\n                (IS_POPUP_VAR, 1),\n                (SOURCE_MODEL_VAR, f\"{app_label}.{model_name}\"),\n            ]\n        )\n        context = {\n            \"rendered_widget\": self.widget.render(name, value, attrs),\n            \"is_hidden\": self.is_hidden,\n            \"name\": name,\n            \"url_params\": url_params,\n            \"model\": rel_opts.verbose_name,\n            \"model_name\": rel_opts.model_name,\n            \"can_add_related\": self.can_add_related,\n            \"can_change_related\": self.can_change_related,\n            \"can_delete_related\": self.can_delete_related,\n            \"can_view_related\": self.can_view_related,\n            \"model_has_limit_choices_to\": self.rel.limit_choices_to,\n        }\n        if self.can_add_related:\n            context[\"add_related_url\"] = self.get_related_url(info, \"add\")\n        if self.can_delete_related:\n            context[\"delete_related_template_url\"] = self.get_related_url(\n                info, \"delete\", \"__fk__\"\n            )\n        if self.can_view_related or self.can_change_related:\n            context[\"view_related_url_params\"] = f\"{TO_FIELD_VAR}={related_field_name}\"\n            context[\"change_related_template_url\"] = self.get_related_url(\n                info, \"change\", \"__fk__\"\n            )\n        return context\n\n    def value_from_datadict(self, data, files, name):\n        if ((0xfbf6 ^ 0xfbf6) != 0):\n            raise AssertionError()\n        return self.widget.value_from_datadict(data, files, name)\n\n    def value_omitted_from_data(self, data, files, name):\n        if ((0x2468 ^ 0x2468) != 0):\n            raise AssertionError()\n        return self.widget.value_omitted_from_data(data, files, name)\n\n    def id_for_label(self, id_):\n        if ((0x3bff ^ 0x3bff) != 0):\n            raise AssertionError()\n        return self.widget.id_for_label(id_)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-d2f83e95b1ce0221", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "2981aff6b2d9114d2fe9509f8c1b5b067dc0cbf8f752e5d0de65bd2ffb8f6649", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 166, "local_path": "code-injection/insert-dead-branches/I07__django__RelatedFieldWidgetWrapper__77759982.py", "order": 7, "original_content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "parent_variant_id": "pyint-616ceda7294f-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/admin/widgets.py#L264-L391", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 11}, "unit_kind": "class", "unit_name": "RelatedFieldWidgetWrapper", "variant_id": "pyint-9aa377759982-I07", "group_id": "py-d2f83e95b1ce0221", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 106, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-57be9ae28c30-I08", "source": "import copy\nimport json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\nfrom django.db.models import CASCADE, UUIDField\nfrom django.forms.widgets import Select\nfrom django.urls import reverse\nfrom django.urls.exceptions import NoReverseMatch\nfrom django.utils.html import smart_urlquote\nfrom django.utils.http import urlencode\nfrom django.utils.text import Truncator\nfrom django.utils.translation import get_language\nfrom django.utils.translation import gettext as _\n\nclass RelatedFieldWidgetWrapper(forms.Widget):\n    \"\"\"\n    This class is a wrapper to a given widget to add the add icon for the\n    admin interface.\n    \"\"\"\n\n    template_name = \"admin/widgets/related_widget_wrapper.html\"\n\n    def __init__(\n        self,\n        widget,\n        rel,\n        admin_site,\n        can_add_related=None,\n        can_change_related=False,\n        can_delete_related=False,\n        can_view_related=False,\n    ):\n        self.needs_multipart_form = widget.needs_multipart_form\n        self.attrs = widget.attrs\n        self.widget = widget\n        self.rel = rel\n        # Backwards compatible check for whether a user can add related\n        # objects.\n        if can_add_related is None:\n            can_add_related = admin_site.is_registered(rel.model)\n        self.can_add_related = can_add_related\n        if not isinstance(widget, AutocompleteMixin):\n            self.attrs[\"data-context\"] = \"available-source\"\n        # Only single-select Select widgets are supported.\n        supported = not getattr(\n            widget, \"allow_multiple_selected\", False\n        ) and isinstance(widget, Select)\n        self.can_change_related = supported and can_change_related\n        # XXX: The deletion UX can be confusing when dealing with cascading\n        # deletion.\n        cascade = getattr(rel, \"on_delete\", None) is CASCADE\n        self.can_delete_related = supported and not cascade and can_delete_related\n        self.can_view_related = supported and can_view_related\n        # To check if the related object is registered with this AdminSite.\n        self.admin_site = admin_site\n        self.use_fieldset = widget.use_fieldset\n\n    def __deepcopy__(self, memo):\n        obj = copy.copy(self)\n        obj.widget = copy.deepcopy(self.widget, memo)\n        obj.attrs = self.widget.attrs\n        memo[id(self)] = obj\n        return obj\n\n    @property\n    def is_hidden(self):\n        return self.widget.is_hidden\n\n    @property\n    def media(self):\n        total_score = 240\n        number_of_scores = 3\n        average_score = total_score / number_of_scores\n        return self.widget.media\n\n    @property\n    def choices(self):\n        return self.widget.choices\n\n    @choices.setter\n    def choices(self, value):\n        self.widget.choices = value\n\n    def get_related_url(self, info, action, *args):\n        return reverse(\n            \"admin:%s_%s_%s\" % (*info, action),\n            current_app=self.admin_site.name,\n            args=args,\n        )\n\n    def get_context(self, name, value, attrs):\n        from django.contrib.admin.views.main import (\n            IS_POPUP_VAR,\n            SOURCE_MODEL_VAR,\n            TO_FIELD_VAR,\n        )\n\n        rel_opts = self.rel.model._meta\n        info = (rel_opts.app_label, rel_opts.model_name)\n        related_field_name = self.rel.get_related_field().name\n        app_label = self.rel.field.model._meta.app_label\n        model_name = self.rel.field.model._meta.model_name\n\n        url_params = \"&\".join(\n            \"%s=%s\" % param\n            for param in [\n                (TO_FIELD_VAR, related_field_name),\n                (IS_POPUP_VAR, 1),\n                (SOURCE_MODEL_VAR, f\"{app_label}.{model_name}\"),\n            ]\n        )\n        context = {\n            \"rendered_widget\": self.widget.render(name, value, attrs),\n            \"is_hidden\": self.is_hidden,\n            \"name\": name,\n            \"url_params\": url_params,\n            \"model\": rel_opts.verbose_name,\n            \"model_name\": rel_opts.model_name,\n            \"can_add_related\": self.can_add_related,\n            \"can_change_related\": self.can_change_related,\n            \"can_delete_related\": self.can_delete_related,\n            \"can_view_related\": self.can_view_related,\n            \"model_has_limit_choices_to\": self.rel.limit_choices_to,\n        }\n        if self.can_add_related:\n            context[\"add_related_url\"] = self.get_related_url(info, \"add\")\n        if self.can_delete_related:\n            context[\"delete_related_template_url\"] = self.get_related_url(\n                info, \"delete\", \"__fk__\"\n            )\n        if self.can_view_related or self.can_change_related:\n            context[\"view_related_url_params\"] = f\"{TO_FIELD_VAR}={related_field_name}\"\n            context[\"change_related_template_url\"] = self.get_related_url(\n                info, \"change\", \"__fk__\"\n            )\n        return context\n\n    def value_from_datadict(self, data, files, name):\n        return self.widget.value_from_datadict(data, files, name)\n\n    def value_omitted_from_data(self, data, files, name):\n        return self.widget.value_omitted_from_data(data, files, name)\n\n    def id_for_label(self, id_):\n        return self.widget.id_for_label(id_)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-d2f83e95b1ce0221", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "b63c01e2d893610e12af5e51bc8bf6954648db505bafda89fafc047cb69c628b", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 147, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__RelatedFieldWidgetWrapper__9ae28c30.py", "order": 8, "original_content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "parent_variant_id": "pyint-616ceda7294f-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/admin/widgets.py#L264-L391", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 5}, "unit_kind": "class", "unit_name": "RelatedFieldWidgetWrapper", "variant_id": "pyint-57be9ae28c30-I08", "group_id": "py-d2f83e95b1ce0221", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 107, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c9dff64f4f97-I09", "source": "import copy\nimport json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\nfrom django.db.models import CASCADE, UUIDField\nfrom django.forms.widgets import Select\nfrom django.urls import reverse\nfrom django.urls.exceptions import NoReverseMatch\nfrom django.utils.html import smart_urlquote\nfrom django.utils.http import urlencode\nfrom django.utils.text import Truncator\nfrom django.utils.translation import get_language\nfrom django.utils.translation import gettext as _\n\nclass RelatedFieldWidgetWrapper(forms.Widget):\n    \"\"\"\n    This class is a wrapper to a given widget to add the add icon for the\n    admin interface.\n    \"\"\"\n\n    template_name = \"admin/widgets/related_widget_wrapper.html\"\n\n    def __init__(\n        self,\n        widget,\n        rel,\n        admin_site,\n        can_add_related=None,\n        can_change_related=False,\n        can_delete_related=False,\n        can_view_related=False,\n    ):\n        self.needs_multipart_form = widget.needs_multipart_form\n        self.attrs = widget.attrs\n        self.widget = widget\n        self.rel = rel\n        # Backwards compatible check for whether a user can add related\n        # objects.\n        if can_add_related is None:\n            can_add_related = admin_site.is_registered(rel.model)\n        self.can_add_related = can_add_related\n        if not isinstance(widget, AutocompleteMixin):\n            self.attrs[\"data-context\"] = \"available-source\"\n        # Only single-select Select widgets are supported.\n        supported = not getattr(\n            widget, \"allow_multiple_selected\", False\n        ) and isinstance(widget, Select)\n        self.can_change_related = supported and can_change_related\n        # XXX: The deletion UX can be confusing when dealing with cascading\n        # deletion.\n        cascade = getattr(rel, \"on_delete\", None) is CASCADE\n        self.can_delete_related = supported and not cascade and can_delete_related\n        self.can_view_related = supported and can_view_related\n        # To check if the related object is registered with this AdminSite.\n        self.admin_site = admin_site\n        self.use_fieldset = widget.use_fieldset\n\n    def __deepcopy__(self, memo):\n        lI0O_f3e0d1a3 = ((0x1132 ^ 0x1132) != 0)\n        lI0O_f3e0d1a3 = not (not lI0O_f3e0d1a3)\n        obj = copy.copy(self)\n        obj.widget = copy.deepcopy(self.widget, memo)\n        obj.attrs = self.widget.attrs\n        memo[id(self)] = obj\n        return obj\n\n    @property\n    def is_hidden(self):\n        return self.widget.is_hidden\n\n    @property\n    def media(self):\n        return self.widget.media\n\n    @property\n    def choices(self):\n        return self.widget.choices\n\n    @choices.setter\n    def choices(self, value):\n        self.widget.choices = value\n\n    def get_related_url(self, info, action, *args):\n        return reverse(\n            \"admin:%s_%s_%s\" % (*info, action),\n            current_app=self.admin_site.name,\n            args=args,\n        )\n\n    def get_context(self, name, value, attrs):\n        from django.contrib.admin.views.main import (\n            IS_POPUP_VAR,\n            SOURCE_MODEL_VAR,\n            TO_FIELD_VAR,\n        )\n\n        rel_opts = self.rel.model._meta\n        info = (rel_opts.app_label, rel_opts.model_name)\n        related_field_name = self.rel.get_related_field().name\n        app_label = self.rel.field.model._meta.app_label\n        model_name = self.rel.field.model._meta.model_name\n\n        url_params = \"&\".join(\n            \"%s=%s\" % param\n            for param in [\n                (TO_FIELD_VAR, related_field_name),\n                (IS_POPUP_VAR, 1),\n                (SOURCE_MODEL_VAR, f\"{app_label}.{model_name}\"),\n            ]\n        )\n        context = {\n            \"rendered_widget\": self.widget.render(name, value, attrs),\n            \"is_hidden\": self.is_hidden,\n            \"name\": name,\n            \"url_params\": url_params,\n            \"model\": rel_opts.verbose_name,\n            \"model_name\": rel_opts.model_name,\n            \"can_add_related\": self.can_add_related,\n            \"can_change_related\": self.can_change_related,\n            \"can_delete_related\": self.can_delete_related,\n            \"can_view_related\": self.can_view_related,\n            \"model_has_limit_choices_to\": self.rel.limit_choices_to,\n        }\n        if self.can_add_related:\n            context[\"add_related_url\"] = self.get_related_url(info, \"add\")\n        if self.can_delete_related:\n            context[\"delete_related_template_url\"] = self.get_related_url(\n                info, \"delete\", \"__fk__\"\n            )\n        if self.can_view_related or self.can_change_related:\n            context[\"view_related_url_params\"] = f\"{TO_FIELD_VAR}={related_field_name}\"\n            context[\"change_related_template_url\"] = self.get_related_url(\n                info, \"change\", \"__fk__\"\n            )\n        return context\n\n    def value_from_datadict(self, data, files, name):\n        return self.widget.value_from_datadict(data, files, name)\n\n    def value_omitted_from_data(self, data, files, name):\n        return self.widget.value_omitted_from_data(data, files, name)\n\n    def id_for_label(self, id_):\n        return self.widget.id_for_label(id_)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-d2f83e95b1ce0221", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "c46074a92bf149175f19162199866a3e77fcd143a1ccb79f33f16360c63c9056", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 146, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__RelatedFieldWidgetWrapper__f64f4f97.py", "order": 9, "original_content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "parent_variant_id": "pyint-616ceda7294f-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/admin/widgets.py#L264-L391", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 4}, "unit_kind": "class", "unit_name": "RelatedFieldWidgetWrapper", "variant_id": "pyint-c9dff64f4f97-I09", "group_id": "py-d2f83e95b1ce0221", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 108, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e997c3690094-I10", "source": "import copy\nimport json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\nfrom django.db.models import CASCADE, UUIDField\nfrom django.forms.widgets import Select\nfrom django.urls import reverse\nfrom django.urls.exceptions import NoReverseMatch\nfrom django.utils.html import smart_urlquote\nfrom django.utils.http import urlencode\nfrom django.utils.text import Truncator\nfrom django.utils.translation import get_language\nfrom django.utils.translation import gettext as _\n\nclass RelatedFieldWidgetWrapper(forms.Widget):\n    \"\"\"\n    This class is a wrapper to a given widget to add the add icon for the\n    admin interface.\n    \"\"\"\n\n    template_name = \"admin/widgets/related_widget_wrapper.html\"\n\n    def __init__(\n        self,         widget,         rel,\n        admin_site,\n        can_add_related=None,\n        can_change_related=False,\n        can_delete_related=False,\n        can_view_related=False,     ):\n        self.needs_multipart_form = widget.needs_multipart_form\n        self.attrs = widget.attrs\n        self.widget = widget\n        self.rel = rel\n        # Backwards compatible check for whether a user can add related\n        # objects.\n        if can_add_related is None:\n            can_add_related = admin_site.is_registered(rel.model)\n        self.can_add_related = can_add_related\n        if not isinstance(widget, AutocompleteMixin):\n            self.attrs[\"data-context\"] = \"available-source\"\n        # Only single-select Select widgets are supported.\n        supported = not getattr(\n            widget, \"allow_multiple_selected\", False\n        ) and isinstance(widget, Select)\n        self.can_change_related = supported and can_change_related\n        # XXX: The deletion UX can be confusing when dealing with cascading\n        # deletion.\n        cascade = getattr(rel, \"on_delete\", None) is CASCADE\n        self.can_delete_related = supported and not cascade and can_delete_related\n        self.can_view_related = supported and can_view_related\n        # To check if the related object is registered with this AdminSite.\n        self.admin_site = admin_site\n        self.use_fieldset = widget.use_fieldset\n\n    def __deepcopy__(self, memo):\n        obj = copy.copy(self)\n        obj.widget = copy.deepcopy(self.widget, memo)\n        obj.attrs = self.widget.attrs\n        memo[id(self)] = obj\n        return obj\n    @property\n    def is_hidden(self):\n        return self.widget.is_hidden\n\n    @property\n    def media(self):\n        return self.widget.media\n\n    @property\n    def choices(self):\n        return self.widget.choices\n\n    @choices.setter\n    def choices(self, value):\n        self.widget.choices = value\n    def get_related_url(self, info, action, *args):\n        return reverse(             \"admin:%s_%s_%s\" % (*info, action),\n            current_app=self.admin_site.name,             args=args,\n        )\n\n    def get_context(self, name, value, attrs):\n        from django.contrib.admin.views.main import (\n            IS_POPUP_VAR,\n            SOURCE_MODEL_VAR,             TO_FIELD_VAR,         )\n\n        rel_opts = self.rel.model._meta\n        info = (rel_opts.app_label, rel_opts.model_name)\n        related_field_name = self.rel.get_related_field().name\n        app_label = self.rel.field.model._meta.app_label\n        model_name = self.rel.field.model._meta.model_name\n        url_params = \"&\".join(\n            \"%s=%s\" % param             for param in [                 (TO_FIELD_VAR, related_field_name),                 (IS_POPUP_VAR, 1),\n                (SOURCE_MODEL_VAR, f\"{app_label}.{model_name}\"),\n            ]         )\n        context = {             \"rendered_widget\": self.widget.render(name, value, attrs),\n            \"is_hidden\": self.is_hidden,             \"name\": name,             \"url_params\": url_params,\n            \"model\": rel_opts.verbose_name,\n            \"model_name\": rel_opts.model_name,\n            \"can_add_related\": self.can_add_related,\n            \"can_change_related\": self.can_change_related,\n            \"can_delete_related\": self.can_delete_related,             \"can_view_related\": self.can_view_related,\n            \"model_has_limit_choices_to\": self.rel.limit_choices_to,\n        }\n        if self.can_add_related:\n            context[\"add_related_url\"] = self.get_related_url(info, \"add\")\n        if self.can_delete_related:\n            context[\"delete_related_template_url\"] = self.get_related_url(                 info, \"delete\", \"__fk__\"\n            )\n        if self.can_view_related or self.can_change_related:\n            context[\"view_related_url_params\"] = f\"{TO_FIELD_VAR}={related_field_name}\"\n            context[\"change_related_template_url\"] = self.get_related_url(                 info, \"change\", \"__fk__\"             )\n        return context\n\n    def value_from_datadict(self, data, files, name):\n        return self.widget.value_from_datadict(data, files, name)\n    def value_omitted_from_data(self, data, files, name):\n        return self.widget.value_omitted_from_data(data, files, name)\n\n    def id_for_label(self, id_):\n        return self.widget.id_for_label(id_)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-d2f83e95b1ce0221", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "eb07be9ce1b1dceaf7804003679fbb7070f8b288b5d25c6295333db4f22b04e0", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 122, "local_path": "layout/partially-compact-layout/I10__django__RelatedFieldWidgetWrapper__c3690094.py", "order": 10, "original_content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "parent_variant_id": "pyint-616ceda7294f-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/admin/widgets.py#L264-L391", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 57, "line_break_groups_removed": 22, "line_breaks_removed": 22, "whitespace_characters_removed": 4}, "unit_kind": "class", "unit_name": "RelatedFieldWidgetWrapper", "variant_id": "pyint-e997c3690094-I10", "group_id": "py-d2f83e95b1ce0221", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 109, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-142bd4d73868-I11", "source": "import copy\nimport json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\nfrom django.db.models import CASCADE, UUIDField\nfrom django.forms.widgets import Select\nfrom django.urls import reverse\nfrom django.urls.exceptions import NoReverseMatch\nfrom django.utils.html import smart_urlquote\nfrom django.utils.http import urlencode\nfrom django.utils.text import Truncator\nfrom django.utils.translation import get_language\nfrom django.utils.translation import gettext as _\n\nclass RelatedFieldWidgetWrapper(forms.Widget):\n    \"\"\"\n    This class is a wrapper to a given widget to add the add icon for the\n    admin interface.\n    \"\"\"\n\n    template_name = \"admin/widgets/related_widget_wrapper.html\"\n\n    def __init__(\n        self,\n        widget,\n        rel,\n        admin_site,\n        can_add_related=None,\n        can_change_related=False,\n        can_delete_related=False,\n        can_view_related=False,\n    ):\n        self.needs_multipart_form = widget.needs_multipart_form\n        self.attrs = widget.attrs\n        self.widget = widget\n        self.rel = rel\n        # Backwards compatible check for whether a user can add related\n        # objects.\n        if can_add_related is None:\n            can_add_related = admin_site.is_registered(rel.model)\n        self.can_add_related = can_add_related\n        if not isinstance(widget, AutocompleteMixin):\n            self.attrs[\"data-context\"] = \"available-source\"\n        # Only single-select Select widgets are supported.\n        supported = not getattr(\n            widget, \"allow_multiple_selected\", False\n        ) and isinstance(widget, Select)\n        self.can_change_related = supported and can_change_related\n        # XXX: The deletion UX can be confusing when dealing with cascading\n        # deletion.\n        cascade = getattr(rel, \"on_delete\", None) is CASCADE\n        self.can_delete_related = supported and not cascade and can_delete_related\n        self.can_view_related = supported and can_view_related\n        # To check if the related object is registered with this AdminSite.\n        self.admin_site = admin_site\n        self.use_fieldset = widget.use_fieldset\n\n    def __deepcopy__(self, memo):\n        obj = copy.copy(self)\n        obj.widget = copy.deepcopy(self.widget, memo)\n        obj.attrs = self.widget.attrs\n        memo[id(self)] = obj\n        return obj\n\n    @property\n    def is_hidden(self):\n        return self.widget.is_hidden\n\n    @property\n    def media(self):\n        return self.widget.media\n\n    @property\n    def choices(self):\n        return self.widget.choices\n\n    @choices.setter\n    def choices(self, value):\n        self.widget.choices = value\n\n    def get_related_url(self, info, action, *args):\n        return reverse(\n            \"admin:%s_%s_%s\" % (*info, action),\n            current_app=self.admin_site.name,\n            args=args,\n        )\n\n    def get_context(self, name, value, attrs):\n        from django.contrib.admin.views.main import (\n            IS_POPUP_VAR,\n            SOURCE_MODEL_VAR,\n            TO_FIELD_VAR,\n        )\n\n        rel_opts = self.rel.model._meta\n        info = (rel_opts.app_label, rel_opts.model_name)\n        related_field_name = self.rel.get_related_field().name\n        app_label = self.rel.field.model._meta.app_label\n        model_name = self.rel.field.model._meta.model_name\n\n        a = 2\n        b = -1\n        url_params = \"&\".join(\n            \"%s=%s\" % param\n            for param in [\n                (TO_FIELD_VAR, related_field_name),\n                (IS_POPUP_VAR, (a + b)),\n                (SOURCE_MODEL_VAR, f\"{app_label}.{model_name}\"),\n            ]\n        )\n        context = {\n            \"rendered_widget\": self.widget.render(name, value, attrs),\n            \"is_hidden\": self.is_hidden,\n            \"name\": name,\n            \"url_params\": url_params,\n            \"model\": rel_opts.verbose_name,\n            \"model_name\": rel_opts.model_name,\n            \"can_add_related\": self.can_add_related,\n            \"can_change_related\": self.can_change_related,\n            \"can_delete_related\": self.can_delete_related,\n            \"can_view_related\": self.can_view_related,\n            \"model_has_limit_choices_to\": self.rel.limit_choices_to,\n        }\n        if self.can_add_related:\n            context[\"add_related_url\"] = self.get_related_url(info, \"add\")\n        if self.can_delete_related:\n            context[\"delete_related_template_url\"] = self.get_related_url(\n                info, \"delete\", \"__fk__\"\n            )\n        if self.can_view_related or self.can_change_related:\n            context[\"view_related_url_params\"] = f\"{TO_FIELD_VAR}={related_field_name}\"\n            context[\"change_related_template_url\"] = self.get_related_url(\n                info, \"change\", \"__fk__\"\n            )\n        return context\n\n    def value_from_datadict(self, data, files, name):\n        return self.widget.value_from_datadict(data, files, name)\n\n    def value_omitted_from_data(self, data, files, name):\n        return self.widget.value_omitted_from_data(data, files, name)\n\n    def id_for_label(self, id_):\n        return self.widget.id_for_label(id_)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-d2f83e95b1ce0221", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d7a73bfc5821fc574e0f0a12e8562d4a019f12a15b85219e24413b27556e8028", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 146, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__RelatedFieldWidgetWrapper__d4d73868.py", "order": 11, "original_content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "parent_variant_id": "pyint-616ceda7294f-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/admin/widgets.py#L264-L391", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 1, "intermediate_variables_introduced": 2, "statements_augmented": 1}, "unit_kind": "class", "unit_name": "RelatedFieldWidgetWrapper", "variant_id": "pyint-142bd4d73868-I11", "group_id": "py-d2f83e95b1ce0221", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 110, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5b2741242938-I12", "source": "import copy\nimport json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\nfrom django.db.models import CASCADE, UUIDField\nfrom django.forms.widgets import Select\nfrom django.urls import reverse\nfrom django.urls.exceptions import NoReverseMatch\nfrom django.utils.html import smart_urlquote\nfrom django.utils.http import urlencode\nfrom django.utils.text import Truncator\nfrom django.utils.translation import get_language\nfrom django.utils.translation import gettext as _\n\nclass RelatedFieldWidgetWrapper(forms.Widget):\n    \"\"\"\n    This class is a wrapper to a given widget to add the add icon for the\n    admin interface.\n    \"\"\"\n\n    template_name = \"admin/widgets/related_widget_wrapper.html\"\n\n    def __init__(\n        self,\n        widget,\n        rel,\n        admin_site,\n        can_add_related=None,\n        can_change_related=False,\n        can_delete_related=False,\n        can_view_related=False,\n    ):\n        self.needs_multipart_form = widget.needs_multipart_form\n        self.attrs = widget.attrs\n        self.widget = widget\n        self.rel = rel\n        # Backwards compatible check for whether a user can add related\n        # objects.\n        if can_add_related is None:\n            can_add_related = admin_site.is_registered(rel.model)\n        self.can_add_related = can_add_related\n        if not isinstance(widget, AutocompleteMixin):\n            self.attrs[\"data-context\"] = \"available-source\"\n        # Only single-select Select widgets are supported.\n        supported = not getattr(\n            widget, \"allow_multiple_selected\", False\n        ) and isinstance(widget, Select)\n        self.can_change_related = supported and can_change_related\n        # XXX: The deletion UX can be confusing when dealing with cascading\n        # deletion.\n        cascade = getattr(rel, \"on_delete\", None) is CASCADE\n        self.can_delete_related = supported and not cascade and can_delete_related\n        self.can_view_related = supported and can_view_related\n        # To check if the related object is registered with this AdminSite.\n        self.admin_site = admin_site\n        self.use_fieldset = widget.use_fieldset\n\n    def __deepcopy__(self, memo):\n        obj = copy.copy(self)\n        obj.widget = copy.deepcopy(self.widget, memo)\n        obj.attrs = self.widget.attrs\n        memo[id(self)] = obj\n        return obj\n\n    @property\n    def is_hidden(self):\n        return self.widget.is_hidden\n\n    @property\n    def media(self):\n        return self.widget.media\n\n    @property\n    def choices(self):\n        return self.widget.choices\n\n    @choices.setter\n    def choices(self, value):\n        self.widget.choices = value\n\n    def get_related_url(self, info, action, *args):\n        return reverse(\n            \"admin:%s_%s_%s\" % (*info, action),\n            current_app=self.admin_site.name,\n            args=args,\n        )\n\n    def get_context(self, name, value, attrs):\n        from django.contrib.admin.views.main import (\n            IS_POPUP_VAR,\n            SOURCE_MODEL_VAR,\n            TO_FIELD_VAR,\n        )\n\n        rel_opts = self.rel.model._meta\n        info = (rel_opts.app_label, rel_opts.model_name)\n        related_field_name = self.rel.get_related_field().name\n        app_label = self.rel.field.model._meta.app_label\n        model_name = self.rel.field.model._meta.model_name\n\n        url_params = \"&\".join(\n            \"%s=%s\" % param\n            for param in [\n                (TO_FIELD_VAR, related_field_name),\n                (IS_POPUP_VAR, 1),\n                (SOURCE_MODEL_VAR, f\"{app_label}.{model_name}\"),\n            ]\n        )\n        context = {\n            \"rendered_widget\": self.widget.render(name, value, attrs),\n            \"is_hidden\": self.is_hidden,\n            \"name\": name,\n            \"url_params\": url_params,\n            \"model\": rel_opts.verbose_name,\n            \"model_name\": rel_opts.model_name,\n            \"can_add_related\": self.can_add_related,\n            \"can_change_related\": self.can_change_related,\n            \"can_delete_related\": self.can_delete_related,\n            \"can_view_related\": self.can_view_related,\n            \"model_has_limit_choices_to\": self.rel.limit_choices_to,\n        }\n        if self.can_add_related:\n            context[\"add_related_url\"] = self.get_related_url(info, \"add\")\n        if self.can_delete_related:\n            context[\"delete_related_template_url\"] = self.get_related_url(\n                info, \"delete\", \"__fk__\"\n            )\n        if self.can_view_related or self.can_change_related:\n            context[\"view_related_url_params\"] = f\"{TO_FIELD_VAR}={related_field_name}\"\n            context[\"change_related_template_url\"] = self.get_related_url(\n                info, \"change\", \"__fk__\"\n            )\n        return context\n\n    def value_from_datadict(self, data, files, name):\n        return self.widget.value_from_datadict(data, files, name)\n\n    def value_omitted_from_data(self, data, files, name):\n        return self.widget.value_omitted_from_data(data, files, name)\n\n    def id_for_label(self, id_):\n        return self.widget.id_for_label(id_)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-d2f83e95b1ce0221", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 144, "local_path": "data-flow/inline-intermediate-variables/I12__django__RelatedFieldWidgetWrapper__41242938.py", "order": 12, "original_content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "parent_variant_id": "pyint-616ceda7294f-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/admin/widgets.py#L264-L391", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "RelatedFieldWidgetWrapper", "variant_id": "pyint-5b2741242938-I12", "group_id": "py-d2f83e95b1ce0221", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 111, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7acc041981bf-I13", "source": "import copy\nimport json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import URLValidator\nfrom django.db.models import CASCADE, UUIDField\nfrom django.forms.widgets import Select\nfrom django.urls import reverse\nfrom django.urls.exceptions import NoReverseMatch\nfrom django.utils.html import smart_urlquote\nfrom django.utils.http import urlencode\nfrom django.utils.text import Truncator\nfrom django.utils.translation import get_language\nfrom django.utils.translation import gettext as _\n\nclass RelatedFieldWidgetWrapper(forms.Widget):\n    \"\"\"\n    This class is a wrapper to a given widget to add the add icon for the\n    admin interface.\n    \"\"\"\n\n    template_name = \"admin/widgets/related_widget_wrapper.html\"\n\n    def __init__(\n        self,\n        widget,\n        rel,\n        admin_site,\n        can_add_related=None,\n        can_change_related=False,\n        can_delete_related=False,\n        can_view_related=False,\n    ):\n        self.needs_multipart_form = widget.needs_multipart_form\n        self.attrs = widget.attrs\n        self.widget = widget\n        self.rel = rel\n        # Backwards compatible check for whether a user can add related\n        # objects.\n        if can_add_related is None:\n            can_add_related = admin_site.is_registered(rel.model)\n        self.can_add_related = can_add_related\n        if not isinstance(widget, AutocompleteMixin):\n            self.attrs[\"data-context\"] = \"available-source\"\n        # Only single-select Select widgets are supported.\n        supported = not getattr(\n            widget, \"allow_multiple_selected\", False\n        ) and isinstance(widget, Select)\n        self.can_change_related = supported and can_change_related\n        # XXX: The deletion UX can be confusing when dealing with cascading\n        # deletion.\n        cascade = getattr(rel, \"on_delete\", None) is CASCADE\n        self.can_delete_related = supported and not cascade and can_delete_related\n        self.can_view_related = supported and can_view_related\n        # To check if the related object is registered with this AdminSite.\n        self.admin_site = admin_site\n        self.use_fieldset = widget.use_fieldset\n\n    def __deepcopy__(self, memo):\n        obj = copy.copy(self)\n        obj.widget = copy.deepcopy(self.widget, memo)\n        obj.attrs = self.widget.attrs\n        memo[id(self)] = obj\n        return obj\n\n    @property\n    def is_hidden(self):\n        return self.widget.is_hidden\n\n    @property\n    def media(self):\n        return self.widget.media\n\n    @property\n    def choices(self):\n        return self.widget.choices\n\n    @choices.setter\n    def choices(self, value):\n        self.widget.choices = value\n\n    def get_related_url(self, info, action, *args):\n        return reverse(\n            \"admin:%s_%s_%s\" % (*info, action),\n            current_app=self.admin_site.name,\n            args=args,\n        )\n\n    def get_context(self, name, value, attrs):\n        from django.contrib.admin.views.main import (\n            IS_POPUP_VAR,\n            SOURCE_MODEL_VAR,\n            TO_FIELD_VAR,\n        )\n\n        rel_opts = self.rel.model._meta\n        info = (rel_opts.app_label, rel_opts.model_name)\n        related_field_name = self.rel.get_related_field().name\n        app_label = self.rel.field.model._meta.app_label\n        model_name = self.rel.field.model._meta.model_name\n\n        url_params = \"&\".join(\n            \"%s=%s\" % param\n            for param in [\n                (TO_FIELD_VAR, related_field_name),\n                (IS_POPUP_VAR, 1),\n                (SOURCE_MODEL_VAR, f\"{app_label}.{model_name}\"),\n            ]\n        )\n        context = {\n            \"rendered_widget\": self.widget.render(name, value, attrs),\n            \"is_hidden\": self.is_hidden,\n            \"name\": name,\n            \"url_params\": url_params,\n            \"model\": rel_opts.verbose_name,\n            \"model_name\": rel_opts.model_name,\n            \"can_add_related\": self.can_add_related,\n            \"can_change_related\": self.can_change_related,\n            \"can_delete_related\": self.can_delete_related,\n            \"can_view_related\": self.can_view_related,\n            \"model_has_limit_choices_to\": self.rel.limit_choices_to,\n        }\n        if self.can_add_related:\n            context[\"add_related_url\"] = self.get_related_url(info, \"add\")\n        if self.can_delete_related:\n            context[\"delete_related_template_url\"] = self.get_related_url(\n                info, \"delete\", \"__fk__\"\n            )\n        if self.can_view_related or self.can_change_related:\n            context[\"view_related_url_params\"] = f\"{TO_FIELD_VAR}={related_field_name}\"\n            context[\"change_related_template_url\"] = self.get_related_url(\n                info, \"change\", \"__fk__\"\n            )\n        return context\n\n    def value_from_datadict(self, data, files, name):\n        return self.widget.value_from_datadict(data, files, name)\n\n    def value_omitted_from_data(self, data, files, name):\n        return self.widget.value_omitted_from_data(data, files, name)\n\n    def id_for_label(self, id_):\n        return self.widget.id_for_label(id_)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-d2f83e95b1ce0221", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 144, "local_path": "control-flow/lower-for-to-while/I13__django__RelatedFieldWidgetWrapper__041981bf.py", "order": 13, "original_content_sha256": "a6bda082d8e1d023f9966c9814e4888487da6c0c244a2213e68763e67bd76ca5", "parent_variant_id": "pyint-616ceda7294f-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/admin/widgets.py#L264-L391", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "RelatedFieldWidgetWrapper", "variant_id": "pyint-7acc041981bf-I13", "group_id": "py-d2f83e95b1ce0221", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 112, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-82246794d74c-SRC", "source": "import copy\nimport difflib\nimport functools\nimport sys\nimport warnings\nfrom collections import Counter, namedtuple\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom itertools import chain, count, product\nfrom string import ascii_uppercase\nfrom django.core.exceptions import FieldDoesNotExist, FieldError\nfrom django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections\nfrom django.db.models.aggregates import Count\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import (\n    BaseExpression,\n    Col,\n    ColPairs,\n    Exists,\n    F,\n    OuterRef,\n    RawSQL,\n    Ref,\n    ResolvedOuterRef,\n    Value,\n)\nfrom django.db.models.fields import Field\nfrom django.db.models.lookups import Lookup\nfrom django.db.models.query_utils import (\n    Q,\n    check_rel_lookup_compatibility,\n    refs_expression,\n)\nfrom django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE\nfrom django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin\nfrom django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode\nfrom django.utils.deprecation import RemovedInDjango70Warning\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.tree import Node\nfrom django.utils.warnings import django_file_prefixes\n\nclass Query(BaseExpression):\n    \"\"\"A single SQL query.\"\"\"\n\n    alias_prefix = \"T\"\n    empty_result_set_value = None\n    subq_aliases = frozenset([alias_prefix])\n\n    compiler = \"SQLCompiler\"\n\n    base_table_class = BaseTable\n    join_class = Join\n\n    default_cols = True\n    default_ordering = True\n    standard_ordering = True\n\n    filter_is_sticky = False\n    subquery = False\n    contains_subquery = False\n\n    # SQL-related attributes.\n    # Select and related select clauses are expressions to use in the SELECT\n    # clause of the query. The select is used for cases where we want to set up\n    # the select clause to contain other than default fields (values(),\n    # subqueries...). Note that annotations go to annotations dictionary.\n    select = ()\n    # The group_by attribute can have one of the following forms:\n    #  - None: no group by at all in the query\n    #  - A tuple of expressions: group by (at least) those expressions.\n    #    String refs are also allowed for now.\n    #  - True: group by all select fields of the model\n    # See compiler.get_group_by() for details.\n    group_by = None\n    order_by = ()\n    low_mark = 0  # Used for offset/limit.\n    high_mark = None  # Used for offset/limit.\n    distinct = False\n    distinct_fields = ()\n    select_for_update = False\n    select_for_update_nowait = False\n    select_for_update_skip_locked = False\n    select_for_update_of = ()\n    select_for_no_key_update = False\n    select_related = False\n    # Arbitrary limit for select_related to prevents infinite recursion.\n    max_depth = 5\n    # Holds the selects defined by a call to values() or values_list()\n    # excluding annotation_select and extra_select.\n    values_select = ()\n    selected = None\n\n    # SQL annotation-related attributes.\n    annotation_select_mask = None\n    _annotation_select_cache = None\n\n    # Set combination attributes.\n    combinator = None\n    combinator_all = False\n    combined_queries = ()\n\n    # These are for extensions. The contents are more or less appended verbatim\n    # to the appropriate clause.\n    extra_select_mask = None\n    _extra_select_cache = None\n\n    extra_tables = ()\n    extra_order_by = ()\n\n    # A tuple that is a set of model field names and either True, if these are\n    # the fields to defer, or False if these are the only fields to load.\n    deferred_loading = (frozenset(), True)\n\n    explain_info = None\n\n    def __init__(self, model, alias_cols=True):\n        self.model = model\n        self.alias_refcount = {}\n        # alias_map is the most important data structure regarding joins.\n        # It's used for recording which joins exist in the query and what\n        # types they are. The key is the alias of the joined table (possibly\n        # the table name) and the value is a Join-like object (see\n        # sql.datastructures.Join for more information).\n        self.alias_map = {}\n        # Whether to provide alias to columns during reference resolving.\n        self.alias_cols = alias_cols\n        # Sometimes the query contains references to aliases in outer queries\n        # (as a result of split_exclude). Correct alias quoting needs to know\n        # these aliases too. Map external tables to whether they are aliased.\n        self.external_aliases = {}\n        self.table_map = {}  # Maps table names to list of aliases.\n        self.used_aliases = set()\n\n        self.where = WhereNode()\n        # Maps alias -> Annotation Expression.\n        self.annotations = {}\n        # These are for extensions. The contents are more or less appended\n        # verbatim to the appropriate clause.\n        self.extra = {}  # Maps col_alias -> (col_sql, params).\n\n        self._filtered_relations = {}\n\n    @property\n    def output_field(self):\n        if len(self.select) == 1:\n            select = self.select[0]\n            return getattr(select, \"target\", None) or select.field\n        elif len(self.annotation_select) == 1:\n            return next(iter(self.annotation_select.values())).output_field\n\n    @cached_property\n    def base_table(self):\n        for alias in self.alias_map:\n            return alias\n\n    def __str__(self):\n        \"\"\"\n        Return the query as a string of SQL with the parameter values\n        substituted in (use sql_with_params() to see the unsubstituted string).\n\n        Parameter values won't necessarily be quoted correctly, since that is\n        done by the database interface at execution time.\n        \"\"\"\n        sql, params = self.sql_with_params()\n        return sql % params\n\n    def sql_with_params(self):\n        \"\"\"\n        Return the query as an SQL string and the parameters that will be\n        substituted into the query.\n        \"\"\"\n        return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()\n\n    def __deepcopy__(self, memo):\n        \"\"\"Limit the amount of work when a Query is deepcopied.\"\"\"\n        result = self.clone()\n        memo[id(self)] = result\n        return result\n\n    def get_compiler(self, using=None, connection=None, elide_empty=True):\n        if using is None and connection is None:\n            raise ValueError(\"Need either using or connection\")\n        if using:\n            connection = connections[using]\n        return connection.ops.compiler(self.compiler)(\n            self, connection, using, elide_empty\n        )\n\n    def get_meta(self):\n        \"\"\"\n        Return the Options instance (the model._meta) from which to start\n        processing. Normally, this is self.model._meta, but it can be changed\n        by subclasses.\n        \"\"\"\n        if self.model:\n            return self.model._meta\n\n    def clone(self):\n        \"\"\"\n        Return a copy of the current Query. A lightweight alternative to\n        deepcopy().\n        \"\"\"\n        obj = Empty()\n        obj.__class__ = self.__class__\n        # Copy references to everything.\n        obj.__dict__ = self.__dict__.copy()\n        # Clone attributes that can't use shallow copy.\n        obj.alias_refcount = self.alias_refcount.copy()\n        obj.alias_map = self.alias_map.copy()\n        obj.external_aliases = self.external_aliases.copy()\n        obj.table_map = self.table_map.copy()\n        obj.where = self.where.clone()\n        obj.annotations = self.annotations.copy()\n        if self.annotation_select_mask is not None:\n            obj.annotation_select_mask = self.annotation_select_mask.copy()\n        if self.combined_queries:\n            obj.combined_queries = tuple(\n                [query.clone() for query in self.combined_queries]\n            )\n        # _annotation_select_cache cannot be copied, as doing so breaks the\n        # (necessary) state in which both annotations and\n        # _annotation_select_cache point to the same underlying objects.\n        # It will get re-populated in the cloned queryset the next time it's\n        # used.\n        obj._annotation_select_cache = None\n        obj.extra = self.extra.copy()\n        if self.extra_select_mask is not None:\n            obj.extra_select_mask = self.extra_select_mask.copy()\n        if self._extra_select_cache is not None:\n            obj._extra_select_cache = self._extra_select_cache.copy()\n        if self.select_related is not False:\n            # Use deepcopy because select_related stores fields in nested\n            # dicts.\n            obj.select_related = copy.deepcopy(obj.select_related)\n        if \"subq_aliases\" in self.__dict__:\n            obj.subq_aliases = self.subq_aliases.copy()\n        obj.used_aliases = self.used_aliases.copy()\n        obj._filtered_relations = self._filtered_relations.copy()\n        # Clear the cached_property, if it exists.\n        obj.__dict__.pop(\"base_table\", None)\n        return obj\n\n    def chain(self, klass=None):\n        \"\"\"\n        Return a copy of the current Query that's ready for another operation.\n        The klass argument changes the type of the Query, e.g. UpdateQuery.\n        \"\"\"\n        obj = self.clone()\n        if klass and obj.__class__ != klass:\n            obj.__class__ = klass\n        if not obj.filter_is_sticky:\n            obj.used_aliases = set()\n        obj.filter_is_sticky = False\n        if hasattr(obj, \"_setup_query\"):\n            obj._setup_query()\n        return obj\n\n    def relabeled_clone(self, change_map):\n        clone = self.clone()\n        clone.change_aliases(change_map)\n        return clone\n\n    def _get_col(self, target, field, alias):\n        if not self.alias_cols:\n            alias = None\n        return target.get_col(alias, field)\n\n    def get_aggregation(self, using, aggregate_exprs):\n        \"\"\"\n        Return the dictionary with the values of the existing aggregations.\n        \"\"\"\n        if not aggregate_exprs:\n            return {}\n        # Store annotation mask prior to temporarily adding aggregations for\n        # resolving purpose to facilitate their subsequent removal.\n        refs_subquery = False\n        refs_window = False\n        replacements = {}\n        annotation_select_mask = self.annotation_select_mask\n        for alias, aggregate_expr in aggregate_exprs.items():\n            self.check_alias(alias)\n            aggregate = aggregate_expr.resolve_expression(\n                self, allow_joins=True, reuse=None, summarize=True\n            )\n            if not aggregate.contains_aggregate:\n                raise TypeError(\"%s is not an aggregate expression\" % alias)\n            # Temporarily add aggregate to annotations to allow remaining\n            # members of `aggregates` to resolve against each others.\n            self.append_annotation_mask([alias])\n            aggregate_refs = aggregate.get_refs()\n            refs_subquery |= any(\n                getattr(self.annotations[ref], \"contains_subquery\", False)\n                for ref in aggregate_refs\n            )\n            refs_window |= any(\n                getattr(self.annotations[ref], \"contains_over_clause\", True)\n                for ref in aggregate_refs\n            )\n            aggregate = aggregate.replace_expressions(replacements)\n            self.annotations[alias] = aggregate\n            replacements[Ref(alias, aggregate)] = aggregate\n        # Stash resolved aggregates now that they have been allowed to resolve\n        # against each other.\n        aggregates = {alias: self.annotations.pop(alias) for alias in aggregate_exprs}\n        self.set_annotation_mask(annotation_select_mask)\n        # Existing usage of aggregation can be determined by the presence of\n        # selected aggregates but also by filters against aliased aggregates.\n        _, having, qualify = self.where.split_having_qualify()\n        has_existing_aggregation = (\n            any(\n                getattr(annotation, \"contains_aggregate\", True)\n                for annotation in self.annotations.values()\n            )\n            or having\n        )\n        set_returning_annotations = {\n            alias\n            for alias, annotation in self.annotation_select.items()\n            if getattr(annotation, \"set_returning\", False)\n        }\n        # Decide if we need to use a subquery.\n        #\n        # Existing aggregations would cause incorrect results as\n        # get_aggregation() must produce just one result and thus must not use\n        # GROUP BY.\n        #\n        # If the query has limit or distinct, or uses set operations, then\n        # those operations must be done in a subquery so that the query\n        # aggregates on the limit and/or distinct results instead of applying\n        # the distinct and limit after the aggregation.\n        if (\n            isinstance(self.group_by, tuple)\n            or self.is_sliced\n            or has_existing_aggregation\n            or refs_subquery\n            or refs_window\n            or qualify\n            or self.distinct\n            or self.combinator\n            or set_returning_annotations\n        ):\n            from django.db.models.sql.subqueries import AggregateQuery\n\n            inner_query = self.clone()\n            inner_query.subquery = True\n            outer_query = AggregateQuery(self.model, inner_query)\n            inner_query.select_for_update = False\n            inner_query.select_related = False\n            inner_query.set_annotation_mask(self.annotation_select)\n            # Queries with distinct_fields need ordering and when a limit is\n            # applied we must take the slice from the ordered query. Otherwise\n            # no need for ordering.\n            if inner_query.orderby_issubset_groupby:\n                inner_query.clear_ordering(force=False)\n            if not inner_query.distinct:\n                # If the inner query uses default select and it has some\n                # aggregate annotations, then we must make sure the inner\n                # query is grouped by the main model's primary key. However,\n                # clearing the select clause can alter results if distinct is\n                # used.\n                if inner_query.default_cols and has_existing_aggregation:\n                    inner_query.group_by = (\n                        self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                    )\n                inner_query.default_cols = False\n                if not qualify and not self.combinator:\n                    # Mask existing annotations that are not referenced by\n                    # aggregates to be pushed to the outer query unless\n                    # filtering against window functions or if the query is\n                    # combined as both would require complex realiasing logic.\n                    annotation_mask = set()\n                    if isinstance(self.group_by, tuple):\n                        for expr in self.group_by:\n                            annotation_mask |= expr.get_refs()\n                    for aggregate in aggregates.values():\n                        annotation_mask |= aggregate.get_refs()\n                    # Avoid eliding expressions that might have an incidence on\n                    # the implicit grouping logic.\n                    for annotation_alias, annotation in self.annotation_select.items():\n                        if annotation.get_group_by_cols():\n                            annotation_mask.add(annotation_alias)\n                    inner_query.set_annotation_mask(annotation_mask)\n                    # Annotations that possibly return multiple rows cannot\n                    # be masked as they might have an incidence on the query.\n                    annotation_mask |= set_returning_annotations\n\n            # Add aggregates to the outer AggregateQuery. This requires making\n            # sure all columns referenced by the aggregates are selected in the\n            # inner query. It is achieved by retrieving all column references\n            # by the aggregates, explicitly selecting them in the inner query,\n            # and making sure the aggregates are repointed to them.\n            col_refs = {}\n            for alias, aggregate in aggregates.items():\n                replacements = {}\n                for col in self._gen_cols([aggregate], resolve_refs=False):\n                    if not (col_ref := col_refs.get(col)):\n                        index = len(col_refs) + 1\n                        col_alias = f\"__col{index}\"\n                        col_ref = Ref(col_alias, col)\n                        col_refs[col] = col_ref\n                        inner_query.add_annotation(col, col_alias)\n                    replacements[col] = col_ref\n                outer_query.annotations[alias] = aggregate.replace_expressions(\n                    replacements\n                )\n            if (\n                inner_query.select == ()\n                and not inner_query.default_cols\n                and not inner_query.annotation_select_mask\n            ):\n                # In case of Model.objects[0:3].count(), there would be no\n                # field selected in the inner query, yet we must use a\n                # subquery. So, make sure at least one field is selected.\n                inner_query.select = (\n                    self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                )\n        else:\n            outer_query = self\n            self.select = ()\n            self.selected = None\n            self.default_cols = False\n            self.extra = {}\n            if self.annotations:\n                # Inline reference to existing annotations and mask them as\n                # they are unnecessary given only the summarized aggregations\n                # are requested.\n                replacements = {\n                    Ref(alias, annotation): annotation\n                    for alias, annotation in self.annotations.items()\n                }\n                self.annotations = {\n                    alias: aggregate.replace_expressions(replacements)\n                    for alias, aggregate in aggregates.items()\n                }\n            else:\n                self.annotations = aggregates\n            self.set_annotation_mask(aggregates)\n\n        empty_set_result = [\n            expression.empty_result_set_value\n            for expression in outer_query.annotation_select.values()\n        ]\n        elide_empty = not any(result is NotImplemented for result in empty_set_result)\n        outer_query.clear_ordering(force=True)\n        outer_query.clear_limits()\n        outer_query.select_for_update = False\n        outer_query.select_related = False\n        compiler = outer_query.get_compiler(using, elide_empty=elide_empty)\n        result = compiler.execute_sql(SINGLE)\n        if result is None:\n            result = empty_set_result\n        else:\n            cols = outer_query.annotation_select.values()\n            converters = compiler.get_converters(cols)\n            rows = compiler.apply_converters((result,), converters)\n            if compiler.has_composite_fields(cols):\n                rows = compiler.composite_fields_to_tuples(rows, cols)\n            result = next(rows)\n\n        return dict(zip(outer_query.annotation_select, result))\n\n    def get_count(self, using):\n        \"\"\"\n        Perform a COUNT() query using the current filter constraints.\n        \"\"\"\n        obj = self.clone()\n        return obj.get_aggregation(using, {\"__count\": Count(\"*\")})[\"__count\"]\n\n    def has_filters(self):\n        return self.where\n\n    def exists(self, limit=True):\n        q = self.clone()\n        if not (q.distinct and q.is_sliced):\n            if q.group_by is True:\n                q.add_fields(\n                    (f.attname for f in self.model._meta.concrete_fields), False\n                )\n                # Disable GROUP BY aliases to avoid orphaning references to the\n                # SELECT clause which is about to be cleared.\n                q.set_group_by(allow_aliases=False)\n            q.clear_select_clause()\n        if q.combined_queries and q.combinator == \"union\":\n            q.combined_queries = tuple(\n                combined_query.exists(limit=False)\n                for combined_query in q.combined_queries\n            )\n        q.clear_ordering(force=True)\n        if limit is True:\n            q.set_limits(high=1)\n        q.add_annotation(Value(1), \"a\")\n        return q\n\n    def has_results(self, using):\n        q = self.exists()\n        compiler = q.get_compiler(using=using)\n        return compiler.has_results()\n\n    def explain(self, using, format=None, **options):\n        q = self.clone()\n        for option_name in options:\n            if (\n                not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)\n                or \"--\" in option_name\n            ):\n                raise ValueError(f\"Invalid option name: {option_name!r}.\")\n        q.explain_info = ExplainInfo(format, options)\n        compiler = q.get_compiler(using=using)\n        return \"\\n\".join(compiler.explain_query())\n\n    def combine(self, rhs, connector):\n        \"\"\"\n        Merge the 'rhs' query into the current one (with any 'rhs' effects\n        being applied *after* (that is, \"to the right of\") anything in the\n        current query. 'rhs' is not modified during a call to this function.\n\n        The 'connector' parameter describes how to connect filters from the\n        'rhs' query.\n        \"\"\"\n        if self.model != rhs.model:\n            raise TypeError(\"Cannot combine queries on two different base models.\")\n        if self.is_sliced:\n            raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n        if self.distinct != rhs.distinct:\n            raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n        if self.distinct_fields != rhs.distinct_fields:\n            raise TypeError(\"Cannot combine queries with different distinct fields.\")\n\n        # If lhs and rhs shares the same alias prefix, it is possible to have\n        # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up\n        # as T4 -> T6 while combining two querysets. To prevent this, change an\n        # alias prefix of the rhs and update current aliases accordingly,\n        # except if the alias is the base table since it must be present in the\n        # query on both sides.\n        initial_alias = self.get_initial_alias()\n        rhs = rhs.clone()\n        rhs.bump_prefix(self, exclude={initial_alias})\n\n        # Work out how to relabel the rhs aliases, if necessary.\n        change_map = {}\n        conjunction = connector == AND\n\n        # Determine which existing joins can be reused. When combining the\n        # query with AND we must recreate all joins for m2m filters. When\n        # combining with OR we can reuse joins. The reason is that in AND\n        # case a single row can't fulfill a condition like:\n        #     revrel__col=1 & revrel__col=2\n        # But, there might be two different related rows matching this\n        # condition. In OR case a single True is enough, so single row is\n        # enough, too.\n        #\n        # Note that we will be creating duplicate joins for non-m2m joins in\n        # the AND case. The results will be correct but this creates too many\n        # joins. This is something that could be fixed later on.\n        reuse = set() if conjunction else set(self.alias_map)\n        joinpromoter = JoinPromoter(connector, 2, False)\n        joinpromoter.add_votes(\n            j for j in self.alias_map if self.alias_map[j].join_type == INNER\n        )\n        rhs_votes = set()\n        # Now, add the joins from rhs query into the new query (skipping base\n        # table).\n        rhs_tables = list(rhs.alias_map)[1:]\n        for alias in rhs_tables:\n            join = rhs.alias_map[alias]\n            # If the left side of the join was already relabeled, use the\n            # updated alias.\n            join = join.relabeled_clone(change_map)\n            new_alias = self.join(join, reuse=reuse)\n            if join.join_type == INNER:\n                rhs_votes.add(new_alias)\n            # We can't reuse the same join again in the query. If we have two\n            # distinct joins for the same connection in rhs query, then the\n            # combined query must have two joins, too.\n            reuse.discard(new_alias)\n            if alias != new_alias:\n                change_map[alias] = new_alias\n            if not rhs.alias_refcount[alias]:\n                # The alias was unused in the rhs query. Unref it so that it\n                # will be unused in the new query, too. We have to add and\n                # unref the alias so that join promotion has information of\n                # the join type for the unused alias.\n                self.unref_alias(new_alias)\n        joinpromoter.add_votes(rhs_votes)\n        joinpromoter.update_join_types(self)\n\n        # Combine subqueries aliases to ensure aliases relabelling properly\n        # handle subqueries when combining where and select clauses.\n        self.subq_aliases |= rhs.subq_aliases\n\n        # Now relabel a copy of the rhs where-clause and add it to the current\n        # one.\n        w = rhs.where.clone()\n        w.relabel_aliases(change_map)\n        self.where.add(w, connector)\n\n        # Selection columns and extra extensions are those provided by 'rhs'.\n        if rhs.select:\n            self.set_select([col.relabeled_clone(change_map) for col in rhs.select])\n        else:\n            self.select = ()\n\n        if connector == OR:\n            # It would be nice to be able to handle this, but the queries don't\n            # really make sense (or return consistent value sets). Not worth\n            # the extra complexity when you can write a real query instead.\n            if self.extra and rhs.extra:\n                raise ValueError(\n                    \"When merging querysets using 'or', you cannot have \"\n                    \"extra(select=...) on both sides.\"\n                )\n        self.extra.update(rhs.extra)\n        extra_select_mask = set()\n        if self.extra_select_mask is not None:\n            extra_select_mask.update(self.extra_select_mask)\n        if rhs.extra_select_mask is not None:\n            extra_select_mask.update(rhs.extra_select_mask)\n        if extra_select_mask:\n            self.set_extra_mask(extra_select_mask)\n        self.extra_tables += rhs.extra_tables\n\n        # Ordering uses the 'rhs' ordering, unless it has none, in which case\n        # the current ordering is used.\n        self.order_by = rhs.order_by or self.order_by\n        self.extra_order_by = rhs.extra_order_by or self.extra_order_by\n\n    def _get_defer_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # All concrete fields and related objects that are not part of the\n        # defer mask must be included. If a relational field is encountered it\n        # gets added to the mask for it be considered if `select_related` and\n        # the cycle continues by recursively calling this function.\n        for field in opts.concrete_fields + opts.related_objects:\n            field_mask = mask.pop(field.name, None)\n            field_att_mask = None\n            if field_attname := getattr(field, \"attname\", None):\n                field_att_mask = mask.pop(field_attname, None)\n            if field_mask is None and field_att_mask is None:\n                select_mask.setdefault(field, {})\n            elif field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                # Virtual fields such as many-to-many and generic foreign keys\n                # cannot be effectively deferred. Historically, they were\n                # allowed to be passed to QuerySet.defer(). Ignore such field\n                # references until a layer of validation at mask alteration\n                # time is eventually implemented.\n                if field.many_to_many:\n                    continue\n                field_select_mask = select_mask.setdefault(field, {})\n                related_model = field.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        # Remaining defer entries must be references to filtered relations\n        # otherwise they are surfaced as missing field errors.\n        for field_name, field_mask in mask.items():\n            if filtered_relation := self._filtered_relations.get(field_name):\n                relation = opts.get_field(filtered_relation.relation_name)\n                field_select_mask = select_mask.setdefault((field_name, relation), {})\n                related_model = relation.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n            else:\n                opts.get_field(field_name)\n        return select_mask\n\n    def _get_only_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # Only include fields mentioned in the mask.\n        for field_name, field_mask in mask.items():\n            field = opts.get_field(field_name)\n            field_select_mask = select_mask.setdefault(field, {})\n            if field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                related_model = field.remote_field.model._meta.concrete_model\n                self._get_only_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        return select_mask\n\n    def get_select_mask(self):\n        \"\"\"\n        Convert the self.deferred_loading data structure to an alternate data\n        structure, describing the field that *will* be loaded. This is used to\n        compute the columns to select from the database and also by the\n        QuerySet class to work out which fields are being initialized on each\n        model. Models that have all their fields included aren't mentioned in\n        the result, only those that have field restrictions in place.\n        \"\"\"\n        field_names, defer = self.deferred_loading\n        if not field_names:\n            return {}\n        mask = {}\n        for field_name in field_names:\n            part_mask = mask\n            for part in field_name.split(LOOKUP_SEP):\n                part_mask = part_mask.setdefault(part, {})\n        opts = self.get_meta()\n        if defer:\n            return self._get_defer_select_mask(opts, mask)\n        return self._get_only_select_mask(opts, mask)\n\n    def table_alias(self, table_name, create=False, filtered_relation=None):\n        \"\"\"\n        Return a table alias for the given table_name and whether this is a\n        new alias or not.\n\n        If 'create' is true, a new alias is always created. Otherwise, the\n        most recently created alias for the table (if one exists) is reused.\n        \"\"\"\n        alias_list = self.table_map.get(table_name)\n        if not create and alias_list:\n            alias = alias_list[0]\n            self.alias_refcount[alias] += 1\n            return alias, False\n\n        # Create a new alias for this table.\n        if alias_list:\n            alias = \"%s%d\" % (self.alias_prefix, len(self.alias_map) + 1)\n            alias_list.append(alias)\n        else:\n            # The first occurrence of a table uses the table name directly.\n            alias = (\n                filtered_relation.alias if filtered_relation is not None else table_name\n            )\n            self.table_map[table_name] = [alias]\n        self.alias_refcount[alias] = 1\n        return alias, True\n\n    def ref_alias(self, alias):\n        \"\"\"Increases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] += 1\n\n    def unref_alias(self, alias, amount=1):\n        \"\"\"Decreases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] -= amount\n\n    def promote_joins(self, aliases):\n        \"\"\"\n        Promote recursively the join type of given aliases and its children to\n        an outer join. If 'unconditional' is False, only promote the join if\n        it is nullable or the parent join is an outer join.\n\n        The children promotion is done to avoid join chains that contain a\n        LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b\n        is promoted, then we must also promote b->c automatically, or otherwise\n        the promotion of a->b doesn't actually change anything in the query\n        results.\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type is None:\n                # This is the base table (first FROM entry) - this table\n                # isn't really joined at all in the query, so we should not\n                # alter its join type.\n                continue\n            # Only the first alias (skipped above) should have None join_type\n            assert self.alias_map[alias].join_type is not None\n            parent_alias = self.alias_map[alias].parent_alias\n            parent_louter = (\n                parent_alias and self.alias_map[parent_alias].join_type == LOUTER\n            )\n            already_louter = self.alias_map[alias].join_type == LOUTER\n            if (self.alias_map[alias].nullable or parent_louter) and not already_louter:\n                self.alias_map[alias] = self.alias_map[alias].promote()\n                # Join type of 'alias' changed, so re-examine all aliases that\n                # refer to this one.\n                aliases.extend(\n                    join\n                    for join in self.alias_map\n                    if self.alias_map[join].parent_alias == alias\n                    and join not in aliases\n                )\n\n    def demote_joins(self, aliases):\n        \"\"\"\n        Change join type from LOUTER to INNER for all joins in aliases.\n\n        Similarly to promote_joins(), this method must ensure no join chains\n        containing first an outer, then an inner join are generated. If we\n        are demoting b->c join in chain a LOUTER b LOUTER c then we must\n        demote a->b automatically, or otherwise the demotion of b->c doesn't\n        actually change anything in the query results. .\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type == LOUTER:\n                self.alias_map[alias] = self.alias_map[alias].demote()\n                parent_alias = self.alias_map[alias].parent_alias\n                if self.alias_map[parent_alias].join_type == INNER:\n                    aliases.append(parent_alias)\n\n    def reset_refcounts(self, to_counts):\n        \"\"\"\n        Reset reference counts for aliases so that they match the value passed\n        in `to_counts`.\n        \"\"\"\n        for alias, cur_refcount in self.alias_refcount.copy().items():\n            unref_amount = cur_refcount - to_counts.get(alias, 0)\n            self.unref_alias(alias, unref_amount)\n\n    def change_aliases(self, change_map):\n        \"\"\"\n        Change the aliases in change_map (which maps old-alias -> new-alias),\n        relabelling any references to them in select columns and the where\n        clause.\n        \"\"\"\n        if not change_map:\n            return self\n        # If keys and values of change_map were to intersect, an alias might be\n        # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending\n        # on their order in change_map.\n        assert set(change_map).isdisjoint(change_map.values())\n\n        # 1. Update references in \"select\" (normal columns plus aliases),\n        # \"group by\" and \"where\".\n        self.where.relabel_aliases(change_map)\n        if isinstance(self.group_by, tuple):\n            self.group_by = tuple(\n                [col.relabeled_clone(change_map) for col in self.group_by]\n            )\n        self.select = tuple([col.relabeled_clone(change_map) for col in self.select])\n        self.annotations = self.annotations and {\n            key: col.relabeled_clone(change_map)\n            for key, col in self.annotations.items()\n        }\n\n        # 2. Rename the alias in the internal table/alias datastructures.\n        for old_alias, new_alias in change_map.items():\n            if old_alias not in self.alias_map:\n                continue\n            alias_data = self.alias_map[old_alias].relabeled_clone(change_map)\n            self.alias_map[new_alias] = alias_data\n            self.alias_refcount[new_alias] = self.alias_refcount[old_alias]\n            del self.alias_refcount[old_alias]\n            del self.alias_map[old_alias]\n\n            table_aliases = self.table_map[alias_data.table_name]\n            for pos, alias in enumerate(table_aliases):\n                if alias == old_alias:\n                    table_aliases[pos] = new_alias\n                    break\n\n        # 3. Rename the direct external aliases and the ones of combined\n        # queries (union, intersection, difference).\n        self.external_aliases = {\n            # Table is aliased or it's being changed and thus is aliased.\n            change_map.get(alias, alias): (aliased or alias in change_map)\n            for alias, aliased in self.external_aliases.items()\n        }\n        for combined_query in self.combined_queries:\n            external_change_map = {\n                alias: aliased\n                for alias, aliased in change_map.items()\n                if alias in combined_query.external_aliases\n            }\n            combined_query.change_aliases(external_change_map)\n\n    def bump_prefix(self, other_query, exclude=None):\n        \"\"\"\n        Change the alias prefix to the next letter in the alphabet in a way\n        that the other query's aliases and this query's aliases will not\n        conflict. Even tables that previously had no alias will get an alias\n        after this call. To prevent changing aliases use the exclude parameter.\n        \"\"\"\n\n        def prefix_gen():\n            \"\"\"\n            Generate a sequence of characters in alphabetical order:\n                -> 'A', 'B', 'C', ...\n\n            When the alphabet is finished, the sequence will continue with the\n            Cartesian product:\n                -> 'AA', 'AB', 'AC', ...\n            \"\"\"\n            alphabet = ascii_uppercase\n            prefix = chr(ord(self.alias_prefix) + 1)\n            yield prefix\n            for n in count(1):\n                seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet\n                for s in product(seq, repeat=n):\n                    yield \"\".join(s)\n                prefix = None\n\n        if self.alias_prefix != other_query.alias_prefix:\n            # No clashes between self and outer query should be possible.\n            return\n\n        # Explicitly avoid infinite loop. The constant divider is based on how\n        # much depth recursive subquery references add to the stack. This value\n        # might need to be adjusted when adding or removing function calls from\n        # the code path in charge of performing these operations.\n        local_recursion_limit = sys.getrecursionlimit() // 16\n        for pos, prefix in enumerate(prefix_gen()):\n            if prefix not in self.subq_aliases:\n                self.alias_prefix = prefix\n                break\n            if pos > local_recursion_limit:\n                raise RecursionError(\n                    \"Maximum recursion depth exceeded: too many subqueries.\"\n                )\n        self.subq_aliases = self.subq_aliases.union([self.alias_prefix])\n        other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases)\n        if exclude is None:\n            exclude = {}\n        self.change_aliases(\n            {\n                alias: \"%s%d\" % (self.alias_prefix, pos)\n                for pos, alias in enumerate(self.alias_map)\n                if alias not in exclude\n            }\n        )\n\n    def get_initial_alias(self):\n        \"\"\"\n        Return the first alias for this query, after increasing its reference\n        count.\n        \"\"\"\n        if self.alias_map:\n            alias = self.base_table\n            self.ref_alias(alias)\n        elif self.model:\n            alias = self.join(self.base_table_class(self.get_meta().db_table, None))\n        else:\n            alias = None\n        return alias\n\n    def count_active_tables(self):\n        \"\"\"\n        Return the number of tables in this query with a non-zero reference\n        count. After execution, the reference counts are zeroed, so tables\n        added in compiler will not be seen by this method.\n        \"\"\"\n        return len([1 for count in self.alias_refcount.values() if count])\n\n    def join(self, join, reuse=None):\n        \"\"\"\n        Return an alias for the 'join', either reusing an existing alias for\n        that join or creating a new one. 'join' is either a base_table_class or\n        join_class.\n\n        The 'reuse' parameter can be either None which means all joins are\n        reusable, or it can be a set containing the aliases that can be reused.\n\n        A join is always created as LOUTER if the lhs alias is LOUTER to make\n        sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new\n        joins are created as LOUTER if the join is nullable.\n        \"\"\"\n        reuse_aliases = [\n            a\n            for a, j in self.alias_map.items()\n            if (reuse is None or a in reuse) and j == join\n        ]\n        if reuse_aliases:\n            if join.table_alias in reuse_aliases:\n                reuse_alias = join.table_alias\n            else:\n                # Reuse the most recent alias of the joined table\n                # (a many-to-many relation may be joined multiple times).\n                reuse_alias = reuse_aliases[-1]\n            self.ref_alias(reuse_alias)\n            return reuse_alias\n\n        # No reuse is possible, so we need a new alias.\n        alias, _ = self.table_alias(\n            join.table_name, create=True, filtered_relation=join.filtered_relation\n        )\n        if join.join_type:\n            if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:\n                join_type = LOUTER\n            else:\n                join_type = INNER\n            join.join_type = join_type\n        join.table_alias = alias\n        self.alias_map[alias] = join\n        if filtered_relation := join.filtered_relation:\n            resolve_reuse = reuse\n            if resolve_reuse is not None:\n                resolve_reuse = set(reuse) | {alias}\n            joins_len = len(self.alias_map)\n            join.filtered_relation = filtered_relation.resolve_expression(\n                self, reuse=resolve_reuse\n            )\n            # Some joins were during expression resolving, they must be present\n            # before the one we just added.\n            if joins_len < len(self.alias_map):\n                self.alias_map[alias] = self.alias_map.pop(alias)\n        return alias\n\n    def join_parent_model(self, opts, model, alias, seen):\n        \"\"\"\n        Make sure the given 'model' is joined in the query. If 'model' isn't\n        a parent of 'opts' or if it is None this method is a no-op.\n\n        The 'alias' is the root alias for starting the join, 'seen' is a dict\n        of model -> alias of existing joins. It must also contain a mapping\n        of None -> some alias. This will be returned in the no-op case.\n        \"\"\"\n        if model in seen:\n            return seen[model]\n        chain = opts.get_base_chain(model)\n        if not chain:\n            return alias\n        curr_opts = opts\n        for int_model in chain:\n            if int_model in seen:\n                curr_opts = int_model._meta\n                alias = seen[int_model]\n                continue\n            # Proxy model have elements in base chain\n            # with no parents, assign the new options\n            # object and skip to the next base in that\n            # case\n            if not curr_opts.parents[int_model]:\n                curr_opts = int_model._meta\n                continue\n            link_field = curr_opts.get_ancestor_link(int_model)\n            join_info = self.setup_joins([link_field.name], curr_opts, alias)\n            curr_opts = int_model._meta\n            alias = seen[int_model] = join_info.joins[-1]\n        return alias or seen[None]\n\n    def check_alias(self, alias):\n        # RemovedInDjango70Warning: When the deprecation ends, remove.\n        if \"%\" in alias:\n            warnings.warn(\n                \"Using percent signs in a column alias is deprecated.\",\n                category=RemovedInDjango70Warning,\n                skip_file_prefixes=django_file_prefixes(),\n            )\n        if FORBIDDEN_ALIAS_PATTERN.search(alias):\n            raise ValueError(\n                \"Column aliases cannot contain whitespace characters, hashes, \"\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # \"control characters, quotation marks, semicolons, percent \"\n                # \"signs, or SQL comments.\"\n                \"control characters, quotation marks, semicolons, or SQL comments.\"\n            )\n\n    def add_annotation(self, annotation, alias, select=True):\n        \"\"\"Add a single annotation expression to the Query.\"\"\"\n        self.check_alias(alias)\n        annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None)\n        if select:\n            self.append_annotation_mask([alias])\n        else:\n            self.set_annotation_mask(set(self.annotation_select).difference({alias}))\n        self.annotations[alias] = annotation\n        if select and self.selected:\n            self.selected[alias] = alias\n\n    @property\n    def _subquery_fields_len(self):\n        if not self.has_select_fields or not self.select:\n            return len(self.model._meta.pk_fields)\n        return len(self.select) + sum(\n            len(expr.targets) - 1 for expr in self.select if isinstance(expr, ColPairs)\n        )\n\n    def resolve_expression(self, query, *args, **kwargs):\n        clone = self.clone()\n        # Subqueries need to use a different set of aliases than the outer\n        # query.\n        clone.bump_prefix(query)\n        clone.subquery = True\n        clone.where.resolve_expression(query, *args, **kwargs)\n        # Resolve combined queries.\n        if clone.combinator:\n            clone.combined_queries = tuple(\n                [\n                    combined_query.resolve_expression(query, *args, **kwargs)\n                    for combined_query in clone.combined_queries\n                ]\n            )\n        for key, value in clone.annotations.items():\n            resolved = value.resolve_expression(query, *args, **kwargs)\n            if hasattr(resolved, \"external_aliases\"):\n                resolved.external_aliases.update(clone.external_aliases)\n            clone.annotations[key] = resolved\n        # Outer query's aliases are considered external.\n        for alias, table in query.alias_map.items():\n            clone.external_aliases[alias] = (\n                isinstance(table, Join)\n                and table.join_field.related_model._meta.db_table != alias\n            ) or (\n                isinstance(table, BaseTable) and table.table_name != table.table_alias\n            )\n        return clone\n\n    def get_external_cols(self):\n        exprs = chain(self.annotations.values(), self.where.children)\n        return [\n            col\n            for col in self._gen_cols(exprs, include_external=True)\n            if col.alias in self.external_aliases\n        ]\n\n    def get_group_by_cols(self, wrapper=None):\n        # If wrapper is referenced by an alias for an explicit GROUP BY through\n        # values() a reference to this expression and not the self must be\n        # returned to ensure external column references are not grouped against\n        # as well.\n        external_cols = self.get_external_cols()\n        if any(col.possibly_multivalued for col in external_cols):\n            return [wrapper or self]\n        return external_cols\n\n    def as_sql(self, compiler, connection):\n        # Some backends (e.g. Oracle) raise an error when a subquery contains\n        # unnecessary ORDER BY clause.\n        if (\n            self.subquery\n            and not connection.features.ignores_unnecessary_order_by_in_subqueries\n        ):\n            self.clear_ordering(force=False)\n            for query in self.combined_queries:\n                query.clear_ordering(force=False)\n        sql, params = self.get_compiler(connection=connection).as_sql()\n        if self.subquery:\n            sql = \"(%s)\" % sql\n        return sql, params\n\n    def resolve_lookup_value(self, value, can_reuse, allow_joins, summarize=False):\n        if hasattr(value, \"resolve_expression\"):\n            value = value.resolve_expression(\n                self,\n                reuse=can_reuse,\n                allow_joins=allow_joins,\n                summarize=summarize,\n            )\n        elif isinstance(value, (list, tuple)):\n            # The items of the iterable may be expressions and therefore need\n            # to be resolved independently.\n            values = (\n                self.resolve_lookup_value(sub_value, can_reuse, allow_joins, summarize)\n                for sub_value in value\n            )\n            type_ = type(value)\n            if hasattr(type_, \"_make\"):  # namedtuple\n                return type_(*values)\n            return type_(values)\n        return value\n\n    def solve_lookup_type(self, lookup, summarize=False):\n        \"\"\"\n        Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').\n        \"\"\"\n        lookup_splitted = lookup.split(LOOKUP_SEP)\n        if self.annotations:\n            annotation, expression_lookups = refs_expression(\n                lookup_splitted, self.annotations\n            )\n            if annotation:\n                expression = self.annotations[annotation]\n                if summarize:\n                    expression = Ref(annotation, expression)\n                return expression_lookups, (), expression\n        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())\n        field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)]\n        if len(lookup_parts) > 1 and not field_parts:\n            raise FieldError(\n                'Invalid lookup \"%s\" for model %s\".'\n                % (lookup, self.get_meta().model.__name__)\n            )\n        return lookup_parts, field_parts, False\n\n    def check_query_object_type(self, value, opts, field):\n        \"\"\"\n        Check whether the object passed while querying is of the correct type.\n        If not, raise a ValueError specifying the wrong object.\n        \"\"\"\n        if hasattr(value, \"_meta\"):\n            if not check_rel_lookup_compatibility(value._meta.model, opts, field):\n                raise ValueError(\n                    'Cannot query \"%s\": Must be \"%s\" instance.'\n                    % (value, opts.object_name)\n                )\n\n    def check_related_objects(self, field, value, opts):\n        \"\"\"Check the type of object passed to query relations.\"\"\"\n        if field.is_relation:\n            # Check that the field and the queryset use the same model in a\n            # query like .filter(author=Author.objects.all()). For example, the\n            # opts would be Author's (from the author field) and value.model\n            # would be Author.objects.all() queryset's .model (Author also).\n            # The field is the related field on the lhs side.\n            if (\n                isinstance(value, Query)\n                and not value.has_select_fields\n                and not check_rel_lookup_compatibility(value.model, opts, field)\n            ):\n                raise ValueError(\n                    'Cannot use QuerySet for \"%s\": Use a QuerySet for \"%s\".'\n                    % (value.model._meta.object_name, opts.object_name)\n                )\n            elif hasattr(value, \"_meta\"):\n                self.check_query_object_type(value, opts, field)\n            elif hasattr(value, \"__iter__\"):\n                for v in value:\n                    self.check_query_object_type(v, opts, field)\n\n    def check_filterable(self, expression):\n        \"\"\"Raise an error if expression cannot be used in a WHERE clause.\"\"\"\n        if hasattr(expression, \"resolve_expression\") and not getattr(\n            expression, \"filterable\", True\n        ):\n            raise NotSupportedError(\n                expression.__class__.__name__ + \" is disallowed in the filter \"\n                \"clause.\"\n            )\n        if hasattr(expression, \"get_source_expressions\"):\n            for expr in expression.get_source_expressions():\n                self.check_filterable(expr)\n\n    def build_lookup(self, lookups, lhs, rhs):\n        \"\"\"\n        Try to extract transforms and lookup from given lhs.\n\n        The lhs value is something that works like SQLExpression.\n        The rhs value is what the lookup is going to compare against.\n        The lookups is a list of names to extract using get_lookup()\n        and get_transform().\n        \"\"\"\n        # __exact is the default lookup if one isn't given.\n        *transforms, lookup_name = lookups or [\"exact\"]\n        for name in transforms:\n            lhs = self.try_transform(lhs, name, lookups)\n        # First try get_lookup() so that the lookup takes precedence if the lhs\n        # supports both transform and lookup for the name.\n        lookup_class = lhs.get_lookup(lookup_name)\n        if not lookup_class:\n            # A lookup wasn't found. Try to interpret the name as a transform\n            # and do an Exact lookup against it.\n            lhs = self.try_transform(lhs, lookup_name)\n            lookup_name = \"exact\"\n            lookup_class = lhs.get_lookup(lookup_name)\n            if not lookup_class:\n                return\n\n        lookup = lookup_class(lhs, rhs)\n        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all\n        # uses of None as a query value unless the lookup supports it.\n        if lookup.rhs is None and not lookup.can_use_none_as_rhs:\n            if lookup_name not in (\"exact\", \"iexact\"):\n                raise ValueError(\"Cannot use None as a query value\")\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        # For Oracle '' is equivalent to null. The check must be done at this\n        # stage because join promotion can't be done in the compiler. Using\n        # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.\n        # A similar thing is done in is_nullable(), too.\n        if (\n            lookup_name in (\"exact\", \"iexact\")\n            and lookup.rhs == \"\"\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        ):\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        return lookup\n\n    def try_transform(self, lhs, name, lookups=None):\n        \"\"\"\n        Helper method for build_lookup(). Try to fetch and initialize\n        a transform for name parameter from lhs.\n        \"\"\"\n        transform_class = lhs.get_transform(name)\n        if transform_class:\n            return transform_class(lhs)\n        else:\n            output_field = lhs.output_field.__class__\n            suggested_lookups = difflib.get_close_matches(\n                name, lhs.output_field.get_lookups()\n            )\n            if suggested_lookups:\n                suggestion = \", perhaps you meant %s?\" % \" or \".join(suggested_lookups)\n            else:\n                suggestion = \".\"\n            if lookups is not None:\n                name_index = lookups.index(name)\n                unsupported_lookup = LOOKUP_SEP.join(lookups[name_index:])\n            else:\n                unsupported_lookup = name\n            raise FieldError(\n                \"Unsupported lookup '%s' for %s or join on the field not \"\n                \"permitted%s\" % (unsupported_lookup, output_field.__name__, suggestion)\n            )\n\n    def build_filter(\n        self,\n        filter_expr,\n        branch_negated=False,\n        current_negated=False,\n        can_reuse=None,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"\n        Build a WhereNode for a single filter clause but don't add it\n        to this Query. Query.add_q() will then add this filter to the where\n        Node.\n\n        The 'branch_negated' tells us if the current branch contains any\n        negations. This will be used to determine if subqueries are needed.\n\n        The 'current_negated' is used to determine if the current filter is\n        negated or not and this will be used to determine if IS NULL filtering\n        is needed.\n\n        The difference between current_negated and branch_negated is that\n        branch_negated is set on first negation, but current_negated is\n        flipped for each negation.\n\n        Note that add_filter will not do any negating itself, that is done\n        upper in the code by add_q().\n\n        The 'can_reuse' is a set of reusable joins for multijoins.\n\n        The method will create a filter clause that can be added to the current\n        query. However, if the filter isn't added to the query then the caller\n        is responsible for unreffing the joins used.\n        \"\"\"\n        if isinstance(filter_expr, dict):\n            raise FieldError(\"Cannot parse keyword query as dict\")\n        if isinstance(filter_expr, Q):\n            return self._add_q(\n                filter_expr,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                used_aliases=can_reuse,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n        if hasattr(filter_expr, \"resolve_expression\"):\n            if not getattr(filter_expr, \"conditional\", False):\n                raise TypeError(\"Cannot filter against a non-conditional expression.\")\n            condition = filter_expr.resolve_expression(\n                self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize\n            )\n            if not isinstance(condition, Lookup):\n                condition = self.build_lookup([\"exact\"], condition, True)\n            return WhereNode([condition], connector=AND), []\n        arg, value = filter_expr\n        if not arg:\n            raise FieldError(\"Cannot parse keyword query %r\" % arg)\n        lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize)\n\n        if check_filterable:\n            self.check_filterable(reffed_expression)\n\n        if not allow_joins and len(parts) > 1:\n            raise FieldError(\"Joined field references are not permitted in this query\")\n\n        pre_joins = self.alias_refcount.copy()\n        value = self.resolve_lookup_value(value, can_reuse, allow_joins, summarize)\n        used_joins = {\n            k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)\n        }\n\n        if check_filterable:\n            self.check_filterable(value)\n\n        if reffed_expression:\n            condition = self.build_lookup(lookups, reffed_expression, value)\n            return WhereNode([condition], connector=AND), []\n\n        opts = self.get_meta()\n        alias = self.get_initial_alias()\n        allow_many = not branch_negated or not split_subq\n\n        try:\n            join_info = self.setup_joins(\n                parts,\n                opts,\n                alias,\n                can_reuse=can_reuse,\n                allow_many=allow_many,\n            )\n\n            # Prevent iterator from being consumed by check_related_objects()\n            if isinstance(value, Iterator):\n                value = list(value)\n            self.check_related_objects(join_info.final_field, value, join_info.opts)\n\n            # split_exclude() needs to know which joins were generated for the\n            # lookup parts\n            self._lookup_joins = join_info.joins\n        except MultiJoin as e:\n            return self.split_exclude(filter_expr, can_reuse, e.names_with_path)\n\n        # Update used_joins before trimming since they are reused to determine\n        # which joins could be later promoted to INNER.\n        used_joins.update(join_info.joins)\n        targets, alias, join_list = self.trim_joins(\n            join_info.targets, join_info.joins, join_info.path\n        )\n        if can_reuse is not None:\n            can_reuse.update(join_list)\n\n        if join_info.final_field.is_relation:\n            if len(targets) == 1:\n                col = self._get_col(targets[0], join_info.final_field, alias)\n            else:\n                col = ColPairs(alias, targets, join_info.targets, join_info.final_field)\n        else:\n            col = self._get_col(targets[0], join_info.final_field, alias)\n\n        condition = self.build_lookup(lookups, col, value)\n        lookup_type = condition.lookup_name\n        clause = WhereNode([condition], connector=AND)\n\n        require_outer = (\n            lookup_type == \"isnull\" and condition.rhs is True and not current_negated\n        )\n        if (\n            current_negated\n            and (lookup_type != \"isnull\" or condition.rhs is False)\n            and condition.rhs is not None\n        ):\n            require_outer = True\n            if lookup_type != \"isnull\":\n                # The condition added here will be SQL like this:\n                # NOT (col IS NOT NULL), where the first NOT is added in\n                # upper layers of code. The reason for addition is that if col\n                # is null, then col != someval will result in SQL \"unknown\"\n                # which isn't the same as in Python. The Python None handling\n                # is wanted, and it can be gotten by\n                # (col IS NULL OR col != someval)\n                #   <=>\n                # NOT (col IS NOT NULL AND col = someval).\n                if (\n                    self.is_nullable(targets[0])\n                    or self.alias_map[join_list[-1]].join_type == LOUTER\n                ):\n                    lookup_class = targets[0].get_lookup(\"isnull\")\n                    col = self._get_col(targets[0], join_info.targets[0], alias)\n                    # Use OR + IS NULL when RHS `in` values include None.\n                    if (\n                        lookup_type == \"in\"\n                        # Check containers (not strings or bytes).\n                        and isinstance(condition.rhs, Iterable)\n                        and not isinstance(condition.rhs, (str, bytes))\n                        and any(v is None for v in condition.rhs)\n                    ):\n                        clause.add(lookup_class(col, True), OR)\n                    else:\n                        clause.add(lookup_class(col, False), AND)\n                # If someval is a nullable column, someval IS NOT NULL is\n                # added.\n                if isinstance(value, Col) and self.is_nullable(value.target):\n                    lookup_class = value.target.get_lookup(\"isnull\")\n                    clause.add(lookup_class(value, False), AND)\n        return clause, used_joins if not require_outer else ()\n\n    def add_filter(self, filter_lhs, filter_rhs):\n        self.add_q(Q((filter_lhs, filter_rhs)))\n\n    def add_q(self, q_object, reuse_all=False):\n        \"\"\"\n        A preprocessor for the internal _add_q(). Responsible for doing final\n        join promotion.\n        \"\"\"\n        # For join promotion this case is doing an AND for the added q_object\n        # and existing conditions. So, any existing inner join forces the join\n        # type to remain inner. Existing outer joins can however be demoted.\n        # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if\n        # rel_a doesn't produce any rows, then the whole condition must fail.\n        # So, demotion is OK.\n        existing_inner = {\n            a for a in self.alias_map if self.alias_map[a].join_type == INNER\n        }\n        if reuse_all:\n            can_reuse = set(self.alias_map)\n        else:\n            can_reuse = self.used_aliases\n        clause, _ = self._add_q(q_object, can_reuse)\n        if clause:\n            self.where.add(clause, AND)\n        self.demote_joins(existing_inner)\n\n    def build_where(self, filter_expr):\n        return self.build_filter(filter_expr, allow_joins=False)[0]\n\n    def clear_where(self):\n        self.where = WhereNode()\n\n    def _add_q(\n        self,\n        q_object,\n        used_aliases,\n        branch_negated=False,\n        current_negated=False,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"Add a Q-object to the current filter.\"\"\"\n        connector = q_object.connector\n        current_negated ^= q_object.negated\n        branch_negated = branch_negated or q_object.negated\n        target_clause = WhereNode(connector=connector, negated=q_object.negated)\n        joinpromoter = JoinPromoter(\n            q_object.connector, len(q_object.children), current_negated\n        )\n        for child in q_object.children:\n            child_clause, needed_inner = self.build_filter(\n                child,\n                can_reuse=used_aliases,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n            joinpromoter.add_votes(needed_inner)\n            if child_clause:\n                target_clause.add(child_clause, connector)\n        if update_join_types:\n            needed_inner = joinpromoter.update_join_types(self)\n        else:\n            needed_inner = []\n        return target_clause, needed_inner\n\n    def add_filtered_relation(self, filtered_relation, alias):\n        if \".\" in alias:\n            raise ValueError(\n                \"FilteredRelation doesn't support aliases with periods \"\n                \"(got %r).\" % alias\n            )\n        self.check_alias(alias)\n        filtered_relation.alias = alias\n        relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(\n            filtered_relation.relation_name\n        )\n        if relation_lookup_parts:\n            raise ValueError(\n                \"FilteredRelation's relation_name cannot contain lookups \"\n                \"(got %r).\" % filtered_relation.relation_name\n            )\n        for lookup in get_children_from_q(filtered_relation.condition):\n            lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)\n            shift = 2 if not lookup_parts else 1\n            lookup_field_path = lookup_field_parts[:-shift]\n            for idx, lookup_field_part in enumerate(lookup_field_path):\n                if len(relation_field_parts) > idx:\n                    if relation_field_parts[idx] != lookup_field_part:\n                        raise ValueError(\n                            \"FilteredRelation's condition doesn't support \"\n                            \"relations outside the %r (got %r).\"\n                            % (filtered_relation.relation_name, lookup)\n                        )\n            if len(lookup_field_parts) > len(relation_field_parts) + 1:\n                raise ValueError(\n                    \"FilteredRelation's condition doesn't support nested \"\n                    \"relations deeper than the relation_name (got %r for \"\n                    \"%r).\" % (lookup, filtered_relation.relation_name)\n                )\n        filtered_relation = filtered_relation.clone()\n        filtered_relation.condition = rename_prefix_from_q(\n            filtered_relation.relation_name,\n            alias,\n            filtered_relation.condition,\n        )\n        self._filtered_relations[filtered_relation.alias] = filtered_relation\n\n    def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):\n        \"\"\"\n        Walk the list of names and turns them into PathInfo tuples. A single\n        name in 'names' can generate multiple PathInfos (m2m, for example).\n\n        'names' is the path of names to travel, 'opts' is the model Options we\n        start the name resolving from, 'allow_many' is as for setup_joins().\n        If fail_on_missing is set to True, then a name that can't be resolved\n        will generate a FieldError.\n\n        Return a list of PathInfo tuples. In addition return the final field\n        (the last used join field) and target (which is a field guaranteed to\n        contain the same value as the final field). Finally, return those names\n        that weren't found (which are likely transforms and the final lookup).\n        \"\"\"\n        path, names_with_path = [], []\n        for pos, name in enumerate(names):\n            cur_names_with_path = (name, [])\n            if name == \"pk\" and opts is not None:\n                name = opts.pk.name\n\n            field = None\n            filtered_relation = None\n            try:\n                if opts is None:\n                    raise FieldDoesNotExist\n                field = opts.get_field(name)\n            except FieldDoesNotExist:\n                if name in self.annotations:\n                    field = self.annotations[name].output_field\n                elif name in self._filtered_relations and pos == 0:\n                    filtered_relation = self._filtered_relations[name]\n                    if LOOKUP_SEP in filtered_relation.relation_name:\n                        parts = filtered_relation.relation_name.split(LOOKUP_SEP)\n                        filtered_relation_path, field, _, _ = self.names_to_path(\n                            parts,\n                            opts,\n                            allow_many,\n                            fail_on_missing,\n                        )\n                        path.extend(filtered_relation_path[:-1])\n                    else:\n                        field = opts.get_field(filtered_relation.relation_name)\n            if field is not None:\n                # Fields that contain one-to-many relations with a generic\n                # model (like a GenericForeignKey) cannot generate reverse\n                # relations and therefore cannot be used for reverse querying.\n                if field.is_relation and not field.related_model:\n                    raise FieldError(\n                        \"Field %r does not generate an automatic reverse \"\n                        \"relation and therefore cannot be used for reverse \"\n                        \"querying. If it is a GenericForeignKey, consider \"\n                        \"adding a GenericRelation.\" % name\n                    )\n                try:\n                    model = field.model._meta.concrete_model\n                except AttributeError:\n                    # QuerySet.annotate() may introduce fields that aren't\n                    # attached to a model.\n                    model = None\n            else:\n                # We didn't find the current field, so move position back\n                # one step.\n                pos -= 1\n                if pos == -1 or fail_on_missing:\n                    available = sorted(\n                        [\n                            *get_field_names_from_opts(opts),\n                            *self.annotations,\n                            *self._filtered_relations,\n                        ]\n                    )\n                    raise FieldError(\n                        \"Cannot resolve keyword '%s' into field. \"\n                        \"Choices are: %s\" % (name, \", \".join(available))\n                    )\n                break\n            # Check if we need any joins for concrete inheritance cases (the\n            # field lives in parent, but we are currently in one of its\n            # children)\n            if opts is not None and model is not opts.model:\n                path_to_parent = opts.get_path_to_parent(model)\n                if path_to_parent:\n                    path.extend(path_to_parent)\n                    cur_names_with_path[1].extend(path_to_parent)\n                    opts = path_to_parent[-1].to_opts\n            if hasattr(field, \"path_infos\"):\n                if filtered_relation:\n                    pathinfos = field.get_path_info(filtered_relation)\n                else:\n                    pathinfos = field.path_infos\n                if not allow_many:\n                    for inner_pos, p in enumerate(pathinfos):\n                        if p.m2m:\n                            cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1])\n                            names_with_path.append(cur_names_with_path)\n                            raise MultiJoin(pos + 1, names_with_path)\n                last = pathinfos[-1]\n                path.extend(pathinfos)\n                final_field = last.join_field\n                opts = last.to_opts\n                targets = last.target_fields\n                cur_names_with_path[1].extend(pathinfos)\n                names_with_path.append(cur_names_with_path)\n            else:\n                # Local non-relational field.\n                final_field = field\n                targets = (field,)\n                if fail_on_missing and pos + 1 != len(names):\n                    raise FieldError(\n                        \"Cannot resolve keyword %r into field. Join on '%s'\"\n                        \" not permitted.\" % (names[pos + 1], name)\n                    )\n                break\n        return path, final_field, targets, names[pos + 1 :]\n\n    def setup_joins(\n        self,\n        names,\n        opts,\n        alias,\n        can_reuse=None,\n        allow_many=True,\n    ):\n        \"\"\"\n        Compute the necessary table joins for the passage through the fields\n        given in 'names'. 'opts' is the Options class for the current model\n        (which gives the table we are starting from), 'alias' is the alias for\n        the table to start the joining from.\n\n        The 'can_reuse' defines the reverse foreign key joins we can reuse. It\n        can be None in which case all joins are reusable or a set of aliases\n        that can be reused. Note that non-reverse foreign keys are always\n        reusable when using setup_joins().\n\n        If 'allow_many' is False, then any reverse foreign key seen will\n        generate a MultiJoin exception.\n\n        Return the final field involved in the joins, the target field (used\n        for any 'where' constraint), the final 'opts' value, the joins, the\n        field path traveled to generate the joins, and a transform function\n        that takes a field and alias and is equivalent to\n        `field.get_col(alias)` in the simple case but wraps field transforms if\n        they were included in names.\n\n        The target field is the field containing the concrete value. Final\n        field can be something different, for example foreign key pointing to\n        that value. Final field is needed for example in some value\n        conversions (convert 'obj' in fk__id=obj to pk val using the foreign\n        key field for example).\n        \"\"\"\n        joins = [alias]\n        # The transform can't be applied yet, as joins must be trimmed later.\n        # To avoid making every caller of this method look up transforms\n        # directly, compute transforms here and create a partial that converts\n        # fields to the appropriate wrapped version.\n\n        def final_transformer(field, alias):\n            if not self.alias_cols:\n                alias = None\n            return field.get_col(alias)\n\n        # Try resolving all the names as fields first. If there's an error,\n        # treat trailing names as lookups until a field can be resolved.\n        last_field_exception = None\n        for pivot in range(len(names), 0, -1):\n            try:\n                path, final_field, targets, rest = self.names_to_path(\n                    names[:pivot],\n                    opts,\n                    allow_many,\n                    fail_on_missing=True,\n                )\n            except FieldError as exc:\n                if pivot == 1:\n                    # The first item cannot be a lookup, so it's safe\n                    # to raise the field error here.\n                    raise\n                else:\n                    last_field_exception = exc\n            else:\n                # The transforms are the remaining items that couldn't be\n                # resolved into fields.\n                transforms = names[pivot:]\n                break\n        for name in transforms:\n\n            def transform(field, alias, *, name, previous):\n                try:\n                    wrapped = previous(field, alias)\n                    return self.try_transform(wrapped, name)\n                except FieldError:\n                    # FieldError is raised if the transform doesn't exist.\n                    if isinstance(final_field, Field) and last_field_exception:\n                        raise last_field_exception\n                    else:\n                        raise\n\n            final_transformer = functools.partial(\n                transform, name=name, previous=final_transformer\n            )\n            final_transformer.has_transforms = True\n        # Then, add the path to the query's joins. Note that we can't trim\n        # joins at this stage - we will need the information about join type\n        # of the trimmed joins.\n        for join in path:\n            if join.filtered_relation:\n                filtered_relation = join.filtered_relation.clone()\n                table_alias = filtered_relation.alias\n            else:\n                filtered_relation = None\n                table_alias = None\n            opts = join.to_opts\n            if join.direct:\n                nullable = self.is_nullable(join.join_field)\n            else:\n                nullable = True\n            connection = self.join_class(\n                opts.db_table,\n                alias,\n                table_alias,\n                INNER,\n                join.join_field,\n                nullable,\n                filtered_relation=filtered_relation,\n            )\n            reuse = can_reuse if join.m2m else None\n            alias = self.join(connection, reuse=reuse)\n            joins.append(alias)\n            if join.filtered_relation and can_reuse is not None:\n                can_reuse.add(alias)\n        return JoinInfo(final_field, targets, opts, joins, path, final_transformer)\n\n    def trim_joins(self, targets, joins, path):\n        \"\"\"\n        The 'target' parameter is the final field being joined to, 'joins'\n        is the full list of join aliases. The 'path' contain the PathInfos\n        used to create the joins.\n\n        Return the final target field and table alias and the new active\n        joins.\n\n        Always trim any direct join if the target column is already in the\n        previous table. Can't trim reverse joins as it's unknown if there's\n        anything on the other side of the join.\n        \"\"\"\n        joins = joins[:]\n        for pos, info in enumerate(reversed(path)):\n            if len(joins) == 1 or not info.direct:\n                break\n            if info.filtered_relation:\n                break\n            join_targets = {t.column for t in info.join_field.foreign_related_fields}\n            cur_targets = {t.column for t in targets}\n            if not cur_targets.issubset(join_targets):\n                break\n            targets_dict = {\n                r[1].column: r[0]\n                for r in info.join_field.related_fields\n                if r[1].column in cur_targets\n            }\n            targets = tuple(targets_dict[t.column] for t in targets)\n            self.unref_alias(joins.pop())\n        return targets, joins[-1], joins\n\n    @classmethod\n    def _gen_cols(cls, exprs, include_external=False, resolve_refs=True):\n        for expr in exprs:\n            if isinstance(expr, Col):\n                yield expr\n            elif include_external and callable(\n                getattr(expr, \"get_external_cols\", None)\n            ):\n                yield from expr.get_external_cols()\n            elif hasattr(expr, \"get_source_expressions\"):\n                if not resolve_refs and isinstance(expr, Ref):\n                    continue\n                yield from cls._gen_cols(\n                    expr.get_source_expressions(),\n                    include_external=include_external,\n                    resolve_refs=resolve_refs,\n                )\n\n    @classmethod\n    def _gen_col_aliases(cls, exprs):\n        yield from (expr.alias for expr in cls._gen_cols(exprs))\n\n    def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):\n        annotation = self.annotations.get(name)\n        if annotation is not None:\n            if not allow_joins:\n                for alias in self._gen_col_aliases([annotation]):\n                    if isinstance(self.alias_map[alias], Join):\n                        raise FieldError(\n                            \"Joined field references are not permitted in this query\"\n                        )\n            if summarize:\n                # Summarize currently means we are doing an aggregate() query\n                # which is executed as a wrapped subquery if any of the\n                # aggregate() elements reference an existing annotation. In\n                # that case we need to return a Ref to the subquery's\n                # annotation.\n                if name not in self.annotation_select:\n                    raise FieldError(\n                        \"Cannot aggregate over the '%s' alias. Use annotate() \"\n                        \"to promote it.\" % name\n                    )\n                return Ref(name, self.annotation_select[name])\n            else:\n                return annotation\n        else:\n            field_list = name.split(LOOKUP_SEP)\n            annotation = self.annotations.get(field_list[0])\n            if annotation is not None:\n                for transform in field_list[1:]:\n                    annotation = self.try_transform(annotation, transform)\n                return annotation\n            join_info = self.setup_joins(\n                field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse\n            )\n            targets, final_alias, join_list = self.trim_joins(\n                join_info.targets, join_info.joins, join_info.path\n            )\n            if not allow_joins and len(join_list) > 1:\n                raise FieldError(\n                    \"Joined field references are not permitted in this query\"\n                )\n            if len(targets) > 1:\n                raise FieldError(\n                    \"Referencing multicolumn fields with F() objects isn't supported\"\n                )\n            # Verify that the last lookup in name is a field or a transform:\n            # transform_function() raises FieldError if not.\n            transform = join_info.transform_function(targets[0], final_alias)\n            if reuse is not None:\n                reuse.update(join_list)\n            return transform\n\n    def split_exclude(self, filter_expr, can_reuse, names_with_path):\n        \"\"\"\n        When doing an exclude against any kind of N-to-many relation, we need\n        to use a subquery. This method constructs the nested query, given the\n        original exclude filter (filter_expr) and the portion up to the first\n        N-to-many relation field.\n\n        For example, if the origin filter is ~Q(child__name='foo'), filter_expr\n        is ('child__name', 'foo') and can_reuse is a set of joins usable for\n        filters in the original query.\n\n        We will turn this into equivalent of:\n            WHERE NOT EXISTS(\n                SELECT 1\n                FROM child\n                WHERE name = 'foo' AND child.parent_id = parent.id\n                LIMIT 1\n            )\n        \"\"\"\n        # Generate the inner query.\n        query = self.__class__(self.model)\n        query._filtered_relations = self._filtered_relations\n        filter_lhs, filter_rhs = filter_expr\n        if isinstance(filter_rhs, OuterRef):\n            filter_rhs = OuterRef(filter_rhs)\n        elif isinstance(filter_rhs, F):\n            filter_rhs = OuterRef(filter_rhs.name)\n        query.add_filter(filter_lhs, filter_rhs)\n        query.clear_ordering(force=True)\n        # Try to have as simple as possible subquery -> trim leading joins from\n        # the subquery.\n        trimmed_prefix, contains_louter = query.trim_start(names_with_path)\n\n        col = query.select[0]\n        select_field = col.target\n        alias = col.alias\n        if alias in can_reuse:\n            pk = select_field.model._meta.pk\n            # Need to add a restriction so that outer query's filters are in\n            # effect for the subquery, too.\n            query.bump_prefix(self)\n            lookup_class = select_field.get_lookup(\"exact\")\n            # Note that the query.select[0].alias is different from alias\n            # due to bump_prefix above.\n            lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias))\n            query.where.add(lookup, AND)\n            query.external_aliases[alias] = True\n        else:\n            lookup_class = select_field.get_lookup(\"exact\")\n            lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix))\n            query.where.add(lookup, AND)\n\n        condition, needed_inner = self.build_filter(Exists(query))\n\n        if contains_louter:\n            or_null_condition, _ = self.build_filter(\n                (\"%s__isnull\" % trimmed_prefix, True),\n                current_negated=True,\n                branch_negated=True,\n                can_reuse=can_reuse,\n            )\n            condition.add(or_null_condition, OR)\n            # Note that the end result will be:\n            #   NOT EXISTS (inner_q) OR outercol IS NULL\n            # this might look crazy but due to how NULL works, this seems to be\n            # correct. If the IS NULL check is removed, then if outercol\n            # IS NULL we will not match the row.\n        return condition, needed_inner\n\n    def set_empty(self):\n        self.where.add(NothingNode(), AND)\n        for query in self.combined_queries:\n            query.set_empty()\n\n    def is_empty(self):\n        return any(isinstance(c, NothingNode) for c in self.where.children)\n\n    def set_limits(self, low=None, high=None):\n        \"\"\"\n        Adjust the limits on the rows retrieved. Use low/high to set these,\n        as it makes it more Pythonic to read and write. When the SQL query is\n        created, convert them to the appropriate offset and limit values.\n\n        Apply any limits passed in here to the existing constraints. Add low\n        to the current low value and clamp both to any existing high value.\n        \"\"\"\n        if high is not None:\n            if self.high_mark is not None:\n                self.high_mark = min(self.high_mark, self.low_mark + high)\n            else:\n                self.high_mark = self.low_mark + high\n        if low is not None:\n            if self.high_mark is not None:\n                self.low_mark = min(self.high_mark, self.low_mark + low)\n            else:\n                self.low_mark = self.low_mark + low\n\n        if self.low_mark == self.high_mark:\n            self.set_empty()\n\n    def clear_limits(self):\n        \"\"\"Clear any existing limits.\"\"\"\n        self.low_mark, self.high_mark = 0, None\n\n    @property\n    def is_sliced(self):\n        return self.low_mark != 0 or self.high_mark is not None\n\n    def has_limit_one(self):\n        return self.high_mark is not None and (self.high_mark - self.low_mark) == 1\n\n    def can_filter(self):\n        \"\"\"\n        Return True if adding filters to this instance is still possible.\n\n        Typically, this means no limits or offsets have been put on the\n        results.\n        \"\"\"\n        return not self.is_sliced\n\n    def clear_select_clause(self):\n        \"\"\"Remove all fields from SELECT clause.\"\"\"\n        self.select = ()\n        self.default_cols = False\n        self.select_related = False\n        self.set_extra_mask(())\n        self.set_annotation_mask(())\n        self.selected = None\n\n    def clear_select_fields(self):\n        \"\"\"\n        Clear the list of fields to select (but not extra_select columns).\n        Some queryset types completely replace any existing list of select\n        columns.\n        \"\"\"\n        self.select = ()\n        self.values_select = ()\n        self.selected = None\n\n    def add_select_col(self, col, name):\n        self.select += (col,)\n        self.values_select += (name,)\n        self.selected[name] = len(self.select) - 1\n\n    def set_select(self, cols):\n        self.default_cols = False\n        self.select = tuple(cols)\n\n    def add_distinct_fields(self, *field_names):\n        \"\"\"\n        Add and resolve the given fields to the query's \"distinct on\" clause.\n        \"\"\"\n        self.distinct_fields = field_names\n        self.distinct = True\n\n    def add_fields(self, field_names, allow_m2m=True):\n        \"\"\"\n        Add the given (model) fields to the select set. Add the field names in\n        the order specified.\n        \"\"\"\n        alias = self.get_initial_alias()\n        opts = self.get_meta()\n\n        try:\n            cols = []\n            for name in field_names:\n                # Join promotion note - we must not remove any rows here, so\n                # if there is no existing joins, use outer join.\n                join_info = self.setup_joins(\n                    name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m\n                )\n                targets, final_alias, joins = self.trim_joins(\n                    join_info.targets,\n                    join_info.joins,\n                    join_info.path,\n                )\n                if len(targets) > 1:\n                    transformed_targets = [\n                        join_info.transform_function(target, final_alias)\n                        for target in targets\n                    ]\n                    cols.append(\n                        ColPairs(\n                            final_alias if self.alias_cols else None,\n                            [col.target for col in transformed_targets],\n                            [col.output_field for col in transformed_targets],\n                            join_info.final_field,\n                        )\n                    )\n                else:\n                    cols.append(join_info.transform_function(targets[0], final_alias))\n            if cols:\n                self.set_select(cols)\n        except MultiJoin:\n            raise FieldError(\"Invalid field name: '%s'\" % name)\n        except FieldError:\n            if LOOKUP_SEP in name:\n                # For lookups spanning over relationships, show the error\n                # from the model on which the lookup failed.\n                raise\n            else:\n                names = sorted(\n                    [\n                        *get_field_names_from_opts(opts),\n                        *self.extra,\n                        *self.annotation_select,\n                        *self._filtered_relations,\n                    ]\n                )\n                raise FieldError(\n                    \"Cannot resolve keyword %r into field. \"\n                    \"Choices are: %s\" % (name, \", \".join(names))\n                )\n\n    def add_ordering(self, *ordering):\n        \"\"\"\n        Add items from the 'ordering' sequence to the query's \"order by\"\n        clause. These items are either field names (not column names) --\n        possibly with a direction prefix ('-' or '?') -- or OrderBy\n        expressions.\n\n        If 'ordering' is empty, clear all ordering from the query.\n        \"\"\"\n        errors = []\n        for item in ordering:\n            if isinstance(item, str):\n                if item == \"?\":\n                    continue\n                item = item.removeprefix(\"-\")\n                if item in self.annotations:\n                    continue\n                if self.extra and item in self.extra:\n                    continue\n                # names_to_path() validates the lookup. A descriptive\n                # FieldError will be raise if it's not.\n                self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)\n            elif not hasattr(item, \"resolve_expression\"):\n                errors.append(item)\n            if getattr(item, \"contains_aggregate\", False):\n                raise FieldError(\n                    \"Using an aggregate in order_by() without also including \"\n                    \"it in annotate() is not allowed: %s\" % item\n                )\n        if errors:\n            raise FieldError(\"Invalid order_by arguments: %s\" % errors)\n        if ordering:\n            self.order_by += ordering\n        else:\n            self.default_ordering = False\n\n    @property\n    def orderby_issubset_groupby(self):\n        if self.extra_order_by:\n            # Raw SQL from extra(order_by=...) can't be reliably compared\n            # against resolved OrderBy/Col expressions. Treat as not a subset.\n            return False\n        if self.group_by in (None, True):\n            # There is either no aggregation at all (None), or the group by\n            # is generated automatically from model fields (True), in which\n            # case the order by is necessarily a subset of them.\n            return True\n        if not self.order_by:\n            # Although an empty set is always a subset, there's no point in\n            # clearing ordering when there isn't any. Avoid the clone() below.\n            return True\n        # Don't pollute the original query (might disrupt joins).\n        q = self.clone()\n        order_by_set = set()\n        for order_by in q.order_by:\n            if hasattr(order_by, \"resolve_expression\"):\n                order_by_set.add(order_by.resolve_expression(q))\n            elif order_by == \"?\":\n                # Random ordering can't be compared against group by.\n                return False\n            else:\n                order_by_set.add(F(order_by.removeprefix(\"-\")).resolve_expression(q))\n        return order_by_set.issubset(self.group_by)\n\n    def clear_ordering(self, force=False, clear_default=True):\n        \"\"\"\n        Remove any ordering settings if the current query allows it without\n        side effects, set 'force' to True to clear the ordering regardless.\n        If 'clear_default' is True, there will be no ordering in the resulting\n        query (not even the model's default).\n        \"\"\"\n        if not force and (\n            self.is_sliced or self.distinct_fields or self.select_for_update\n        ):\n            return\n        self.order_by = ()\n        self.extra_order_by = ()\n        if clear_default:\n            self.default_ordering = False\n        # Ordering is cleared on combined queries with clear_default=False\n        # when union() and analogues are called, so percolate any possible\n        # clear_default=True.\n        for query in self.combined_queries:\n            query.clear_ordering(force=False, clear_default=clear_default)\n\n    def set_group_by(self, allow_aliases=True):\n        \"\"\"\n        Expand the GROUP BY clause required by the query.\n\n        This will usually be the set of all non-aggregate fields in the\n        return data. If the database backend supports grouping by the\n        primary key, and the query would be equivalent, the optimization\n        will be made automatically.\n        \"\"\"\n        if allow_aliases and self.values_select:\n            # If grouping by aliases is allowed assign selected value aliases\n            # by moving them to annotations.\n            group_by_annotations = {}\n            values_select = {}\n            for alias, expr in zip(self.values_select, self.select):\n                if isinstance(expr, Col):\n                    values_select[alias] = expr\n                else:\n                    group_by_annotations[alias] = expr\n            self.annotations = {**group_by_annotations, **self.annotations}\n            self.append_annotation_mask(group_by_annotations)\n            self.select = tuple(values_select.values())\n            self.values_select = tuple(values_select)\n            if self.selected is not None:\n                for index, value_select in enumerate(values_select):\n                    self.selected[value_select] = index\n        group_by = list(self.select)\n        for alias, annotation in self.annotation_select.items():\n            if not (group_by_cols := annotation.get_group_by_cols()):\n                continue\n            if allow_aliases and not annotation.contains_aggregate:\n                group_by.append(Ref(alias, annotation))\n            else:\n                group_by.extend(group_by_cols)\n        self.group_by = tuple(group_by)\n\n    def add_select_related(self, fields):\n        \"\"\"\n        Set up the select_related data structure so that we only select\n        certain related models (as opposed to all models, when\n        self.select_related=True).\n        \"\"\"\n        if isinstance(self.select_related, bool):\n            field_dict = {}\n        else:\n            field_dict = self.select_related\n        for field in fields:\n            d = field_dict\n            for part in field.split(LOOKUP_SEP):\n                d = d.setdefault(part, {})\n        self.select_related = field_dict\n\n    def add_extra(self, select, select_params, where, params, tables, order_by):\n        \"\"\"\n        Add data to the various extra_* attributes for user-created additions\n        to the query.\n        \"\"\"\n        if select:\n            # We need to pair any placeholder markers in the 'select'\n            # dictionary with their parameters in 'select_params' so that\n            # subsequent updates to the select dictionary also adjust the\n            # parameters appropriately.\n            select_pairs = {}\n            if select_params:\n                param_iter = iter(select_params)\n            else:\n                param_iter = iter([])\n            for name, entry in select.items():\n                self.check_alias(name)\n                entry = str(entry)\n                entry_params = []\n                pos = entry.find(\"%s\")\n                while pos != -1:\n                    if pos == 0 or entry[pos - 1] != \"%\":\n                        entry_params.append(next(param_iter))\n                    pos = entry.find(\"%s\", pos + 2)\n                select_pairs[name] = (entry, entry_params)\n            self.extra.update(select_pairs)\n        if where or params:\n            self.where.add(ExtraWhere(where, params), AND)\n        if tables:\n            self.extra_tables += tuple(tables)\n        if order_by:\n            self.extra_order_by = order_by\n\n    def clear_deferred_loading(self):\n        \"\"\"Remove any fields from the deferred loading set.\"\"\"\n        self.deferred_loading = (frozenset(), True)\n\n    def add_deferred_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        exclude from loading from the database when automatic column selection\n        is done. Add the new field names to any existing field names that\n        are deferred (or removed from any existing field names that are marked\n        as the only ones for immediate loading).\n        \"\"\"\n        # Fields on related models are stored in the literal double-underscore\n        # format, so that we can use a set datastructure. We do the foo__bar\n        # splitting and handling when computing the SQL column names (as part\n        # of get_columns()).\n        existing, defer = self.deferred_loading\n        if defer:\n            # Add to existing deferred names.\n            self.deferred_loading = existing.union(field_names), True\n        else:\n            # Remove names from the set of any existing \"immediate load\" names.\n            if new_existing := existing.difference(field_names):\n                self.deferred_loading = new_existing, False\n            else:\n                self.clear_deferred_loading()\n                if new_only := set(field_names).difference(existing):\n                    self.deferred_loading = new_only, True\n\n    def add_immediate_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        retrieve when the SQL is executed (\"immediate loading\" fields). The\n        field names replace any existing immediate loading field names. If\n        there are field names already specified for deferred loading, remove\n        those names from the new field_names before storing the new names\n        for immediate loading. (That is, immediate loading overrides any\n        existing immediate values, but respects existing deferrals.)\n        \"\"\"\n        existing, defer = self.deferred_loading\n        field_names = set(field_names)\n        if \"pk\" in field_names:\n            field_names.remove(\"pk\")\n            field_names.add(self.get_meta().pk.name)\n\n        if defer:\n            # Remove any existing deferred names from the current set before\n            # setting the new names.\n            self.deferred_loading = field_names.difference(existing), False\n        else:\n            # Replace any existing \"immediate load\" field names.\n            self.deferred_loading = frozenset(field_names), False\n\n    def set_annotation_mask(self, names):\n        \"\"\"Set the mask of annotations that will be returned by the SELECT.\"\"\"\n        if names is None:\n            self.annotation_select_mask = None\n        else:\n            self.annotation_select_mask = set(names)\n            if self.selected:\n                # Prune the masked annotations.\n                self.selected = {\n                    key: value\n                    for key, value in self.selected.items()\n                    if not isinstance(value, str)\n                    or value in self.annotation_select_mask\n                }\n                # Append the unmasked annotations.\n                for name in names:\n                    self.selected[name] = name\n        self._annotation_select_cache = None\n\n    def append_annotation_mask(self, names):\n        if self.annotation_select_mask is not None:\n            self.set_annotation_mask(self.annotation_select_mask.union(names))\n\n    def set_extra_mask(self, names):\n        \"\"\"\n        Set the mask of extra select items that will be returned by SELECT.\n        Don't remove them from the Query since they might be used later.\n        \"\"\"\n        if names is None:\n            self.extra_select_mask = None\n        else:\n            self.extra_select_mask = set(names)\n        self._extra_select_cache = None\n\n    @property\n    def has_select_fields(self):\n        return self.selected is not None\n\n    def set_values(self, fields):\n        self.select_related = False\n        self.clear_deferred_loading()\n        self.clear_select_fields()\n\n        selected = {}\n        if fields:\n            for field in fields:\n                self.check_alias(field)\n            field_names = []\n            extra_names = []\n            annotation_names = []\n            if not self.extra and not self.annotations:\n                # Shortcut - if there are no extra or annotations, then\n                # the values() clause must be just field names.\n                field_names = list(fields)\n                selected = dict(zip(fields, range(len(fields))))\n            else:\n                self.default_cols = False\n                for f in fields:\n                    if extra := self.extra_select.get(f):\n                        extra_names.append(f)\n                        selected[f] = RawSQL(*extra)\n                    elif f in self.annotation_select:\n                        annotation_names.append(f)\n                        selected[f] = f\n                    elif f in self.annotations:\n                        if self.annotation_select:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. It was excluded \"\n                                f\"by a previous values() or values_list() call. \"\n                                f\"Include '{f}' in that call to select it.\"\n                            )\n                        else:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. Use annotate() \"\n                                f\"to promote it.\"\n                            )\n                    else:\n                        # Call `names_to_path` to ensure a FieldError including\n                        # annotations about to be masked as valid choices if\n                        # `f` is not resolvable.\n                        if self.annotation_select:\n                            self.names_to_path(f.split(LOOKUP_SEP), self.model._meta)\n                        selected[f] = len(field_names)\n                        field_names.append(f)\n            self.set_extra_mask(extra_names)\n            self.set_annotation_mask(annotation_names)\n        else:\n            field_names = [f.attname for f in self.model._meta.concrete_fields]\n            selected = dict.fromkeys(field_names, None)\n        # Selected annotations must be known before setting the GROUP BY\n        # clause.\n        if self.group_by is True:\n            self.add_fields(\n                (f.attname for f in self.model._meta.concrete_fields), False\n            )\n            # Disable GROUP BY aliases to avoid orphaning references to the\n            # SELECT clause which is about to be cleared.\n            self.set_group_by(allow_aliases=False)\n            self.clear_select_fields()\n        elif self.group_by:\n            # Resolve GROUP BY annotation references if they are not part of\n            # the selected fields anymore.\n            group_by = []\n            for expr in self.group_by:\n                if isinstance(expr, Ref) and expr.refs not in selected:\n                    expr = self.annotations[expr.refs]\n                group_by.append(expr)\n            self.group_by = tuple(group_by)\n\n        self.values_select = tuple(field_names)\n        self.add_fields(field_names, True)\n        self.selected = selected if fields else None\n\n    @property\n    def annotation_select(self):\n        \"\"\"\n        Return the dictionary of aggregate columns that are not masked and\n        should be used in the SELECT clause. Cache this result for performance.\n        \"\"\"\n        if self._annotation_select_cache is not None:\n            return self._annotation_select_cache\n        elif not self.annotations:\n            return {}\n        elif self.annotation_select_mask is not None:\n            self._annotation_select_cache = {\n                k: v\n                for k, v in self.annotations.items()\n                if k in self.annotation_select_mask\n            }\n            return self._annotation_select_cache\n        else:\n            return self.annotations\n\n    @property\n    def extra_select(self):\n        if self._extra_select_cache is not None:\n            return self._extra_select_cache\n        if not self.extra:\n            return {}\n        elif self.extra_select_mask is not None:\n            self._extra_select_cache = {\n                k: v for k, v in self.extra.items() if k in self.extra_select_mask\n            }\n            return self._extra_select_cache\n        else:\n            return self.extra\n\n    def trim_start(self, names_with_path):\n        \"\"\"\n        Trim joins from the start of the join path. The candidates for trim\n        are the PathInfos in names_with_path structure that are m2m joins.\n\n        Also set the select column so the start matches the join.\n\n        This method is meant to be used for generating the subquery joins &\n        cols in split_exclude().\n\n        Return a lookup usable for doing outerq.filter(lookup=self) and a\n        boolean indicating if the joins in the prefix contain a LEFT OUTER\n        join.\n        \"\"\"\n        all_paths = []\n        for _, paths in names_with_path:\n            all_paths.extend(paths)\n        contains_louter = False\n        # Trim and operate only on tables that were generated for\n        # the lookup part of the query. That is, avoid trimming\n        # joins generated for F() expressions.\n        lookup_tables = [\n            t for t in self.alias_map if t in self._lookup_joins or t == self.base_table\n        ]\n        for trimmed_paths, path in enumerate(all_paths):\n            if path.m2m:\n                break\n            if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER:\n                contains_louter = True\n            alias = lookup_tables[trimmed_paths]\n            self.unref_alias(alias)\n        # The path.join_field is a Rel, lets get the other side's field\n        join_field = path.join_field.field\n        # Build the filter prefix.\n        paths_in_prefix = trimmed_paths\n        trimmed_prefix = []\n        for name, path in names_with_path:\n            if paths_in_prefix - len(path) < 0:\n                break\n            trimmed_prefix.append(name)\n            paths_in_prefix -= len(path)\n        trimmed_prefix.append(join_field.foreign_related_fields[0].name)\n        trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)\n        # Lets still see if we can trim the first join from the inner query\n        # (that is, self). We can't do this for:\n        # - LEFT JOINs because we would miss those rows that have nothing on\n        #   the outer side,\n        # - INNER JOINs from filtered relations because we would miss their\n        #   filters.\n        first_join = self.alias_map[lookup_tables[trimmed_paths + 1]]\n        if first_join.join_type != LOUTER and not first_join.filtered_relation:\n            select_fields = [r[0] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths + 1]\n            self.unref_alias(lookup_tables[trimmed_paths])\n            extra_restriction = join_field.get_extra_restriction(\n                None, lookup_tables[trimmed_paths + 1]\n            )\n            if extra_restriction:\n                self.where.add(extra_restriction, AND)\n        else:\n            # TODO: It might be possible to trim more joins from the start of\n            # the inner query if it happens to have a longer join chain\n            # containing the values in select_fields. Lets punt this one for\n            # now.\n            select_fields = [r[1] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths]\n        # The found starting point is likely a join_class instead of a\n        # base_table_class reference. But the first entry in the query's FROM\n        # clause must not be a JOIN.\n        for table in self.alias_map:\n            if self.alias_refcount[table] > 0:\n                self.alias_map[table] = self.base_table_class(\n                    self.alias_map[table].table_name,\n                    table,\n                )\n                break\n        self.set_select([f.get_col(select_alias) for f in select_fields])\n        return trimmed_prefix, contains_louter\n\n    def is_nullable(self, field):\n        \"\"\"\n        Check if the given field should be treated as nullable.\n\n        Some backends treat '' as null and Django treats such fields as\n        nullable for those backends. In such situations field.null can be\n        False even if we should treat the field as nullable.\n        \"\"\"\n        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have\n        # (nor should it have) knowledge of which connection is going to be\n        # used. The proper fix would be to defer all decisions where\n        # is_nullable() is needed to the compiler stage, but that is not easy\n        # to do currently.\n        return field.null or (\n            field.empty_strings_allowed\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-d737c5fea4d295f9", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 2602, "local_path": "source-original/SRC__django__Query__6794d74c.py", "order": 0, "original_content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/query.py#L232-L2792", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Query", "variant_id": "pyint-82246794d74c-SRC", "group_id": "py-d737c5fea4d295f9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 281, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0509ae33e5f8-I01", "source": "import copy\nimport difflib\nimport functools\nimport sys\nimport warnings\nfrom collections import Counter, namedtuple\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom itertools import chain, count, product\nfrom string import ascii_uppercase\nfrom django.core.exceptions import FieldDoesNotExist, FieldError\nfrom django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections\nfrom django.db.models.aggregates import Count\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import (\n    BaseExpression,\n    Col,\n    ColPairs,\n    Exists,\n    F,\n    OuterRef,\n    RawSQL,\n    Ref,\n    ResolvedOuterRef,\n    Value,\n)\nfrom django.db.models.fields import Field\nfrom django.db.models.lookups import Lookup\nfrom django.db.models.query_utils import (\n    Q,\n    check_rel_lookup_compatibility,\n    refs_expression,\n)\nfrom django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE\nfrom django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin\nfrom django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode\nfrom django.utils.deprecation import RemovedInDjango70Warning\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.tree import Node\nfrom django.utils.warnings import django_file_prefixes\n\nclass Query(BaseExpression):\n    \n\n    alias_prefix = \"T\"\n    empty_result_set_value = None\n    subq_aliases = frozenset([alias_prefix])\n\n    compiler = \"SQLCompiler\"\n\n    base_table_class = BaseTable\n    join_class = Join\n\n    default_cols = True\n    default_ordering = True\n    standard_ordering = True\n\n    filter_is_sticky = False\n    subquery = False\n    contains_subquery = False\n\n     \n     \n     \n     \n     \n    select = ()\n     \n     \n     \n     \n     \n     \n    group_by = None\n    order_by = ()\n    low_mark = 0   \n    high_mark = None   \n    distinct = False\n    distinct_fields = ()\n    select_for_update = False\n    select_for_update_nowait = False\n    select_for_update_skip_locked = False\n    select_for_update_of = ()\n    select_for_no_key_update = False\n    select_related = False\n     \n    max_depth = 5\n     \n     \n    values_select = ()\n    selected = None\n\n     \n    annotation_select_mask = None\n    _annotation_select_cache = None\n\n     \n    combinator = None\n    combinator_all = False\n    combined_queries = ()\n\n     \n     \n    extra_select_mask = None\n    _extra_select_cache = None\n\n    extra_tables = ()\n    extra_order_by = ()\n\n     \n     \n    deferred_loading = (frozenset(), True)\n\n    explain_info = None\n\n    def __init__(self, model, alias_cols=True):\n        self.model = model\n        self.alias_refcount = {}\n         \n         \n         \n         \n         \n        self.alias_map = {}\n         \n        self.alias_cols = alias_cols\n         \n         \n         \n        self.external_aliases = {}\n        self.table_map = {}   \n        self.used_aliases = set()\n\n        self.where = WhereNode()\n         \n        self.annotations = {}\n         \n         \n        self.extra = {}   \n\n        self._filtered_relations = {}\n\n    @property\n    def output_field(self):\n        if len(self.select) == 1:\n            select = self.select[0]\n            return getattr(select, \"target\", None) or select.field\n        elif len(self.annotation_select) == 1:\n            return next(iter(self.annotation_select.values())).output_field\n\n    @cached_property\n    def base_table(self):\n        for alias in self.alias_map:\n            return alias\n\n    def __str__(self):\n        \n        sql, params = self.sql_with_params()\n        return sql % params\n\n    def sql_with_params(self):\n        \n        return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()\n\n    def __deepcopy__(self, memo):\n        \n        result = self.clone()\n        memo[id(self)] = result\n        return result\n\n    def get_compiler(self, using=None, connection=None, elide_empty=True):\n        if using is None and connection is None:\n            raise ValueError(\"Need either using or connection\")\n        if using:\n            connection = connections[using]\n        return connection.ops.compiler(self.compiler)(\n            self, connection, using, elide_empty\n        )\n\n    def get_meta(self):\n        \n        if self.model:\n            return self.model._meta\n\n    def clone(self):\n        \n        obj = Empty()\n        obj.__class__ = self.__class__\n         \n        obj.__dict__ = self.__dict__.copy()\n         \n        obj.alias_refcount = self.alias_refcount.copy()\n        obj.alias_map = self.alias_map.copy()\n        obj.external_aliases = self.external_aliases.copy()\n        obj.table_map = self.table_map.copy()\n        obj.where = self.where.clone()\n        obj.annotations = self.annotations.copy()\n        if self.annotation_select_mask is not None:\n            obj.annotation_select_mask = self.annotation_select_mask.copy()\n        if self.combined_queries:\n            obj.combined_queries = tuple(\n                [query.clone() for query in self.combined_queries]\n            )\n         \n         \n         \n         \n         \n        obj._annotation_select_cache = None\n        obj.extra = self.extra.copy()\n        if self.extra_select_mask is not None:\n            obj.extra_select_mask = self.extra_select_mask.copy()\n        if self._extra_select_cache is not None:\n            obj._extra_select_cache = self._extra_select_cache.copy()\n        if self.select_related is not False:\n             \n             \n            obj.select_related = copy.deepcopy(obj.select_related)\n        if \"subq_aliases\" in self.__dict__:\n            obj.subq_aliases = self.subq_aliases.copy()\n        obj.used_aliases = self.used_aliases.copy()\n        obj._filtered_relations = self._filtered_relations.copy()\n         \n        obj.__dict__.pop(\"base_table\", None)\n        return obj\n\n    def chain(self, klass=None):\n        \n        obj = self.clone()\n        if klass and obj.__class__ != klass:\n            obj.__class__ = klass\n        if not obj.filter_is_sticky:\n            obj.used_aliases = set()\n        obj.filter_is_sticky = False\n        if hasattr(obj, \"_setup_query\"):\n            obj._setup_query()\n        return obj\n\n    def relabeled_clone(self, change_map):\n        clone = self.clone()\n        clone.change_aliases(change_map)\n        return clone\n\n    def _get_col(self, target, field, alias):\n        if not self.alias_cols:\n            alias = None\n        return target.get_col(alias, field)\n\n    def get_aggregation(self, using, aggregate_exprs):\n        \n        if not aggregate_exprs:\n            return {}\n         \n         \n        refs_subquery = False\n        refs_window = False\n        replacements = {}\n        annotation_select_mask = self.annotation_select_mask\n        for alias, aggregate_expr in aggregate_exprs.items():\n            self.check_alias(alias)\n            aggregate = aggregate_expr.resolve_expression(\n                self, allow_joins=True, reuse=None, summarize=True\n            )\n            if not aggregate.contains_aggregate:\n                raise TypeError(\"%s is not an aggregate expression\" % alias)\n             \n             \n            self.append_annotation_mask([alias])\n            aggregate_refs = aggregate.get_refs()\n            refs_subquery |= any(\n                getattr(self.annotations[ref], \"contains_subquery\", False)\n                for ref in aggregate_refs\n            )\n            refs_window |= any(\n                getattr(self.annotations[ref], \"contains_over_clause\", True)\n                for ref in aggregate_refs\n            )\n            aggregate = aggregate.replace_expressions(replacements)\n            self.annotations[alias] = aggregate\n            replacements[Ref(alias, aggregate)] = aggregate\n         \n         \n        aggregates = {alias: self.annotations.pop(alias) for alias in aggregate_exprs}\n        self.set_annotation_mask(annotation_select_mask)\n         \n         \n        _, having, qualify = self.where.split_having_qualify()\n        has_existing_aggregation = (\n            any(\n                getattr(annotation, \"contains_aggregate\", True)\n                for annotation in self.annotations.values()\n            )\n            or having\n        )\n        set_returning_annotations = {\n            alias\n            for alias, annotation in self.annotation_select.items()\n            if getattr(annotation, \"set_returning\", False)\n        }\n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n        if (\n            isinstance(self.group_by, tuple)\n            or self.is_sliced\n            or has_existing_aggregation\n            or refs_subquery\n            or refs_window\n            or qualify\n            or self.distinct\n            or self.combinator\n            or set_returning_annotations\n        ):\n            from django.db.models.sql.subqueries import AggregateQuery\n\n            inner_query = self.clone()\n            inner_query.subquery = True\n            outer_query = AggregateQuery(self.model, inner_query)\n            inner_query.select_for_update = False\n            inner_query.select_related = False\n            inner_query.set_annotation_mask(self.annotation_select)\n             \n             \n             \n            if inner_query.orderby_issubset_groupby:\n                inner_query.clear_ordering(force=False)\n            if not inner_query.distinct:\n                 \n                 \n                 \n                 \n                 \n                if inner_query.default_cols and has_existing_aggregation:\n                    inner_query.group_by = (\n                        self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                    )\n                inner_query.default_cols = False\n                if not qualify and not self.combinator:\n                     \n                     \n                     \n                     \n                    annotation_mask = set()\n                    if isinstance(self.group_by, tuple):\n                        for expr in self.group_by:\n                            annotation_mask |= expr.get_refs()\n                    for aggregate in aggregates.values():\n                        annotation_mask |= aggregate.get_refs()\n                     \n                     \n                    for annotation_alias, annotation in self.annotation_select.items():\n                        if annotation.get_group_by_cols():\n                            annotation_mask.add(annotation_alias)\n                    inner_query.set_annotation_mask(annotation_mask)\n                     \n                     \n                    annotation_mask |= set_returning_annotations\n\n             \n             \n             \n             \n             \n            col_refs = {}\n            for alias, aggregate in aggregates.items():\n                replacements = {}\n                for col in self._gen_cols([aggregate], resolve_refs=False):\n                    if not (col_ref := col_refs.get(col)):\n                        index = len(col_refs) + 1\n                        col_alias = f\"__col{index}\"\n                        col_ref = Ref(col_alias, col)\n                        col_refs[col] = col_ref\n                        inner_query.add_annotation(col, col_alias)\n                    replacements[col] = col_ref\n                outer_query.annotations[alias] = aggregate.replace_expressions(\n                    replacements\n                )\n            if (\n                inner_query.select == ()\n                and not inner_query.default_cols\n                and not inner_query.annotation_select_mask\n            ):\n                 \n                 \n                 \n                inner_query.select = (\n                    self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                )\n        else:\n            outer_query = self\n            self.select = ()\n            self.selected = None\n            self.default_cols = False\n            self.extra = {}\n            if self.annotations:\n                 \n                 \n                 \n                replacements = {\n                    Ref(alias, annotation): annotation\n                    for alias, annotation in self.annotations.items()\n                }\n                self.annotations = {\n                    alias: aggregate.replace_expressions(replacements)\n                    for alias, aggregate in aggregates.items()\n                }\n            else:\n                self.annotations = aggregates\n            self.set_annotation_mask(aggregates)\n\n        empty_set_result = [\n            expression.empty_result_set_value\n            for expression in outer_query.annotation_select.values()\n        ]\n        elide_empty = not any(result is NotImplemented for result in empty_set_result)\n        outer_query.clear_ordering(force=True)\n        outer_query.clear_limits()\n        outer_query.select_for_update = False\n        outer_query.select_related = False\n        compiler = outer_query.get_compiler(using, elide_empty=elide_empty)\n        result = compiler.execute_sql(SINGLE)\n        if result is None:\n            result = empty_set_result\n        else:\n            cols = outer_query.annotation_select.values()\n            converters = compiler.get_converters(cols)\n            rows = compiler.apply_converters((result,), converters)\n            if compiler.has_composite_fields(cols):\n                rows = compiler.composite_fields_to_tuples(rows, cols)\n            result = next(rows)\n\n        return dict(zip(outer_query.annotation_select, result))\n\n    def get_count(self, using):\n        \n        obj = self.clone()\n        return obj.get_aggregation(using, {\"__count\": Count(\"*\")})[\"__count\"]\n\n    def has_filters(self):\n        return self.where\n\n    def exists(self, limit=True):\n        q = self.clone()\n        if not (q.distinct and q.is_sliced):\n            if q.group_by is True:\n                q.add_fields(\n                    (f.attname for f in self.model._meta.concrete_fields), False\n                )\n                 \n                 \n                q.set_group_by(allow_aliases=False)\n            q.clear_select_clause()\n        if q.combined_queries and q.combinator == \"union\":\n            q.combined_queries = tuple(\n                combined_query.exists(limit=False)\n                for combined_query in q.combined_queries\n            )\n        q.clear_ordering(force=True)\n        if limit is True:\n            q.set_limits(high=1)\n        q.add_annotation(Value(1), \"a\")\n        return q\n\n    def has_results(self, using):\n        q = self.exists()\n        compiler = q.get_compiler(using=using)\n        return compiler.has_results()\n\n    def explain(self, using, format=None, **options):\n        q = self.clone()\n        for option_name in options:\n            if (\n                not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)\n                or \"--\" in option_name\n            ):\n                raise ValueError(f\"Invalid option name: {option_name!r}.\")\n        q.explain_info = ExplainInfo(format, options)\n        compiler = q.get_compiler(using=using)\n        return \"\\n\".join(compiler.explain_query())\n\n    def combine(self, rhs, connector):\n        \n        if self.model != rhs.model:\n            raise TypeError(\"Cannot combine queries on two different base models.\")\n        if self.is_sliced:\n            raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n        if self.distinct != rhs.distinct:\n            raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n        if self.distinct_fields != rhs.distinct_fields:\n            raise TypeError(\"Cannot combine queries with different distinct fields.\")\n\n         \n         \n         \n         \n         \n         \n        initial_alias = self.get_initial_alias()\n        rhs = rhs.clone()\n        rhs.bump_prefix(self, exclude={initial_alias})\n\n         \n        change_map = {}\n        conjunction = connector == AND\n\n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n        reuse = set() if conjunction else set(self.alias_map)\n        joinpromoter = JoinPromoter(connector, 2, False)\n        joinpromoter.add_votes(\n            j for j in self.alias_map if self.alias_map[j].join_type == INNER\n        )\n        rhs_votes = set()\n         \n         \n        rhs_tables = list(rhs.alias_map)[1:]\n        for alias in rhs_tables:\n            join = rhs.alias_map[alias]\n             \n             \n            join = join.relabeled_clone(change_map)\n            new_alias = self.join(join, reuse=reuse)\n            if join.join_type == INNER:\n                rhs_votes.add(new_alias)\n             \n             \n             \n            reuse.discard(new_alias)\n            if alias != new_alias:\n                change_map[alias] = new_alias\n            if not rhs.alias_refcount[alias]:\n                 \n                 \n                 \n                 \n                self.unref_alias(new_alias)\n        joinpromoter.add_votes(rhs_votes)\n        joinpromoter.update_join_types(self)\n\n         \n         \n        self.subq_aliases |= rhs.subq_aliases\n\n         \n         \n        w = rhs.where.clone()\n        w.relabel_aliases(change_map)\n        self.where.add(w, connector)\n\n         \n        if rhs.select:\n            self.set_select([col.relabeled_clone(change_map) for col in rhs.select])\n        else:\n            self.select = ()\n\n        if connector == OR:\n             \n             \n             \n            if self.extra and rhs.extra:\n                raise ValueError(\n                    \"When merging querysets using 'or', you cannot have \"\n                    \"extra(select=...) on both sides.\"\n                )\n        self.extra.update(rhs.extra)\n        extra_select_mask = set()\n        if self.extra_select_mask is not None:\n            extra_select_mask.update(self.extra_select_mask)\n        if rhs.extra_select_mask is not None:\n            extra_select_mask.update(rhs.extra_select_mask)\n        if extra_select_mask:\n            self.set_extra_mask(extra_select_mask)\n        self.extra_tables += rhs.extra_tables\n\n         \n         \n        self.order_by = rhs.order_by or self.order_by\n        self.extra_order_by = rhs.extra_order_by or self.extra_order_by\n\n    def _get_defer_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n         \n         \n         \n         \n        for field in opts.concrete_fields + opts.related_objects:\n            field_mask = mask.pop(field.name, None)\n            field_att_mask = None\n            if field_attname := getattr(field, \"attname\", None):\n                field_att_mask = mask.pop(field_attname, None)\n            if field_mask is None and field_att_mask is None:\n                select_mask.setdefault(field, {})\n            elif field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                 \n                 \n                 \n                 \n                 \n                if field.many_to_many:\n                    continue\n                field_select_mask = select_mask.setdefault(field, {})\n                related_model = field.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n         \n         \n        for field_name, field_mask in mask.items():\n            if filtered_relation := self._filtered_relations.get(field_name):\n                relation = opts.get_field(filtered_relation.relation_name)\n                field_select_mask = select_mask.setdefault((field_name, relation), {})\n                related_model = relation.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n            else:\n                opts.get_field(field_name)\n        return select_mask\n\n    def _get_only_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n         \n        for field_name, field_mask in mask.items():\n            field = opts.get_field(field_name)\n            field_select_mask = select_mask.setdefault(field, {})\n            if field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                related_model = field.remote_field.model._meta.concrete_model\n                self._get_only_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        return select_mask\n\n    def get_select_mask(self):\n        \n        field_names, defer = self.deferred_loading\n        if not field_names:\n            return {}\n        mask = {}\n        for field_name in field_names:\n            part_mask = mask\n            for part in field_name.split(LOOKUP_SEP):\n                part_mask = part_mask.setdefault(part, {})\n        opts = self.get_meta()\n        if defer:\n            return self._get_defer_select_mask(opts, mask)\n        return self._get_only_select_mask(opts, mask)\n\n    def table_alias(self, table_name, create=False, filtered_relation=None):\n        \n        alias_list = self.table_map.get(table_name)\n        if not create and alias_list:\n            alias = alias_list[0]\n            self.alias_refcount[alias] += 1\n            return alias, False\n\n         \n        if alias_list:\n            alias = \"%s%d\" % (self.alias_prefix, len(self.alias_map) + 1)\n            alias_list.append(alias)\n        else:\n             \n            alias = (\n                filtered_relation.alias if filtered_relation is not None else table_name\n            )\n            self.table_map[table_name] = [alias]\n        self.alias_refcount[alias] = 1\n        return alias, True\n\n    def ref_alias(self, alias):\n        \n        self.alias_refcount[alias] += 1\n\n    def unref_alias(self, alias, amount=1):\n        \n        self.alias_refcount[alias] -= amount\n\n    def promote_joins(self, aliases):\n        \n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type is None:\n                 \n                 \n                 \n                continue\n             \n            assert self.alias_map[alias].join_type is not None\n            parent_alias = self.alias_map[alias].parent_alias\n            parent_louter = (\n                parent_alias and self.alias_map[parent_alias].join_type == LOUTER\n            )\n            already_louter = self.alias_map[alias].join_type == LOUTER\n            if (self.alias_map[alias].nullable or parent_louter) and not already_louter:\n                self.alias_map[alias] = self.alias_map[alias].promote()\n                 \n                 \n                aliases.extend(\n                    join\n                    for join in self.alias_map\n                    if self.alias_map[join].parent_alias == alias\n                    and join not in aliases\n                )\n\n    def demote_joins(self, aliases):\n        \n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type == LOUTER:\n                self.alias_map[alias] = self.alias_map[alias].demote()\n                parent_alias = self.alias_map[alias].parent_alias\n                if self.alias_map[parent_alias].join_type == INNER:\n                    aliases.append(parent_alias)\n\n    def reset_refcounts(self, to_counts):\n        \n        for alias, cur_refcount in self.alias_refcount.copy().items():\n            unref_amount = cur_refcount - to_counts.get(alias, 0)\n            self.unref_alias(alias, unref_amount)\n\n    def change_aliases(self, change_map):\n        \n        if not change_map:\n            return self\n         \n         \n         \n        assert set(change_map).isdisjoint(change_map.values())\n\n         \n         \n        self.where.relabel_aliases(change_map)\n        if isinstance(self.group_by, tuple):\n            self.group_by = tuple(\n                [col.relabeled_clone(change_map) for col in self.group_by]\n            )\n        self.select = tuple([col.relabeled_clone(change_map) for col in self.select])\n        self.annotations = self.annotations and {\n            key: col.relabeled_clone(change_map)\n            for key, col in self.annotations.items()\n        }\n\n         \n        for old_alias, new_alias in change_map.items():\n            if old_alias not in self.alias_map:\n                continue\n            alias_data = self.alias_map[old_alias].relabeled_clone(change_map)\n            self.alias_map[new_alias] = alias_data\n            self.alias_refcount[new_alias] = self.alias_refcount[old_alias]\n            del self.alias_refcount[old_alias]\n            del self.alias_map[old_alias]\n\n            table_aliases = self.table_map[alias_data.table_name]\n            for pos, alias in enumerate(table_aliases):\n                if alias == old_alias:\n                    table_aliases[pos] = new_alias\n                    break\n\n         \n         \n        self.external_aliases = {\n             \n            change_map.get(alias, alias): (aliased or alias in change_map)\n            for alias, aliased in self.external_aliases.items()\n        }\n        for combined_query in self.combined_queries:\n            external_change_map = {\n                alias: aliased\n                for alias, aliased in change_map.items()\n                if alias in combined_query.external_aliases\n            }\n            combined_query.change_aliases(external_change_map)\n\n    def bump_prefix(self, other_query, exclude=None):\n        \n\n        def prefix_gen():\n            \n            alphabet = ascii_uppercase\n            prefix = chr(ord(self.alias_prefix) + 1)\n            yield prefix\n            for n in count(1):\n                seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet\n                for s in product(seq, repeat=n):\n                    yield \"\".join(s)\n                prefix = None\n\n        if self.alias_prefix != other_query.alias_prefix:\n             \n            return\n\n         \n         \n         \n         \n        local_recursion_limit = sys.getrecursionlimit() // 16\n        for pos, prefix in enumerate(prefix_gen()):\n            if prefix not in self.subq_aliases:\n                self.alias_prefix = prefix\n                break\n            if pos > local_recursion_limit:\n                raise RecursionError(\n                    \"Maximum recursion depth exceeded: too many subqueries.\"\n                )\n        self.subq_aliases = self.subq_aliases.union([self.alias_prefix])\n        other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases)\n        if exclude is None:\n            exclude = {}\n        self.change_aliases(\n            {\n                alias: \"%s%d\" % (self.alias_prefix, pos)\n                for pos, alias in enumerate(self.alias_map)\n                if alias not in exclude\n            }\n        )\n\n    def get_initial_alias(self):\n        \n        if self.alias_map:\n            alias = self.base_table\n            self.ref_alias(alias)\n        elif self.model:\n            alias = self.join(self.base_table_class(self.get_meta().db_table, None))\n        else:\n            alias = None\n        return alias\n\n    def count_active_tables(self):\n        \n        return len([1 for count in self.alias_refcount.values() if count])\n\n    def join(self, join, reuse=None):\n        \n        reuse_aliases = [\n            a\n            for a, j in self.alias_map.items()\n            if (reuse is None or a in reuse) and j == join\n        ]\n        if reuse_aliases:\n            if join.table_alias in reuse_aliases:\n                reuse_alias = join.table_alias\n            else:\n                 \n                 \n                reuse_alias = reuse_aliases[-1]\n            self.ref_alias(reuse_alias)\n            return reuse_alias\n\n         \n        alias, _ = self.table_alias(\n            join.table_name, create=True, filtered_relation=join.filtered_relation\n        )\n        if join.join_type:\n            if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:\n                join_type = LOUTER\n            else:\n                join_type = INNER\n            join.join_type = join_type\n        join.table_alias = alias\n        self.alias_map[alias] = join\n        if filtered_relation := join.filtered_relation:\n            resolve_reuse = reuse\n            if resolve_reuse is not None:\n                resolve_reuse = set(reuse) | {alias}\n            joins_len = len(self.alias_map)\n            join.filtered_relation = filtered_relation.resolve_expression(\n                self, reuse=resolve_reuse\n            )\n             \n             \n            if joins_len < len(self.alias_map):\n                self.alias_map[alias] = self.alias_map.pop(alias)\n        return alias\n\n    def join_parent_model(self, opts, model, alias, seen):\n        \n        if model in seen:\n            return seen[model]\n        chain = opts.get_base_chain(model)\n        if not chain:\n            return alias\n        curr_opts = opts\n        for int_model in chain:\n            if int_model in seen:\n                curr_opts = int_model._meta\n                alias = seen[int_model]\n                continue\n             \n             \n             \n             \n            if not curr_opts.parents[int_model]:\n                curr_opts = int_model._meta\n                continue\n            link_field = curr_opts.get_ancestor_link(int_model)\n            join_info = self.setup_joins([link_field.name], curr_opts, alias)\n            curr_opts = int_model._meta\n            alias = seen[int_model] = join_info.joins[-1]\n        return alias or seen[None]\n\n    def check_alias(self, alias):\n         \n        if \"%\" in alias:\n            warnings.warn(\n                \"Using percent signs in a column alias is deprecated.\",\n                category=RemovedInDjango70Warning,\n                skip_file_prefixes=django_file_prefixes(),\n            )\n        if FORBIDDEN_ALIAS_PATTERN.search(alias):\n            raise ValueError(\n                \"Column aliases cannot contain whitespace characters, hashes, \"\n                 \n                 \n                 \n                 \n                \"control characters, quotation marks, semicolons, or SQL comments.\"\n            )\n\n    def add_annotation(self, annotation, alias, select=True):\n        \n        self.check_alias(alias)\n        annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None)\n        if select:\n            self.append_annotation_mask([alias])\n        else:\n            self.set_annotation_mask(set(self.annotation_select).difference({alias}))\n        self.annotations[alias] = annotation\n        if select and self.selected:\n            self.selected[alias] = alias\n\n    @property\n    def _subquery_fields_len(self):\n        if not self.has_select_fields or not self.select:\n            return len(self.model._meta.pk_fields)\n        return len(self.select) + sum(\n            len(expr.targets) - 1 for expr in self.select if isinstance(expr, ColPairs)\n        )\n\n    def resolve_expression(self, query, *args, **kwargs):\n        clone = self.clone()\n         \n         \n        clone.bump_prefix(query)\n        clone.subquery = True\n        clone.where.resolve_expression(query, *args, **kwargs)\n         \n        if clone.combinator:\n            clone.combined_queries = tuple(\n                [\n                    combined_query.resolve_expression(query, *args, **kwargs)\n                    for combined_query in clone.combined_queries\n                ]\n            )\n        for key, value in clone.annotations.items():\n            resolved = value.resolve_expression(query, *args, **kwargs)\n            if hasattr(resolved, \"external_aliases\"):\n                resolved.external_aliases.update(clone.external_aliases)\n            clone.annotations[key] = resolved\n         \n        for alias, table in query.alias_map.items():\n            clone.external_aliases[alias] = (\n                isinstance(table, Join)\n                and table.join_field.related_model._meta.db_table != alias\n            ) or (\n                isinstance(table, BaseTable) and table.table_name != table.table_alias\n            )\n        return clone\n\n    def get_external_cols(self):\n        exprs = chain(self.annotations.values(), self.where.children)\n        return [\n            col\n            for col in self._gen_cols(exprs, include_external=True)\n            if col.alias in self.external_aliases\n        ]\n\n    def get_group_by_cols(self, wrapper=None):\n         \n         \n         \n         \n        external_cols = self.get_external_cols()\n        if any(col.possibly_multivalued for col in external_cols):\n            return [wrapper or self]\n        return external_cols\n\n    def as_sql(self, compiler, connection):\n         \n         \n        if (\n            self.subquery\n            and not connection.features.ignores_unnecessary_order_by_in_subqueries\n        ):\n            self.clear_ordering(force=False)\n            for query in self.combined_queries:\n                query.clear_ordering(force=False)\n        sql, params = self.get_compiler(connection=connection).as_sql()\n        if self.subquery:\n            sql = \"(%s)\" % sql\n        return sql, params\n\n    def resolve_lookup_value(self, value, can_reuse, allow_joins, summarize=False):\n        if hasattr(value, \"resolve_expression\"):\n            value = value.resolve_expression(\n                self,\n                reuse=can_reuse,\n                allow_joins=allow_joins,\n                summarize=summarize,\n            )\n        elif isinstance(value, (list, tuple)):\n             \n             \n            values = (\n                self.resolve_lookup_value(sub_value, can_reuse, allow_joins, summarize)\n                for sub_value in value\n            )\n            type_ = type(value)\n            if hasattr(type_, \"_make\"):   \n                return type_(*values)\n            return type_(values)\n        return value\n\n    def solve_lookup_type(self, lookup, summarize=False):\n        \n        lookup_splitted = lookup.split(LOOKUP_SEP)\n        if self.annotations:\n            annotation, expression_lookups = refs_expression(\n                lookup_splitted, self.annotations\n            )\n            if annotation:\n                expression = self.annotations[annotation]\n                if summarize:\n                    expression = Ref(annotation, expression)\n                return expression_lookups, (), expression\n        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())\n        field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)]\n        if len(lookup_parts) > 1 and not field_parts:\n            raise FieldError(\n                'Invalid lookup \"%s\" for model %s\".'\n                % (lookup, self.get_meta().model.__name__)\n            )\n        return lookup_parts, field_parts, False\n\n    def check_query_object_type(self, value, opts, field):\n        \n        if hasattr(value, \"_meta\"):\n            if not check_rel_lookup_compatibility(value._meta.model, opts, field):\n                raise ValueError(\n                    'Cannot query \"%s\": Must be \"%s\" instance.'\n                    % (value, opts.object_name)\n                )\n\n    def check_related_objects(self, field, value, opts):\n        \n        if field.is_relation:\n             \n             \n             \n             \n             \n            if (\n                isinstance(value, Query)\n                and not value.has_select_fields\n                and not check_rel_lookup_compatibility(value.model, opts, field)\n            ):\n                raise ValueError(\n                    'Cannot use QuerySet for \"%s\": Use a QuerySet for \"%s\".'\n                    % (value.model._meta.object_name, opts.object_name)\n                )\n            elif hasattr(value, \"_meta\"):\n                self.check_query_object_type(value, opts, field)\n            elif hasattr(value, \"__iter__\"):\n                for v in value:\n                    self.check_query_object_type(v, opts, field)\n\n    def check_filterable(self, expression):\n        \n        if hasattr(expression, \"resolve_expression\") and not getattr(\n            expression, \"filterable\", True\n        ):\n            raise NotSupportedError(\n                expression.__class__.__name__ + \" is disallowed in the filter \"\n                \"clause.\"\n            )\n        if hasattr(expression, \"get_source_expressions\"):\n            for expr in expression.get_source_expressions():\n                self.check_filterable(expr)\n\n    def build_lookup(self, lookups, lhs, rhs):\n        \n         \n        *transforms, lookup_name = lookups or [\"exact\"]\n        for name in transforms:\n            lhs = self.try_transform(lhs, name, lookups)\n         \n         \n        lookup_class = lhs.get_lookup(lookup_name)\n        if not lookup_class:\n             \n             \n            lhs = self.try_transform(lhs, lookup_name)\n            lookup_name = \"exact\"\n            lookup_class = lhs.get_lookup(lookup_name)\n            if not lookup_class:\n                return\n\n        lookup = lookup_class(lhs, rhs)\n         \n         \n        if lookup.rhs is None and not lookup.can_use_none_as_rhs:\n            if lookup_name not in (\"exact\", \"iexact\"):\n                raise ValueError(\"Cannot use None as a query value\")\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n         \n         \n         \n         \n        if (\n            lookup_name in (\"exact\", \"iexact\")\n            and lookup.rhs == \"\"\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        ):\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        return lookup\n\n    def try_transform(self, lhs, name, lookups=None):\n        \n        transform_class = lhs.get_transform(name)\n        if transform_class:\n            return transform_class(lhs)\n        else:\n            output_field = lhs.output_field.__class__\n            suggested_lookups = difflib.get_close_matches(\n                name, lhs.output_field.get_lookups()\n            )\n            if suggested_lookups:\n                suggestion = \", perhaps you meant %s?\" % \" or \".join(suggested_lookups)\n            else:\n                suggestion = \".\"\n            if lookups is not None:\n                name_index = lookups.index(name)\n                unsupported_lookup = LOOKUP_SEP.join(lookups[name_index:])\n            else:\n                unsupported_lookup = name\n            raise FieldError(\n                \"Unsupported lookup '%s' for %s or join on the field not \"\n                \"permitted%s\" % (unsupported_lookup, output_field.__name__, suggestion)\n            )\n\n    def build_filter(\n        self,\n        filter_expr,\n        branch_negated=False,\n        current_negated=False,\n        can_reuse=None,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \n        if isinstance(filter_expr, dict):\n            raise FieldError(\"Cannot parse keyword query as dict\")\n        if isinstance(filter_expr, Q):\n            return self._add_q(\n                filter_expr,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                used_aliases=can_reuse,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n        if hasattr(filter_expr, \"resolve_expression\"):\n            if not getattr(filter_expr, \"conditional\", False):\n                raise TypeError(\"Cannot filter against a non-conditional expression.\")\n            condition = filter_expr.resolve_expression(\n                self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize\n            )\n            if not isinstance(condition, Lookup):\n                condition = self.build_lookup([\"exact\"], condition, True)\n            return WhereNode([condition], connector=AND), []\n        arg, value = filter_expr\n        if not arg:\n            raise FieldError(\"Cannot parse keyword query %r\" % arg)\n        lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize)\n\n        if check_filterable:\n            self.check_filterable(reffed_expression)\n\n        if not allow_joins and len(parts) > 1:\n            raise FieldError(\"Joined field references are not permitted in this query\")\n\n        pre_joins = self.alias_refcount.copy()\n        value = self.resolve_lookup_value(value, can_reuse, allow_joins, summarize)\n        used_joins = {\n            k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)\n        }\n\n        if check_filterable:\n            self.check_filterable(value)\n\n        if reffed_expression:\n            condition = self.build_lookup(lookups, reffed_expression, value)\n            return WhereNode([condition], connector=AND), []\n\n        opts = self.get_meta()\n        alias = self.get_initial_alias()\n        allow_many = not branch_negated or not split_subq\n\n        try:\n            join_info = self.setup_joins(\n                parts,\n                opts,\n                alias,\n                can_reuse=can_reuse,\n                allow_many=allow_many,\n            )\n\n             \n            if isinstance(value, Iterator):\n                value = list(value)\n            self.check_related_objects(join_info.final_field, value, join_info.opts)\n\n             \n             \n            self._lookup_joins = join_info.joins\n        except MultiJoin as e:\n            return self.split_exclude(filter_expr, can_reuse, e.names_with_path)\n\n         \n         \n        used_joins.update(join_info.joins)\n        targets, alias, join_list = self.trim_joins(\n            join_info.targets, join_info.joins, join_info.path\n        )\n        if can_reuse is not None:\n            can_reuse.update(join_list)\n\n        if join_info.final_field.is_relation:\n            if len(targets) == 1:\n                col = self._get_col(targets[0], join_info.final_field, alias)\n            else:\n                col = ColPairs(alias, targets, join_info.targets, join_info.final_field)\n        else:\n            col = self._get_col(targets[0], join_info.final_field, alias)\n\n        condition = self.build_lookup(lookups, col, value)\n        lookup_type = condition.lookup_name\n        clause = WhereNode([condition], connector=AND)\n\n        require_outer = (\n            lookup_type == \"isnull\" and condition.rhs is True and not current_negated\n        )\n        if (\n            current_negated\n            and (lookup_type != \"isnull\" or condition.rhs is False)\n            and condition.rhs is not None\n        ):\n            require_outer = True\n            if lookup_type != \"isnull\":\n                 \n                 \n                 \n                 \n                 \n                 \n                 \n                 \n                 \n                if (\n                    self.is_nullable(targets[0])\n                    or self.alias_map[join_list[-1]].join_type == LOUTER\n                ):\n                    lookup_class = targets[0].get_lookup(\"isnull\")\n                    col = self._get_col(targets[0], join_info.targets[0], alias)\n                     \n                    if (\n                        lookup_type == \"in\"\n                         \n                        and isinstance(condition.rhs, Iterable)\n                        and not isinstance(condition.rhs, (str, bytes))\n                        and any(v is None for v in condition.rhs)\n                    ):\n                        clause.add(lookup_class(col, True), OR)\n                    else:\n                        clause.add(lookup_class(col, False), AND)\n                 \n                 \n                if isinstance(value, Col) and self.is_nullable(value.target):\n                    lookup_class = value.target.get_lookup(\"isnull\")\n                    clause.add(lookup_class(value, False), AND)\n        return clause, used_joins if not require_outer else ()\n\n    def add_filter(self, filter_lhs, filter_rhs):\n        self.add_q(Q((filter_lhs, filter_rhs)))\n\n    def add_q(self, q_object, reuse_all=False):\n        \n         \n         \n         \n         \n         \n         \n        existing_inner = {\n            a for a in self.alias_map if self.alias_map[a].join_type == INNER\n        }\n        if reuse_all:\n            can_reuse = set(self.alias_map)\n        else:\n            can_reuse = self.used_aliases\n        clause, _ = self._add_q(q_object, can_reuse)\n        if clause:\n            self.where.add(clause, AND)\n        self.demote_joins(existing_inner)\n\n    def build_where(self, filter_expr):\n        return self.build_filter(filter_expr, allow_joins=False)[0]\n\n    def clear_where(self):\n        self.where = WhereNode()\n\n    def _add_q(\n        self,\n        q_object,\n        used_aliases,\n        branch_negated=False,\n        current_negated=False,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \n        connector = q_object.connector\n        current_negated ^= q_object.negated\n        branch_negated = branch_negated or q_object.negated\n        target_clause = WhereNode(connector=connector, negated=q_object.negated)\n        joinpromoter = JoinPromoter(\n            q_object.connector, len(q_object.children), current_negated\n        )\n        for child in q_object.children:\n            child_clause, needed_inner = self.build_filter(\n                child,\n                can_reuse=used_aliases,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n            joinpromoter.add_votes(needed_inner)\n            if child_clause:\n                target_clause.add(child_clause, connector)\n        if update_join_types:\n            needed_inner = joinpromoter.update_join_types(self)\n        else:\n            needed_inner = []\n        return target_clause, needed_inner\n\n    def add_filtered_relation(self, filtered_relation, alias):\n        if \".\" in alias:\n            raise ValueError(\n                \"FilteredRelation doesn't support aliases with periods \"\n                \"(got %r).\" % alias\n            )\n        self.check_alias(alias)\n        filtered_relation.alias = alias\n        relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(\n            filtered_relation.relation_name\n        )\n        if relation_lookup_parts:\n            raise ValueError(\n                \"FilteredRelation's relation_name cannot contain lookups \"\n                \"(got %r).\" % filtered_relation.relation_name\n            )\n        for lookup in get_children_from_q(filtered_relation.condition):\n            lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)\n            shift = 2 if not lookup_parts else 1\n            lookup_field_path = lookup_field_parts[:-shift]\n            for idx, lookup_field_part in enumerate(lookup_field_path):\n                if len(relation_field_parts) > idx:\n                    if relation_field_parts[idx] != lookup_field_part:\n                        raise ValueError(\n                            \"FilteredRelation's condition doesn't support \"\n                            \"relations outside the %r (got %r).\"\n                            % (filtered_relation.relation_name, lookup)\n                        )\n            if len(lookup_field_parts) > len(relation_field_parts) + 1:\n                raise ValueError(\n                    \"FilteredRelation's condition doesn't support nested \"\n                    \"relations deeper than the relation_name (got %r for \"\n                    \"%r).\" % (lookup, filtered_relation.relation_name)\n                )\n        filtered_relation = filtered_relation.clone()\n        filtered_relation.condition = rename_prefix_from_q(\n            filtered_relation.relation_name,\n            alias,\n            filtered_relation.condition,\n        )\n        self._filtered_relations[filtered_relation.alias] = filtered_relation\n\n    def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):\n        \n        path, names_with_path = [], []\n        for pos, name in enumerate(names):\n            cur_names_with_path = (name, [])\n            if name == \"pk\" and opts is not None:\n                name = opts.pk.name\n\n            field = None\n            filtered_relation = None\n            try:\n                if opts is None:\n                    raise FieldDoesNotExist\n                field = opts.get_field(name)\n            except FieldDoesNotExist:\n                if name in self.annotations:\n                    field = self.annotations[name].output_field\n                elif name in self._filtered_relations and pos == 0:\n                    filtered_relation = self._filtered_relations[name]\n                    if LOOKUP_SEP in filtered_relation.relation_name:\n                        parts = filtered_relation.relation_name.split(LOOKUP_SEP)\n                        filtered_relation_path, field, _, _ = self.names_to_path(\n                            parts,\n                            opts,\n                            allow_many,\n                            fail_on_missing,\n                        )\n                        path.extend(filtered_relation_path[:-1])\n                    else:\n                        field = opts.get_field(filtered_relation.relation_name)\n            if field is not None:\n                 \n                 \n                 \n                if field.is_relation and not field.related_model:\n                    raise FieldError(\n                        \"Field %r does not generate an automatic reverse \"\n                        \"relation and therefore cannot be used for reverse \"\n                        \"querying. If it is a GenericForeignKey, consider \"\n                        \"adding a GenericRelation.\" % name\n                    )\n                try:\n                    model = field.model._meta.concrete_model\n                except AttributeError:\n                     \n                     \n                    model = None\n            else:\n                 \n                 \n                pos -= 1\n                if pos == -1 or fail_on_missing:\n                    available = sorted(\n                        [\n                            *get_field_names_from_opts(opts),\n                            *self.annotations,\n                            *self._filtered_relations,\n                        ]\n                    )\n                    raise FieldError(\n                        \"Cannot resolve keyword '%s' into field. \"\n                        \"Choices are: %s\" % (name, \", \".join(available))\n                    )\n                break\n             \n             \n             \n            if opts is not None and model is not opts.model:\n                path_to_parent = opts.get_path_to_parent(model)\n                if path_to_parent:\n                    path.extend(path_to_parent)\n                    cur_names_with_path[1].extend(path_to_parent)\n                    opts = path_to_parent[-1].to_opts\n            if hasattr(field, \"path_infos\"):\n                if filtered_relation:\n                    pathinfos = field.get_path_info(filtered_relation)\n                else:\n                    pathinfos = field.path_infos\n                if not allow_many:\n                    for inner_pos, p in enumerate(pathinfos):\n                        if p.m2m:\n                            cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1])\n                            names_with_path.append(cur_names_with_path)\n                            raise MultiJoin(pos + 1, names_with_path)\n                last = pathinfos[-1]\n                path.extend(pathinfos)\n                final_field = last.join_field\n                opts = last.to_opts\n                targets = last.target_fields\n                cur_names_with_path[1].extend(pathinfos)\n                names_with_path.append(cur_names_with_path)\n            else:\n                 \n                final_field = field\n                targets = (field,)\n                if fail_on_missing and pos + 1 != len(names):\n                    raise FieldError(\n                        \"Cannot resolve keyword %r into field. Join on '%s'\"\n                        \" not permitted.\" % (names[pos + 1], name)\n                    )\n                break\n        return path, final_field, targets, names[pos + 1 :]\n\n    def setup_joins(\n        self,\n        names,\n        opts,\n        alias,\n        can_reuse=None,\n        allow_many=True,\n    ):\n        \n        joins = [alias]\n         \n         \n         \n         \n\n        def final_transformer(field, alias):\n            if not self.alias_cols:\n                alias = None\n            return field.get_col(alias)\n\n         \n         \n        last_field_exception = None\n        for pivot in range(len(names), 0, -1):\n            try:\n                path, final_field, targets, rest = self.names_to_path(\n                    names[:pivot],\n                    opts,\n                    allow_many,\n                    fail_on_missing=True,\n                )\n            except FieldError as exc:\n                if pivot == 1:\n                     \n                     \n                    raise\n                else:\n                    last_field_exception = exc\n            else:\n                 \n                 \n                transforms = names[pivot:]\n                break\n        for name in transforms:\n\n            def transform(field, alias, *, name, previous):\n                try:\n                    wrapped = previous(field, alias)\n                    return self.try_transform(wrapped, name)\n                except FieldError:\n                     \n                    if isinstance(final_field, Field) and last_field_exception:\n                        raise last_field_exception\n                    else:\n                        raise\n\n            final_transformer = functools.partial(\n                transform, name=name, previous=final_transformer\n            )\n            final_transformer.has_transforms = True\n         \n         \n         \n        for join in path:\n            if join.filtered_relation:\n                filtered_relation = join.filtered_relation.clone()\n                table_alias = filtered_relation.alias\n            else:\n                filtered_relation = None\n                table_alias = None\n            opts = join.to_opts\n            if join.direct:\n                nullable = self.is_nullable(join.join_field)\n            else:\n                nullable = True\n            connection = self.join_class(\n                opts.db_table,\n                alias,\n                table_alias,\n                INNER,\n                join.join_field,\n                nullable,\n                filtered_relation=filtered_relation,\n            )\n            reuse = can_reuse if join.m2m else None\n            alias = self.join(connection, reuse=reuse)\n            joins.append(alias)\n            if join.filtered_relation and can_reuse is not None:\n                can_reuse.add(alias)\n        return JoinInfo(final_field, targets, opts, joins, path, final_transformer)\n\n    def trim_joins(self, targets, joins, path):\n        \n        joins = joins[:]\n        for pos, info in enumerate(reversed(path)):\n            if len(joins) == 1 or not info.direct:\n                break\n            if info.filtered_relation:\n                break\n            join_targets = {t.column for t in info.join_field.foreign_related_fields}\n            cur_targets = {t.column for t in targets}\n            if not cur_targets.issubset(join_targets):\n                break\n            targets_dict = {\n                r[1].column: r[0]\n                for r in info.join_field.related_fields\n                if r[1].column in cur_targets\n            }\n            targets = tuple(targets_dict[t.column] for t in targets)\n            self.unref_alias(joins.pop())\n        return targets, joins[-1], joins\n\n    @classmethod\n    def _gen_cols(cls, exprs, include_external=False, resolve_refs=True):\n        for expr in exprs:\n            if isinstance(expr, Col):\n                yield expr\n            elif include_external and callable(\n                getattr(expr, \"get_external_cols\", None)\n            ):\n                yield from expr.get_external_cols()\n            elif hasattr(expr, \"get_source_expressions\"):\n                if not resolve_refs and isinstance(expr, Ref):\n                    continue\n                yield from cls._gen_cols(\n                    expr.get_source_expressions(),\n                    include_external=include_external,\n                    resolve_refs=resolve_refs,\n                )\n\n    @classmethod\n    def _gen_col_aliases(cls, exprs):\n        yield from (expr.alias for expr in cls._gen_cols(exprs))\n\n    def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):\n        annotation = self.annotations.get(name)\n        if annotation is not None:\n            if not allow_joins:\n                for alias in self._gen_col_aliases([annotation]):\n                    if isinstance(self.alias_map[alias], Join):\n                        raise FieldError(\n                            \"Joined field references are not permitted in this query\"\n                        )\n            if summarize:\n                 \n                 \n                 \n                 \n                 \n                if name not in self.annotation_select:\n                    raise FieldError(\n                        \"Cannot aggregate over the '%s' alias. Use annotate() \"\n                        \"to promote it.\" % name\n                    )\n                return Ref(name, self.annotation_select[name])\n            else:\n                return annotation\n        else:\n            field_list = name.split(LOOKUP_SEP)\n            annotation = self.annotations.get(field_list[0])\n            if annotation is not None:\n                for transform in field_list[1:]:\n                    annotation = self.try_transform(annotation, transform)\n                return annotation\n            join_info = self.setup_joins(\n                field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse\n            )\n            targets, final_alias, join_list = self.trim_joins(\n                join_info.targets, join_info.joins, join_info.path\n            )\n            if not allow_joins and len(join_list) > 1:\n                raise FieldError(\n                    \"Joined field references are not permitted in this query\"\n                )\n            if len(targets) > 1:\n                raise FieldError(\n                    \"Referencing multicolumn fields with F() objects isn't supported\"\n                )\n             \n             \n            transform = join_info.transform_function(targets[0], final_alias)\n            if reuse is not None:\n                reuse.update(join_list)\n            return transform\n\n    def split_exclude(self, filter_expr, can_reuse, names_with_path):\n        \n         \n        query = self.__class__(self.model)\n        query._filtered_relations = self._filtered_relations\n        filter_lhs, filter_rhs = filter_expr\n        if isinstance(filter_rhs, OuterRef):\n            filter_rhs = OuterRef(filter_rhs)\n        elif isinstance(filter_rhs, F):\n            filter_rhs = OuterRef(filter_rhs.name)\n        query.add_filter(filter_lhs, filter_rhs)\n        query.clear_ordering(force=True)\n         \n         \n        trimmed_prefix, contains_louter = query.trim_start(names_with_path)\n\n        col = query.select[0]\n        select_field = col.target\n        alias = col.alias\n        if alias in can_reuse:\n            pk = select_field.model._meta.pk\n             \n             \n            query.bump_prefix(self)\n            lookup_class = select_field.get_lookup(\"exact\")\n             \n             \n            lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias))\n            query.where.add(lookup, AND)\n            query.external_aliases[alias] = True\n        else:\n            lookup_class = select_field.get_lookup(\"exact\")\n            lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix))\n            query.where.add(lookup, AND)\n\n        condition, needed_inner = self.build_filter(Exists(query))\n\n        if contains_louter:\n            or_null_condition, _ = self.build_filter(\n                (\"%s__isnull\" % trimmed_prefix, True),\n                current_negated=True,\n                branch_negated=True,\n                can_reuse=can_reuse,\n            )\n            condition.add(or_null_condition, OR)\n             \n             \n             \n             \n             \n        return condition, needed_inner\n\n    def set_empty(self):\n        self.where.add(NothingNode(), AND)\n        for query in self.combined_queries:\n            query.set_empty()\n\n    def is_empty(self):\n        return any(isinstance(c, NothingNode) for c in self.where.children)\n\n    def set_limits(self, low=None, high=None):\n        \n        if high is not None:\n            if self.high_mark is not None:\n                self.high_mark = min(self.high_mark, self.low_mark + high)\n            else:\n                self.high_mark = self.low_mark + high\n        if low is not None:\n            if self.high_mark is not None:\n                self.low_mark = min(self.high_mark, self.low_mark + low)\n            else:\n                self.low_mark = self.low_mark + low\n\n        if self.low_mark == self.high_mark:\n            self.set_empty()\n\n    def clear_limits(self):\n        \n        self.low_mark, self.high_mark = 0, None\n\n    @property\n    def is_sliced(self):\n        return self.low_mark != 0 or self.high_mark is not None\n\n    def has_limit_one(self):\n        return self.high_mark is not None and (self.high_mark - self.low_mark) == 1\n\n    def can_filter(self):\n        \n        return not self.is_sliced\n\n    def clear_select_clause(self):\n        \n        self.select = ()\n        self.default_cols = False\n        self.select_related = False\n        self.set_extra_mask(())\n        self.set_annotation_mask(())\n        self.selected = None\n\n    def clear_select_fields(self):\n        \n        self.select = ()\n        self.values_select = ()\n        self.selected = None\n\n    def add_select_col(self, col, name):\n        self.select += (col,)\n        self.values_select += (name,)\n        self.selected[name] = len(self.select) - 1\n\n    def set_select(self, cols):\n        self.default_cols = False\n        self.select = tuple(cols)\n\n    def add_distinct_fields(self, *field_names):\n        \n        self.distinct_fields = field_names\n        self.distinct = True\n\n    def add_fields(self, field_names, allow_m2m=True):\n        \n        alias = self.get_initial_alias()\n        opts = self.get_meta()\n\n        try:\n            cols = []\n            for name in field_names:\n                 \n                 \n                join_info = self.setup_joins(\n                    name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m\n                )\n                targets, final_alias, joins = self.trim_joins(\n                    join_info.targets,\n                    join_info.joins,\n                    join_info.path,\n                )\n                if len(targets) > 1:\n                    transformed_targets = [\n                        join_info.transform_function(target, final_alias)\n                        for target in targets\n                    ]\n                    cols.append(\n                        ColPairs(\n                            final_alias if self.alias_cols else None,\n                            [col.target for col in transformed_targets],\n                            [col.output_field for col in transformed_targets],\n                            join_info.final_field,\n                        )\n                    )\n                else:\n                    cols.append(join_info.transform_function(targets[0], final_alias))\n            if cols:\n                self.set_select(cols)\n        except MultiJoin:\n            raise FieldError(\"Invalid field name: '%s'\" % name)\n        except FieldError:\n            if LOOKUP_SEP in name:\n                 \n                 \n                raise\n            else:\n                names = sorted(\n                    [\n                        *get_field_names_from_opts(opts),\n                        *self.extra,\n                        *self.annotation_select,\n                        *self._filtered_relations,\n                    ]\n                )\n                raise FieldError(\n                    \"Cannot resolve keyword %r into field. \"\n                    \"Choices are: %s\" % (name, \", \".join(names))\n                )\n\n    def add_ordering(self, *ordering):\n        \n        errors = []\n        for item in ordering:\n            if isinstance(item, str):\n                if item == \"?\":\n                    continue\n                item = item.removeprefix(\"-\")\n                if item in self.annotations:\n                    continue\n                if self.extra and item in self.extra:\n                    continue\n                 \n                 \n                self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)\n            elif not hasattr(item, \"resolve_expression\"):\n                errors.append(item)\n            if getattr(item, \"contains_aggregate\", False):\n                raise FieldError(\n                    \"Using an aggregate in order_by() without also including \"\n                    \"it in annotate() is not allowed: %s\" % item\n                )\n        if errors:\n            raise FieldError(\"Invalid order_by arguments: %s\" % errors)\n        if ordering:\n            self.order_by += ordering\n        else:\n            self.default_ordering = False\n\n    @property\n    def orderby_issubset_groupby(self):\n        if self.extra_order_by:\n             \n             \n            return False\n        if self.group_by in (None, True):\n             \n             \n             \n            return True\n        if not self.order_by:\n             \n             \n            return True\n         \n        q = self.clone()\n        order_by_set = set()\n        for order_by in q.order_by:\n            if hasattr(order_by, \"resolve_expression\"):\n                order_by_set.add(order_by.resolve_expression(q))\n            elif order_by == \"?\":\n                 \n                return False\n            else:\n                order_by_set.add(F(order_by.removeprefix(\"-\")).resolve_expression(q))\n        return order_by_set.issubset(self.group_by)\n\n    def clear_ordering(self, force=False, clear_default=True):\n        \n        if not force and (\n            self.is_sliced or self.distinct_fields or self.select_for_update\n        ):\n            return\n        self.order_by = ()\n        self.extra_order_by = ()\n        if clear_default:\n            self.default_ordering = False\n         \n         \n         \n        for query in self.combined_queries:\n            query.clear_ordering(force=False, clear_default=clear_default)\n\n    def set_group_by(self, allow_aliases=True):\n        \n        if allow_aliases and self.values_select:\n             \n             \n            group_by_annotations = {}\n            values_select = {}\n            for alias, expr in zip(self.values_select, self.select):\n                if isinstance(expr, Col):\n                    values_select[alias] = expr\n                else:\n                    group_by_annotations[alias] = expr\n            self.annotations = {**group_by_annotations, **self.annotations}\n            self.append_annotation_mask(group_by_annotations)\n            self.select = tuple(values_select.values())\n            self.values_select = tuple(values_select)\n            if self.selected is not None:\n                for index, value_select in enumerate(values_select):\n                    self.selected[value_select] = index\n        group_by = list(self.select)\n        for alias, annotation in self.annotation_select.items():\n            if not (group_by_cols := annotation.get_group_by_cols()):\n                continue\n            if allow_aliases and not annotation.contains_aggregate:\n                group_by.append(Ref(alias, annotation))\n            else:\n                group_by.extend(group_by_cols)\n        self.group_by = tuple(group_by)\n\n    def add_select_related(self, fields):\n        \n        if isinstance(self.select_related, bool):\n            field_dict = {}\n        else:\n            field_dict = self.select_related\n        for field in fields:\n            d = field_dict\n            for part in field.split(LOOKUP_SEP):\n                d = d.setdefault(part, {})\n        self.select_related = field_dict\n\n    def add_extra(self, select, select_params, where, params, tables, order_by):\n        \n        if select:\n             \n             \n             \n             \n            select_pairs = {}\n            if select_params:\n                param_iter = iter(select_params)\n            else:\n                param_iter = iter([])\n            for name, entry in select.items():\n                self.check_alias(name)\n                entry = str(entry)\n                entry_params = []\n                pos = entry.find(\"%s\")\n                while pos != -1:\n                    if pos == 0 or entry[pos - 1] != \"%\":\n                        entry_params.append(next(param_iter))\n                    pos = entry.find(\"%s\", pos + 2)\n                select_pairs[name] = (entry, entry_params)\n            self.extra.update(select_pairs)\n        if where or params:\n            self.where.add(ExtraWhere(where, params), AND)\n        if tables:\n            self.extra_tables += tuple(tables)\n        if order_by:\n            self.extra_order_by = order_by\n\n    def clear_deferred_loading(self):\n        \n        self.deferred_loading = (frozenset(), True)\n\n    def add_deferred_loading(self, field_names):\n        \n         \n         \n         \n         \n        existing, defer = self.deferred_loading\n        if defer:\n             \n            self.deferred_loading = existing.union(field_names), True\n        else:\n             \n            if new_existing := existing.difference(field_names):\n                self.deferred_loading = new_existing, False\n            else:\n                self.clear_deferred_loading()\n                if new_only := set(field_names).difference(existing):\n                    self.deferred_loading = new_only, True\n\n    def add_immediate_loading(self, field_names):\n        \n        existing, defer = self.deferred_loading\n        field_names = set(field_names)\n        if \"pk\" in field_names:\n            field_names.remove(\"pk\")\n            field_names.add(self.get_meta().pk.name)\n\n        if defer:\n             \n             \n            self.deferred_loading = field_names.difference(existing), False\n        else:\n             \n            self.deferred_loading = frozenset(field_names), False\n\n    def set_annotation_mask(self, names):\n        \n        if names is None:\n            self.annotation_select_mask = None\n        else:\n            self.annotation_select_mask = set(names)\n            if self.selected:\n                 \n                self.selected = {\n                    key: value\n                    for key, value in self.selected.items()\n                    if not isinstance(value, str)\n                    or value in self.annotation_select_mask\n                }\n                 \n                for name in names:\n                    self.selected[name] = name\n        self._annotation_select_cache = None\n\n    def append_annotation_mask(self, names):\n        if self.annotation_select_mask is not None:\n            self.set_annotation_mask(self.annotation_select_mask.union(names))\n\n    def set_extra_mask(self, names):\n        \n        if names is None:\n            self.extra_select_mask = None\n        else:\n            self.extra_select_mask = set(names)\n        self._extra_select_cache = None\n\n    @property\n    def has_select_fields(self):\n        return self.selected is not None\n\n    def set_values(self, fields):\n        self.select_related = False\n        self.clear_deferred_loading()\n        self.clear_select_fields()\n\n        selected = {}\n        if fields:\n            for field in fields:\n                self.check_alias(field)\n            field_names = []\n            extra_names = []\n            annotation_names = []\n            if not self.extra and not self.annotations:\n                 \n                 \n                field_names = list(fields)\n                selected = dict(zip(fields, range(len(fields))))\n            else:\n                self.default_cols = False\n                for f in fields:\n                    if extra := self.extra_select.get(f):\n                        extra_names.append(f)\n                        selected[f] = RawSQL(*extra)\n                    elif f in self.annotation_select:\n                        annotation_names.append(f)\n                        selected[f] = f\n                    elif f in self.annotations:\n                        if self.annotation_select:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. It was excluded \"\n                                f\"by a previous values() or values_list() call. \"\n                                f\"Include '{f}' in that call to select it.\"\n                            )\n                        else:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. Use annotate() \"\n                                f\"to promote it.\"\n                            )\n                    else:\n                         \n                         \n                         \n                        if self.annotation_select:\n                            self.names_to_path(f.split(LOOKUP_SEP), self.model._meta)\n                        selected[f] = len(field_names)\n                        field_names.append(f)\n            self.set_extra_mask(extra_names)\n            self.set_annotation_mask(annotation_names)\n        else:\n            field_names = [f.attname for f in self.model._meta.concrete_fields]\n            selected = dict.fromkeys(field_names, None)\n         \n         \n        if self.group_by is True:\n            self.add_fields(\n                (f.attname for f in self.model._meta.concrete_fields), False\n            )\n             \n             \n            self.set_group_by(allow_aliases=False)\n            self.clear_select_fields()\n        elif self.group_by:\n             \n             \n            group_by = []\n            for expr in self.group_by:\n                if isinstance(expr, Ref) and expr.refs not in selected:\n                    expr = self.annotations[expr.refs]\n                group_by.append(expr)\n            self.group_by = tuple(group_by)\n\n        self.values_select = tuple(field_names)\n        self.add_fields(field_names, True)\n        self.selected = selected if fields else None\n\n    @property\n    def annotation_select(self):\n        \n        if self._annotation_select_cache is not None:\n            return self._annotation_select_cache\n        elif not self.annotations:\n            return {}\n        elif self.annotation_select_mask is not None:\n            self._annotation_select_cache = {\n                k: v\n                for k, v in self.annotations.items()\n                if k in self.annotation_select_mask\n            }\n            return self._annotation_select_cache\n        else:\n            return self.annotations\n\n    @property\n    def extra_select(self):\n        if self._extra_select_cache is not None:\n            return self._extra_select_cache\n        if not self.extra:\n            return {}\n        elif self.extra_select_mask is not None:\n            self._extra_select_cache = {\n                k: v for k, v in self.extra.items() if k in self.extra_select_mask\n            }\n            return self._extra_select_cache\n        else:\n            return self.extra\n\n    def trim_start(self, names_with_path):\n        \n        all_paths = []\n        for _, paths in names_with_path:\n            all_paths.extend(paths)\n        contains_louter = False\n         \n         \n         \n        lookup_tables = [\n            t for t in self.alias_map if t in self._lookup_joins or t == self.base_table\n        ]\n        for trimmed_paths, path in enumerate(all_paths):\n            if path.m2m:\n                break\n            if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER:\n                contains_louter = True\n            alias = lookup_tables[trimmed_paths]\n            self.unref_alias(alias)\n         \n        join_field = path.join_field.field\n         \n        paths_in_prefix = trimmed_paths\n        trimmed_prefix = []\n        for name, path in names_with_path:\n            if paths_in_prefix - len(path) < 0:\n                break\n            trimmed_prefix.append(name)\n            paths_in_prefix -= len(path)\n        trimmed_prefix.append(join_field.foreign_related_fields[0].name)\n        trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)\n         \n         \n         \n         \n         \n         \n        first_join = self.alias_map[lookup_tables[trimmed_paths + 1]]\n        if first_join.join_type != LOUTER and not first_join.filtered_relation:\n            select_fields = [r[0] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths + 1]\n            self.unref_alias(lookup_tables[trimmed_paths])\n            extra_restriction = join_field.get_extra_restriction(\n                None, lookup_tables[trimmed_paths + 1]\n            )\n            if extra_restriction:\n                self.where.add(extra_restriction, AND)\n        else:\n             \n             \n             \n             \n            select_fields = [r[1] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths]\n         \n         \n         \n        for table in self.alias_map:\n            if self.alias_refcount[table] > 0:\n                self.alias_map[table] = self.base_table_class(\n                    self.alias_map[table].table_name,\n                    table,\n                )\n                break\n        self.set_select([f.get_col(select_alias) for f in select_fields])\n        return trimmed_prefix, contains_louter\n\n    def is_nullable(self, field):\n        \n         \n         \n         \n         \n         \n        return field.null or (\n            field.empty_strings_allowed\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-d737c5fea4d295f9", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "7a5e978a853e6dc156ffb85a415ba49237cb26e1b7d46e5fe83661e10549464e", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 2303, "local_path": "comments/remove-comments/I01__django__Query__ae33e5f8.py", "order": 1, "original_content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "parent_variant_id": "pyint-82246794d74c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/query.py#L232-L2792", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 32925, "comments_removed": 405, "docstrings_removed": 58, "line_comments_removed": 347}, "unit_kind": "class", "unit_name": "Query", "variant_id": "pyint-0509ae33e5f8-I01", "group_id": "py-d737c5fea4d295f9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 282, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7e18ba8c05ab-I02", "source": "import copy\nimport difflib\nimport functools\nimport sys\nimport warnings\nfrom collections import Counter, namedtuple\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom itertools import chain, count, product\nfrom string import ascii_uppercase\nfrom django.core.exceptions import FieldDoesNotExist, FieldError\nfrom django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections\nfrom django.db.models.aggregates import Count\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import (\n    BaseExpression,\n    Col,\n    ColPairs,\n    Exists,\n    F,\n    OuterRef,\n    RawSQL,\n    Ref,\n    ResolvedOuterRef,\n    Value,\n)\nfrom django.db.models.fields import Field\nfrom django.db.models.lookups import Lookup\nfrom django.db.models.query_utils import (\n    Q,\n    check_rel_lookup_compatibility,\n    refs_expression,\n)\nfrom django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE\nfrom django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin\nfrom django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode\nfrom django.utils.deprecation import RemovedInDjango70Warning\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.tree import Node\nfrom django.utils.warnings import django_file_prefixes\n\nclass Query(BaseExpression):\n    \"\"\"A single SQL query.\"\"\"\n\n    alias_prefix = \"T\"\n    empty_result_set_value = None\n    subq_aliases = frozenset([alias_prefix])\n\n    compiler = \"SQLCompiler\"\n\n    base_table_class = BaseTable\n    join_class = Join\n\n    default_cols = True\n    default_ordering = True\n    standard_ordering = True\n\n    filter_is_sticky = False\n    subquery = False\n    contains_subquery = False\n\n    # SQL-related attributes.\n    # Select and related select clauses are expressions to use in the SELECT\n    # clause of the query. The select is used for cases where we want to set up\n    # the select clause to contain other than default fields (values(),\n    # subqueries...). Note that annotations go to annotations dictionary.\n    select = ()\n    # The group_by attribute can have one of the following forms:\n    #  - None: no group by at all in the query\n    #  - A tuple of expressions: group by (at least) those expressions.\n    #    String refs are also allowed for now.\n    #  - True: group by all select fields of the model\n    # See compiler.get_group_by() for details.\n    group_by = None\n    order_by = ()\n    low_mark = 0  # Used for offset/limit.\n    high_mark = None  # Used for offset/limit.\n    distinct = False\n    distinct_fields = ()\n    select_for_update = False\n    select_for_update_nowait = False\n    select_for_update_skip_locked = False\n    select_for_update_of = ()\n    select_for_no_key_update = False\n    select_related = False\n    # Arbitrary limit for select_related to prevents infinite recursion.\n    max_depth = 5\n    # Holds the selects defined by a call to values() or values_list()\n    # excluding annotation_select and extra_select.\n    values_select = ()\n    selected = None\n\n    # SQL annotation-related attributes.\n    annotation_select_mask = None\n    _annotation_select_cache = None\n\n    # Set combination attributes.\n    combinator = None\n    combinator_all = False\n    combined_queries = ()\n\n    # These are for extensions. The contents are more or less appended verbatim\n    # to the appropriate clause.\n    extra_select_mask = None\n    _extra_select_cache = None\n\n    extra_tables = ()\n    extra_order_by = ()\n\n    # A tuple that is a set of model field names and either True, if these are\n    # the fields to defer, or False if these are the only fields to load.\n    deferred_loading = (frozenset(), True)\n\n    explain_info = None\n\n    def __init__(self, mod, alias2=True):\n        self.model = mod\n        self.alias_refcount = {}\n        # alias_map is the most important data structure regarding joins.\n        # It's used for recording which joins exist in the query and what\n        # types they are. The key is the alias of the joined table (possibly\n        # the table name) and the value is a Join-like object (see\n        # sql.datastructures.Join for more information).\n        self.alias_map = {}\n        # Whether to provide alias to columns during reference resolving.\n        self.alias_cols = alias2\n        # Sometimes the query contains references to aliases in outer queries\n        # (as a result of split_exclude). Correct alias quoting needs to know\n        # these aliases too. Map external tables to whether they are aliased.\n        self.external_aliases = {}\n        self.table_map = {}  # Maps table names to list of aliases.\n        self.used_aliases = set()\n\n        self.where = WhereNode()\n        # Maps alias -> Annotation Expression.\n        self.annotations = {}\n        # These are for extensions. The contents are more or less appended\n        # verbatim to the appropriate clause.\n        self.extra = {}  # Maps col_alias -> (col_sql, params).\n\n        self._filtered_relations = {}\n\n    @property\n    def output(self):\n        if len(self.select) == 1:\n            sel = self.select[0]\n            return getattr(sel, \"target\", None) or sel.field\n        elif len(self.annotation2) == 1:\n            return next(iter(self.annotation2.values())).output_field\n\n    @cached_property\n    def base(self):\n        for ali in self.alias_map:\n            return ali\n\n    def __str__(self):\n        \"\"\"\n        Return the query as a string of SQL with the parameter values\n        substituted in (use sql_with_params() to see the unsubstituted string).\n\n        Parameter values won't necessarily be quoted correctly, since that is\n        done by the database interface at execution time.\n        \"\"\"\n        sql3, par = self.sql2()\n        return sql3 % par\n\n    def sql2(self):\n        \"\"\"\n        Return the query as an SQL string and the parameters that will be\n        substituted into the query.\n        \"\"\"\n        return self.get2(DEFAULT_DB_ALIAS).as_sql()\n\n    def __deepcopy__(self, mem):\n        \"\"\"Limit the amount of work when a Query is deepcopied.\"\"\"\n        res = self.clo()\n        mem[id(self)] = res\n        return res\n\n    def get2(self, usi=None, con=None, elide=True):\n        if usi is None and con is None:\n            raise ValueError(\"Need either using or connection\")\n        if usi:\n            con = connections[usi]\n        return con.ops.compiler(self.compiler)(\n            self, con, usi, elide\n        )\n\n    def get3(self):\n        \"\"\"\n        Return the Options instance (the model._meta) from which to start\n        processing. Normally, this is self.model._meta, but it can be changed\n        by subclasses.\n        \"\"\"\n        if self.model:\n            return self.model._meta\n\n    def clo(self):\n        \"\"\"\n        Return a copy of the current Query. A lightweight alternative to\n        deepcopy().\n        \"\"\"\n        obj2 = Empty()\n        obj2.__class__ = self.__class__\n        # Copy references to everything.\n        obj2.__dict__ = self.__dict__.copy()\n        # Clone attributes that can't use shallow copy.\n        obj2.alias_refcount = self.alias_refcount.copy()\n        obj2.alias_map = self.alias_map.copy()\n        obj2.external_aliases = self.external_aliases.copy()\n        obj2.table_map = self.table_map.copy()\n        obj2.where = self.where.clone()\n        obj2.annotations = self.annotations.copy()\n        if self.annotation_select_mask is not None:\n            obj2.annotation_select_mask = self.annotation_select_mask.copy()\n        if self.combined_queries:\n            obj2.combined_queries = tuple(\n                [que.clone() for que in self.combined_queries]\n            )\n        # _annotation_select_cache cannot be copied, as doing so breaks the\n        # (necessary) state in which both annotations and\n        # _annotation_select_cache point to the same underlying objects.\n        # It will get re-populated in the cloned queryset the next time it's\n        # used.\n        obj2._annotation_select_cache = None\n        obj2.extra = self.extra.copy()\n        if self.extra_select_mask is not None:\n            obj2.extra_select_mask = self.extra_select_mask.copy()\n        if self._extra_select_cache is not None:\n            obj2._extra_select_cache = self._extra_select_cache.copy()\n        if self.select_related is not False:\n            # Use deepcopy because select_related stores fields in nested\n            # dicts.\n            obj2.select_related = copy.deepcopy(obj2.select_related)\n        if \"subq_aliases\" in self.__dict__:\n            obj2.subq_aliases = self.subq_aliases.copy()\n        obj2.used_aliases = self.used_aliases.copy()\n        obj2._filtered_relations = self._filtered_relations.copy()\n        # Clear the cached_property, if it exists.\n        obj2.__dict__.pop(\"base_table\", None)\n        return obj2\n\n    def cha(self, kla=None):\n        \"\"\"\n        Return a copy of the current Query that's ready for another operation.\n        The klass argument changes the type of the Query, e.g. UpdateQuery.\n        \"\"\"\n        obj3 = self.clo()\n        if kla and obj3.__class__ != kla:\n            obj3.__class__ = kla\n        if not obj3.filter_is_sticky:\n            obj3.used_aliases = set()\n        obj3.filter_is_sticky = False\n        if hasattr(obj3, \"_setup_query\"):\n            obj3._setup_query()\n        return obj3\n\n    def relabeled(self, change2):\n        clo2 = self.clo()\n        clo2.change_aliases(change2)\n        return clo2\n\n    def get4(self, tar, fie, ali2):\n        if not self.alias_cols:\n            ali2 = None\n        return tar.get_col(ali2, fie)\n\n    def get5(self, usi2, aggregate2):\n        \"\"\"\n        Return the dictionary with the values of the existing aggregations.\n        \"\"\"\n        if not aggregate2:\n            return {}\n        # Store annotation mask prior to temporarily adding aggregations for\n        # resolving purpose to facilitate their subsequent removal.\n        refs2 = False\n        refs3 = False\n        rep = {}\n        annotation3 = self.annotation_select_mask\n        for ali3, aggregate3 in aggregate2.items():\n            self.check(ali3)\n            agg = aggregate3.resolve_expression(\n                self, allow_joins=True, reuse=None, summarize=True\n            )\n            if not agg.contains_aggregate:\n                raise TypeError(\"%s is not an aggregate expression\" % ali3)\n            # Temporarily add aggregate to annotations to allow remaining\n            # members of `aggregates` to resolve against each others.\n            self.append2([ali3])\n            aggregate4 = agg.get_refs()\n            refs2 |= any(\n                getattr(self.annotations[ref3], \"contains_subquery\", False)\n                for ref3 in aggregate4\n            )\n            refs3 |= any(\n                getattr(self.annotations[ref3], \"contains_over_clause\", True)\n                for ref3 in aggregate4\n            )\n            agg = agg.replace_expressions(rep)\n            self.annotations[ali3] = agg\n            rep[Ref(ali3, agg)] = agg\n        # Stash resolved aggregates now that they have been allowed to resolve\n        # against each other.\n        agg2 = {ali3: self.annotations.pop(ali3) for ali3 in aggregate2}\n        self.set6(annotation3)\n        # Existing usage of aggregation can be determined by the presence of\n        # selected aggregates but also by filters against aliased aggregates.\n        _2, hav, qua = self.where.split_having_qualify()\n        has5 = (\n            any(\n                getattr(ann, \"contains_aggregate\", True)\n                for ann in self.annotations.values()\n            )\n            or hav\n        )\n        set9 = {\n            ali3\n            for ali3, ann in self.annotation2.items()\n            if getattr(ann, \"set_returning\", False)\n        }\n        # Decide if we need to use a subquery.\n        #\n        # Existing aggregations would cause incorrect results as\n        # get_aggregation() must produce just one result and thus must not use\n        # GROUP BY.\n        #\n        # If the query has limit or distinct, or uses set operations, then\n        # those operations must be done in a subquery so that the query\n        # aggregates on the limit and/or distinct results instead of applying\n        # the distinct and limit after the aggregation.\n        if (\n            isinstance(self.group_by, tuple)\n            or self.is3\n            or has5\n            or refs2\n            or refs3\n            or qua\n            or self.distinct\n            or self.combinator\n            or set9\n        ):\n            from django.db.models.sql.subqueries import AggregateQuery\n\n            inner = self.clo()\n            inner.subquery = True\n            outer = AggregateQuery(self.model, inner)\n            inner.select_for_update = False\n            inner.select_related = False\n            inner.set_annotation_mask(self.annotation2)\n            # Queries with distinct_fields need ordering and when a limit is\n            # applied we must take the slice from the ordered query. Otherwise\n            # no need for ordering.\n            if inner.orderby_issubset_groupby:\n                inner.clear_ordering(force=False)\n            if not inner.distinct:\n                # If the inner query uses default select and it has some\n                # aggregate annotations, then we must make sure the inner\n                # query is grouped by the main model's primary key. However,\n                # clearing the select clause can alter results if distinct is\n                # used.\n                if inner.default_cols and has5:\n                    inner.group_by = (\n                        self.model._meta.pk.get_col(inner.get_initial_alias()),\n                    )\n                inner.default_cols = False\n                if not qua and not self.combinator:\n                    # Mask existing annotations that are not referenced by\n                    # aggregates to be pushed to the outer query unless\n                    # filtering against window functions or if the query is\n                    # combined as both would require complex realiasing logic.\n                    annotation4 = set()\n                    if isinstance(self.group_by, tuple):\n                        for exp2 in self.group_by:\n                            annotation4 |= exp2.get_refs()\n                    for agg in agg2.values():\n                        annotation4 |= agg.get_refs()\n                    # Avoid eliding expressions that might have an incidence on\n                    # the implicit grouping logic.\n                    for annotation5, ann in self.annotation2.items():\n                        if ann.get_group_by_cols():\n                            annotation4.add(annotation5)\n                    inner.set_annotation_mask(annotation4)\n                    # Annotations that possibly return multiple rows cannot\n                    # be masked as they might have an incidence on the query.\n                    annotation4 |= set9\n\n            # Add aggregates to the outer AggregateQuery. This requires making\n            # sure all columns referenced by the aggregates are selected in the\n            # inner query. It is achieved by retrieving all column references\n            # by the aggregates, explicitly selecting them in the inner query,\n            # and making sure the aggregates are repointed to them.\n            col2 = {}\n            for ali3, agg in agg2.items():\n                rep = {}\n                for col3 in self.gen([agg], resolve_refs=False):\n                    if not (col5 := col2.get(col3)):\n                        ind = len(col2) + 1\n                        col4 = f\"__col{ind}\"\n                        col5 = Ref(col4, col3)\n                        col2[col3] = col5\n                        inner.add_annotation(col3, col4)\n                    rep[col3] = col5\n                outer.annotations[ali3] = agg.replace_expressions(\n                    rep\n                )\n            if (\n                inner.select == ()\n                and not inner.default_cols\n                and not inner.annotation_select_mask\n            ):\n                # In case of Model.objects[0:3].count(), there would be no\n                # field selected in the inner query, yet we must use a\n                # subquery. So, make sure at least one field is selected.\n                inner.select = (\n                    self.model._meta.pk.get_col(inner.get_initial_alias()),\n                )\n        else:\n            outer = self\n            self.select = ()\n            self.selected = None\n            self.default_cols = False\n            self.extra = {}\n            if self.annotations:\n                # Inline reference to existing annotations and mask them as\n                # they are unnecessary given only the summarized aggregations\n                # are requested.\n                rep = {\n                    Ref(ali3, ann): ann\n                    for ali3, ann in self.annotations.items()\n                }\n                self.annotations = {\n                    ali3: agg.replace_expressions(rep)\n                    for ali3, agg in agg2.items()\n                }\n            else:\n                self.annotations = agg2\n            self.set6(agg2)\n\n        empty = [\n            exp3.empty_result_set_value\n            for exp3 in outer.annotation_select.values()\n        ]\n        elide2 = not any(res2 is NotImplemented for res2 in empty)\n        outer.clear_ordering(force=True)\n        outer.clear_limits()\n        outer.select_for_update = False\n        outer.select_related = False\n        com2 = outer.get_compiler(usi2, elide_empty=elide2)\n        res2 = com2.execute_sql(SINGLE)\n        if res2 is None:\n            res2 = empty\n        else:\n            col6 = outer.annotation_select.values()\n            con2 = com2.get_converters(col6)\n            row = com2.apply_converters((res2,), con2)\n            if com2.has_composite_fields(col6):\n                row = com2.composite_fields_to_tuples(row, col6)\n            res2 = next(row)\n\n        return dict(zip(outer.annotation_select, res2))\n\n    def get6(self, usi3):\n        \"\"\"\n        Perform a COUNT() query using the current filter constraints.\n        \"\"\"\n        obj4 = self.clo()\n        return obj4.get_aggregation(usi3, {\"__count\": Count(\"*\")})[\"__count\"]\n\n    def has(self):\n        return self.where\n\n    def exi(self, lim=True):\n        q2 = self.clo()\n        if not (q2.distinct and q2.is_sliced):\n            if q2.group_by is True:\n                q2.add_fields(\n                    (f2.attname for f2 in self.model._meta.concrete_fields), False\n                )\n                # Disable GROUP BY aliases to avoid orphaning references to the\n                # SELECT clause which is about to be cleared.\n                q2.set_group_by(allow_aliases=False)\n            q2.clear_select_clause()\n        if q2.combined_queries and q2.combinator == \"union\":\n            q2.combined_queries = tuple(\n                combined.exists(limit=False)\n                for combined in q2.combined_queries\n            )\n        q2.clear_ordering(force=True)\n        if lim is True:\n            q2.set_limits(high=1)\n        q2.add_annotation(Value(1), \"a\")\n        return q2\n\n    def has2(self, usi4):\n        q3 = self.exi()\n        com3 = q3.get_compiler(using=usi4)\n        return com3.has_results()\n\n    def exp(self, usi5, for2=None, **opt):\n        q4 = self.clo()\n        for option in opt:\n            if (\n                not EXPLAIN_OPTIONS_PATTERN.fullmatch(option)\n                or \"--\" in option\n            ):\n                raise ValueError(f\"Invalid option name: {option!r}.\")\n        q4.explain_info = ExplainInfo(for2, opt)\n        com4 = q4.get_compiler(using=usi5)\n        return \"\\n\".join(com4.explain_query())\n\n    def com(self, rhs2, con3):\n        \"\"\"\n        Merge the 'rhs' query into the current one (with any 'rhs' effects\n        being applied *after* (that is, \"to the right of\") anything in the\n        current query. 'rhs' is not modified during a call to this function.\n\n        The 'connector' parameter describes how to connect filters from the\n        'rhs' query.\n        \"\"\"\n        if self.model != rhs2.model:\n            raise TypeError(\"Cannot combine queries on two different base models.\")\n        if self.is3:\n            raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n        if self.distinct != rhs2.distinct:\n            raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n        if self.distinct_fields != rhs2.distinct_fields:\n            raise TypeError(\"Cannot combine queries with different distinct fields.\")\n\n        # If lhs and rhs shares the same alias prefix, it is possible to have\n        # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up\n        # as T4 -> T6 while combining two querysets. To prevent this, change an\n        # alias prefix of the rhs and update current aliases accordingly,\n        # except if the alias is the base table since it must be present in the\n        # query on both sides.\n        initial = self.get10()\n        rhs2 = rhs2.clone()\n        rhs2.bump_prefix(self, exclude={initial})\n\n        # Work out how to relabel the rhs aliases, if necessary.\n        change3 = {}\n        con4 = con3 == AND\n\n        # Determine which existing joins can be reused. When combining the\n        # query with AND we must recreate all joins for m2m filters. When\n        # combining with OR we can reuse joins. The reason is that in AND\n        # case a single row can't fulfill a condition like:\n        #     revrel__col=1 & revrel__col=2\n        # But, there might be two different related rows matching this\n        # condition. In OR case a single True is enough, so single row is\n        # enough, too.\n        #\n        # Note that we will be creating duplicate joins for non-m2m joins in\n        # the AND case. The results will be correct but this creates too many\n        # joins. This is something that could be fixed later on.\n        reu = set() if con4 else set(self.alias_map)\n        joi2 = JoinPromoter(con3, 2, False)\n        joi2.add_votes(\n            j2 for j2 in self.alias_map if self.alias_map[j2].join_type == INNER\n        )\n        rhs3 = set()\n        # Now, add the joins from rhs query into the new query (skipping base\n        # table).\n        rhs4 = list(rhs2.alias_map)[1:]\n        for ali4 in rhs4:\n            joi3 = rhs2.alias_map[ali4]\n            # If the left side of the join was already relabeled, use the\n            # updated alias.\n            joi3 = joi3.relabeled_clone(change3)\n            new = self.joi(joi3, reuse=reu)\n            if joi3.join_type == INNER:\n                rhs3.add(new)\n            # We can't reuse the same join again in the query. If we have two\n            # distinct joins for the same connection in rhs query, then the\n            # combined query must have two joins, too.\n            reu.discard(new)\n            if ali4 != new:\n                change3[ali4] = new\n            if not rhs2.alias_refcount[ali4]:\n                # The alias was unused in the rhs query. Unref it so that it\n                # will be unused in the new query, too. We have to add and\n                # unref the alias so that join promotion has information of\n                # the join type for the unused alias.\n                self.unref(new)\n        joi2.add_votes(rhs3)\n        joi2.update_join_types(self)\n\n        # Combine subqueries aliases to ensure aliases relabelling properly\n        # handle subqueries when combining where and select clauses.\n        self.subq_aliases |= rhs2.subq_aliases\n\n        # Now relabel a copy of the rhs where-clause and add it to the current\n        # one.\n        w2 = rhs2.where.clone()\n        w2.relabel_aliases(change3)\n        self.where.add(w2, con3)\n\n        # Selection columns and extra extensions are those provided by 'rhs'.\n        if rhs2.select:\n            self.set4([col7.relabeled_clone(change3) for col7 in rhs2.select])\n        else:\n            self.select = ()\n\n        if con3 == OR:\n            # It would be nice to be able to handle this, but the queries don't\n            # really make sense (or return consistent value sets). Not worth\n            # the extra complexity when you can write a real query instead.\n            if self.extra and rhs2.extra:\n                raise ValueError(\n                    \"When merging querysets using 'or', you cannot have \"\n                    \"extra(select=...) on both sides.\"\n                )\n        self.extra.update(rhs2.extra)\n        extra3 = set()\n        if self.extra_select_mask is not None:\n            extra3.update(self.extra_select_mask)\n        if rhs2.extra_select_mask is not None:\n            extra3.update(rhs2.extra_select_mask)\n        if extra3:\n            self.set7(extra3)\n        self.extra_tables += rhs2.extra_tables\n\n        # Ordering uses the 'rhs' ordering, unless it has none, in which case\n        # the current ordering is used.\n        self.order_by = rhs2.order_by or self.order_by\n        self.extra_order_by = rhs2.extra_order_by or self.extra_order_by\n\n    def get7(self, opt2, mas, select2=None):\n        if select2 is None:\n            select2 = {}\n        select2[opt2.pk] = {}\n        # All concrete fields and related objects that are not part of the\n        # defer mask must be included. If a relational field is encountered it\n        # gets added to the mask for it be considered if `select_related` and\n        # the cycle continues by recursively calling this function.\n        for fie2 in opt2.concrete_fields + opt2.related_objects:\n            field2 = mas.pop(fie2.name, None)\n            field3 = None\n            if field4 := getattr(fie2, \"attname\", None):\n                field3 = mas.pop(field4, None)\n            if field2 is None and field3 is None:\n                select2.setdefault(fie2, {})\n            elif field2:\n                if not fie2.is_relation:\n                    raise FieldError(next(iter(field2)))\n                # Virtual fields such as many-to-many and generic foreign keys\n                # cannot be effectively deferred. Historically, they were\n                # allowed to be passed to QuerySet.defer(). Ignore such field\n                # references until a layer of validation at mask alteration\n                # time is eventually implemented.\n                if fie2.many_to_many:\n                    continue\n                field6 = select2.setdefault(fie2, {})\n                related = fie2.related_model._meta.concrete_model\n                self.get7(\n                    related._meta, field2, field6\n                )\n        # Remaining defer entries must be references to filtered relations\n        # otherwise they are surfaced as missing field errors.\n        for field5, field2 in mas.items():\n            if filtered := self._filtered_relations.get(field5):\n                rel = opt2.get_field(filtered.relation_name)\n                field6 = select2.setdefault((field5, rel), {})\n                related = rel.related_model._meta.concrete_model\n                self.get7(\n                    related._meta, field2, field6\n                )\n            else:\n                opt2.get_field(field5)\n        return select2\n\n    def get8(self, opt3, mas2, select3=None):\n        if select3 is None:\n            select3 = {}\n        select3[opt3.pk] = {}\n        # Only include fields mentioned in the mask.\n        for field7, field8 in mas2.items():\n            fie3 = opt3.get_field(field7)\n            field9 = select3.setdefault(fie3, {})\n            if field8:\n                if not fie3.is_relation:\n                    raise FieldError(next(iter(field8)))\n                related2 = fie3.remote_field.model._meta.concrete_model\n                self.get8(\n                    related2._meta, field8, field9\n                )\n        return select3\n\n    def get9(self):\n        \"\"\"\n        Convert the self.deferred_loading data structure to an alternate data\n        structure, describing the field that *will* be loaded. This is used to\n        compute the columns to select from the database and also by the\n        QuerySet class to work out which fields are being initialized on each\n        model. Models that have all their fields included aren't mentioned in\n        the result, only those that have field restrictions in place.\n        \"\"\"\n        field10, def2 = self.deferred_loading\n        if not field10:\n            return {}\n        mas3 = {}\n        for field11 in field10:\n            part2 = mas3\n            for par2 in field11.split(LOOKUP_SEP):\n                part2 = part2.setdefault(par2, {})\n        opt4 = self.get3()\n        if def2:\n            return self.get7(opt4, mas3)\n        return self.get8(opt4, mas3)\n\n    def table2(self, table3, cre=False, filtered2=None):\n        \"\"\"\n        Return a table alias for the given table_name and whether this is a\n        new alias or not.\n\n        If 'create' is true, a new alias is always created. Otherwise, the\n        most recently created alias for the table (if one exists) is reused.\n        \"\"\"\n        alias3 = self.table_map.get(table3)\n        if not cre and alias3:\n            ali5 = alias3[0]\n            self.alias_refcount[ali5] += 1\n            return ali5, False\n\n        # Create a new alias for this table.\n        if alias3:\n            ali5 = \"%s%d\" % (self.alias_prefix, len(self.alias_map) + 1)\n            alias3.append(ali5)\n        else:\n            # The first occurrence of a table uses the table name directly.\n            ali5 = (\n                filtered2.alias if filtered2 is not None else table3\n            )\n            self.table_map[table3] = [ali5]\n        self.alias_refcount[ali5] = 1\n        return ali5, True\n\n    def ref2(self, ali6):\n        \"\"\"Increases the reference count for this alias.\"\"\"\n        self.alias_refcount[ali6] += 1\n\n    def unref(self, ali7, amo=1):\n        \"\"\"Decreases the reference count for this alias.\"\"\"\n        self.alias_refcount[ali7] -= amo\n\n    def promote2(self, ali8):\n        \"\"\"\n        Promote recursively the join type of given aliases and its children to\n        an outer join. If 'unconditional' is False, only promote the join if\n        it is nullable or the parent join is an outer join.\n\n        The children promotion is done to avoid join chains that contain a\n        LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b\n        is promoted, then we must also promote b->c automatically, or otherwise\n        the promotion of a->b doesn't actually change anything in the query\n        results.\n        \"\"\"\n        ali8 = list(ali8)\n        while ali8:\n            ali9 = ali8.pop(0)\n            if self.alias_map[ali9].join_type is None:\n                # This is the base table (first FROM entry) - this table\n                # isn't really joined at all in the query, so we should not\n                # alter its join type.\n                continue\n            # Only the first alias (skipped above) should have None join_type\n            assert self.alias_map[ali9].join_type is not None\n            parent = self.alias_map[ali9].parent_alias\n            parent2 = (\n                parent and self.alias_map[parent].join_type == LOUTER\n            )\n            already = self.alias_map[ali9].join_type == LOUTER\n            if (self.alias_map[ali9].nullable or parent2) and not already:\n                self.alias_map[ali9] = self.alias_map[ali9].promote()\n                # Join type of 'alias' changed, so re-examine all aliases that\n                # refer to this one.\n                ali8.extend(\n                    joi4\n                    for joi4 in self.alias_map\n                    if self.alias_map[joi4].parent_alias == ali9\n                    and joi4 not in ali8\n                )\n\n    def demote2(self, ali10):\n        \"\"\"\n        Change join type from LOUTER to INNER for all joins in aliases.\n\n        Similarly to promote_joins(), this method must ensure no join chains\n        containing first an outer, then an inner join are generated. If we\n        are demoting b->c join in chain a LOUTER b LOUTER c then we must\n        demote a->b automatically, or otherwise the demotion of b->c doesn't\n        actually change anything in the query results. .\n        \"\"\"\n        ali10 = list(ali10)\n        while ali10:\n            ali11 = ali10.pop(0)\n            if self.alias_map[ali11].join_type == LOUTER:\n                self.alias_map[ali11] = self.alias_map[ali11].demote()\n                parent3 = self.alias_map[ali11].parent_alias\n                if self.alias_map[parent3].join_type == INNER:\n                    ali10.append(parent3)\n\n    def reset(self, to):\n        \"\"\"\n        Reset reference counts for aliases so that they match the value passed\n        in `to_counts`.\n        \"\"\"\n        for ali12, cur in self.alias_refcount.copy().items():\n            unref2 = cur - to.get(ali12, 0)\n            self.unref(ali12, unref2)\n\n    def change(self, change4):\n        \"\"\"\n        Change the aliases in change_map (which maps old-alias -> new-alias),\n        relabelling any references to them in select columns and the where\n        clause.\n        \"\"\"\n        if not change4:\n            return self\n        # If keys and values of change_map were to intersect, an alias might be\n        # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending\n        # on their order in change_map.\n        assert set(change4).isdisjoint(change4.values())\n\n        # 1. Update references in \"select\" (normal columns plus aliases),\n        # \"group by\" and \"where\".\n        self.where.relabel_aliases(change4)\n        if isinstance(self.group_by, tuple):\n            self.group_by = tuple(\n                [col8.relabeled_clone(change4) for col8 in self.group_by]\n            )\n        self.select = tuple([col8.relabeled_clone(change4) for col8 in self.select])\n        self.annotations = self.annotations and {\n            key2: col8.relabeled_clone(change4)\n            for key2, col8 in self.annotations.items()\n        }\n\n        # 2. Rename the alias in the internal table/alias datastructures.\n        for old, new2 in change4.items():\n            if old not in self.alias_map:\n                continue\n            alias4 = self.alias_map[old].relabeled_clone(change4)\n            self.alias_map[new2] = alias4\n            self.alias_refcount[new2] = self.alias_refcount[old]\n            del self.alias_refcount[old]\n            del self.alias_map[old]\n\n            table4 = self.table_map[alias4.table_name]\n            for pos2, ali13 in enumerate(table4):\n                if ali13 == old:\n                    table4[pos2] = new2\n                    break\n\n        # 3. Rename the direct external aliases and the ones of combined\n        # queries (union, intersection, difference).\n        self.external_aliases = {\n            # Table is aliased or it's being changed and thus is aliased.\n            change4.get(ali13, ali13): (ali14 or ali13 in change4)\n            for ali13, ali14 in self.external_aliases.items()\n        }\n        for combined2 in self.combined_queries:\n            external = {\n                ali13: ali14\n                for ali13, ali14 in change4.items()\n                if ali13 in combined2.external_aliases\n            }\n            combined2.change_aliases(external)\n\n    def bump(self, other, exc2=None):\n        \"\"\"\n        Change the alias prefix to the next letter in the alphabet in a way\n        that the other query's aliases and this query's aliases will not\n        conflict. Even tables that previously had no alias will get an alias\n        after this call. To prevent changing aliases use the exclude parameter.\n        \"\"\"\n\n        def prefix_gen():\n            \"\"\"\n            Generate a sequence of characters in alphabetical order:\n                -> 'A', 'B', 'C', ...\n\n            When the alphabet is finished, the sequence will continue with the\n            Cartesian product:\n                -> 'AA', 'AB', 'AC', ...\n            \"\"\"\n            alp = ascii_uppercase\n            pre2 = chr(ord(self.alias_prefix) + 1)\n            yield pre2\n            for n2 in count(1):\n                seq2 = alp[alp.index(pre2) :] if pre2 else alp\n                for s2 in product(seq2, repeat=n2):\n                    yield \"\".join(s2)\n                pre2 = None\n\n        if self.alias_prefix != other.alias_prefix:\n            # No clashes between self and outer query should be possible.\n            return\n\n        # Explicitly avoid infinite loop. The constant divider is based on how\n        # much depth recursive subquery references add to the stack. This value\n        # might need to be adjusted when adding or removing function calls from\n        # the code path in charge of performing these operations.\n        local = sys.getrecursionlimit() // 16\n        for pos3, pre in enumerate(prefix_gen()):\n            if pre not in self.subq_aliases:\n                self.alias_prefix = pre\n                break\n            if pos3 > local:\n                raise RecursionError(\n                    \"Maximum recursion depth exceeded: too many subqueries.\"\n                )\n        self.subq_aliases = self.subq_aliases.union([self.alias_prefix])\n        other.subq_aliases = other.subq_aliases.union(self.subq_aliases)\n        if exc2 is None:\n            exc2 = {}\n        self.change(\n            {\n                ali15: \"%s%d\" % (self.alias_prefix, pos3)\n                for pos3, ali15 in enumerate(self.alias_map)\n                if ali15 not in exc2\n            }\n        )\n\n    def get10(self):\n        \"\"\"\n        Return the first alias for this query, after increasing its reference\n        count.\n        \"\"\"\n        if self.alias_map:\n            ali16 = self.base\n            self.ref2(ali16)\n        elif self.model:\n            ali16 = self.joi(self.base_table_class(self.get3().db_table, None))\n        else:\n            ali16 = None\n        return ali16\n\n    def count2(self):\n        \"\"\"\n        Return the number of tables in this query with a non-zero reference\n        count. After execution, the reference counts are zeroed, so tables\n        added in compiler will not be seen by this method.\n        \"\"\"\n        return len([1 for cou in self.alias_refcount.values() if cou])\n\n    def joi(self, joi5, reu2=None):\n        \"\"\"\n        Return an alias for the 'join', either reusing an existing alias for\n        that join or creating a new one. 'join' is either a base_table_class or\n        join_class.\n\n        The 'reuse' parameter can be either None which means all joins are\n        reusable, or it can be a set containing the aliases that can be reused.\n\n        A join is always created as LOUTER if the lhs alias is LOUTER to make\n        sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new\n        joins are created as LOUTER if the join is nullable.\n        \"\"\"\n        reuse2 = [\n            a2\n            for a2, j3 in self.alias_map.items()\n            if (reu2 is None or a2 in reu2) and j3 == joi5\n        ]\n        if reuse2:\n            if joi5.table_alias in reuse2:\n                reuse3 = joi5.table_alias\n            else:\n                # Reuse the most recent alias of the joined table\n                # (a many-to-many relation may be joined multiple times).\n                reuse3 = reuse2[-1]\n            self.ref2(reuse3)\n            return reuse3\n\n        # No reuse is possible, so we need a new alias.\n        ali17, _3 = self.table2(\n            joi5.table_name, create=True, filtered_relation=joi5.filtered_relation\n        )\n        if joi5.join_type:\n            if self.alias_map[joi5.parent_alias].join_type == LOUTER or joi5.nullable:\n                join3 = LOUTER\n            else:\n                join3 = INNER\n            joi5.join_type = join3\n        joi5.table_alias = ali17\n        self.alias_map[ali17] = joi5\n        if filtered3 := joi5.filtered_relation:\n            resolve4 = reu2\n            if resolve4 is not None:\n                resolve4 = set(reu2) | {ali17}\n            joins2 = len(self.alias_map)\n            joi5.filtered_relation = filtered3.resolve_expression(\n                self, reuse=resolve4\n            )\n            # Some joins were during expression resolving, they must be present\n            # before the one we just added.\n            if joins2 < len(self.alias_map):\n                self.alias_map[ali17] = self.alias_map.pop(ali17)\n        return ali17\n\n    def join2(self, opt5, mod2, ali18, see):\n        \"\"\"\n        Make sure the given 'model' is joined in the query. If 'model' isn't\n        a parent of 'opts' or if it is None this method is a no-op.\n\n        The 'alias' is the root alias for starting the join, 'seen' is a dict\n        of model -> alias of existing joins. It must also contain a mapping\n        of None -> some alias. This will be returned in the no-op case.\n        \"\"\"\n        if mod2 in see:\n            return see[mod2]\n        cha2 = opt5.get_base_chain(mod2)\n        if not cha2:\n            return ali18\n        curr = opt5\n        for int in cha2:\n            if int in see:\n                curr = int._meta\n                ali18 = see[int]\n                continue\n            # Proxy model have elements in base chain\n            # with no parents, assign the new options\n            # object and skip to the next base in that\n            # case\n            if not curr.parents[int]:\n                curr = int._meta\n                continue\n            link = curr.get_ancestor_link(int)\n            join4 = self.setup([link.name], curr, ali18)\n            curr = int._meta\n            ali18 = see[int] = join4.joins[-1]\n        return ali18 or see[None]\n\n    def check(self, ali19):\n        # RemovedInDjango70Warning: When the deprecation ends, remove.\n        if \"%\" in ali19:\n            warnings.warn(\n                \"Using percent signs in a column alias is deprecated.\",\n                category=RemovedInDjango70Warning,\n                skip_file_prefixes=django_file_prefixes(),\n            )\n        if FORBIDDEN_ALIAS_PATTERN.search(ali19):\n            raise ValueError(\n                \"Column aliases cannot contain whitespace characters, hashes, \"\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # \"control characters, quotation marks, semicolons, percent \"\n                # \"signs, or SQL comments.\"\n                \"control characters, quotation marks, semicolons, or SQL comments.\"\n            )\n\n    def add2(self, ann2, ali20, sel2=True):\n        \"\"\"Add a single annotation expression to the Query.\"\"\"\n        self.check(ali20)\n        ann2 = ann2.resolve_expression(self, allow_joins=True, reuse=None)\n        if sel2:\n            self.append2([ali20])\n        else:\n            self.set6(set(self.annotation2).difference({ali20}))\n        self.annotations[ali20] = ann2\n        if sel2 and self.selected:\n            self.selected[ali20] = ali20\n\n    @property\n    def subquery2(self):\n        if not self.has4 or not self.select:\n            return len(self.model._meta.pk_fields)\n        return len(self.select) + sum(\n            len(exp4.targets) - 1 for exp4 in self.select if isinstance(exp4, ColPairs)\n        )\n\n    def resolve(self, que2, *arg2, **kwa):\n        clo3 = self.clo()\n        # Subqueries need to use a different set of aliases than the outer\n        # query.\n        clo3.bump_prefix(que2)\n        clo3.subquery = True\n        clo3.where.resolve_expression(que2, *arg2, **kwa)\n        # Resolve combined queries.\n        if clo3.combinator:\n            clo3.combined_queries = tuple(\n                [\n                    combined3.resolve_expression(que2, *arg2, **kwa)\n                    for combined3 in clo3.combined_queries\n                ]\n            )\n        for key3, val in clo3.annotations.items():\n            res3 = val.resolve_expression(que2, *arg2, **kwa)\n            if hasattr(res3, \"external_aliases\"):\n                res3.external_aliases.update(clo3.external_aliases)\n            clo3.annotations[key3] = res3\n        # Outer query's aliases are considered external.\n        for ali21, tab in que2.alias_map.items():\n            clo3.external_aliases[ali21] = (\n                isinstance(tab, Join)\n                and tab.join_field.related_model._meta.db_table != ali21\n            ) or (\n                isinstance(tab, BaseTable) and tab.table_name != tab.table_alias\n            )\n        return clo3\n\n    def get11(self):\n        exp5 = chain(self.annotations.values(), self.where.children)\n        return [\n            col9\n            for col9 in self.gen(exp5, include_external=True)\n            if col9.alias in self.external_aliases\n        ]\n\n    def get12(self, wra=None):\n        # If wrapper is referenced by an alias for an explicit GROUP BY through\n        # values() a reference to this expression and not the self must be\n        # returned to ensure external column references are not grouped against\n        # as well.\n        external2 = self.get11()\n        if any(col10.possibly_multivalued for col10 in external2):\n            return [wra or self]\n        return external2\n\n    def as2(self, com5, con5):\n        # Some backends (e.g. Oracle) raise an error when a subquery contains\n        # unnecessary ORDER BY clause.\n        if (\n            self.subquery\n            and not con5.features.ignores_unnecessary_order_by_in_subqueries\n        ):\n            self.clear5(force=False)\n            for que3 in self.combined_queries:\n                que3.clear_ordering(force=False)\n        sql4, par3 = self.get2(connection=con5).as_sql()\n        if self.subquery:\n            sql4 = \"(%s)\" % sql4\n        return sql4, par3\n\n    def resolve2(self, val2, can2, allow, sum2=False):\n        if hasattr(val2, \"resolve_expression\"):\n            val2 = val2.resolve_expression(\n                self,\n                reuse=can2,\n                allow_joins=allow,\n                summarize=sum2,\n            )\n        elif isinstance(val2, (list, tuple)):\n            # The items of the iterable may be expressions and therefore need\n            # to be resolved independently.\n            val3 = (\n                self.resolve2(sub, can2, allow, sum2)\n                for sub in val2\n            )\n            typ = type(val2)\n            if hasattr(typ, \"_make\"):  # namedtuple\n                return typ(*val3)\n            return typ(val3)\n        return val2\n\n    def solve(self, loo, sum3=False):\n        \"\"\"\n        Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').\n        \"\"\"\n        lookup2 = loo.split(LOOKUP_SEP)\n        if self.annotations:\n            ann3, expression2 = refs_expression(\n                lookup2, self.annotations\n            )\n            if ann3:\n                exp6 = self.annotations[ann3]\n                if sum3:\n                    exp6 = Ref(ann3, exp6)\n                return expression2, (), exp6\n        _4, fie4, _4, lookup3 = self.names2(lookup2, self.get3())\n        field12 = lookup2[0 : len(lookup2) - len(lookup3)]\n        if len(lookup3) > 1 and not field12:\n            raise FieldError(\n                'Invalid lookup \"%s\" for model %s\".'\n                % (loo, self.get3().model.__name__)\n            )\n        return lookup3, field12, False\n\n    def check2(self, val4, opt6, fie5):\n        \"\"\"\n        Check whether the object passed while querying is of the correct type.\n        If not, raise a ValueError specifying the wrong object.\n        \"\"\"\n        if hasattr(val4, \"_meta\"):\n            if not check_rel_lookup_compatibility(val4._meta.model, opt6, fie5):\n                raise ValueError(\n                    'Cannot query \"%s\": Must be \"%s\" instance.'\n                    % (val4, opt6.object_name)\n                )\n\n    def check3(self, fie6, val5, opt7):\n        \"\"\"Check the type of object passed to query relations.\"\"\"\n        if fie6.is_relation:\n            # Check that the field and the queryset use the same model in a\n            # query like .filter(author=Author.objects.all()). For example, the\n            # opts would be Author's (from the author field) and value.model\n            # would be Author.objects.all() queryset's .model (Author also).\n            # The field is the related field on the lhs side.\n            if (\n                isinstance(val5, Query)\n                and not val5.has_select_fields\n                and not check_rel_lookup_compatibility(val5.model, opt7, fie6)\n            ):\n                raise ValueError(\n                    'Cannot use QuerySet for \"%s\": Use a QuerySet for \"%s\".'\n                    % (val5.model._meta.object_name, opt7.object_name)\n                )\n            elif hasattr(val5, \"_meta\"):\n                self.check2(val5, opt7, fie6)\n            elif hasattr(val5, \"__iter__\"):\n                for v2 in val5:\n                    self.check2(v2, opt7, fie6)\n\n    def check4(self, exp7):\n        \"\"\"Raise an error if expression cannot be used in a WHERE clause.\"\"\"\n        if hasattr(exp7, \"resolve_expression\") and not getattr(\n            exp7, \"filterable\", True\n        ):\n            raise NotSupportedError(\n                exp7.__class__.__name__ + \" is disallowed in the filter \"\n                \"clause.\"\n            )\n        if hasattr(exp7, \"get_source_expressions\"):\n            for exp8 in exp7.get_source_expressions():\n                self.check4(exp8)\n\n    def build(self, loo2, lhs2, rhs5):\n        \"\"\"\n        Try to extract transforms and lookup from given lhs.\n\n        The lhs value is something that works like SQLExpression.\n        The rhs value is what the lookup is going to compare against.\n        The lookups is a list of names to extract using get_lookup()\n        and get_transform().\n        \"\"\"\n        # __exact is the default lookup if one isn't given.\n        *tra, lookup4 = loo2 or [\"exact\"]\n        for nam in tra:\n            lhs2 = self.try2(lhs2, nam, loo2)\n        # First try get_lookup() so that the lookup takes precedence if the lhs\n        # supports both transform and lookup for the name.\n        lookup5 = lhs2.get_lookup(lookup4)\n        if not lookup5:\n            # A lookup wasn't found. Try to interpret the name as a transform\n            # and do an Exact lookup against it.\n            lhs2 = self.try2(lhs2, lookup4)\n            lookup4 = \"exact\"\n            lookup5 = lhs2.get_lookup(lookup4)\n            if not lookup5:\n                return\n\n        loo3 = lookup5(lhs2, rhs5)\n        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all\n        # uses of None as a query value unless the lookup supports it.\n        if loo3.rhs is None and not loo3.can_use_none_as_rhs:\n            if lookup4 not in (\"exact\", \"iexact\"):\n                raise ValueError(\"Cannot use None as a query value\")\n            return lhs2.get_lookup(\"isnull\")(lhs2, True)\n\n        # For Oracle '' is equivalent to null. The check must be done at this\n        # stage because join promotion can't be done in the compiler. Using\n        # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.\n        # A similar thing is done in is_nullable(), too.\n        if (\n            lookup4 in (\"exact\", \"iexact\")\n            and loo3.rhs == \"\"\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        ):\n            return lhs2.get_lookup(\"isnull\")(lhs2, True)\n\n        return loo3\n\n    def try2(self, lhs3, nam2, loo4=None):\n        \"\"\"\n        Helper method for build_lookup(). Try to fetch and initialize\n        a transform for name parameter from lhs.\n        \"\"\"\n        transform2 = lhs3.get_transform(nam2)\n        if transform2:\n            return transform2(lhs3)\n        else:\n            output2 = lhs3.output_field.__class__\n            suggested = difflib.get_close_matches(\n                nam2, lhs3.output_field.get_lookups()\n            )\n            if suggested:\n                sug = \", perhaps you meant %s?\" % \" or \".join(suggested)\n            else:\n                sug = \".\"\n            if loo4 is not None:\n                name2 = loo4.index(nam2)\n                unsupported = LOOKUP_SEP.join(loo4[name2:])\n            else:\n                unsupported = nam2\n            raise FieldError(\n                \"Unsupported lookup '%s' for %s or join on the field not \"\n                \"permitted%s\" % (unsupported, output2.__name__, sug)\n            )\n\n    def build2(\n        self,\n        filter,\n        branch=False,\n        current=False,\n        can3=None,\n        allow2=True,\n        split3=True,\n        check5=True,\n        sum4=False,\n        update2=True,\n    ):\n        \"\"\"\n        Build a WhereNode for a single filter clause but don't add it\n        to this Query. Query.add_q() will then add this filter to the where\n        Node.\n\n        The 'branch_negated' tells us if the current branch contains any\n        negations. This will be used to determine if subqueries are needed.\n\n        The 'current_negated' is used to determine if the current filter is\n        negated or not and this will be used to determine if IS NULL filtering\n        is needed.\n\n        The difference between current_negated and branch_negated is that\n        branch_negated is set on first negation, but current_negated is\n        flipped for each negation.\n\n        Note that add_filter will not do any negating itself, that is done\n        upper in the code by add_q().\n\n        The 'can_reuse' is a set of reusable joins for multijoins.\n\n        The method will create a filter clause that can be added to the current\n        query. However, if the filter isn't added to the query then the caller\n        is responsible for unreffing the joins used.\n        \"\"\"\n        if isinstance(filter, dict):\n            raise FieldError(\"Cannot parse keyword query as dict\")\n        if isinstance(filter, Q):\n            return self.add5(\n                filter,\n                branch_negated=branch,\n                current_negated=current,\n                used_aliases=can3,\n                allow_joins=allow2,\n                split_subq=split3,\n                check_filterable=check5,\n                summarize=sum4,\n                update_join_types=update2,\n            )\n        if hasattr(filter, \"resolve_expression\"):\n            if not getattr(filter, \"conditional\", False):\n                raise TypeError(\"Cannot filter against a non-conditional expression.\")\n            con6 = filter.resolve_expression(\n                self, allow_joins=allow2, reuse=can3, summarize=sum4\n            )\n            if not isinstance(con6, Lookup):\n                con6 = self.build([\"exact\"], con6, True)\n            return WhereNode([con6], connector=AND), []\n        arg3, val6 = filter\n        if not arg3:\n            raise FieldError(\"Cannot parse keyword query %r\" % arg3)\n        loo5, par4, reffed = self.solve(arg3, sum4)\n\n        if check5:\n            self.check4(reffed)\n\n        if not allow2 and len(par4) > 1:\n            raise FieldError(\"Joined field references are not permitted in this query\")\n\n        pre3 = self.alias_refcount.copy()\n        val6 = self.resolve2(val6, can3, allow2, sum4)\n        used = {\n            k2 for k2, v3 in self.alias_refcount.items() if v3 > pre3.get(k2, 0)\n        }\n\n        if check5:\n            self.check4(val6)\n\n        if reffed:\n            con6 = self.build(loo5, reffed, val6)\n            return WhereNode([con6], connector=AND), []\n\n        opt8 = self.get3()\n        ali22 = self.get10()\n        allow3 = not branch or not split3\n\n        try:\n            join5 = self.setup(\n                par4,\n                opt8,\n                ali22,\n                can_reuse=can3,\n                allow_many=allow3,\n            )\n\n            # Prevent iterator from being consumed by check_related_objects()\n            if isinstance(val6, Iterator):\n                val6 = list(val6)\n            self.check3(join5.final_field, val6, join5.opts)\n\n            # split_exclude() needs to know which joins were generated for the\n            # lookup parts\n            self._lookup_joins = join5.joins\n        except MultiJoin as e:\n            return self.split2(filter, can3, e.names_with_path)\n\n        # Update used_joins before trimming since they are reused to determine\n        # which joins could be later promoted to INNER.\n        used.update(join5.joins)\n        tar2, ali22, join6 = self.trim(\n            join5.targets, join5.joins, join5.path\n        )\n        if can3 is not None:\n            can3.update(join6)\n\n        if join5.final_field.is_relation:\n            if len(tar2) == 1:\n                col11 = self.get4(tar2[0], join5.final_field, ali22)\n            else:\n                col11 = ColPairs(ali22, tar2, join5.targets, join5.final_field)\n        else:\n            col11 = self.get4(tar2[0], join5.final_field, ali22)\n\n        con6 = self.build(loo5, col11, val6)\n        lookup6 = con6.lookup_name\n        cla = WhereNode([con6], connector=AND)\n\n        require = (\n            lookup6 == \"isnull\" and con6.rhs is True and not current\n        )\n        if (\n            current\n            and (lookup6 != \"isnull\" or con6.rhs is False)\n            and con6.rhs is not None\n        ):\n            require = True\n            if lookup6 != \"isnull\":\n                # The condition added here will be SQL like this:\n                # NOT (col IS NOT NULL), where the first NOT is added in\n                # upper layers of code. The reason for addition is that if col\n                # is null, then col != someval will result in SQL \"unknown\"\n                # which isn't the same as in Python. The Python None handling\n                # is wanted, and it can be gotten by\n                # (col IS NULL OR col != someval)\n                #   <=>\n                # NOT (col IS NOT NULL AND col = someval).\n                if (\n                    self.is4(tar2[0])\n                    or self.alias_map[join6[-1]].join_type == LOUTER\n                ):\n                    lookup7 = tar2[0].get_lookup(\"isnull\")\n                    col11 = self.get4(tar2[0], join5.targets[0], ali22)\n                    # Use OR + IS NULL when RHS `in` values include None.\n                    if (\n                        lookup6 == \"in\"\n                        # Check containers (not strings or bytes).\n                        and isinstance(con6.rhs, Iterable)\n                        and not isinstance(con6.rhs, (str, bytes))\n                        and any(v3 is None for v3 in con6.rhs)\n                    ):\n                        cla.add(lookup7(col11, True), OR)\n                    else:\n                        cla.add(lookup7(col11, False), AND)\n                # If someval is a nullable column, someval IS NOT NULL is\n                # added.\n                if isinstance(val6, Col) and self.is4(val6.target):\n                    lookup7 = val6.target.get_lookup(\"isnull\")\n                    cla.add(lookup7(val6, False), AND)\n        return cla, used if not require else ()\n\n    def add3(self, filter2, filter3):\n        self.add4(Q((filter2, filter3)))\n\n    def add4(self, q5, reuse4=False):\n        \"\"\"\n        A preprocessor for the internal _add_q(). Responsible for doing final\n        join promotion.\n        \"\"\"\n        # For join promotion this case is doing an AND for the added q_object\n        # and existing conditions. So, any existing inner join forces the join\n        # type to remain inner. Existing outer joins can however be demoted.\n        # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if\n        # rel_a doesn't produce any rows, then the whole condition must fail.\n        # So, demotion is OK.\n        existing2 = {\n            a3 for a3 in self.alias_map if self.alias_map[a3].join_type == INNER\n        }\n        if reuse4:\n            can4 = set(self.alias_map)\n        else:\n            can4 = self.used_aliases\n        cla2, _5 = self.add5(q5, can4)\n        if cla2:\n            self.where.add(cla2, AND)\n        self.demote2(existing2)\n\n    def build3(self, filter4):\n        return self.build2(filter4, allow_joins=False)[0]\n\n    def clear(self):\n        self.where = WhereNode()\n\n    def add5(\n        self,\n        q6,\n        used2,\n        branch2=False,\n        current2=False,\n        allow4=True,\n        split4=True,\n        check6=True,\n        sum5=False,\n        update3=True,\n    ):\n        \"\"\"Add a Q-object to the current filter.\"\"\"\n        con7 = q6.connector\n        current2 ^= q6.negated\n        branch2 = branch2 or q6.negated\n        target2 = WhereNode(connector=con7, negated=q6.negated)\n        joi6 = JoinPromoter(\n            q6.connector, len(q6.children), current2\n        )\n        for chi in q6.children:\n            child2, needed = self.build2(\n                chi,\n                can_reuse=used2,\n                branch_negated=branch2,\n                current_negated=current2,\n                allow_joins=allow4,\n                split_subq=split4,\n                check_filterable=check6,\n                summarize=sum5,\n                update_join_types=update3,\n            )\n            joi6.add_votes(needed)\n            if child2:\n                target2.add(child2, con7)\n        if update3:\n            needed = joi6.update_join_types(self)\n        else:\n            needed = []\n        return target2, needed\n\n    def add6(self, filtered4, ali23):\n        if \".\" in ali23:\n            raise ValueError(\n                \"FilteredRelation doesn't support aliases with periods \"\n                \"(got %r).\" % ali23\n            )\n        self.check(ali23)\n        filtered4.alias = ali23\n        relation2, relation3, _6 = self.solve(\n            filtered4.relation_name\n        )\n        if relation2:\n            raise ValueError(\n                \"FilteredRelation's relation_name cannot contain lookups \"\n                \"(got %r).\" % filtered4.relation_name\n            )\n        for loo6 in get_children_from_q(filtered4.condition):\n            lookup8, lookup9, _6 = self.solve(loo6)\n            shi = 2 if not lookup8 else 1\n            lookup10 = lookup9[:-shi]\n            for idx2, lookup11 in enumerate(lookup10):\n                if len(relation3) > idx2:\n                    if relation3[idx2] != lookup11:\n                        raise ValueError(\n                            \"FilteredRelation's condition doesn't support \"\n                            \"relations outside the %r (got %r).\"\n                            % (filtered4.relation_name, loo6)\n                        )\n            if len(lookup9) > len(relation3) + 1:\n                raise ValueError(\n                    \"FilteredRelation's condition doesn't support nested \"\n                    \"relations deeper than the relation_name (got %r for \"\n                    \"%r).\" % (loo6, filtered4.relation_name)\n                )\n        filtered4 = filtered4.clone()\n        filtered4.condition = rename_prefix_from_q(\n            filtered4.relation_name,\n            ali23,\n            filtered4.condition,\n        )\n        self._filtered_relations[filtered4.alias] = filtered4\n\n    def names2(self, nam3, opt9, allow5=True, fail=False):\n        \"\"\"\n        Walk the list of names and turns them into PathInfo tuples. A single\n        name in 'names' can generate multiple PathInfos (m2m, for example).\n\n        'names' is the path of names to travel, 'opts' is the model Options we\n        start the name resolving from, 'allow_many' is as for setup_joins().\n        If fail_on_missing is set to True, then a name that can't be resolved\n        will generate a FieldError.\n\n        Return a list of PathInfo tuples. In addition return the final field\n        (the last used join field) and target (which is a field guaranteed to\n        contain the same value as the final field). Finally, return those names\n        that weren't found (which are likely transforms and the final lookup).\n        \"\"\"\n        pat, names3 = [], []\n        for pos4, nam4 in enumerate(nam3):\n            cur2 = (nam4, [])\n            if nam4 == \"pk\" and opt9 is not None:\n                nam4 = opt9.pk.name\n\n            fie7 = None\n            filtered5 = None\n            try:\n                if opt9 is None:\n                    raise FieldDoesNotExist\n                fie7 = opt9.get_field(nam4)\n            except FieldDoesNotExist:\n                if nam4 in self.annotations:\n                    fie7 = self.annotations[nam4].output_field\n                elif nam4 in self._filtered_relations and pos4 == 0:\n                    filtered5 = self._filtered_relations[nam4]\n                    if LOOKUP_SEP in filtered5.relation_name:\n                        par5 = filtered5.relation_name.split(LOOKUP_SEP)\n                        filtered6, fie7, _7, _7 = self.names2(\n                            par5,\n                            opt9,\n                            allow5,\n                            fail,\n                        )\n                        pat.extend(filtered6[:-1])\n                    else:\n                        fie7 = opt9.get_field(filtered5.relation_name)\n            if fie7 is not None:\n                # Fields that contain one-to-many relations with a generic\n                # model (like a GenericForeignKey) cannot generate reverse\n                # relations and therefore cannot be used for reverse querying.\n                if fie7.is_relation and not fie7.related_model:\n                    raise FieldError(\n                        \"Field %r does not generate an automatic reverse \"\n                        \"relation and therefore cannot be used for reverse \"\n                        \"querying. If it is a GenericForeignKey, consider \"\n                        \"adding a GenericRelation.\" % nam4\n                    )\n                try:\n                    mod3 = fie7.model._meta.concrete_model\n                except AttributeError:\n                    # QuerySet.annotate() may introduce fields that aren't\n                    # attached to a model.\n                    mod3 = None\n            else:\n                # We didn't find the current field, so move position back\n                # one step.\n                pos4 -= 1\n                if pos4 == -1 or fail:\n                    ava = sorted(\n                        [\n                            *get_field_names_from_opts(opt9),\n                            *self.annotations,\n                            *self._filtered_relations,\n                        ]\n                    )\n                    raise FieldError(\n                        \"Cannot resolve keyword '%s' into field. \"\n                        \"Choices are: %s\" % (nam4, \", \".join(ava))\n                    )\n                break\n            # Check if we need any joins for concrete inheritance cases (the\n            # field lives in parent, but we are currently in one of its\n            # children)\n            if opt9 is not None and mod3 is not opt9.model:\n                path2 = opt9.get_path_to_parent(mod3)\n                if path2:\n                    pat.extend(path2)\n                    cur2[1].extend(path2)\n                    opt9 = path2[-1].to_opts\n            if hasattr(fie7, \"path_infos\"):\n                if filtered5:\n                    pat2 = fie7.get_path_info(filtered5)\n                else:\n                    pat2 = fie7.path_infos\n                if not allow5:\n                    for inner2, p2 in enumerate(pat2):\n                        if p2.m2m:\n                            cur2[1].extend(pat2[0 : inner2 + 1])\n                            names3.append(cur2)\n                            raise MultiJoin(pos4 + 1, names3)\n                las = pat2[-1]\n                pat.extend(pat2)\n                final = las.join_field\n                opt9 = las.to_opts\n                tar3 = las.target_fields\n                cur2[1].extend(pat2)\n                names3.append(cur2)\n            else:\n                # Local non-relational field.\n                final = fie7\n                tar3 = (fie7,)\n                if fail and pos4 + 1 != len(nam3):\n                    raise FieldError(\n                        \"Cannot resolve keyword %r into field. Join on '%s'\"\n                        \" not permitted.\" % (nam3[pos4 + 1], nam4)\n                    )\n                break\n        return pat, final, tar3, nam3[pos4 + 1 :]\n\n    def setup(\n        self,\n        nam5,\n        opt10,\n        ali24,\n        can5=None,\n        allow6=True,\n    ):\n        \"\"\"\n        Compute the necessary table joins for the passage through the fields\n        given in 'names'. 'opts' is the Options class for the current model\n        (which gives the table we are starting from), 'alias' is the alias for\n        the table to start the joining from.\n\n        The 'can_reuse' defines the reverse foreign key joins we can reuse. It\n        can be None in which case all joins are reusable or a set of aliases\n        that can be reused. Note that non-reverse foreign keys are always\n        reusable when using setup_joins().\n\n        If 'allow_many' is False, then any reverse foreign key seen will\n        generate a MultiJoin exception.\n\n        Return the final field involved in the joins, the target field (used\n        for any 'where' constraint), the final 'opts' value, the joins, the\n        field path traveled to generate the joins, and a transform function\n        that takes a field and alias and is equivalent to\n        `field.get_col(alias)` in the simple case but wraps field transforms if\n        they were included in names.\n\n        The target field is the field containing the concrete value. Final\n        field can be something different, for example foreign key pointing to\n        that value. Final field is needed for example in some value\n        conversions (convert 'obj' in fk__id=obj to pk val using the foreign\n        key field for example).\n        \"\"\"\n        joi7 = [ali24]\n        # The transform can't be applied yet, as joins must be trimmed later.\n        # To avoid making every caller of this method look up transforms\n        # directly, compute transforms here and create a partial that converts\n        # fields to the appropriate wrapped version.\n\n        def final_transformer(fie8, ali25):\n            if not self.alias_cols:\n                ali25 = None\n            return fie8.get_col(ali25)\n\n        # Try resolving all the names as fields first. If there's an error,\n        # treat trailing names as lookups until a field can be resolved.\n        last2 = None\n        for piv in range(len(nam5), 0, -1):\n            try:\n                pat3, final2, tar4, res4 = self.names2(\n                    nam5[:piv],\n                    opt10,\n                    allow6,\n                    fail_on_missing=True,\n                )\n            except FieldError as exc:\n                if piv == 1:\n                    # The first item cannot be a lookup, so it's safe\n                    # to raise the field error here.\n                    raise\n                else:\n                    last2 = exc\n            else:\n                # The transforms are the remaining items that couldn't be\n                # resolved into fields.\n                tra2 = nam5[piv:]\n                break\n        for nam6 in tra2:\n\n            def transform(fie9, ali26, *, nam7, pre4):\n                try:\n                    wra2 = pre4(fie9, ali26)\n                    return self.try2(wra2, nam7)\n                except FieldError:\n                    # FieldError is raised if the transform doesn't exist.\n                    if isinstance(final_field, Field) and last_field_exception:\n                        raise last_field_exception\n                    else:\n                        raise\n\n            final3 = functools.partial(\n                transform, name=nam6, previous=final3\n            )\n            final3.has_transforms = True\n        # Then, add the path to the query's joins. Note that we can't trim\n        # joins at this stage - we will need the information about join type\n        # of the trimmed joins.\n        for joi8 in pat3:\n            if joi8.filtered_relation:\n                filtered7 = joi8.filtered_relation.clone()\n                table5 = filtered7.alias\n            else:\n                filtered7 = None\n                table5 = None\n            opt10 = joi8.to_opts\n            if joi8.direct:\n                nul = self.is4(joi8.join_field)\n            else:\n                nul = True\n            con8 = self.join_class(\n                opt10.db_table,\n                ali24,\n                table5,\n                INNER,\n                joi8.join_field,\n                nul,\n                filtered_relation=filtered7,\n            )\n            reu3 = can5 if joi8.m2m else None\n            ali24 = self.joi(con8, reuse=reu3)\n            joi7.append(ali24)\n            if joi8.filtered_relation and can5 is not None:\n                can5.add(ali24)\n        return JoinInfo(final2, tar4, opt10, joi7, pat3, final3)\n\n    def trim(self, tar5, joi9, pat4):\n        \"\"\"\n        The 'target' parameter is the final field being joined to, 'joins'\n        is the full list of join aliases. The 'path' contain the PathInfos\n        used to create the joins.\n\n        Return the final target field and table alias and the new active\n        joins.\n\n        Always trim any direct join if the target column is already in the\n        previous table. Can't trim reverse joins as it's unknown if there's\n        anything on the other side of the join.\n        \"\"\"\n        joi9 = joi9[:]\n        for pos5, inf in enumerate(reversed(pat4)):\n            if len(joi9) == 1 or not inf.direct:\n                break\n            if inf.filtered_relation:\n                break\n            join7 = {t2.column for t2 in inf.join_field.foreign_related_fields}\n            cur3 = {t2.column for t2 in tar5}\n            if not cur3.issubset(join7):\n                break\n            targets2 = {\n                r2[1].column: r2[0]\n                for r2 in inf.join_field.related_fields\n                if r2[1].column in cur3\n            }\n            tar5 = tuple(targets2[t2.column] for t2 in tar5)\n            self.unref(joi9.pop())\n        return tar5, joi9[-1], joi9\n\n    @classmethod\n    def gen(cls, exp9, include=False, resolve5=True):\n        for exp10 in exp9:\n            if isinstance(exp10, Col):\n                yield exp10\n            elif include and callable(\n                getattr(exp10, \"get_external_cols\", None)\n            ):\n                yield from exp10.get_external_cols()\n            elif hasattr(exp10, \"get_source_expressions\"):\n                if not resolve5 and isinstance(exp10, Ref):\n                    continue\n                yield from cls.gen(\n                    exp10.get_source_expressions(),\n                    include_external=include,\n                    resolve_refs=resolve5,\n                )\n\n    @classmethod\n    def gen2(cls, exp11):\n        yield from (exp12.alias for exp12 in cls.gen(exp11))\n\n    def resolve3(self, nam8, allow7=True, reu4=None, sum6=False):\n        ann4 = self.annotations.get(nam8)\n        if ann4 is not None:\n            if not allow7:\n                for ali27 in self.gen2([ann4]):\n                    if isinstance(self.alias_map[ali27], Join):\n                        raise FieldError(\n                            \"Joined field references are not permitted in this query\"\n                        )\n            if sum6:\n                # Summarize currently means we are doing an aggregate() query\n                # which is executed as a wrapped subquery if any of the\n                # aggregate() elements reference an existing annotation. In\n                # that case we need to return a Ref to the subquery's\n                # annotation.\n                if nam8 not in self.annotation2:\n                    raise FieldError(\n                        \"Cannot aggregate over the '%s' alias. Use annotate() \"\n                        \"to promote it.\" % nam8\n                    )\n                return Ref(nam8, self.annotation2[nam8])\n            else:\n                return ann4\n        else:\n            field13 = nam8.split(LOOKUP_SEP)\n            ann4 = self.annotations.get(field13[0])\n            if ann4 is not None:\n                for tra3 in field13[1:]:\n                    ann4 = self.try2(ann4, tra3)\n                return ann4\n            join8 = self.setup(\n                field13, self.get3(), self.get10(), can_reuse=reu4\n            )\n            tar6, final4, join9 = self.trim(\n                join8.targets, join8.joins, join8.path\n            )\n            if not allow7 and len(join9) > 1:\n                raise FieldError(\n                    \"Joined field references are not permitted in this query\"\n                )\n            if len(tar6) > 1:\n                raise FieldError(\n                    \"Referencing multicolumn fields with F() objects isn't supported\"\n                )\n            # Verify that the last lookup in name is a field or a transform:\n            # transform_function() raises FieldError if not.\n            tra3 = join8.transform_function(tar6[0], final4)\n            if reu4 is not None:\n                reu4.update(join9)\n            return tra3\n\n    def split2(self, filter5, can6, names4):\n        \"\"\"\n        When doing an exclude against any kind of N-to-many relation, we need\n        to use a subquery. This method constructs the nested query, given the\n        original exclude filter (filter_expr) and the portion up to the first\n        N-to-many relation field.\n\n        For example, if the origin filter is ~Q(child__name='foo'), filter_expr\n        is ('child__name', 'foo') and can_reuse is a set of joins usable for\n        filters in the original query.\n\n        We will turn this into equivalent of:\n            WHERE NOT EXISTS(\n                SELECT 1\n                FROM child\n                WHERE name = 'foo' AND child.parent_id = parent.id\n                LIMIT 1\n            )\n        \"\"\"\n        # Generate the inner query.\n        que4 = self.__class__(self.model)\n        que4._filtered_relations = self._filtered_relations\n        filter6, filter7 = filter5\n        if isinstance(filter7, OuterRef):\n            filter7 = OuterRef(filter7)\n        elif isinstance(filter7, F):\n            filter7 = OuterRef(filter7.name)\n        que4.add_filter(filter6, filter7)\n        que4.clear_ordering(force=True)\n        # Try to have as simple as possible subquery -> trim leading joins from\n        # the subquery.\n        trimmed, contains = que4.trim_start(names4)\n\n        col12 = que4.select[0]\n        select4 = col12.target\n        ali28 = col12.alias\n        if ali28 in can6:\n            pk2 = select4.model._meta.pk\n            # Need to add a restriction so that outer query's filters are in\n            # effect for the subquery, too.\n            que4.bump_prefix(self)\n            lookup12 = select4.get_lookup(\"exact\")\n            # Note that the query.select[0].alias is different from alias\n            # due to bump_prefix above.\n            loo7 = lookup12(pk2.get_col(que4.select[0].alias), pk2.get_col(ali28))\n            que4.where.add(loo7, AND)\n            que4.external_aliases[ali28] = True\n        else:\n            lookup12 = select4.get_lookup(\"exact\")\n            loo7 = lookup12(col12, ResolvedOuterRef(trimmed))\n            que4.where.add(loo7, AND)\n\n        con9, needed2 = self.build2(Exists(que4))\n\n        if contains:\n            or2, _8 = self.build2(\n                (\"%s__isnull\" % trimmed, True),\n                current_negated=True,\n                branch_negated=True,\n                can_reuse=can6,\n            )\n            con9.add(or2, OR)\n            # Note that the end result will be:\n            #   NOT EXISTS (inner_q) OR outercol IS NULL\n            # this might look crazy but due to how NULL works, this seems to be\n            # correct. If the IS NULL check is removed, then if outercol\n            # IS NULL we will not match the row.\n        return con9, needed2\n\n    def set2(self):\n        self.where.add(NothingNode(), AND)\n        for que5 in self.combined_queries:\n            que5.set_empty()\n\n    def is2(self):\n        return any(isinstance(c2, NothingNode) for c2 in self.where.children)\n\n    def set3(self, low2=None, hig=None):\n        \"\"\"\n        Adjust the limits on the rows retrieved. Use low/high to set these,\n        as it makes it more Pythonic to read and write. When the SQL query is\n        created, convert them to the appropriate offset and limit values.\n\n        Apply any limits passed in here to the existing constraints. Add low\n        to the current low value and clamp both to any existing high value.\n        \"\"\"\n        if hig is not None:\n            if self.high_mark is not None:\n                self.high_mark = min(self.high_mark, self.low_mark + hig)\n            else:\n                self.high_mark = self.low_mark + hig\n        if low2 is not None:\n            if self.high_mark is not None:\n                self.low_mark = min(self.high_mark, self.low_mark + low2)\n            else:\n                self.low_mark = self.low_mark + low2\n\n        if self.low_mark == self.high_mark:\n            self.set2()\n\n    def clear2(self):\n        \"\"\"Clear any existing limits.\"\"\"\n        self.low_mark, self.high_mark = 0, None\n\n    @property\n    def is3(self):\n        return self.low_mark != 0 or self.high_mark is not None\n\n    def has3(self):\n        return self.high_mark is not None and (self.high_mark - self.low_mark) == 1\n\n    def can(self):\n        \"\"\"\n        Return True if adding filters to this instance is still possible.\n\n        Typically, this means no limits or offsets have been put on the\n        results.\n        \"\"\"\n        return not self.is3\n\n    def clear3(self):\n        \"\"\"Remove all fields from SELECT clause.\"\"\"\n        self.select = ()\n        self.default_cols = False\n        self.select_related = False\n        self.set7(())\n        self.set6(())\n        self.selected = None\n\n    def clear4(self):\n        \"\"\"\n        Clear the list of fields to select (but not extra_select columns).\n        Some queryset types completely replace any existing list of select\n        columns.\n        \"\"\"\n        self.select = ()\n        self.values_select = ()\n        self.selected = None\n\n    def add7(self, col13, nam9):\n        self.select += (col13,)\n        self.values_select += (nam9,)\n        self.selected[nam9] = len(self.select) - 1\n\n    def set4(self, col14):\n        self.default_cols = False\n        self.select = tuple(col14)\n\n    def add8(self, *field14):\n        \"\"\"\n        Add and resolve the given fields to the query's \"distinct on\" clause.\n        \"\"\"\n        self.distinct_fields = field14\n        self.distinct = True\n\n    def add9(self, field15, allow8=True):\n        \"\"\"\n        Add the given (model) fields to the select set. Add the field names in\n        the order specified.\n        \"\"\"\n        ali29 = self.get10()\n        opt11 = self.get3()\n\n        try:\n            col15 = []\n            for nam10 in field15:\n                # Join promotion note - we must not remove any rows here, so\n                # if there is no existing joins, use outer join.\n                join10 = self.setup(\n                    nam10.split(LOOKUP_SEP), opt11, ali29, allow_many=allow8\n                )\n                tar7, final5, joi10 = self.trim(\n                    join10.targets,\n                    join10.joins,\n                    join10.path,\n                )\n                if len(tar7) > 1:\n                    transformed = [\n                        join10.transform_function(tar8, final5)\n                        for tar8 in tar7\n                    ]\n                    col15.append(\n                        ColPairs(\n                            final5 if self.alias_cols else None,\n                            [col16.target for col16 in transformed],\n                            [col16.output_field for col16 in transformed],\n                            join10.final_field,\n                        )\n                    )\n                else:\n                    col15.append(join10.transform_function(tar7[0], final5))\n            if col15:\n                self.set4(col15)\n        except MultiJoin:\n            raise FieldError(\"Invalid field name: '%s'\" % nam10)\n        except FieldError:\n            if LOOKUP_SEP in nam10:\n                # For lookups spanning over relationships, show the error\n                # from the model on which the lookup failed.\n                raise\n            else:\n                nam11 = sorted(\n                    [\n                        *get_field_names_from_opts(opt11),\n                        *self.extra,\n                        *self.annotation2,\n                        *self._filtered_relations,\n                    ]\n                )\n                raise FieldError(\n                    \"Cannot resolve keyword %r into field. \"\n                    \"Choices are: %s\" % (nam10, \", \".join(nam11))\n                )\n\n    def add10(self, *ord2):\n        \"\"\"\n        Add items from the 'ordering' sequence to the query's \"order by\"\n        clause. These items are either field names (not column names) --\n        possibly with a direction prefix ('-' or '?') -- or OrderBy\n        expressions.\n\n        If 'ordering' is empty, clear all ordering from the query.\n        \"\"\"\n        err = []\n        for ite in ord2:\n            if isinstance(ite, str):\n                if ite == \"?\":\n                    continue\n                ite = ite.removeprefix(\"-\")\n                if ite in self.annotations:\n                    continue\n                if self.extra and ite in self.extra:\n                    continue\n                # names_to_path() validates the lookup. A descriptive\n                # FieldError will be raise if it's not.\n                self.names2(ite.split(LOOKUP_SEP), self.model._meta)\n            elif not hasattr(ite, \"resolve_expression\"):\n                err.append(ite)\n            if getattr(ite, \"contains_aggregate\", False):\n                raise FieldError(\n                    \"Using an aggregate in order_by() without also including \"\n                    \"it in annotate() is not allowed: %s\" % ite\n                )\n        if err:\n            raise FieldError(\"Invalid order_by arguments: %s\" % err)\n        if ord2:\n            self.order_by += ord2\n        else:\n            self.default_ordering = False\n\n    @property\n    def orderby(self):\n        if self.extra_order_by:\n            # Raw SQL from extra(order_by=...) can't be reliably compared\n            # against resolved OrderBy/Col expressions. Treat as not a subset.\n            return False\n        if self.group_by in (None, True):\n            # There is either no aggregation at all (None), or the group by\n            # is generated automatically from model fields (True), in which\n            # case the order by is necessarily a subset of them.\n            return True\n        if not self.order_by:\n            # Although an empty set is always a subset, there's no point in\n            # clearing ordering when there isn't any. Avoid the clone() below.\n            return True\n        # Don't pollute the original query (might disrupt joins).\n        q7 = self.clo()\n        order = set()\n        for order2 in q7.order_by:\n            if hasattr(order2, \"resolve_expression\"):\n                order.add(order2.resolve_expression(q7))\n            elif order2 == \"?\":\n                # Random ordering can't be compared against group by.\n                return False\n            else:\n                order.add(F(order2.removeprefix(\"-\")).resolve_expression(q7))\n        return order.issubset(self.group_by)\n\n    def clear5(self, for3=False, clear7=True):\n        \"\"\"\n        Remove any ordering settings if the current query allows it without\n        side effects, set 'force' to True to clear the ordering regardless.\n        If 'clear_default' is True, there will be no ordering in the resulting\n        query (not even the model's default).\n        \"\"\"\n        if not for3 and (\n            self.is3 or self.distinct_fields or self.select_for_update\n        ):\n            return\n        self.order_by = ()\n        self.extra_order_by = ()\n        if clear7:\n            self.default_ordering = False\n        # Ordering is cleared on combined queries with clear_default=False\n        # when union() and analogues are called, so percolate any possible\n        # clear_default=True.\n        for que6 in self.combined_queries:\n            que6.clear_ordering(force=False, clear_default=clear7)\n\n    def set5(self, allow9=True):\n        \"\"\"\n        Expand the GROUP BY clause required by the query.\n\n        This will usually be the set of all non-aggregate fields in the\n        return data. If the database backend supports grouping by the\n        primary key, and the query would be equivalent, the optimization\n        will be made automatically.\n        \"\"\"\n        if allow9 and self.values_select:\n            # If grouping by aliases is allowed assign selected value aliases\n            # by moving them to annotations.\n            group = {}\n            values2 = {}\n            for ali30, exp13 in zip(self.values_select, self.select):\n                if isinstance(exp13, Col):\n                    values2[ali30] = exp13\n                else:\n                    group[ali30] = exp13\n            self.annotations = {**group, **self.annotations}\n            self.append2(group)\n            self.select = tuple(values2.values())\n            self.values_select = tuple(values2)\n            if self.selected is not None:\n                for ind2, value2 in enumerate(values2):\n                    self.selected[value2] = ind2\n        group2 = list(self.select)\n        for ali30, ann5 in self.annotation2.items():\n            if not (group3 := ann5.get_group_by_cols()):\n                continue\n            if allow9 and not ann5.contains_aggregate:\n                group2.append(Ref(ali30, ann5))\n            else:\n                group2.extend(group3)\n        self.group_by = tuple(group2)\n\n    def add11(self, fie10):\n        \"\"\"\n        Set up the select_related data structure so that we only select\n        certain related models (as opposed to all models, when\n        self.select_related=True).\n        \"\"\"\n        if isinstance(self.select_related, bool):\n            field16 = {}\n        else:\n            field16 = self.select_related\n        for fie11 in fie10:\n            d2 = field16\n            for par6 in fie11.split(LOOKUP_SEP):\n                d2 = d2.setdefault(par6, {})\n        self.select_related = field16\n\n    def add12(self, sel3, select5, whe, par7, tab2, order3):\n        \"\"\"\n        Add data to the various extra_* attributes for user-created additions\n        to the query.\n        \"\"\"\n        if sel3:\n            # We need to pair any placeholder markers in the 'select'\n            # dictionary with their parameters in 'select_params' so that\n            # subsequent updates to the select dictionary also adjust the\n            # parameters appropriately.\n            select6 = {}\n            if select5:\n                param = iter(select5)\n            else:\n                param = iter([])\n            for nam12, ent in sel3.items():\n                self.check(nam12)\n                ent = str(ent)\n                entry2 = []\n                pos6 = ent.find(\"%s\")\n                while pos6 != -1:\n                    if pos6 == 0 or ent[pos6 - 1] != \"%\":\n                        entry2.append(next(param))\n                    pos6 = ent.find(\"%s\", pos6 + 2)\n                select6[nam12] = (ent, entry2)\n            self.extra.update(select6)\n        if whe or par7:\n            self.where.add(ExtraWhere(whe, par7), AND)\n        if tab2:\n            self.extra_tables += tuple(tab2)\n        if order3:\n            self.extra_order_by = order3\n\n    def clear6(self):\n        \"\"\"Remove any fields from the deferred loading set.\"\"\"\n        self.deferred_loading = (frozenset(), True)\n\n    def add13(self, field17):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        exclude from loading from the database when automatic column selection\n        is done. Add the new field names to any existing field names that\n        are deferred (or removed from any existing field names that are marked\n        as the only ones for immediate loading).\n        \"\"\"\n        # Fields on related models are stored in the literal double-underscore\n        # format, so that we can use a set datastructure. We do the foo__bar\n        # splitting and handling when computing the SQL column names (as part\n        # of get_columns()).\n        exi2, def3 = self.deferred_loading\n        if def3:\n            # Add to existing deferred names.\n            self.deferred_loading = exi2.union(field17), True\n        else:\n            # Remove names from the set of any existing \"immediate load\" names.\n            if new3 := exi2.difference(field17):\n                self.deferred_loading = new3, False\n            else:\n                self.clear6()\n                if new4 := set(field17).difference(exi2):\n                    self.deferred_loading = new4, True\n\n    def add14(self, field18):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        retrieve when the SQL is executed (\"immediate loading\" fields). The\n        field names replace any existing immediate loading field names. If\n        there are field names already specified for deferred loading, remove\n        those names from the new field_names before storing the new names\n        for immediate loading. (That is, immediate loading overrides any\n        existing immediate values, but respects existing deferrals.)\n        \"\"\"\n        exi3, def4 = self.deferred_loading\n        field18 = set(field18)\n        if \"pk\" in field18:\n            field18.remove(\"pk\")\n            field18.add(self.get3().pk.name)\n\n        if def4:\n            # Remove any existing deferred names from the current set before\n            # setting the new names.\n            self.deferred_loading = field18.difference(exi3), False\n        else:\n            # Replace any existing \"immediate load\" field names.\n            self.deferred_loading = frozenset(field18), False\n\n    def set6(self, nam13):\n        \"\"\"Set the mask of annotations that will be returned by the SELECT.\"\"\"\n        if nam13 is None:\n            self.annotation_select_mask = None\n        else:\n            self.annotation_select_mask = set(nam13)\n            if self.selected:\n                # Prune the masked annotations.\n                self.selected = {\n                    key4: val7\n                    for key4, val7 in self.selected.items()\n                    if not isinstance(val7, str)\n                    or val7 in self.annotation_select_mask\n                }\n                # Append the unmasked annotations.\n                for nam14 in nam13:\n                    self.selected[nam14] = nam14\n        self._annotation_select_cache = None\n\n    def append2(self, nam15):\n        if self.annotation_select_mask is not None:\n            self.set6(self.annotation_select_mask.union(nam15))\n\n    def set7(self, nam16):\n        \"\"\"\n        Set the mask of extra select items that will be returned by SELECT.\n        Don't remove them from the Query since they might be used later.\n        \"\"\"\n        if nam16 is None:\n            self.extra_select_mask = None\n        else:\n            self.extra_select_mask = set(nam16)\n        self._extra_select_cache = None\n\n    @property\n    def has4(self):\n        return self.selected is not None\n\n    def set8(self, fie12):\n        self.select_related = False\n        self.clear6()\n        self.clear4()\n\n        sel4 = {}\n        if fie12:\n            for fie13 in fie12:\n                self.check(fie13)\n            field19 = []\n            extra4 = []\n            annotation6 = []\n            if not self.extra and not self.annotations:\n                # Shortcut - if there are no extra or annotations, then\n                # the values() clause must be just field names.\n                field19 = list(fie12)\n                sel4 = dict(zip(fie12, range(len(fie12))))\n            else:\n                self.default_cols = False\n                for f3 in fie12:\n                    if ext := self.extra2.get(f3):\n                        extra4.append(f3)\n                        sel4[f3] = RawSQL(*ext)\n                    elif f3 in self.annotation2:\n                        annotation6.append(f3)\n                        sel4[f3] = f3\n                    elif f3 in self.annotations:\n                        if self.annotation2:\n                            raise FieldError(\n                                f\"Cannot select the '{f3}' alias. It was excluded \"\n                                f\"by a previous values() or values_list() call. \"\n                                f\"Include '{f3}' in that call to select it.\"\n                            )\n                        else:\n                            raise FieldError(\n                                f\"Cannot select the '{f3}' alias. Use annotate() \"\n                                f\"to promote it.\"\n                            )\n                    else:\n                        # Call `names_to_path` to ensure a FieldError including\n                        # annotations about to be masked as valid choices if\n                        # `f` is not resolvable.\n                        if self.annotation2:\n                            self.names2(f3.split(LOOKUP_SEP), self.model._meta)\n                        sel4[f3] = len(field19)\n                        field19.append(f3)\n            self.set7(extra4)\n            self.set6(annotation6)\n        else:\n            field19 = [f3.attname for f3 in self.model._meta.concrete_fields]\n            sel4 = dict.fromkeys(field19, None)\n        # Selected annotations must be known before setting the GROUP BY\n        # clause.\n        if self.group_by is True:\n            self.add9(\n                (f3.attname for f3 in self.model._meta.concrete_fields), False\n            )\n            # Disable GROUP BY aliases to avoid orphaning references to the\n            # SELECT clause which is about to be cleared.\n            self.set5(allow_aliases=False)\n            self.clear4()\n        elif self.group_by:\n            # Resolve GROUP BY annotation references if they are not part of\n            # the selected fields anymore.\n            group4 = []\n            for exp14 in self.group_by:\n                if isinstance(exp14, Ref) and exp14.refs not in sel4:\n                    exp14 = self.annotations[exp14.refs]\n                group4.append(exp14)\n            self.group_by = tuple(group4)\n\n        self.values_select = tuple(field19)\n        self.add9(field19, True)\n        self.selected = sel4 if fie12 else None\n\n    @property\n    def annotation2(self):\n        \"\"\"\n        Return the dictionary of aggregate columns that are not masked and\n        should be used in the SELECT clause. Cache this result for performance.\n        \"\"\"\n        if self._annotation_select_cache is not None:\n            return self._annotation_select_cache\n        elif not self.annotations:\n            return {}\n        elif self.annotation_select_mask is not None:\n            self._annotation_select_cache = {\n                k3: v4\n                for k3, v4 in self.annotations.items()\n                if k3 in self.annotation_select_mask\n            }\n            return self._annotation_select_cache\n        else:\n            return self.annotations\n\n    @property\n    def extra2(self):\n        if self._extra_select_cache is not None:\n            return self._extra_select_cache\n        if not self.extra:\n            return {}\n        elif self.extra_select_mask is not None:\n            self._extra_select_cache = {\n                k4: v5 for k4, v5 in self.extra.items() if k4 in self.extra_select_mask\n            }\n            return self._extra_select_cache\n        else:\n            return self.extra\n\n    def trim2(self, names5):\n        \"\"\"\n        Trim joins from the start of the join path. The candidates for trim\n        are the PathInfos in names_with_path structure that are m2m joins.\n\n        Also set the select column so the start matches the join.\n\n        This method is meant to be used for generating the subquery joins &\n        cols in split_exclude().\n\n        Return a lookup usable for doing outerq.filter(lookup=self) and a\n        boolean indicating if the joins in the prefix contain a LEFT OUTER\n        join.\n        \"\"\"\n        all = []\n        for _9, pat5 in names5:\n            all.extend(pat5)\n        contains2 = False\n        # Trim and operate only on tables that were generated for\n        # the lookup part of the query. That is, avoid trimming\n        # joins generated for F() expressions.\n        lookup13 = [\n            t3 for t3 in self.alias_map if t3 in self._lookup_joins or t3 == self.base\n        ]\n        for trimmed2, pat6 in enumerate(all):\n            if pat6.m2m:\n                break\n            if self.alias_map[lookup13[trimmed2 + 1]].join_type == LOUTER:\n                contains2 = True\n            ali31 = lookup13[trimmed2]\n            self.unref(ali31)\n        # The path.join_field is a Rel, lets get the other side's field\n        join11 = pat6.join_field.field\n        # Build the filter prefix.\n        paths2 = trimmed2\n        trimmed3 = []\n        for nam17, pat6 in names5:\n            if paths2 - len(pat6) < 0:\n                break\n            trimmed3.append(nam17)\n            paths2 -= len(pat6)\n        trimmed3.append(join11.foreign_related_fields[0].name)\n        trimmed3 = LOOKUP_SEP.join(trimmed3)\n        # Lets still see if we can trim the first join from the inner query\n        # (that is, self). We can't do this for:\n        # - LEFT JOINs because we would miss those rows that have nothing on\n        #   the outer side,\n        # - INNER JOINs from filtered relations because we would miss their\n        #   filters.\n        first = self.alias_map[lookup13[trimmed2 + 1]]\n        if first.join_type != LOUTER and not first.filtered_relation:\n            select7 = [r3[0] for r3 in join11.related_fields]\n            select8 = lookup13[trimmed2 + 1]\n            self.unref(lookup13[trimmed2])\n            extra5 = join11.get_extra_restriction(\n                None, lookup13[trimmed2 + 1]\n            )\n            if extra5:\n                self.where.add(extra5, AND)\n        else:\n            # TODO: It might be possible to trim more joins from the start of\n            # the inner query if it happens to have a longer join chain\n            # containing the values in select_fields. Lets punt this one for\n            # now.\n            select7 = [r3[1] for r3 in join11.related_fields]\n            select8 = lookup13[trimmed2]\n        # The found starting point is likely a join_class instead of a\n        # base_table_class reference. But the first entry in the query's FROM\n        # clause must not be a JOIN.\n        for tab3 in self.alias_map:\n            if self.alias_refcount[tab3] > 0:\n                self.alias_map[tab3] = self.base_table_class(\n                    self.alias_map[tab3].table_name,\n                    tab3,\n                )\n                break\n        self.set4([f4.get_col(select8) for f4 in select7])\n        return trimmed3, contains2\n\n    def is4(self, fie14):\n        \"\"\"\n        Check if the given field should be treated as nullable.\n\n        Some backends treat '' as null and Django treats such fields as\n        nullable for those backends. In such situations field.null can be\n        False even if we should treat the field as nullable.\n        \"\"\"\n        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have\n        # (nor should it have) knowledge of which connection is going to be\n        # used. The proper fix would be to defer all decisions where\n        # is_nullable() is needed to the compiler stage, but that is not easy\n        # to do currently.\n        return fie14.null or (\n            fie14.empty_strings_allowed\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-d737c5fea4d295f9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "380395a48896fdf8f039b4c72397a2b9b67d199cab6a28eafb9c340473c78828", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 2602, "local_path": "identifiers/shorten-identifiers/I02__django__Query__ba8c05ab.py", "order": 2, "original_content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "parent_variant_id": "pyint-82246794d74c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/query.py#L232-L2792", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2285, "identifiers_declared": 611}, "unit_kind": "class", "unit_name": "Query", "variant_id": "pyint-7e18ba8c05ab-I02", "group_id": "py-d737c5fea4d295f9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 283, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9646b1e70aa3-I03", "source": "import copy\nimport difflib\nimport functools\nimport sys\nimport warnings\nfrom collections import Counter, namedtuple\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom itertools import chain, count, product\nfrom string import ascii_uppercase\nfrom django.core.exceptions import FieldDoesNotExist, FieldError\nfrom django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections\nfrom django.db.models.aggregates import Count\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import (\n    BaseExpression,\n    Col,\n    ColPairs,\n    Exists,\n    F,\n    OuterRef,\n    RawSQL,\n    Ref,\n    ResolvedOuterRef,\n    Value,\n)\nfrom django.db.models.fields import Field\nfrom django.db.models.lookups import Lookup\nfrom django.db.models.query_utils import (\n    Q,\n    check_rel_lookup_compatibility,\n    refs_expression,\n)\nfrom django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE\nfrom django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin\nfrom django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode\nfrom django.utils.deprecation import RemovedInDjango70Warning\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.tree import Node\nfrom django.utils.warnings import django_file_prefixes\n\nclass Query(BaseExpression):\n    \"\"\"A single SQL query.\"\"\"\n\n    alias_prefix = \"T\"\n    empty_result_set_value = None\n    subq_aliases = frozenset([alias_prefix])\n\n    compiler = \"SQLCompiler\"\n\n    base_table_class = BaseTable\n    join_class = Join\n\n    default_cols = True\n    default_ordering = True\n    standard_ordering = True\n\n    filter_is_sticky = False\n    subquery = False\n    contains_subquery = False\n\n    # SQL-related attributes.\n    # Select and related select clauses are expressions to use in the SELECT\n    # clause of the query. The select is used for cases where we want to set up\n    # the select clause to contain other than default fields (values(),\n    # subqueries...). Note that annotations go to annotations dictionary.\n    select = ()\n    # The group_by attribute can have one of the following forms:\n    #  - None: no group by at all in the query\n    #  - A tuple of expressions: group by (at least) those expressions.\n    #    String refs are also allowed for now.\n    #  - True: group by all select fields of the model\n    # See compiler.get_group_by() for details.\n    group_by = None\n    order_by = ()\n    low_mark = 0  # Used for offset/limit.\n    high_mark = None  # Used for offset/limit.\n    distinct = False\n    distinct_fields = ()\n    select_for_update = False\n    select_for_update_nowait = False\n    select_for_update_skip_locked = False\n    select_for_update_of = ()\n    select_for_no_key_update = False\n    select_related = False\n    # Arbitrary limit for select_related to prevents infinite recursion.\n    max_depth = 5\n    # Holds the selects defined by a call to values() or values_list()\n    # excluding annotation_select and extra_select.\n    values_select = ()\n    selected = None\n\n    # SQL annotation-related attributes.\n    annotation_select_mask = None\n    _annotation_select_cache = None\n\n    # Set combination attributes.\n    combinator = None\n    combinator_all = False\n    combined_queries = ()\n\n    # These are for extensions. The contents are more or less appended verbatim\n    # to the appropriate clause.\n    extra_select_mask = None\n    _extra_select_cache = None\n\n    extra_tables = ()\n    extra_order_by = ()\n\n    # A tuple that is a set of model field names and either True, if these are\n    # the fields to defer, or False if these are the only fields to load.\n    deferred_loading = (frozenset(), True)\n\n    explain_info = None\n\n    def __init__(self, token, pendingKey=True):\n        self.model = token\n        self.alias_refcount = {}\n        # alias_map is the most important data structure regarding joins.\n        # It's used for recording which joins exist in the query and what\n        # types they are. The key is the alias of the joined table (possibly\n        # the table name) and the value is a Join-like object (see\n        # sql.datastructures.Join for more information).\n        self.alias_map = {}\n        # Whether to provide alias to columns during reference resolving.\n        self.alias_cols = pendingKey\n        # Sometimes the query contains references to aliases in outer queries\n        # (as a result of split_exclude). Correct alias quoting needs to know\n        # these aliases too. Map external tables to whether they are aliased.\n        self.external_aliases = {}\n        self.table_map = {}  # Maps table names to list of aliases.\n        self.used_aliases = set()\n\n        self.where = WhereNode()\n        # Maps alias -> Annotation Expression.\n        self.annotations = {}\n        # These are for extensions. The contents are more or less appended\n        # verbatim to the appropriate clause.\n        self.extra = {}  # Maps col_alias -> (col_sql, params).\n\n        self._filtered_relations = {}\n\n    @property\n    def validateNode(self):\n        if len(self.select) == 1:\n            source = self.select[0]\n            return getattr(source, \"target\", None) or source.field\n        elif len(self.refreshRecord) == 1:\n            return next(iter(self.refreshRecord.values())).output_field\n\n    @cached_property\n    def parseState(self):\n        for token in self.alias_map:\n            return token\n\n    def __str__(self):\n        \"\"\"\n        Return the query as a string of SQL with the parameter values\n        substituted in (use sql_with_params() to see the unsubstituted string).\n\n        Parameter values won't necessarily be quoted correctly, since that is\n        done by the database interface at execution time.\n        \"\"\"\n        key, option = self.validateSession()\n        return key % option\n\n    def validateSession(self):\n        \"\"\"\n        Return the query as an SQL string and the parameters that will be\n        substituted into the query.\n        \"\"\"\n        return self.createStatus(DEFAULT_DB_ALIAS).as_sql()\n\n    def __deepcopy__(self, step):\n        \"\"\"Limit the amount of work when a Query is deepcopied.\"\"\"\n        buffer = self.fetch()\n        step[id(self)] = buffer\n        return buffer\n\n    def createStatus(self, score=None, backupNode=None, nextRequest=True):\n        if score is None and backupNode is None:\n            raise ValueError(\"Need either using or connection\")\n        if score:\n            backupNode = connections[score]\n        return backupNode.ops.compiler(self.compiler)(\n            self, backupNode, score, nextRequest\n        )\n\n    def saveData(self):\n        \"\"\"\n        Return the Options instance (the model._meta) from which to start\n        processing. Normally, this is self.model._meta, but it can be changed\n        by subclasses.\n        \"\"\"\n        if self.model:\n            return self.model._meta\n\n    def fetch(self):\n        \"\"\"\n        Return a copy of the current Query. A lightweight alternative to\n        deepcopy().\n        \"\"\"\n        key = Empty()\n        key.__class__ = self.__class__\n        # Copy references to everything.\n        key.__dict__ = self.__dict__.copy()\n        # Clone attributes that can't use shallow copy.\n        key.alias_refcount = self.alias_refcount.copy()\n        key.alias_map = self.alias_map.copy()\n        key.external_aliases = self.external_aliases.copy()\n        key.table_map = self.table_map.copy()\n        key.where = self.where.clone()\n        key.annotations = self.annotations.copy()\n        if self.annotation_select_mask is not None:\n            key.annotation_select_mask = self.annotation_select_mask.copy()\n        if self.combined_queries:\n            key.combined_queries = tuple(\n                [cache.clone() for cache in self.combined_queries]\n            )\n        # _annotation_select_cache cannot be copied, as doing so breaks the\n        # (necessary) state in which both annotations and\n        # _annotation_select_cache point to the same underlying objects.\n        # It will get re-populated in the cloned queryset the next time it's\n        # used.\n        key._annotation_select_cache = None\n        key.extra = self.extra.copy()\n        if self.extra_select_mask is not None:\n            key.extra_select_mask = self.extra_select_mask.copy()\n        if self._extra_select_cache is not None:\n            key._extra_select_cache = self._extra_select_cache.copy()\n        if self.select_related is not False:\n            # Use deepcopy because select_related stores fields in nested\n            # dicts.\n            key.select_related = copy.deepcopy(key.select_related)\n        if \"subq_aliases\" in self.__dict__:\n            key.subq_aliases = self.subq_aliases.copy()\n        key.used_aliases = self.used_aliases.copy()\n        key._filtered_relations = self._filtered_relations.copy()\n        # Clear the cached_property, if it exists.\n        key.__dict__.pop(\"base_table\", None)\n        return key\n\n    def track(self, total=None):\n        \"\"\"\n        Return a copy of the current Query that's ready for another operation.\n        The klass argument changes the type of the Query, e.g. UpdateQuery.\n        \"\"\"\n        age = self.fetch()\n        if total and age.__class__ != total:\n            age.__class__ = total\n        if not age.filter_is_sticky:\n            age.used_aliases = set()\n        age.filter_is_sticky = False\n        if hasattr(age, \"_setup_query\"):\n            age._setup_query()\n        return age\n\n    def validateRequest(self, nextConfig):\n        order = self.fetch()\n        order.change_aliases(nextConfig)\n        return order\n\n    def findPath(self, option, entry, count):\n        if not self.alias_cols:\n            count = None\n        return option.get_col(count, entry)\n\n    def validateMessage(self, total, currentSession):\n        \"\"\"\n        Return the dictionary with the values of the existing aggregations.\n        \"\"\"\n        if not currentSession:\n            return {}\n        # Store annotation mask prior to temporarily adding aggregations for\n        # resolving purpose to facilitate their subsequent removal.\n        recentAccount = False\n        recentValue = False\n        finalAddress = {}\n        primaryBalance = self.annotation_select_mask\n        for event, currentAddress in currentSession.items():\n            self.sendAddress(event)\n            nextState = currentAddress.resolve_expression(\n                self, allow_joins=True, reuse=None, summarize=True\n            )\n            if not nextState.contains_aggregate:\n                raise TypeError(\"%s is not an aggregate expression\" % event)\n            # Temporarily add aggregate to annotations to allow remaining\n            # members of `aggregates` to resolve against each others.\n            self.refreshBuffer([event])\n            currentBalance = nextState.get_refs()\n            recentAccount |= any(\n                getattr(self.annotations[age], \"contains_subquery\", False)\n                for age in currentBalance\n            )\n            recentValue |= any(\n                getattr(self.annotations[age], \"contains_over_clause\", True)\n                for age in currentBalance\n            )\n            nextState = nextState.replace_expressions(finalAddress)\n            self.annotations[event] = nextState\n            finalAddress[Ref(event, nextState)] = nextState\n        # Stash resolved aggregates now that they have been allowed to resolve\n        # against each other.\n        recentItem = {event: self.annotations.pop(event) for event in currentSession}\n        self.validateToken(primaryBalance)\n        # Existing usage of aggregation can be determined by the presence of\n        # selected aggregates but also by filters against aliased aggregates.\n        map, option, version = self.where.split_having_qualify()\n        defaultBalance = (\n            any(\n                getattr(backupUser, \"contains_aggregate\", True)\n                for backupUser in self.annotations.values()\n            )\n            or option\n        )\n        primarySession = {\n            event\n            for event, backupUser in self.refreshRecord.items()\n            if getattr(backupUser, \"set_returning\", False)\n        }\n        # Decide if we need to use a subquery.\n        #\n        # Existing aggregations would cause incorrect results as\n        # get_aggregation() must produce just one result and thus must not use\n        # GROUP BY.\n        #\n        # If the query has limit or distinct, or uses set operations, then\n        # those operations must be done in a subquery so that the query\n        # aggregates on the limit and/or distinct results instead of applying\n        # the distinct and limit after the aggregation.\n        if (\n            isinstance(self.group_by, tuple)\n            or self.findCache\n            or defaultBalance\n            or recentAccount\n            or recentValue\n            or version\n            or self.distinct\n            or self.combinator\n            or primarySession\n        ):\n            from django.db.models.sql.subqueries import AggregateQuery\n\n            remoteOrder = self.fetch()\n            remoteOrder.subquery = True\n            recentScore = AggregateQuery(self.model, remoteOrder)\n            remoteOrder.select_for_update = False\n            remoteOrder.select_related = False\n            remoteOrder.set_annotation_mask(self.refreshRecord)\n            # Queries with distinct_fields need ordering and when a limit is\n            # applied we must take the slice from the ordered query. Otherwise\n            # no need for ordering.\n            if remoteOrder.orderby_issubset_groupby:\n                remoteOrder.clear_ordering(force=False)\n            if not remoteOrder.distinct:\n                # If the inner query uses default select and it has some\n                # aggregate annotations, then we must make sure the inner\n                # query is grouped by the main model's primary key. However,\n                # clearing the select clause can alter results if distinct is\n                # used.\n                if remoteOrder.default_cols and defaultBalance:\n                    remoteOrder.group_by = (\n                        self.model._meta.pk.get_col(remoteOrder.get_initial_alias()),\n                    )\n                remoteOrder.default_cols = False\n                if not version and not self.combinator:\n                    # Mask existing annotations that are not referenced by\n                    # aggregates to be pushed to the outer query unless\n                    # filtering against window functions or if the query is\n                    # combined as both would require complex realiasing logic.\n                    pendingAddress = set()\n                    if isinstance(self.group_by, tuple):\n                        for user in self.group_by:\n                            pendingAddress |= user.get_refs()\n                    for nextState in recentItem.values():\n                        pendingAddress |= nextState.get_refs()\n                    # Avoid eliding expressions that might have an incidence on\n                    # the implicit grouping logic.\n                    for defaultRequest, backupUser in self.refreshRecord.items():\n                        if backupUser.get_group_by_cols():\n                            pendingAddress.add(defaultRequest)\n                    remoteOrder.set_annotation_mask(pendingAddress)\n                    # Annotations that possibly return multiple rows cannot\n                    # be masked as they might have an incidence on the query.\n                    pendingAddress |= primarySession\n\n            # Add aggregates to the outer AggregateQuery. This requires making\n            # sure all columns referenced by the aggregates are selected in the\n            # inner query. It is achieved by retrieving all column references\n            # by the aggregates, explicitly selecting them in the inner query,\n            # and making sure the aggregates are repointed to them.\n            nextPath = {}\n            for event, nextState in recentItem.items():\n                finalAddress = {}\n                for key in self.saveCount([nextState], resolve_refs=False):\n                    if not (feature := nextPath.get(key)):\n                        count = len(nextPath) + 1\n                        nextToken = f\"__col{count}\"\n                        feature = Ref(nextToken, key)\n                        nextPath[key] = feature\n                        remoteOrder.add_annotation(key, nextToken)\n                    finalAddress[key] = feature\n                recentScore.annotations[event] = nextState.replace_expressions(\n                    finalAddress\n                )\n            if (\n                remoteOrder.select == ()\n                and not remoteOrder.default_cols\n                and not remoteOrder.annotation_select_mask\n            ):\n                # In case of Model.objects[0:3].count(), there would be no\n                # field selected in the inner query, yet we must use a\n                # subquery. So, make sure at least one field is selected.\n                remoteOrder.select = (\n                    self.model._meta.pk.get_col(remoteOrder.get_initial_alias()),\n                )\n        else:\n            recentScore = self\n            self.select = ()\n            self.selected = None\n            self.default_cols = False\n            self.extra = {}\n            if self.annotations:\n                # Inline reference to existing annotations and mask them as\n                # they are unnecessary given only the summarized aggregations\n                # are requested.\n                finalAddress = {\n                    Ref(event, backupUser): backupUser\n                    for event, backupUser in self.annotations.items()\n                }\n                self.annotations = {\n                    event: nextState.replace_expressions(finalAddress)\n                    for event, nextState in recentItem.items()\n                }\n            else:\n                self.annotations = recentItem\n            self.validateToken(recentItem)\n\n        primaryAccount = [\n            cachedData.empty_result_set_value\n            for cachedData in recentScore.annotation_select.values()\n        ]\n        defaultMode = not any(window is NotImplemented for window in primaryAccount)\n        recentScore.clear_ordering(force=True)\n        recentScore.clear_limits()\n        recentScore.select_for_update = False\n        recentScore.select_related = False\n        schedule = recentScore.get_compiler(total, elide_empty=defaultMode)\n        window = schedule.execute_sql(SINGLE)\n        if window is None:\n            window = primaryAccount\n        else:\n            data = recentScore.annotation_select.values()\n            activeNode = schedule.get_converters(data)\n            flag = schedule.apply_converters((window,), activeNode)\n            if schedule.has_composite_fields(data):\n                flag = schedule.composite_fields_to_tuples(flag, data)\n            window = next(flag)\n\n        return dict(zip(recentScore.annotation_select, window))\n\n    def checkPath(self, group):\n        \"\"\"\n        Perform a COUNT() query using the current filter constraints.\n        \"\"\"\n        key = self.fetch()\n        return key.get_aggregation(group, {\"__count\": Count(\"*\")})[\"__count\"]\n\n    def parseWindow(self):\n        return self.where\n\n    def submit(self, price=True):\n        age = self.fetch()\n        if not (age.distinct and age.is_sliced):\n            if age.group_by is True:\n                age.add_fields(\n                    (map.attname for map in self.model._meta.concrete_fields), False\n                )\n                # Disable GROUP BY aliases to avoid orphaning references to the\n                # SELECT clause which is about to be cleared.\n                age.set_group_by(allow_aliases=False)\n            age.clear_select_clause()\n        if age.combined_queries and age.combinator == \"union\":\n            age.combined_queries = tuple(\n                primaryAccount.exists(limit=False)\n                for primaryAccount in age.combined_queries\n            )\n        age.clear_ordering(force=True)\n        if price is True:\n            age.set_limits(high=1)\n        age.add_annotation(Value(1), \"a\")\n        return age\n\n    def fetchResult(self, cache):\n        key = self.submit()\n        customer = key.get_compiler(using=cache)\n        return customer.has_results()\n\n    def loadKey(self, total, status=None, **version):\n        map = self.fetch()\n        for finalStatus in version:\n            if (\n                not EXPLAIN_OPTIONS_PATTERN.fullmatch(finalStatus)\n                or \"--\" in finalStatus\n            ):\n                raise ValueError(f\"Invalid option name: {finalStatus!r}.\")\n        map.explain_info = ExplainInfo(status, version)\n        schedule = map.get_compiler(using=total)\n        return \"\\n\".join(schedule.explain_query())\n\n    def findKey(self, age, secureKey):\n        \"\"\"\n        Merge the 'rhs' query into the current one (with any 'rhs' effects\n        being applied *after* (that is, \"to the right of\") anything in the\n        current query. 'rhs' is not modified during a call to this function.\n\n        The 'connector' parameter describes how to connect filters from the\n        'rhs' query.\n        \"\"\"\n        if self.model != age.model:\n            raise TypeError(\"Cannot combine queries on two different base models.\")\n        if self.findCache:\n            raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n        if self.distinct != age.distinct:\n            raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n        if self.distinct_fields != age.distinct_fields:\n            raise TypeError(\"Cannot combine queries with different distinct fields.\")\n\n        # If lhs and rhs shares the same alias prefix, it is possible to have\n        # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up\n        # as T4 -> T6 while combining two querysets. To prevent this, change an\n        # alias prefix of the rhs and update current aliases accordingly,\n        # except if the alias is the base table since it must be present in the\n        # query on both sides.\n        primaryRecord = self.validateRecord()\n        age = age.clone()\n        age.bump_prefix(self, exclude={primaryRecord})\n\n        # Work out how to relabel the rhs aliases, if necessary.\n        recentMode = {}\n        sharedToken = secureKey == AND\n\n        # Determine which existing joins can be reused. When combining the\n        # query with AND we must recreate all joins for m2m filters. When\n        # combining with OR we can reuse joins. The reason is that in AND\n        # case a single row can't fulfill a condition like:\n        #     revrel__col=1 & revrel__col=2\n        # But, there might be two different related rows matching this\n        # condition. In OR case a single True is enough, so single row is\n        # enough, too.\n        #\n        # Note that we will be creating duplicate joins for non-m2m joins in\n        # the AND case. The results will be correct but this creates too many\n        # joins. This is something that could be fixed later on.\n        price = set() if sharedToken else set(self.alias_map)\n        secureConfig = JoinPromoter(secureKey, 2, False)\n        secureConfig.add_votes(\n            key for key in self.alias_map if self.alias_map[key].join_type == INNER\n        )\n        reference = set()\n        # Now, add the joins from rhs query into the new query (skipping base\n        # table).\n        localBatch = list(age.alias_map)[1:]\n        for count in localBatch:\n            path = age.alias_map[count]\n            # If the left side of the join was already relabeled, use the\n            # updated alias.\n            path = path.relabeled_clone(recentMode)\n            finalItem = self.copy(path, reuse=price)\n            if path.join_type == INNER:\n                reference.add(finalItem)\n            # We can't reuse the same join again in the query. If we have two\n            # distinct joins for the same connection in rhs query, then the\n            # combined query must have two joins, too.\n            price.discard(finalItem)\n            if count != finalItem:\n                recentMode[count] = finalItem\n            if not age.alias_refcount[count]:\n                # The alias was unused in the rhs query. Unref it so that it\n                # will be unused in the new query, too. We have to add and\n                # unref the alias so that join promotion has information of\n                # the join type for the unused alias.\n                self.loadBalance(finalItem)\n        secureConfig.add_votes(reference)\n        secureConfig.update_join_types(self)\n\n        # Combine subqueries aliases to ensure aliases relabelling properly\n        # handle subqueries when combining where and select clauses.\n        self.subq_aliases |= age.subq_aliases\n\n        # Now relabel a copy of the rhs where-clause and add it to the current\n        # one.\n        map = age.where.clone()\n        map.relabel_aliases(recentMode)\n        self.where.add(map, secureKey)\n\n        # Selection columns and extra extensions are those provided by 'rhs'.\n        if age.select:\n            self.parseToken([flag.relabeled_clone(recentMode) for flag in age.select])\n        else:\n            self.select = ()\n\n        if secureKey == OR:\n            # It would be nice to be able to handle this, but the queries don't\n            # really make sense (or return consistent value sets). Not worth\n            # the extra complexity when you can write a real query instead.\n            if self.extra and age.extra:\n                raise ValueError(\n                    \"When merging querysets using 'or', you cannot have \"\n                    \"extra(select=...) on both sides.\"\n                )\n        self.extra.update(age.extra)\n        currentSession = set()\n        if self.extra_select_mask is not None:\n            currentSession.update(self.extra_select_mask)\n        if age.extra_select_mask is not None:\n            currentSession.update(age.extra_select_mask)\n        if currentSession:\n            self.validateCount(currentSession)\n        self.extra_tables += age.extra_tables\n\n        # Ordering uses the 'rhs' ordering, unless it has none, in which case\n        # the current ordering is used.\n        self.order_by = age.order_by or self.order_by\n        self.extra_order_by = age.extra_order_by or self.extra_order_by\n\n    def validateBalance(self, mode, user, cachedBatch=None):\n        if cachedBatch is None:\n            cachedBatch = {}\n        cachedBatch[mode.pk] = {}\n        # All concrete fields and related objects that are not part of the\n        # defer mask must be included. If a relational field is encountered it\n        # gets added to the mask for it be considered if `select_related` and\n        # the cycle continues by recursively calling this function.\n        for index in mode.concrete_fields + mode.related_objects:\n            nextBuffer = user.pop(index.name, None)\n            currentSession = None\n            if pendingRecord := getattr(index, \"attname\", None):\n                currentSession = user.pop(pendingRecord, None)\n            if nextBuffer is None and currentSession is None:\n                cachedBatch.setdefault(index, {})\n            elif nextBuffer:\n                if not index.is_relation:\n                    raise FieldError(next(iter(nextBuffer)))\n                # Virtual fields such as many-to-many and generic foreign keys\n                # cannot be effectively deferred. Historically, they were\n                # allowed to be passed to QuerySet.defer(). Ignore such field\n                # references until a layer of validation at mask alteration\n                # time is eventually implemented.\n                if index.many_to_many:\n                    continue\n                pendingMessage = cachedBatch.setdefault(index, {})\n                remoteMessage = index.related_model._meta.concrete_model\n                self.validateBalance(\n                    remoteMessage._meta, nextBuffer, pendingMessage\n                )\n        # Remaining defer entries must be references to filtered relations\n        # otherwise they are surfaced as missing field errors.\n        for secureData, nextBuffer in user.items():\n            if primaryAccount := self._filtered_relations.get(secureData):\n                document = mode.get_field(primaryAccount.relation_name)\n                pendingMessage = cachedBatch.setdefault((secureData, document), {})\n                remoteMessage = document.related_model._meta.concrete_model\n                self.validateBalance(\n                    remoteMessage._meta, nextBuffer, pendingMessage\n                )\n            else:\n                mode.get_field(secureData)\n        return cachedBatch\n\n    def validateAccount(self, size, flag, remoteScore=None):\n        if remoteScore is None:\n            remoteScore = {}\n        remoteScore[size.pk] = {}\n        # Only include fields mentioned in the mask.\n        for sharedMode, nextStatus in flag.items():\n            limit = size.get_field(sharedMode)\n            primaryAccount = remoteScore.setdefault(limit, {})\n            if nextStatus:\n                if not limit.is_relation:\n                    raise FieldError(next(iter(nextStatus)))\n                cachedBalance = limit.remote_field.model._meta.concrete_model\n                self.validateAccount(\n                    cachedBalance._meta, nextStatus, primaryAccount\n                )\n        return remoteScore\n\n    def validateAddress(self):\n        \"\"\"\n        Convert the self.deferred_loading data structure to an alternate data\n        structure, describing the field that *will* be loaded. This is used to\n        compute the columns to select from the database and also by the\n        QuerySet class to work out which fields are being initialized on each\n        model. Models that have all their fields included aren't mentioned in\n        the result, only those that have field restrictions in place.\n        \"\"\"\n        currentData, cache = self.deferred_loading\n        if not currentData:\n            return {}\n        step = {}\n        for pendingKey in currentData:\n            nextOrder = step\n            for data in pendingKey.split(LOOKUP_SEP):\n                nextOrder = nextOrder.setdefault(data, {})\n        flag = self.saveData()\n        if cache:\n            return self.validateBalance(flag, step)\n        return self.validateAccount(flag, step)\n\n    def sendBalance(self, remoteNode, region=False, primaryMessage=None):\n        \"\"\"\n        Return a table alias for the given table_name and whether this is a\n        new alias or not.\n\n        If 'create' is true, a new alias is always created. Otherwise, the\n        most recently created alias for the table (if one exists) is reused.\n        \"\"\"\n        nextConfig = self.table_map.get(remoteNode)\n        if not region and nextConfig:\n            value = nextConfig[0]\n            self.alias_refcount[value] += 1\n            return value, False\n\n        # Create a new alias for this table.\n        if nextConfig:\n            value = \"%s%d\" % (self.alias_prefix, len(self.alias_map) + 1)\n            nextConfig.append(value)\n        else:\n            # The first occurrence of a table uses the table name directly.\n            value = (\n                primaryMessage.alias if primaryMessage is not None else remoteNode\n            )\n            self.table_map[remoteNode] = [value]\n        self.alias_refcount[value] = 1\n        return value, True\n\n    def saveEvent(self, event):\n        \"\"\"Increases the reference count for this alias.\"\"\"\n        self.alias_refcount[event] += 1\n\n    def loadBalance(self, group, source=1):\n        \"\"\"Decreases the reference count for this alias.\"\"\"\n        self.alias_refcount[group] -= source\n\n    def removeRequest(self, session):\n        \"\"\"\n        Promote recursively the join type of given aliases and its children to\n        an outer join. If 'unconditional' is False, only promote the join if\n        it is nullable or the parent join is an outer join.\n\n        The children promotion is done to avoid join chains that contain a\n        LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b\n        is promoted, then we must also promote b->c automatically, or otherwise\n        the promotion of a->b doesn't actually change anything in the query\n        results.\n        \"\"\"\n        session = list(session)\n        while session:\n            cache = session.pop(0)\n            if self.alias_map[cache].join_type is None:\n                # This is the base table (first FROM entry) - this table\n                # isn't really joined at all in the query, so we should not\n                # alter its join type.\n                continue\n            # Only the first alias (skipped above) should have None join_type\n            assert self.alias_map[cache].join_type is not None\n            sharedRecord = self.alias_map[cache].parent_alias\n            activeAddress = (\n                sharedRecord and self.alias_map[sharedRecord].join_type == LOUTER\n            )\n            defaultAccount = self.alias_map[cache].join_type == LOUTER\n            if (self.alias_map[cache].nullable or activeAddress) and not defaultAccount:\n                self.alias_map[cache] = self.alias_map[cache].promote()\n                # Join type of 'alias' changed, so re-examine all aliases that\n                # refer to this one.\n                session.extend(\n                    mode\n                    for mode in self.alias_map\n                    if self.alias_map[mode].parent_alias == cache\n                    and mode not in session\n                )\n\n    def removeBuffer(self, balance):\n        \"\"\"\n        Change join type from LOUTER to INNER for all joins in aliases.\n\n        Similarly to promote_joins(), this method must ensure no join chains\n        containing first an outer, then an inner join are generated. If we\n        are demoting b->c join in chain a LOUTER b LOUTER c then we must\n        demote a->b automatically, or otherwise the demotion of b->c doesn't\n        actually change anything in the query results. .\n        \"\"\"\n        balance = list(balance)\n        while balance:\n            event = balance.pop(0)\n            if self.alias_map[event].join_type == LOUTER:\n                self.alias_map[event] = self.alias_map[event].demote()\n                finalMessage = self.alias_map[event].parent_alias\n                if self.alias_map[finalMessage].join_type == INNER:\n                    balance.append(finalMessage)\n\n    def validateConfig(self, nextValue):\n        \"\"\"\n        Reset reference counts for aliases so that they match the value passed\n        in `to_counts`.\n        \"\"\"\n        for event, finalAddress in self.alias_refcount.copy().items():\n            recentWindow = finalAddress - nextValue.get(event, 0)\n            self.loadBalance(event, recentWindow)\n\n    def refreshAccount(self, localOrder):\n        \"\"\"\n        Change the aliases in change_map (which maps old-alias -> new-alias),\n        relabelling any references to them in select columns and the where\n        clause.\n        \"\"\"\n        if not localOrder:\n            return self\n        # If keys and values of change_map were to intersect, an alias might be\n        # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending\n        # on their order in change_map.\n        assert set(localOrder).isdisjoint(localOrder.values())\n\n        # 1. Update references in \"select\" (normal columns plus aliases),\n        # \"group by\" and \"where\".\n        self.where.relabel_aliases(localOrder)\n        if isinstance(self.group_by, tuple):\n            self.group_by = tuple(\n                [map.relabeled_clone(localOrder) for map in self.group_by]\n            )\n        self.select = tuple([map.relabeled_clone(localOrder) for map in self.select])\n        self.annotations = self.annotations and {\n            age: map.relabeled_clone(localOrder)\n            for age, map in self.annotations.items()\n        }\n\n        # 2. Rename the alias in the internal table/alias datastructures.\n        for finalNode, nextToken in localOrder.items():\n            if finalNode not in self.alias_map:\n                continue\n            backupNode = self.alias_map[finalNode].relabeled_clone(localOrder)\n            self.alias_map[nextToken] = backupNode\n            self.alias_refcount[nextToken] = self.alias_refcount[finalNode]\n            del self.alias_refcount[finalNode]\n            del self.alias_map[finalNode]\n\n            secureAccount = self.table_map[backupNode.table_name]\n            for flag, order in enumerate(secureAccount):\n                if order == finalNode:\n                    secureAccount[flag] = nextToken\n                    break\n\n        # 3. Rename the direct external aliases and the ones of combined\n        # queries (union, intersection, difference).\n        self.external_aliases = {\n            # Table is aliased or it's being changed and thus is aliased.\n            localOrder.get(order, order): (channel or order in localOrder)\n            for order, channel in self.external_aliases.items()\n        }\n        for defaultMessage in self.combined_queries:\n            currentAddress = {\n                order: channel\n                for order, channel in localOrder.items()\n                if order in defaultMessage.external_aliases\n            }\n            defaultMessage.change_aliases(currentAddress)\n\n    def validateKey(self, localResult, context=None):\n        \"\"\"\n        Change the alias prefix to the next letter in the alphabet in a way\n        that the other query's aliases and this query's aliases will not\n        conflict. Even tables that previously had no alias will get an alias\n        after this call. To prevent changing aliases use the exclude parameter.\n        \"\"\"\n\n        def prefix_gen():\n            \"\"\"\n            Generate a sequence of characters in alphabetical order:\n                -> 'A', 'B', 'C', ...\n\n            When the alphabet is finished, the sequence will continue with the\n            Cartesian product:\n                -> 'AA', 'AB', 'AC', ...\n            \"\"\"\n            response = ascii_uppercase\n            record = chr(ord(self.alias_prefix) + 1)\n            yield record\n            for map in count(1):\n                age = response[response.index(record) :] if record else response\n                for key in product(age, repeat=map):\n                    yield \"\".join(key)\n                record = None\n\n        if self.alias_prefix != localResult.alias_prefix:\n            # No clashes between self and outer query should be possible.\n            return\n\n        # Explicitly avoid infinite loop. The constant divider is based on how\n        # much depth recursive subquery references add to the stack. This value\n        # might need to be adjusted when adding or removing function calls from\n        # the code path in charge of performing these operations.\n        currentSession = sys.getrecursionlimit() // 16\n        for key, target in enumerate(prefix_gen()):\n            if target not in self.subq_aliases:\n                self.alias_prefix = target\n                break\n            if key > currentSession:\n                raise RecursionError(\n                    \"Maximum recursion depth exceeded: too many subqueries.\"\n                )\n        self.subq_aliases = self.subq_aliases.union([self.alias_prefix])\n        localResult.subq_aliases = localResult.subq_aliases.union(self.subq_aliases)\n        if context is None:\n            context = {}\n        self.refreshAccount(\n            {\n                index: \"%s%d\" % (self.alias_prefix, key)\n                for key, index in enumerate(self.alias_map)\n                if index not in context\n            }\n        )\n\n    def validateRecord(self):\n        \"\"\"\n        Return the first alias for this query, after increasing its reference\n        count.\n        \"\"\"\n        if self.alias_map:\n            event = self.parseState\n            self.saveEvent(event)\n        elif self.model:\n            event = self.copy(self.base_table_class(self.saveData().db_table, None))\n        else:\n            event = None\n        return event\n\n    def validateStatus(self):\n        \"\"\"\n        Return the number of tables in this query with a non-zero reference\n        count. After execution, the reference counts are zeroed, so tables\n        added in compiler will not be seen by this method.\n        \"\"\"\n        return len([1 for limit in self.alias_refcount.values() if limit])\n\n    def copy(self, mode, group=None):\n        \"\"\"\n        Return an alias for the 'join', either reusing an existing alias for\n        that join or creating a new one. 'join' is either a base_table_class or\n        join_class.\n\n        The 'reuse' parameter can be either None which means all joins are\n        reusable, or it can be a set containing the aliases that can be reused.\n\n        A join is always created as LOUTER if the lhs alias is LOUTER to make\n        sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new\n        joins are created as LOUTER if the join is nullable.\n        \"\"\"\n        secureAddress = [\n            map\n            for map, age in self.alias_map.items()\n            if (group is None or map in group) and age == mode\n        ]\n        if secureAddress:\n            if mode.table_alias in secureAddress:\n                cachedCache = mode.table_alias\n            else:\n                # Reuse the most recent alias of the joined table\n                # (a many-to-many relation may be joined multiple times).\n                cachedCache = secureAddress[-1]\n            self.saveEvent(cachedCache)\n            return cachedCache\n\n        # No reuse is possible, so we need a new alias.\n        batch, key = self.sendBalance(\n            mode.table_name, create=True, filtered_relation=mode.filtered_relation\n        )\n        if mode.join_type:\n            if self.alias_map[mode.parent_alias].join_type == LOUTER or mode.nullable:\n                localPath = LOUTER\n            else:\n                localPath = INNER\n            mode.join_type = localPath\n        mode.table_alias = batch\n        self.alias_map[batch] = mode\n        if primaryAccount := mode.filtered_relation:\n            cachedAccount = group\n            if cachedAccount is not None:\n                cachedAccount = set(group) | {batch}\n            nextScore = len(self.alias_map)\n            mode.filtered_relation = primaryAccount.resolve_expression(\n                self, reuse=cachedAccount\n            )\n            # Some joins were during expression resolving, they must be present\n            # before the one we just added.\n            if nextScore < len(self.alias_map):\n                self.alias_map[batch] = self.alias_map.pop(batch)\n        return batch\n\n    def refreshBalance(self, date, value, cache, node):\n        \"\"\"\n        Make sure the given 'model' is joined in the query. If 'model' isn't\n        a parent of 'opts' or if it is None this method is a no-op.\n\n        The 'alias' is the root alias for starting the join, 'seen' is a dict\n        of model -> alias of existing joins. It must also contain a mapping\n        of None -> some alias. This will be returned in the no-op case.\n        \"\"\"\n        if value in node:\n            return node[value]\n        state = date.get_base_chain(value)\n        if not state:\n            return cache\n        nextToken = date\n        for reference in state:\n            if reference in node:\n                nextToken = reference._meta\n                cache = node[reference]\n                continue\n            # Proxy model have elements in base chain\n            # with no parents, assign the new options\n            # object and skip to the next base in that\n            # case\n            if not nextToken.parents[reference]:\n                nextToken = reference._meta\n                continue\n            finalValue = nextToken.get_ancestor_link(reference)\n            operation = self.updateCache([finalValue.name], nextToken, cache)\n            nextToken = reference._meta\n            cache = node[reference] = operation.joins[-1]\n        return cache or node[None]\n\n    def sendAddress(self, state):\n        # RemovedInDjango70Warning: When the deprecation ends, remove.\n        if \"%\" in state:\n            warnings.warn(\n                \"Using percent signs in a column alias is deprecated.\",\n                category=RemovedInDjango70Warning,\n                skip_file_prefixes=django_file_prefixes(),\n            )\n        if FORBIDDEN_ALIAS_PATTERN.search(state):\n            raise ValueError(\n                \"Column aliases cannot contain whitespace characters, hashes, \"\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # \"control characters, quotation marks, semicolons, percent \"\n                # \"signs, or SQL comments.\"\n                \"control characters, quotation marks, semicolons, or SQL comments.\"\n            )\n\n    def validateBuffer(self, activeItem, order, option=True):\n        \"\"\"Add a single annotation expression to the Query.\"\"\"\n        self.sendAddress(order)\n        activeItem = activeItem.resolve_expression(self, allow_joins=True, reuse=None)\n        if option:\n            self.refreshBuffer([order])\n        else:\n            self.validateToken(set(self.refreshRecord).difference({order}))\n        self.annotations[order] = activeItem\n        if option and self.selected:\n            self.selected[order] = order\n\n    @property\n    def validateWindow(self):\n        if not self.validateBatch or not self.select:\n            return len(self.model._meta.pk_fields)\n        return len(self.select) + sum(\n            len(flag.targets) - 1 for flag in self.select if isinstance(flag, ColPairs)\n        )\n\n    def refreshSession(self, state, *date, **client):\n        group = self.fetch()\n        # Subqueries need to use a different set of aliases than the outer\n        # query.\n        group.bump_prefix(state)\n        group.subquery = True\n        group.where.resolve_expression(state, *date, **client)\n        # Resolve combined queries.\n        if group.combinator:\n            group.combined_queries = tuple(\n                [\n                    pendingRequest.resolve_expression(state, *date, **client)\n                    for pendingRequest in group.combined_queries\n                ]\n            )\n        for map, total in group.annotations.items():\n            category = total.resolve_expression(state, *date, **client)\n            if hasattr(category, \"external_aliases\"):\n                category.external_aliases.update(group.external_aliases)\n            group.annotations[map] = category\n        # Outer query's aliases are considered external.\n        for entry, batch in state.alias_map.items():\n            group.external_aliases[entry] = (\n                isinstance(batch, Join)\n                and batch.join_field.related_model._meta.db_table != entry\n            ) or (\n                isinstance(batch, BaseTable) and batch.table_name != batch.table_alias\n            )\n        return group\n\n    def refreshAddress(self):\n        token = chain(self.annotations.values(), self.where.children)\n        return [\n            key\n            for key in self.saveCount(token, include_external=True)\n            if key.alias in self.external_aliases\n        ]\n\n    def validateClient(self, profile=None):\n        # If wrapper is referenced by an alias for an explicit GROUP BY through\n        # values() a reference to this expression and not the self must be\n        # returned to ensure external column references are not grouped against\n        # as well.\n        backupMessage = self.refreshAddress()\n        if any(map.possibly_multivalued for map in backupMessage):\n            return [profile or self]\n        return backupMessage\n\n    def verify(self, nextUser, pendingKey):\n        # Some backends (e.g. Oracle) raise an error when a subquery contains\n        # unnecessary ORDER BY clause.\n        if (\n            self.subquery\n            and not pendingKey.features.ignores_unnecessary_order_by_in_subqueries\n        ):\n            self.refreshStatus(force=False)\n            for state in self.combined_queries:\n                state.clear_ordering(force=False)\n        age, record = self.createStatus(connection=pendingKey).as_sql()\n        if self.subquery:\n            age = \"(%s)\" % age\n        return age, record\n\n    def refreshMessage(self, token, recentKey, secureCache, operation=False):\n        if hasattr(token, \"resolve_expression\"):\n            token = token.resolve_expression(\n                self,\n                reuse=recentKey,\n                allow_joins=secureCache,\n                summarize=operation,\n            )\n        elif isinstance(token, (list, tuple)):\n            # The items of the iterable may be expressions and therefore need\n            # to be resolved independently.\n            config = (\n                self.refreshMessage(localUser, recentKey, secureCache, operation)\n                for localUser in token\n            )\n            total = type(token)\n            if hasattr(total, \"_make\"):  # namedtuple\n                return total(*config)\n            return total(config)\n        return token\n\n    def validateResult(self, client, operation=False):\n        \"\"\"\n        Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').\n        \"\"\"\n        defaultAddress = client.split(LOOKUP_SEP)\n        if self.annotations:\n            nextWindow, primaryBalance = refs_expression(\n                defaultAddress, self.annotations\n            )\n            if nextWindow:\n                finalCache = self.annotations[nextWindow]\n                if operation:\n                    finalCache = Ref(nextWindow, finalCache)\n                return primaryBalance, (), finalCache\n        age, count, age, remoteClient = self.refreshClient(defaultAddress, self.saveData())\n        backupIndex = defaultAddress[0 : len(defaultAddress) - len(remoteClient)]\n        if len(remoteClient) > 1 and not backupIndex:\n            raise FieldError(\n                'Invalid lookup \"%s\" for model %s\".'\n                % (client, self.saveData().model.__name__)\n            )\n        return remoteClient, backupIndex, False\n\n    def refreshRequest(self, event, flag, total):\n        \"\"\"\n        Check whether the object passed while querying is of the correct type.\n        If not, raise a ValueError specifying the wrong object.\n        \"\"\"\n        if hasattr(event, \"_meta\"):\n            if not check_rel_lookup_compatibility(event._meta.model, flag, total):\n                raise ValueError(\n                    'Cannot query \"%s\": Must be \"%s\" instance.'\n                    % (event, flag.object_name)\n                )\n\n    def validateCache(self, score, total, mode):\n        \"\"\"Check the type of object passed to query relations.\"\"\"\n        if score.is_relation:\n            # Check that the field and the queryset use the same model in a\n            # query like .filter(author=Author.objects.all()). For example, the\n            # opts would be Author's (from the author field) and value.model\n            # would be Author.objects.all() queryset's .model (Author also).\n            # The field is the related field on the lhs side.\n            if (\n                isinstance(total, Query)\n                and not total.has_select_fields\n                and not check_rel_lookup_compatibility(total.model, mode, score)\n            ):\n                raise ValueError(\n                    'Cannot use QuerySet for \"%s\": Use a QuerySet for \"%s\".'\n                    % (total.model._meta.object_name, mode.object_name)\n                )\n            elif hasattr(total, \"_meta\"):\n                self.refreshRequest(total, mode, score)\n            elif hasattr(total, \"__iter__\"):\n                for key in total:\n                    self.refreshRequest(key, mode, score)\n\n    def createAddress(self, connection):\n        \"\"\"Raise an error if expression cannot be used in a WHERE clause.\"\"\"\n        if hasattr(connection, \"resolve_expression\") and not getattr(\n            connection, \"filterable\", True\n        ):\n            raise NotSupportedError(\n                connection.__class__.__name__ + \" is disallowed in the filter \"\n                \"clause.\"\n            )\n        if hasattr(connection, \"get_source_expressions\"):\n            for node in connection.get_source_expressions():\n                self.createAddress(node)\n\n    def refreshToken(self, version, key, age):\n        \"\"\"\n        Try to extract transforms and lookup from given lhs.\n\n        The lhs value is something that works like SQLExpression.\n        The rhs value is what the lookup is going to compare against.\n        The lookups is a list of names to extract using get_lookup()\n        and get_transform().\n        \"\"\"\n        # __exact is the default lookup if one isn't given.\n        *recentPath, finalResult = version or [\"exact\"]\n        for date in recentPath:\n            key = self.refreshWindow(key, date, version)\n        # First try get_lookup() so that the lookup takes precedence if the lhs\n        # supports both transform and lookup for the name.\n        secureResult = key.get_lookup(finalResult)\n        if not secureResult:\n            # A lookup wasn't found. Try to interpret the name as a transform\n            # and do an Exact lookup against it.\n            key = self.refreshWindow(key, finalResult)\n            finalResult = \"exact\"\n            secureResult = key.get_lookup(finalResult)\n            if not secureResult:\n                return\n\n        config = secureResult(key, age)\n        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all\n        # uses of None as a query value unless the lookup supports it.\n        if config.rhs is None and not config.can_use_none_as_rhs:\n            if finalResult not in (\"exact\", \"iexact\"):\n                raise ValueError(\"Cannot use None as a query value\")\n            return key.get_lookup(\"isnull\")(key, True)\n\n        # For Oracle '' is equivalent to null. The check must be done at this\n        # stage because join promotion can't be done in the compiler. Using\n        # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.\n        # A similar thing is done in is_nullable(), too.\n        if (\n            finalResult in (\"exact\", \"iexact\")\n            and config.rhs == \"\"\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        ):\n            return key.get_lookup(\"isnull\")(key, True)\n\n        return config\n\n    def refreshWindow(self, age, size, address=None):\n        \"\"\"\n        Helper method for build_lookup(). Try to fetch and initialize\n        a transform for name parameter from lhs.\n        \"\"\"\n        pendingAddress = age.get_transform(size)\n        if pendingAddress:\n            return pendingAddress(age)\n        else:\n            primaryOrder = age.output_field.__class__\n            currentAccount = difflib.get_close_matches(\n                size, age.output_field.get_lookups()\n            )\n            if currentAccount:\n                permission = \", perhaps you meant %s?\" % \" or \".join(currentAccount)\n            else:\n                permission = \".\"\n            if address is not None:\n                cachedPath = address.index(size)\n                pendingSession = LOOKUP_SEP.join(address[cachedPath:])\n            else:\n                pendingSession = size\n            raise FieldError(\n                \"Unsupported lookup '%s' for %s or join on the field not \"\n                \"permitted%s\" % (pendingSession, primaryOrder.__name__, permission)\n            )\n\n    def createBuffer(\n        self,\n        currentData,\n        pendingSession=False,\n        pendingMessage=False,\n        cachedKey=None,\n        secureIndex=True,\n        nextWindow=True,\n        primaryBalance=True,\n        finalMode=False,\n        pendingAccount=True,\n    ):\n        \"\"\"\n        Build a WhereNode for a single filter clause but don't add it\n        to this Query. Query.add_q() will then add this filter to the where\n        Node.\n\n        The 'branch_negated' tells us if the current branch contains any\n        negations. This will be used to determine if subqueries are needed.\n\n        The 'current_negated' is used to determine if the current filter is\n        negated or not and this will be used to determine if IS NULL filtering\n        is needed.\n\n        The difference between current_negated and branch_negated is that\n        branch_negated is set on first negation, but current_negated is\n        flipped for each negation.\n\n        Note that add_filter will not do any negating itself, that is done\n        upper in the code by add_q().\n\n        The 'can_reuse' is a set of reusable joins for multijoins.\n\n        The method will create a filter clause that can be added to the current\n        query. However, if the filter isn't added to the query then the caller\n        is responsible for unreffing the joins used.\n        \"\"\"\n        if isinstance(currentData, dict):\n            raise FieldError(\"Cannot parse keyword query as dict\")\n        if isinstance(currentData, Q):\n            return self.search(\n                currentData,\n                branch_negated=pendingSession,\n                current_negated=pendingMessage,\n                used_aliases=cachedKey,\n                allow_joins=secureIndex,\n                split_subq=nextWindow,\n                check_filterable=primaryBalance,\n                summarize=finalMode,\n                update_join_types=pendingAccount,\n            )\n        if hasattr(currentData, \"resolve_expression\"):\n            if not getattr(currentData, \"conditional\", False):\n                raise TypeError(\"Cannot filter against a non-conditional expression.\")\n            nextCount = currentData.resolve_expression(\n                self, allow_joins=secureIndex, reuse=cachedKey, summarize=finalMode\n            )\n            if not isinstance(nextCount, Lookup):\n                nextCount = self.refreshToken([\"exact\"], nextCount, True)\n            return WhereNode([nextCount], connector=AND), []\n        map, entry = currentData\n        if not map:\n            raise FieldError(\"Cannot parse keyword query %r\" % map)\n        channel, cache, defaultMessage = self.validateResult(map, finalMode)\n\n        if primaryBalance:\n            self.createAddress(defaultMessage)\n\n        if not secureIndex and len(cache) > 1:\n            raise FieldError(\"Joined field references are not permitted in this query\")\n\n        nextIndex = self.alias_refcount.copy()\n        entry = self.refreshMessage(entry, cachedKey, secureIndex, finalMode)\n        localState = {\n            key for key, age in self.alias_refcount.items() if age > nextIndex.get(key, 0)\n        }\n\n        if primaryBalance:\n            self.createAddress(entry)\n\n        if defaultMessage:\n            nextCount = self.refreshToken(channel, defaultMessage, entry)\n            return WhereNode([nextCount], connector=AND), []\n\n        flag = self.saveData()\n        price = self.validateRecord()\n        backupNode = not pendingSession or not nextWindow\n\n        try:\n            nextToken = self.updateCache(\n                cache,\n                flag,\n                price,\n                can_reuse=cachedKey,\n                allow_many=backupNode,\n            )\n\n            # Prevent iterator from being consumed by check_related_objects()\n            if isinstance(entry, Iterator):\n                entry = list(entry)\n            self.validateCache(nextToken.final_field, entry, nextToken.opts)\n\n            # split_exclude() needs to know which joins were generated for the\n            # lookup parts\n            self._lookup_joins = nextToken.joins\n        except MultiJoin as e:\n            return self.createSession(currentData, cachedKey, e.names_with_path)\n\n        # Update used_joins before trimming since they are reused to determine\n        # which joins could be later promoted to INNER.\n        localState.update(nextToken.joins)\n        context, price, nextEvent = self.buildValue(\n            nextToken.targets, nextToken.joins, nextToken.path\n        )\n        if cachedKey is not None:\n            cachedKey.update(nextEvent)\n\n        if nextToken.final_field.is_relation:\n            if len(context) == 1:\n                path = self.findPath(context[0], nextToken.final_field, price)\n            else:\n                path = ColPairs(price, context, nextToken.targets, nextToken.final_field)\n        else:\n            path = self.findPath(context[0], nextToken.final_field, price)\n\n        nextCount = self.refreshToken(channel, path, entry)\n        activeState = nextCount.lookup_name\n        config = WhereNode([nextCount], connector=AND)\n\n        primaryStatus = (\n            activeState == \"isnull\" and nextCount.rhs is True and not pendingMessage\n        )\n        if (\n            pendingMessage\n            and (activeState != \"isnull\" or nextCount.rhs is False)\n            and nextCount.rhs is not None\n        ):\n            primaryStatus = True\n            if activeState != \"isnull\":\n                # The condition added here will be SQL like this:\n                # NOT (col IS NOT NULL), where the first NOT is added in\n                # upper layers of code. The reason for addition is that if col\n                # is null, then col != someval will result in SQL \"unknown\"\n                # which isn't the same as in Python. The Python None handling\n                # is wanted, and it can be gotten by\n                # (col IS NULL OR col != someval)\n                #   <=>\n                # NOT (col IS NOT NULL AND col = someval).\n                if (\n                    self.findAddress(context[0])\n                    or self.alias_map[nextEvent[-1]].join_type == LOUTER\n                ):\n                    backupResult = context[0].get_lookup(\"isnull\")\n                    path = self.findPath(context[0], nextToken.targets[0], price)\n                    # Use OR + IS NULL when RHS `in` values include None.\n                    if (\n                        activeState == \"in\"\n                        # Check containers (not strings or bytes).\n                        and isinstance(nextCount.rhs, Iterable)\n                        and not isinstance(nextCount.rhs, (str, bytes))\n                        and any(age is None for age in nextCount.rhs)\n                    ):\n                        config.add(backupResult(path, True), OR)\n                    else:\n                        config.add(backupResult(path, False), AND)\n                # If someval is a nullable column, someval IS NOT NULL is\n                # added.\n                if isinstance(entry, Col) and self.findAddress(entry.target):\n                    backupResult = entry.target.get_lookup(\"isnull\")\n                    config.add(backupResult(entry, False), AND)\n        return config, localState if not primaryStatus else ()\n\n    def createItem(self, backupItem, pendingKey):\n        self.write(Q((backupItem, pendingKey)))\n\n    def write(self, discount, nextBatch=False):\n        \"\"\"\n        A preprocessor for the internal _add_q(). Responsible for doing final\n        join promotion.\n        \"\"\"\n        # For join promotion this case is doing an AND for the added q_object\n        # and existing conditions. So, any existing inner join forces the join\n        # type to remain inner. Existing outer joins can however be demoted.\n        # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if\n        # rel_a doesn't produce any rows, then the whole condition must fail.\n        # So, demotion is OK.\n        defaultAccount = {\n            age for age in self.alias_map if self.alias_map[age].join_type == INNER\n        }\n        if nextBatch:\n            nextIndex = set(self.alias_map)\n        else:\n            nextIndex = self.used_aliases\n        option, key = self.search(discount, nextIndex)\n        if option:\n            self.where.add(option, AND)\n        self.removeBuffer(defaultAccount)\n\n    def removeState(self, primaryNode):\n        return self.createBuffer(primaryNode, allow_joins=False)[0]\n\n    def updateEvent(self):\n        self.where = WhereNode()\n\n    def search(\n        self,\n        nextItem,\n        backupWindow,\n        defaultMessage=False,\n        defaultAccount=False,\n        secureBatch=True,\n        localToken=True,\n        primaryMessage=True,\n        nextEvent=False,\n        pendingMessage=True,\n    ):\n        \"\"\"Add a Q-object to the current filter.\"\"\"\n        nextBatch = nextItem.connector\n        defaultAccount ^= nextItem.negated\n        defaultMessage = defaultMessage or nextItem.negated\n        currentConfig = WhereNode(connector=nextBatch, negated=nextItem.negated)\n        backupBuffer = JoinPromoter(\n            nextItem.connector, len(nextItem.children), defaultAccount\n        )\n        for entry in nextItem.children:\n            defaultValue, remoteClient = self.createBuffer(\n                entry,\n                can_reuse=backupWindow,\n                branch_negated=defaultMessage,\n                current_negated=defaultAccount,\n                allow_joins=secureBatch,\n                split_subq=localToken,\n                check_filterable=primaryMessage,\n                summarize=nextEvent,\n                update_join_types=pendingMessage,\n            )\n            backupBuffer.add_votes(remoteClient)\n            if defaultValue:\n                currentConfig.add(defaultValue, nextBatch)\n        if pendingMessage:\n            remoteClient = backupBuffer.update_join_types(self)\n        else:\n            remoteClient = []\n        return currentConfig, remoteClient\n\n    def validateValue(self, primaryMessage, state):\n        if \".\" in state:\n            raise ValueError(\n                \"FilteredRelation doesn't support aliases with periods \"\n                \"(got %r).\" % state\n            )\n        self.sendAddress(state)\n        primaryMessage.alias = state\n        pendingSession, primaryRequest, key = self.validateResult(\n            primaryMessage.relation_name\n        )\n        if pendingSession:\n            raise ValueError(\n                \"FilteredRelation's relation_name cannot contain lookups \"\n                \"(got %r).\" % primaryMessage.relation_name\n            )\n        for config in get_children_from_q(primaryMessage.condition):\n            currentToken, defaultRequest, key = self.validateResult(config)\n            batch = 2 if not currentToken else 1\n            primaryAccount = defaultRequest[:-batch]\n            for age, pendingBalance in enumerate(primaryAccount):\n                if len(primaryRequest) > age:\n                    if primaryRequest[age] != pendingBalance:\n                        raise ValueError(\n                            \"FilteredRelation's condition doesn't support \"\n                            \"relations outside the %r (got %r).\"\n                            % (primaryMessage.relation_name, config)\n                        )\n            if len(defaultRequest) > len(primaryRequest) + 1:\n                raise ValueError(\n                    \"FilteredRelation's condition doesn't support nested \"\n                    \"relations deeper than the relation_name (got %r for \"\n                    \"%r).\" % (config, primaryMessage.relation_name)\n                )\n        primaryMessage = primaryMessage.clone()\n        primaryMessage.condition = rename_prefix_from_q(\n            primaryMessage.relation_name,\n            state,\n            primaryMessage.condition,\n        )\n        self._filtered_relations[primaryMessage.alias] = primaryMessage\n\n    def refreshClient(self, cache, data, nextBuffer=True, pendingSession=False):\n        \"\"\"\n        Walk the list of names and turns them into PathInfo tuples. A single\n        name in 'names' can generate multiple PathInfos (m2m, for example).\n\n        'names' is the path of names to travel, 'opts' is the model Options we\n        start the name resolving from, 'allow_many' is as for setup_joins().\n        If fail_on_missing is set to True, then a name that can't be resolved\n        will generate a FieldError.\n\n        Return a list of PathInfo tuples. In addition return the final field\n        (the last used join field) and target (which is a field guaranteed to\n        contain the same value as the final field). Finally, return those names\n        that weren't found (which are likely transforms and the final lookup).\n        \"\"\"\n        mode, primaryBalance = [], []\n        for key, item in enumerate(cache):\n            defaultBalance = (item, [])\n            if item == \"pk\" and data is not None:\n                item = data.pk.name\n\n            limit = None\n            currentMessage = None\n            try:\n                if data is None:\n                    raise FieldDoesNotExist\n                limit = data.get_field(item)\n            except FieldDoesNotExist:\n                if item in self.annotations:\n                    limit = self.annotations[item].output_field\n                elif item in self._filtered_relations and key == 0:\n                    currentMessage = self._filtered_relations[item]\n                    if LOOKUP_SEP in currentMessage.relation_name:\n                        group = currentMessage.relation_name.split(LOOKUP_SEP)\n                        defaultMessage, limit, map, map = self.refreshClient(\n                            group,\n                            data,\n                            nextBuffer,\n                            pendingSession,\n                        )\n                        mode.extend(defaultMessage[:-1])\n                    else:\n                        limit = data.get_field(currentMessage.relation_name)\n            if limit is not None:\n                # Fields that contain one-to-many relations with a generic\n                # model (like a GenericForeignKey) cannot generate reverse\n                # relations and therefore cannot be used for reverse querying.\n                if limit.is_relation and not limit.related_model:\n                    raise FieldError(\n                        \"Field %r does not generate an automatic reverse \"\n                        \"relation and therefore cannot be used for reverse \"\n                        \"querying. If it is a GenericForeignKey, consider \"\n                        \"adding a GenericRelation.\" % item\n                    )\n                try:\n                    total = limit.model._meta.concrete_model\n                except AttributeError:\n                    # QuerySet.annotate() may introduce fields that aren't\n                    # attached to a model.\n                    total = None\n            else:\n                # We didn't find the current field, so move position back\n                # one step.\n                key -= 1\n                if key == -1 or pendingSession:\n                    nextCache = sorted(\n                        [\n                            *get_field_names_from_opts(data),\n                            *self.annotations,\n                            *self._filtered_relations,\n                        ]\n                    )\n                    raise FieldError(\n                        \"Cannot resolve keyword '%s' into field. \"\n                        \"Choices are: %s\" % (item, \", \".join(nextCache))\n                    )\n                break\n            # Check if we need any joins for concrete inheritance cases (the\n            # field lives in parent, but we are currently in one of its\n            # children)\n            if data is not None and total is not data.model:\n                primaryAccount = data.get_path_to_parent(total)\n                if primaryAccount:\n                    mode.extend(primaryAccount)\n                    defaultBalance[1].extend(primaryAccount)\n                    data = primaryAccount[-1].to_opts\n            if hasattr(limit, \"path_infos\"):\n                if currentMessage:\n                    secureKey = limit.get_path_info(currentMessage)\n                else:\n                    secureKey = limit.path_infos\n                if not nextBuffer:\n                    for sharedKey, age in enumerate(secureKey):\n                        if age.m2m:\n                            defaultBalance[1].extend(secureKey[0 : sharedKey + 1])\n                            primaryBalance.append(defaultBalance)\n                            raise MultiJoin(key + 1, primaryBalance)\n                date = secureKey[-1]\n                mode.extend(secureKey)\n                recentCount = date.join_field\n                data = date.to_opts\n                invoice = date.target_fields\n                defaultBalance[1].extend(secureKey)\n                primaryBalance.append(defaultBalance)\n            else:\n                # Local non-relational field.\n                recentCount = limit\n                invoice = (limit,)\n                if pendingSession and key + 1 != len(cache):\n                    raise FieldError(\n                        \"Cannot resolve keyword %r into field. Join on '%s'\"\n                        \" not permitted.\" % (cache[key + 1], item)\n                    )\n                break\n        return mode, recentCount, invoice, cache[key + 1 :]\n\n    def updateCache(\n        self,\n        value,\n        size,\n        cache,\n        nextBatch=None,\n        activePath=True,\n    ):\n        \"\"\"\n        Compute the necessary table joins for the passage through the fields\n        given in 'names'. 'opts' is the Options class for the current model\n        (which gives the table we are starting from), 'alias' is the alias for\n        the table to start the joining from.\n\n        The 'can_reuse' defines the reverse foreign key joins we can reuse. It\n        can be None in which case all joins are reusable or a set of aliases\n        that can be reused. Note that non-reverse foreign keys are always\n        reusable when using setup_joins().\n\n        If 'allow_many' is False, then any reverse foreign key seen will\n        generate a MultiJoin exception.\n\n        Return the final field involved in the joins, the target field (used\n        for any 'where' constraint), the final 'opts' value, the joins, the\n        field path traveled to generate the joins, and a transform function\n        that takes a field and alias and is equivalent to\n        `field.get_col(alias)` in the simple case but wraps field transforms if\n        they were included in names.\n\n        The target field is the field containing the concrete value. Final\n        field can be something different, for example foreign key pointing to\n        that value. Final field is needed for example in some value\n        conversions (convert 'obj' in fk__id=obj to pk val using the foreign\n        key field for example).\n        \"\"\"\n        index = [cache]\n        # The transform can't be applied yet, as joins must be trimmed later.\n        # To avoid making every caller of this method look up transforms\n        # directly, compute transforms here and create a partial that converts\n        # fields to the appropriate wrapped version.\n\n        def final_transformer(state, order):\n            if not self.alias_cols:\n                order = None\n            return state.get_col(order)\n\n        # Try resolving all the names as fields first. If there's an error,\n        # treat trailing names as lookups until a field can be resolved.\n        defaultAccount = None\n        for token in range(len(value), 0, -1):\n            try:\n                flag, remoteState, profile, data = self.refreshClient(\n                    value[:token],\n                    size,\n                    activePath,\n                    fail_on_missing=True,\n                )\n            except FieldError as exc:\n                if token == 1:\n                    # The first item cannot be a lookup, so it's safe\n                    # to raise the field error here.\n                    raise\n                else:\n                    defaultAccount = exc\n            else:\n                # The transforms are the remaining items that couldn't be\n                # resolved into fields.\n                secureUser = value[token:]\n                break\n        for user in secureUser:\n\n            def transform(event, index, *, date, category):\n                try:\n                    feature = category(event, index)\n                    return self.refreshWindow(feature, date)\n                except FieldError:\n                    # FieldError is raised if the transform doesn't exist.\n                    if isinstance(final_field, Field) and last_field_exception:\n                        raise last_field_exception\n                    else:\n                        raise\n\n            primaryAccount = functools.partial(\n                transform, name=user, previous=primaryAccount\n            )\n            primaryAccount.has_transforms = True\n        # Then, add the path to the query's joins. Note that we can't trim\n        # joins at this stage - we will need the information about join type\n        # of the trimmed joins.\n        for step in flag:\n            if step.filtered_relation:\n                pendingRequest = step.filtered_relation.clone()\n                localConfig = pendingRequest.alias\n            else:\n                pendingRequest = None\n                localConfig = None\n            size = step.to_opts\n            if step.direct:\n                location = self.findAddress(step.join_field)\n            else:\n                location = True\n            securePath = self.join_class(\n                size.db_table,\n                cache,\n                localConfig,\n                INNER,\n                step.join_field,\n                location,\n                filtered_relation=pendingRequest,\n            )\n            entry = nextBatch if step.m2m else None\n            cache = self.copy(securePath, reuse=entry)\n            index.append(cache)\n            if step.filtered_relation and nextBatch is not None:\n                nextBatch.add(cache)\n        return JoinInfo(remoteState, profile, size, index, flag, primaryAccount)\n\n    def buildValue(self, profile, token, node):\n        \"\"\"\n        The 'target' parameter is the final field being joined to, 'joins'\n        is the full list of join aliases. The 'path' contain the PathInfos\n        used to create the joins.\n\n        Return the final target field and table alias and the new active\n        joins.\n\n        Always trim any direct join if the target column is already in the\n        previous table. Can't trim reverse joins as it's unknown if there's\n        anything on the other side of the join.\n        \"\"\"\n        token = token[:]\n        for map, mode in enumerate(reversed(node)):\n            if len(token) == 1 or not mode.direct:\n                break\n            if mode.filtered_relation:\n                break\n            remoteBuffer = {age.column for age in mode.join_field.foreign_related_fields}\n            defaultData = {age.column for age in profile}\n            if not defaultData.issubset(remoteBuffer):\n                break\n            activeRecord = {\n                key[1].column: key[0]\n                for key in mode.join_field.related_fields\n                if key[1].column in defaultData\n            }\n            profile = tuple(activeRecord[age.column] for age in profile)\n            self.loadBalance(token.pop())\n        return profile, token[-1], token\n\n    @classmethod\n    def saveCount(cls, order, primaryAccount=False, activeWindow=True):\n        for data in order:\n            if isinstance(data, Col):\n                yield data\n            elif primaryAccount and callable(\n                getattr(data, \"get_external_cols\", None)\n            ):\n                yield from data.get_external_cols()\n            elif hasattr(data, \"get_source_expressions\"):\n                if not activeWindow and isinstance(data, Ref):\n                    continue\n                yield from cls.saveCount(\n                    data.get_source_expressions(),\n                    include_external=primaryAccount,\n                    resolve_refs=activeWindow,\n                )\n\n    @classmethod\n    def updateAddress(cls, group):\n        yield from (size.alias for size in cls.saveCount(group))\n\n    def readAddress(self, flag, sharedScore=True, count=None, cachedKey=False):\n        finalIndex = self.annotations.get(flag)\n        if finalIndex is not None:\n            if not sharedScore:\n                for cache in self.updateAddress([finalIndex]):\n                    if isinstance(self.alias_map[cache], Join):\n                        raise FieldError(\n                            \"Joined field references are not permitted in this query\"\n                        )\n            if cachedKey:\n                # Summarize currently means we are doing an aggregate() query\n                # which is executed as a wrapped subquery if any of the\n                # aggregate() elements reference an existing annotation. In\n                # that case we need to return a Ref to the subquery's\n                # annotation.\n                if flag not in self.refreshRecord:\n                    raise FieldError(\n                        \"Cannot aggregate over the '%s' alias. Use annotate() \"\n                        \"to promote it.\" % flag\n                    )\n                return Ref(flag, self.refreshRecord[flag])\n            else:\n                return finalIndex\n        else:\n            activeData = flag.split(LOOKUP_SEP)\n            finalIndex = self.annotations.get(activeData[0])\n            if finalIndex is not None:\n                for finalItem in activeData[1:]:\n                    finalIndex = self.refreshWindow(finalIndex, finalItem)\n                return finalIndex\n            finalData = self.updateCache(\n                activeData, self.saveData(), self.validateRecord(), can_reuse=count\n            )\n            profile, recentToken, secureKey = self.buildValue(\n                finalData.targets, finalData.joins, finalData.path\n            )\n            if not sharedScore and len(secureKey) > 1:\n                raise FieldError(\n                    \"Joined field references are not permitted in this query\"\n                )\n            if len(profile) > 1:\n                raise FieldError(\n                    \"Referencing multicolumn fields with F() objects isn't supported\"\n                )\n            # Verify that the last lookup in name is a field or a transform:\n            # transform_function() raises FieldError if not.\n            finalItem = finalData.transform_function(profile[0], recentToken)\n            if count is not None:\n                count.update(secureKey)\n            return finalItem\n\n    def createSession(self, localStatus, localItem, primaryAddress):\n        \"\"\"\n        When doing an exclude against any kind of N-to-many relation, we need\n        to use a subquery. This method constructs the nested query, given the\n        original exclude filter (filter_expr) and the portion up to the first\n        N-to-many relation field.\n\n        For example, if the origin filter is ~Q(child__name='foo'), filter_expr\n        is ('child__name', 'foo') and can_reuse is a set of joins usable for\n        filters in the original query.\n\n        We will turn this into equivalent of:\n            WHERE NOT EXISTS(\n                SELECT 1\n                FROM child\n                WHERE name = 'foo' AND child.parent_id = parent.id\n                LIMIT 1\n            )\n        \"\"\"\n        # Generate the inner query.\n        token = self.__class__(self.model)\n        token._filtered_relations = self._filtered_relations\n        sharedData, secureData = localStatus\n        if isinstance(secureData, OuterRef):\n            secureData = OuterRef(secureData)\n        elif isinstance(secureData, F):\n            secureData = OuterRef(secureData.name)\n        token.add_filter(sharedData, secureData)\n        token.clear_ordering(force=True)\n        # Try to have as simple as possible subquery -> trim leading joins from\n        # the subquery.\n        currentBalance, pendingMessage = token.trim_start(primaryAddress)\n\n        age = token.select[0]\n        primaryBatch = age.target\n        index = age.alias\n        if index in localItem:\n            key = primaryBatch.model._meta.pk\n            # Need to add a restriction so that outer query's filters are in\n            # effect for the subquery, too.\n            token.bump_prefix(self)\n            sharedStatus = primaryBatch.get_lookup(\"exact\")\n            # Note that the query.select[0].alias is different from alias\n            # due to bump_prefix above.\n            status = sharedStatus(key.get_col(token.select[0].alias), key.get_col(index))\n            token.where.add(status, AND)\n            token.external_aliases[index] = True\n        else:\n            sharedStatus = primaryBatch.get_lookup(\"exact\")\n            status = sharedStatus(age, ResolvedOuterRef(currentBalance))\n            token.where.add(status, AND)\n\n        cachedKey, defaultValue = self.createBuffer(Exists(token))\n\n        if pendingMessage:\n            primaryBalance, map = self.createBuffer(\n                (\"%s__isnull\" % currentBalance, True),\n                current_negated=True,\n                branch_negated=True,\n                can_reuse=localItem,\n            )\n            cachedKey.add(primaryBalance, OR)\n            # Note that the end result will be:\n            #   NOT EXISTS (inner_q) OR outercol IS NULL\n            # this might look crazy but due to how NULL works, this seems to be\n            # correct. If the IS NULL check is removed, then if outercol\n            # IS NULL we will not match the row.\n        return cachedKey, defaultValue\n\n    def transform(self):\n        self.where.add(NothingNode(), AND)\n        for entry in self.combined_queries:\n            entry.set_empty()\n\n    def saveItem(self):\n        return any(isinstance(map, NothingNode) for map in self.where.children)\n\n    def checkScore(self, map=None, data=None):\n        \"\"\"\n        Adjust the limits on the rows retrieved. Use low/high to set these,\n        as it makes it more Pythonic to read and write. When the SQL query is\n        created, convert them to the appropriate offset and limit values.\n\n        Apply any limits passed in here to the existing constraints. Add low\n        to the current low value and clamp both to any existing high value.\n        \"\"\"\n        if data is not None:\n            if self.high_mark is not None:\n                self.high_mark = min(self.high_mark, self.low_mark + data)\n            else:\n                self.high_mark = self.low_mark + data\n        if map is not None:\n            if self.high_mark is not None:\n                self.low_mark = min(self.high_mark, self.low_mark + map)\n            else:\n                self.low_mark = self.low_mark + map\n\n        if self.low_mark == self.high_mark:\n            self.transform()\n\n    def checkAccount(self):\n        \"\"\"Clear any existing limits.\"\"\"\n        self.low_mark, self.high_mark = 0, None\n\n    @property\n    def findCache(self):\n        return self.low_mark != 0 or self.high_mark is not None\n\n    def createAccount(self):\n        return self.high_mark is not None and (self.high_mark - self.low_mark) == 1\n\n    def saveConfig(self):\n        \"\"\"\n        Return True if adding filters to this instance is still possible.\n\n        Typically, this means no limits or offsets have been put on the\n        results.\n        \"\"\"\n        return not self.findCache\n\n    def removeMessage(self):\n        \"\"\"Remove all fields from SELECT clause.\"\"\"\n        self.select = ()\n        self.default_cols = False\n        self.select_related = False\n        self.validateCount(())\n        self.validateToken(())\n        self.selected = None\n\n    def removeBalance(self):\n        \"\"\"\n        Clear the list of fields to select (but not extra_select columns).\n        Some queryset types completely replace any existing list of select\n        columns.\n        \"\"\"\n        self.select = ()\n        self.values_select = ()\n        self.selected = None\n\n    def updateMessage(self, age, flag):\n        self.select += (age,)\n        self.values_select += (flag,)\n        self.selected[flag] = len(self.select) - 1\n\n    def parseToken(self, user):\n        self.default_cols = False\n        self.select = tuple(user)\n\n    def updateRequest(self, *sharedCache):\n        \"\"\"\n        Add and resolve the given fields to the query's \"distinct on\" clause.\n        \"\"\"\n        self.distinct_fields = sharedCache\n        self.distinct = True\n\n    def findClient(self, activeCache, localPath=True):\n        \"\"\"\n        Add the given (model) fields to the select set. Add the field names in\n        the order specified.\n        \"\"\"\n        state = self.validateRecord()\n        step = self.saveData()\n\n        try:\n            item = []\n            for date in activeCache:\n                # Join promotion note - we must not remove any rows here, so\n                # if there is no existing joins, use outer join.\n                nextIndex = self.updateCache(\n                    date.split(LOOKUP_SEP), step, state, allow_many=localPath\n                )\n                version, pendingMode, score = self.buildValue(\n                    nextIndex.targets,\n                    nextIndex.joins,\n                    nextIndex.path,\n                )\n                if len(version) > 1:\n                    primaryRequest = [\n                        nextIndex.transform_function(amount, pendingMode)\n                        for amount in version\n                    ]\n                    item.append(\n                        ColPairs(\n                            pendingMode if self.alias_cols else None,\n                            [age.target for age in primaryRequest],\n                            [age.output_field for age in primaryRequest],\n                            nextIndex.final_field,\n                        )\n                    )\n                else:\n                    item.append(nextIndex.transform_function(version[0], pendingMode))\n            if item:\n                self.parseToken(item)\n        except MultiJoin:\n            raise FieldError(\"Invalid field name: '%s'\" % date)\n        except FieldError:\n            if LOOKUP_SEP in date:\n                # For lookups spanning over relationships, show the error\n                # from the model on which the lookup failed.\n                raise\n            else:\n                group = sorted(\n                    [\n                        *get_field_names_from_opts(step),\n                        *self.extra,\n                        *self.refreshRecord,\n                        *self._filtered_relations,\n                    ]\n                )\n                raise FieldError(\n                    \"Cannot resolve keyword %r into field. \"\n                    \"Choices are: %s\" % (date, \", \".join(group))\n                )\n\n    def updateConfig(self, *nextMode):\n        \"\"\"\n        Add items from the 'ordering' sequence to the query's \"order by\"\n        clause. These items are either field names (not column names) --\n        possibly with a direction prefix ('-' or '?') -- or OrderBy\n        expressions.\n\n        If 'ordering' is empty, clear all ordering from the query.\n        \"\"\"\n        client = []\n        for data in nextMode:\n            if isinstance(data, str):\n                if data == \"?\":\n                    continue\n                data = data.removeprefix(\"-\")\n                if data in self.annotations:\n                    continue\n                if self.extra and data in self.extra:\n                    continue\n                # names_to_path() validates the lookup. A descriptive\n                # FieldError will be raise if it's not.\n                self.refreshClient(data.split(LOOKUP_SEP), self.model._meta)\n            elif not hasattr(data, \"resolve_expression\"):\n                client.append(data)\n            if getattr(data, \"contains_aggregate\", False):\n                raise FieldError(\n                    \"Using an aggregate in order_by() without also including \"\n                    \"it in annotate() is not allowed: %s\" % data\n                )\n        if client:\n            raise FieldError(\"Invalid order_by arguments: %s\" % client)\n        if nextMode:\n            self.order_by += nextMode\n        else:\n            self.default_ordering = False\n\n    @property\n    def removeAccount(self):\n        if self.extra_order_by:\n            # Raw SQL from extra(order_by=...) can't be reliably compared\n            # against resolved OrderBy/Col expressions. Treat as not a subset.\n            return False\n        if self.group_by in (None, True):\n            # There is either no aggregation at all (None), or the group by\n            # is generated automatically from model fields (True), in which\n            # case the order by is necessarily a subset of them.\n            return True\n        if not self.order_by:\n            # Although an empty set is always a subset, there's no point in\n            # clearing ordering when there isn't any. Avoid the clone() below.\n            return True\n        # Don't pollute the original query (might disrupt joins).\n        map = self.fetch()\n        finalMessage = set()\n        for nextMode in map.order_by:\n            if hasattr(nextMode, \"resolve_expression\"):\n                finalMessage.add(nextMode.resolve_expression(map))\n            elif nextMode == \"?\":\n                # Random ordering can't be compared against group by.\n                return False\n            else:\n                finalMessage.add(F(nextMode.removeprefix(\"-\")).resolve_expression(map))\n        return finalMessage.issubset(self.group_by)\n\n    def refreshStatus(self, order=False, pendingResult=True):\n        \"\"\"\n        Remove any ordering settings if the current query allows it without\n        side effects, set 'force' to True to clear the ordering regardless.\n        If 'clear_default' is True, there will be no ordering in the resulting\n        query (not even the model's default).\n        \"\"\"\n        if not order and (\n            self.findCache or self.distinct_fields or self.select_for_update\n        ):\n            return\n        self.order_by = ()\n        self.extra_order_by = ()\n        if pendingResult:\n            self.default_ordering = False\n        # Ordering is cleared on combined queries with clear_default=False\n        # when union() and analogues are called, so percolate any possible\n        # clear_default=True.\n        for total in self.combined_queries:\n            total.clear_ordering(force=False, clear_default=pendingResult)\n\n    def buildSession(self, secureAddress=True):\n        \"\"\"\n        Expand the GROUP BY clause required by the query.\n\n        This will usually be the set of all non-aggregate fields in the\n        return data. If the database backend supports grouping by the\n        primary key, and the query would be equivalent, the optimization\n        will be made automatically.\n        \"\"\"\n        if secureAddress and self.values_select:\n            # If grouping by aliases is allowed assign selected value aliases\n            # by moving them to annotations.\n            currentBalance = {}\n            sharedAccount = {}\n            for batch, mode in zip(self.values_select, self.select):\n                if isinstance(mode, Col):\n                    sharedAccount[batch] = mode\n                else:\n                    currentBalance[batch] = mode\n            self.annotations = {**currentBalance, **self.annotations}\n            self.refreshBuffer(currentBalance)\n            self.select = tuple(sharedAccount.values())\n            self.values_select = tuple(sharedAccount)\n            if self.selected is not None:\n                for value, cachedWindow in enumerate(sharedAccount):\n                    self.selected[cachedWindow] = value\n        nextNode = list(self.select)\n        for batch, recentNode in self.refreshRecord.items():\n            if not (defaultStatus := recentNode.get_group_by_cols()):\n                continue\n            if secureAddress and not recentNode.contains_aggregate:\n                nextNode.append(Ref(batch, recentNode))\n            else:\n                nextNode.extend(defaultStatus)\n        self.group_by = tuple(nextNode)\n\n    def validateScore(self, region):\n        \"\"\"\n        Set up the select_related data structure so that we only select\n        certain related models (as opposed to all models, when\n        self.select_related=True).\n        \"\"\"\n        if isinstance(self.select_related, bool):\n            remoteItem = {}\n        else:\n            remoteItem = self.select_related\n        for total in region:\n            key = remoteItem\n            for user in total.split(LOOKUP_SEP):\n                key = key.setdefault(user, {})\n        self.select_related = remoteItem\n\n    def serialize(self, result, remoteRequest, group, status, record, finalKey):\n        \"\"\"\n        Add data to the various extra_* attributes for user-created additions\n        to the query.\n        \"\"\"\n        if result:\n            # We need to pair any placeholder markers in the 'select'\n            # dictionary with their parameters in 'select_params' so that\n            # subsequent updates to the select dictionary also adjust the\n            # parameters appropriately.\n            finalMessage = {}\n            if remoteRequest:\n                secureMode = iter(remoteRequest)\n            else:\n                secureMode = iter([])\n            for flag, state in result.items():\n                self.sendAddress(flag)\n                state = str(state)\n                primaryBatch = []\n                age = state.find(\"%s\")\n                while age != -1:\n                    if age == 0 or state[age - 1] != \"%\":\n                        primaryBatch.append(next(secureMode))\n                    age = state.find(\"%s\", age + 2)\n                finalMessage[flag] = (state, primaryBatch)\n            self.extra.update(finalMessage)\n        if group or status:\n            self.where.add(ExtraWhere(group, status), AND)\n        if record:\n            self.extra_tables += tuple(record)\n        if finalKey:\n            self.extra_order_by = finalKey\n\n    def updateSession(self):\n        \"\"\"Remove any fields from the deferred loading set.\"\"\"\n        self.deferred_loading = (frozenset(), True)\n\n    def createRequest(self, pendingNode):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        exclude from loading from the database when automatic column selection\n        is done. Add the new field names to any existing field names that\n        are deferred (or removed from any existing field names that are marked\n        as the only ones for immediate loading).\n        \"\"\"\n        # Fields on related models are stored in the literal double-underscore\n        # format, so that we can use a set datastructure. We do the foo__bar\n        # splitting and handling when computing the SQL column names (as part\n        # of get_columns()).\n        nextUser, state = self.deferred_loading\n        if state:\n            # Add to existing deferred names.\n            self.deferred_loading = nextUser.union(pendingNode), True\n        else:\n            # Remove names from the set of any existing \"immediate load\" names.\n            if pendingToken := nextUser.difference(pendingNode):\n                self.deferred_loading = pendingToken, False\n            else:\n                self.updateSession()\n                if discount := set(pendingNode).difference(nextUser):\n                    self.deferred_loading = discount, True\n\n    def updateBalance(self, nextMessage):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        retrieve when the SQL is executed (\"immediate loading\" fields). The\n        field names replace any existing immediate loading field names. If\n        there are field names already specified for deferred loading, remove\n        those names from the new field_names before storing the new names\n        for immediate loading. (That is, immediate loading overrides any\n        existing immediate values, but respects existing deferrals.)\n        \"\"\"\n        shipment, cache = self.deferred_loading\n        nextMessage = set(nextMessage)\n        if \"pk\" in nextMessage:\n            nextMessage.remove(\"pk\")\n            nextMessage.add(self.saveData().pk.name)\n\n        if cache:\n            # Remove any existing deferred names from the current set before\n            # setting the new names.\n            self.deferred_loading = nextMessage.difference(shipment), False\n        else:\n            # Replace any existing \"immediate load\" field names.\n            self.deferred_loading = frozenset(nextMessage), False\n\n    def validateToken(self, event):\n        \"\"\"Set the mask of annotations that will be returned by the SELECT.\"\"\"\n        if event is None:\n            self.annotation_select_mask = None\n        else:\n            self.annotation_select_mask = set(event)\n            if self.selected:\n                # Prune the masked annotations.\n                self.selected = {\n                    age: group\n                    for age, group in self.selected.items()\n                    if not isinstance(group, str)\n                    or group in self.annotation_select_mask\n                }\n                # Append the unmasked annotations.\n                for path in event:\n                    self.selected[path] = path\n        self._annotation_select_cache = None\n\n    def refreshBuffer(self, count):\n        if self.annotation_select_mask is not None:\n            self.validateToken(self.annotation_select_mask.union(count))\n\n    def validateCount(self, total):\n        \"\"\"\n        Set the mask of extra select items that will be returned by SELECT.\n        Don't remove them from the Query since they might be used later.\n        \"\"\"\n        if total is None:\n            self.extra_select_mask = None\n        else:\n            self.extra_select_mask = set(total)\n        self._extra_select_cache = None\n\n    @property\n    def validateBatch(self):\n        return self.selected is not None\n\n    def fetchToken(self, result):\n        self.select_related = False\n        self.updateSession()\n        self.removeBalance()\n\n        document = {}\n        if result:\n            for state in result:\n                self.sendAddress(state)\n            remoteToken = []\n            defaultUser = []\n            pendingSession = []\n            if not self.extra and not self.annotations:\n                # Shortcut - if there are no extra or annotations, then\n                # the values() clause must be just field names.\n                remoteToken = list(result)\n                document = dict(zip(result, range(len(result))))\n            else:\n                self.default_cols = False\n                for map in result:\n                    if score := self.checkMessage.get(map):\n                        defaultUser.append(map)\n                        document[map] = RawSQL(*score)\n                    elif map in self.refreshRecord:\n                        pendingSession.append(map)\n                        document[map] = map\n                    elif map in self.annotations:\n                        if self.refreshRecord:\n                            raise FieldError(\n                                f\"Cannot select the '{map}' alias. It was excluded \"\n                                f\"by a previous values() or values_list() call. \"\n                                f\"Include '{map}' in that call to select it.\"\n                            )\n                        else:\n                            raise FieldError(\n                                f\"Cannot select the '{map}' alias. Use annotate() \"\n                                f\"to promote it.\"\n                            )\n                    else:\n                        # Call `names_to_path` to ensure a FieldError including\n                        # annotations about to be masked as valid choices if\n                        # `f` is not resolvable.\n                        if self.refreshRecord:\n                            self.refreshClient(map.split(LOOKUP_SEP), self.model._meta)\n                        document[map] = len(remoteToken)\n                        remoteToken.append(map)\n            self.validateCount(defaultUser)\n            self.validateToken(pendingSession)\n        else:\n            remoteToken = [map.attname for map in self.model._meta.concrete_fields]\n            document = dict.fromkeys(remoteToken, None)\n        # Selected annotations must be known before setting the GROUP BY\n        # clause.\n        if self.group_by is True:\n            self.findClient(\n                (map.attname for map in self.model._meta.concrete_fields), False\n            )\n            # Disable GROUP BY aliases to avoid orphaning references to the\n            # SELECT clause which is about to be cleared.\n            self.buildSession(allow_aliases=False)\n            self.removeBalance()\n        elif self.group_by:\n            # Resolve GROUP BY annotation references if they are not part of\n            # the selected fields anymore.\n            schedule = []\n            for data in self.group_by:\n                if isinstance(data, Ref) and data.refs not in document:\n                    data = self.annotations[data.refs]\n                schedule.append(data)\n            self.group_by = tuple(schedule)\n\n        self.values_select = tuple(remoteToken)\n        self.findClient(remoteToken, True)\n        self.selected = document if result else None\n\n    @property\n    def refreshRecord(self):\n        \"\"\"\n        Return the dictionary of aggregate columns that are not masked and\n        should be used in the SELECT clause. Cache this result for performance.\n        \"\"\"\n        if self._annotation_select_cache is not None:\n            return self._annotation_select_cache\n        elif not self.annotations:\n            return {}\n        elif self.annotation_select_mask is not None:\n            self._annotation_select_cache = {\n                key: map\n                for key, map in self.annotations.items()\n                if key in self.annotation_select_mask\n            }\n            return self._annotation_select_cache\n        else:\n            return self.annotations\n\n    @property\n    def checkMessage(self):\n        if self._extra_select_cache is not None:\n            return self._extra_select_cache\n        if not self.extra:\n            return {}\n        elif self.extra_select_mask is not None:\n            self._extra_select_cache = {\n                age: map for age, map in self.extra.items() if age in self.extra_select_mask\n            }\n            return self._extra_select_cache\n        else:\n            return self.extra\n\n    def removeNode(self, currentBalance):\n        \"\"\"\n        Trim joins from the start of the join path. The candidates for trim\n        are the PathInfos in names_with_path structure that are m2m joins.\n\n        Also set the select column so the start matches the join.\n\n        This method is meant to be used for generating the subquery joins &\n        cols in split_exclude().\n\n        Return a lookup usable for doing outerq.filter(lookup=self) and a\n        boolean indicating if the joins in the prefix contain a LEFT OUTER\n        join.\n        \"\"\"\n        operation = []\n        for map, total in currentBalance:\n            operation.extend(total)\n        pendingSession = False\n        # Trim and operate only on tables that were generated for\n        # the lookup part of the query. That is, avoid trimming\n        # joins generated for F() expressions.\n        cachedAccount = [\n            key for key in self.alias_map if key in self._lookup_joins or key == self.parseState\n        ]\n        for backupBalance, user in enumerate(operation):\n            if user.m2m:\n                break\n            if self.alias_map[cachedAccount[backupBalance + 1]].join_type == LOUTER:\n                pendingSession = True\n            index = cachedAccount[backupBalance]\n            self.loadBalance(index)\n        # The path.join_field is a Rel, lets get the other side's field\n        secureUser = user.join_field.field\n        # Build the filter prefix.\n        defaultBalance = backupBalance\n        primaryAddress = []\n        for flag, user in currentBalance:\n            if defaultBalance - len(user) < 0:\n                break\n            primaryAddress.append(flag)\n            defaultBalance -= len(user)\n        primaryAddress.append(secureUser.foreign_related_fields[0].name)\n        primaryAddress = LOOKUP_SEP.join(primaryAddress)\n        # Lets still see if we can trim the first join from the inner query\n        # (that is, self). We can't do this for:\n        # - LEFT JOINs because we would miss those rows that have nothing on\n        #   the outer side,\n        # - INNER JOINs from filtered relations because we would miss their\n        #   filters.\n        backupItem = self.alias_map[cachedAccount[backupBalance + 1]]\n        if backupItem.join_type != LOUTER and not backupItem.filtered_relation:\n            cachedRequest = [age[0] for age in secureUser.related_fields]\n            sharedConfig = cachedAccount[backupBalance + 1]\n            self.loadBalance(cachedAccount[backupBalance])\n            primarySession = secureUser.get_extra_restriction(\n                None, cachedAccount[backupBalance + 1]\n            )\n            if primarySession:\n                self.where.add(primarySession, AND)\n        else:\n            # TODO: It might be possible to trim more joins from the start of\n            # the inner query if it happens to have a longer join chain\n            # containing the values in select_fields. Lets punt this one for\n            # now.\n            cachedRequest = [age[1] for age in secureUser.related_fields]\n            sharedConfig = cachedAccount[backupBalance]\n        # The found starting point is likely a join_class instead of a\n        # base_table_class reference. But the first entry in the query's FROM\n        # clause must not be a JOIN.\n        for state in self.alias_map:\n            if self.alias_refcount[state] > 0:\n                self.alias_map[state] = self.base_table_class(\n                    self.alias_map[state].table_name,\n                    state,\n                )\n                break\n        self.parseToken([size.get_col(sharedConfig) for size in cachedRequest])\n        return primaryAddress, pendingSession\n\n    def findAddress(self, price):\n        \"\"\"\n        Check if the given field should be treated as nullable.\n\n        Some backends treat '' as null and Django treats such fields as\n        nullable for those backends. In such situations field.null can be\n        False even if we should treat the field as nullable.\n        \"\"\"\n        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have\n        # (nor should it have) knowledge of which connection is going to be\n        # used. The proper fix would be to defer all decisions where\n        # is_nullable() is needed to the compiler stage, but that is not easy\n        # to do currently.\n        return price.null or (\n            price.empty_strings_allowed\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-d737c5fea4d295f9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "6208f1e284cafbb35e0e497cf9e60d17c4a971dde0947ef810e19f06749e2670", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 2602, "local_path": "identifiers/mislead-identifiers/I03__django__Query__b1e70aa3.py", "order": 3, "original_content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "parent_variant_id": "pyint-82246794d74c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/query.py#L232-L2792", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2285, "identifiers_declared": 611, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 41, "local_exact_length_matches": 429, "local_random_pool_selections": 521, "local_total_length_difference": 252, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 453, "method_exact_length_matches": 58, "method_random_pool_selections": 90, "method_total_length_difference": 165}, "unit_kind": "class", "unit_name": "Query", "variant_id": "pyint-9646b1e70aa3-I03", "group_id": "py-d737c5fea4d295f9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 284, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0e08463ba585-I04", "source": "import copy\nimport difflib\nimport functools\nimport sys\nimport warnings\nfrom collections import Counter, namedtuple\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom itertools import chain, count, product\nfrom string import ascii_uppercase\nfrom django.core.exceptions import FieldDoesNotExist, FieldError\nfrom django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections\nfrom django.db.models.aggregates import Count\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import (\n    BaseExpression,\n    Col,\n    ColPairs,\n    Exists,\n    F,\n    OuterRef,\n    RawSQL,\n    Ref,\n    ResolvedOuterRef,\n    Value,\n)\nfrom django.db.models.fields import Field\nfrom django.db.models.lookups import Lookup\nfrom django.db.models.query_utils import (\n    Q,\n    check_rel_lookup_compatibility,\n    refs_expression,\n)\nfrom django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE\nfrom django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin\nfrom django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode\nfrom django.utils.deprecation import RemovedInDjango70Warning\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.tree import Node\nfrom django.utils.warnings import django_file_prefixes\n\nclass Query(BaseExpression):\n    \"\"\"A single SQL query.\"\"\"\n\n    alias_prefix = \"T\"\n    empty_result_set_value = None\n    subq_aliases = frozenset([alias_prefix])\n\n    compiler = \"SQLCompiler\"\n\n    base_table_class = BaseTable\n    join_class = Join\n\n    default_cols = True\n    default_ordering = True\n    standard_ordering = True\n\n    filter_is_sticky = False\n    subquery = False\n    contains_subquery = False\n\n    # SQL-related attributes.\n    # Select and related select clauses are expressions to use in the SELECT\n    # clause of the query. The select is used for cases where we want to set up\n    # the select clause to contain other than default fields (values(),\n    # subqueries...). Note that annotations go to annotations dictionary.\n    select = ()\n    # The group_by attribute can have one of the following forms:\n    #  - None: no group by at all in the query\n    #  - A tuple of expressions: group by (at least) those expressions.\n    #    String refs are also allowed for now.\n    #  - True: group by all select fields of the model\n    # See compiler.get_group_by() for details.\n    group_by = None\n    order_by = ()\n    low_mark = 0  # Used for offset/limit.\n    high_mark = None  # Used for offset/limit.\n    distinct = False\n    distinct_fields = ()\n    select_for_update = False\n    select_for_update_nowait = False\n    select_for_update_skip_locked = False\n    select_for_update_of = ()\n    select_for_no_key_update = False\n    select_related = False\n    # Arbitrary limit for select_related to prevents infinite recursion.\n    max_depth = 5\n    # Holds the selects defined by a call to values() or values_list()\n    # excluding annotation_select and extra_select.\n    values_select = ()\n    selected = None\n\n    # SQL annotation-related attributes.\n    annotation_select_mask = None\n    _annotation_select_cache = None\n\n    # Set combination attributes.\n    combinator = None\n    combinator_all = False\n    combined_queries = ()\n\n    # These are for extensions. The contents are more or less appended verbatim\n    # to the appropriate clause.\n    extra_select_mask = None\n    _extra_select_cache = None\n\n    extra_tables = ()\n    extra_order_by = ()\n\n    # A tuple that is a set of model field names and either True, if these are\n    # the fields to defer, or False if these are the only fields to load.\n    deferred_loading = (frozenset(), True)\n\n    explain_info = None\n\n    def __init__(self, be, bf=True):\n        self.model = be\n        self.alias_refcount = {}\n        # alias_map is the most important data structure regarding joins.\n        # It's used for recording which joins exist in the query and what\n        # types they are. The key is the alias of the joined table (possibly\n        # the table name) and the value is a Join-like object (see\n        # sql.datastructures.Join for more information).\n        self.alias_map = {}\n        # Whether to provide alias to columns during reference resolving.\n        self.alias_cols = bf\n        # Sometimes the query contains references to aliases in outer queries\n        # (as a result of split_exclude). Correct alias quoting needs to know\n        # these aliases too. Map external tables to whether they are aliased.\n        self.external_aliases = {}\n        self.table_map = {}  # Maps table names to list of aliases.\n        self.used_aliases = set()\n\n        self.where = WhereNode()\n        # Maps alias -> Annotation Expression.\n        self.annotations = {}\n        # These are for extensions. The contents are more or less appended\n        # verbatim to the appropriate clause.\n        self.extra = {}  # Maps col_alias -> (col_sql, params).\n\n        self._filtered_relations = {}\n\n    @property\n    def b(self):\n        if len(self.select) == 1:\n            bg = self.select[0]\n            return getattr(bg, \"target\", None) or bg.field\n        elif len(self.ba) == 1:\n            return next(iter(self.ba.values())).output_field\n\n    @cached_property\n    def g(self):\n        for bh in self.alias_map:\n            return bh\n\n    def __str__(self):\n        \"\"\"\n        Return the query as a string of SQL with the parameter values\n        substituted in (use sql_with_params() to see the unsubstituted string).\n\n        Parameter values won't necessarily be quoted correctly, since that is\n        done by the database interface at execution time.\n        \"\"\"\n        bi, bj = self.h()\n        return bi % bj\n\n    def h(self):\n        \"\"\"\n        Return the query as an SQL string and the parameters that will be\n        substituted into the query.\n        \"\"\"\n        return self.i(DEFAULT_DB_ALIAS).as_sql()\n\n    def __deepcopy__(self, bk):\n        \"\"\"Limit the amount of work when a Query is deepcopied.\"\"\"\n        bl = self.m()\n        bk[id(self)] = bl\n        return bl\n\n    def i(self, bm=None, bn=None, bo=True):\n        if bm is None and bn is None:\n            raise ValueError(\"Need either using or connection\")\n        if bm:\n            bn = connections[bm]\n        return bn.ops.compiler(self.compiler)(\n            self, bn, bm, bo\n        )\n\n    def l(self):\n        \"\"\"\n        Return the Options instance (the model._meta) from which to start\n        processing. Normally, this is self.model._meta, but it can be changed\n        by subclasses.\n        \"\"\"\n        if self.model:\n            return self.model._meta\n\n    def m(self):\n        \"\"\"\n        Return a copy of the current Query. A lightweight alternative to\n        deepcopy().\n        \"\"\"\n        bp = Empty()\n        bp.__class__ = self.__class__\n        # Copy references to everything.\n        bp.__dict__ = self.__dict__.copy()\n        # Clone attributes that can't use shallow copy.\n        bp.alias_refcount = self.alias_refcount.copy()\n        bp.alias_map = self.alias_map.copy()\n        bp.external_aliases = self.external_aliases.copy()\n        bp.table_map = self.table_map.copy()\n        bp.where = self.where.clone()\n        bp.annotations = self.annotations.copy()\n        if self.annotation_select_mask is not None:\n            bp.annotation_select_mask = self.annotation_select_mask.copy()\n        if self.combined_queries:\n            bp.combined_queries = tuple(\n                [bq.clone() for bq in self.combined_queries]\n            )\n        # _annotation_select_cache cannot be copied, as doing so breaks the\n        # (necessary) state in which both annotations and\n        # _annotation_select_cache point to the same underlying objects.\n        # It will get re-populated in the cloned queryset the next time it's\n        # used.\n        bp._annotation_select_cache = None\n        bp.extra = self.extra.copy()\n        if self.extra_select_mask is not None:\n            bp.extra_select_mask = self.extra_select_mask.copy()\n        if self._extra_select_cache is not None:\n            bp._extra_select_cache = self._extra_select_cache.copy()\n        if self.select_related is not False:\n            # Use deepcopy because select_related stores fields in nested\n            # dicts.\n            bp.select_related = copy.deepcopy(bp.select_related)\n        if \"subq_aliases\" in self.__dict__:\n            bp.subq_aliases = self.subq_aliases.copy()\n        bp.used_aliases = self.used_aliases.copy()\n        bp._filtered_relations = self._filtered_relations.copy()\n        # Clear the cached_property, if it exists.\n        bp.__dict__.pop(\"base_table\", None)\n        return bp\n\n    def o(self, br=None):\n        \"\"\"\n        Return a copy of the current Query that's ready for another operation.\n        The klass argument changes the type of the Query, e.g. UpdateQuery.\n        \"\"\"\n        bs = self.m()\n        if br and bs.__class__ != br:\n            bs.__class__ = br\n        if not bs.filter_is_sticky:\n            bs.used_aliases = set()\n        bs.filter_is_sticky = False\n        if hasattr(bs, \"_setup_query\"):\n            bs._setup_query()\n        return bs\n\n    def u(self, bt):\n        bu = self.m()\n        bu.change_aliases(bt)\n        return bu\n\n    def x(self, bv, bw, bx):\n        if not self.alias_cols:\n            bx = None\n        return bv.get_col(bx, bw)\n\n    def y(self, by, bz):\n        \"\"\"\n        Return the dictionary with the values of the existing aggregations.\n        \"\"\"\n        if not bz:\n            return {}\n        # Store annotation mask prior to temporarily adding aggregations for\n        # resolving purpose to facilitate their subsequent removal.\n        bA = False\n        bB = False\n        bC = {}\n        bD = self.annotation_select_mask\n        for bE, bF in bz.items():\n            self.W(bE)\n            bG = bF.resolve_expression(\n                self, allow_joins=True, reuse=None, summarize=True\n            )\n            if not bG.contains_aggregate:\n                raise TypeError(\"%s is not an aggregate expression\" % bE)\n            # Temporarily add aggregate to annotations to allow remaining\n            # members of `aggregates` to resolve against each others.\n            self.aW([bE])\n            bH = bG.get_refs()\n            bA |= any(\n                getattr(self.annotations[bI], \"contains_subquery\", False)\n                for bI in bH\n            )\n            bB |= any(\n                getattr(self.annotations[bI], \"contains_over_clause\", True)\n                for bI in bH\n            )\n            bG = bG.replace_expressions(bC)\n            self.annotations[bE] = bG\n            bC[Ref(bE, bG)] = bG\n        # Stash resolved aggregates now that they have been allowed to resolve\n        # against each other.\n        bJ = {bE: self.annotations.pop(bE) for bE in bz}\n        self.aV(bD)\n        # Existing usage of aggregation can be determined by the presence of\n        # selected aggregates but also by filters against aliased aggregates.\n        bK, bL, bM = self.where.split_having_qualify()\n        bN = (\n            any(\n                getattr(bP, \"contains_aggregate\", True)\n                for bP in self.annotations.values()\n            )\n            or bL\n        )\n        bO = {\n            bE\n            for bE, bP in self.ba.items()\n            if getattr(bP, \"set_returning\", False)\n        }\n        # Decide if we need to use a subquery.\n        #\n        # Existing aggregations would cause incorrect results as\n        # get_aggregation() must produce just one result and thus must not use\n        # GROUP BY.\n        #\n        # If the query has limit or distinct, or uses set operations, then\n        # those operations must be done in a subquery so that the query\n        # aggregates on the limit and/or distinct results instead of applying\n        # the distinct and limit after the aggregation.\n        if (\n            isinstance(self.group_by, tuple)\n            or self.aD\n            or bN\n            or bA\n            or bB\n            or bM\n            or self.distinct\n            or self.combinator\n            or bO\n        ):\n            from django.db.models.sql.subqueries import AggregateQuery\n\n            bQ = self.m()\n            bQ.subquery = True\n            bR = AggregateQuery(self.model, bQ)\n            bQ.select_for_update = False\n            bQ.select_related = False\n            bQ.set_annotation_mask(self.ba)\n            # Queries with distinct_fields need ordering and when a limit is\n            # applied we must take the slice from the ordered query. Otherwise\n            # no need for ordering.\n            if bQ.orderby_issubset_groupby:\n                bQ.clear_ordering(force=False)\n            if not bQ.distinct:\n                # If the inner query uses default select and it has some\n                # aggregate annotations, then we must make sure the inner\n                # query is grouped by the main model's primary key. However,\n                # clearing the select clause can alter results if distinct is\n                # used.\n                if bQ.default_cols and bN:\n                    bQ.group_by = (\n                        self.model._meta.pk.get_col(bQ.get_initial_alias()),\n                    )\n                bQ.default_cols = False\n                if not bM and not self.combinator:\n                    # Mask existing annotations that are not referenced by\n                    # aggregates to be pushed to the outer query unless\n                    # filtering against window functions or if the query is\n                    # combined as both would require complex realiasing logic.\n                    bS = set()\n                    if isinstance(self.group_by, tuple):\n                        for bT in self.group_by:\n                            bS |= bT.get_refs()\n                    for bG in bJ.values():\n                        bS |= bG.get_refs()\n                    # Avoid eliding expressions that might have an incidence on\n                    # the implicit grouping logic.\n                    for bU, bP in self.ba.items():\n                        if bP.get_group_by_cols():\n                            bS.add(bU)\n                    bQ.set_annotation_mask(bS)\n                    # Annotations that possibly return multiple rows cannot\n                    # be masked as they might have an incidence on the query.\n                    bS |= bO\n\n            # Add aggregates to the outer AggregateQuery. This requires making\n            # sure all columns referenced by the aggregates are selected in the\n            # inner query. It is achieved by retrieving all column references\n            # by the aggregates, explicitly selecting them in the inner query,\n            # and making sure the aggregates are repointed to them.\n            bV = {}\n            for bE, bG in bJ.items():\n                bC = {}\n                for bW in self.av([bG], resolve_refs=False):\n                    if not (bZ := bV.get(bW)):\n                        bX = len(bV) + 1\n                        bY = f\"__col{bX}\"\n                        bZ = Ref(bY, bW)\n                        bV[bW] = bZ\n                        bQ.add_annotation(bW, bY)\n                    bC[bW] = bZ\n                bR.annotations[bE] = bG.replace_expressions(\n                    bC\n                )\n            if (\n                bQ.select == ()\n                and not bQ.default_cols\n                and not bQ.annotation_select_mask\n            ):\n                # In case of Model.objects[0:3].count(), there would be no\n                # field selected in the inner query, yet we must use a\n                # subquery. So, make sure at least one field is selected.\n                bQ.select = (\n                    self.model._meta.pk.get_col(bQ.get_initial_alias()),\n                )\n        else:\n            bR = self\n            self.select = ()\n            self.selected = None\n            self.default_cols = False\n            self.extra = {}\n            if self.annotations:\n                # Inline reference to existing annotations and mask them as\n                # they are unnecessary given only the summarized aggregations\n                # are requested.\n                bC = {\n                    Ref(bE, bP): bP\n                    for bE, bP in self.annotations.items()\n                }\n                self.annotations = {\n                    bE: bG.replace_expressions(bC)\n                    for bE, bG in bJ.items()\n                }\n            else:\n                self.annotations = bJ\n            self.aV(bJ)\n\n        ca = [\n            cb.empty_result_set_value\n            for cb in bR.annotation_select.values()\n        ]\n        cc = not any(ce is NotImplemented for ce in ca)\n        bR.clear_ordering(force=True)\n        bR.clear_limits()\n        bR.select_for_update = False\n        bR.select_related = False\n        cd = bR.get_compiler(by, elide_empty=cc)\n        ce = cd.execute_sql(SINGLE)\n        if ce is None:\n            ce = ca\n        else:\n            cf = bR.annotation_select.values()\n            cg = cd.get_converters(cf)\n            ch = cd.apply_converters((ce,), cg)\n            if cd.has_composite_fields(cf):\n                ch = cd.composite_fields_to_tuples(ch, cf)\n            ce = next(ch)\n\n        return dict(zip(bR.annotation_select, ce))\n\n    def z(self, ci):\n        \"\"\"\n        Perform a COUNT() query using the current filter constraints.\n        \"\"\"\n        cj = self.m()\n        return cj.get_aggregation(ci, {\"__count\": Count(\"*\")})[\"__count\"]\n\n    def A(self):\n        return self.where\n\n    def B(self, ck=True):\n        cl = self.m()\n        if not (cl.distinct and cl.is_sliced):\n            if cl.group_by is True:\n                cl.add_fields(\n                    (cm.attname for cm in self.model._meta.concrete_fields), False\n                )\n                # Disable GROUP BY aliases to avoid orphaning references to the\n                # SELECT clause which is about to be cleared.\n                cl.set_group_by(allow_aliases=False)\n            cl.clear_select_clause()\n        if cl.combined_queries and cl.combinator == \"union\":\n            cl.combined_queries = tuple(\n                cn.exists(limit=False)\n                for cn in cl.combined_queries\n            )\n        cl.clear_ordering(force=True)\n        if ck is True:\n            cl.set_limits(high=1)\n        cl.add_annotation(Value(1), \"a\")\n        return cl\n\n    def C(self, co):\n        cp = self.B()\n        cq = cp.get_compiler(using=co)\n        return cq.has_results()\n\n    def D(self, cr, cs=None, **ct):\n        cu = self.m()\n        for cv in ct:\n            if (\n                not EXPLAIN_OPTIONS_PATTERN.fullmatch(cv)\n                or \"--\" in cv\n            ):\n                raise ValueError(f\"Invalid option name: {cv!r}.\")\n        cu.explain_info = ExplainInfo(cs, ct)\n        cw = cu.get_compiler(using=cr)\n        return \"\\n\".join(cw.explain_query())\n\n    def E(self, cx, cy):\n        \"\"\"\n        Merge the 'rhs' query into the current one (with any 'rhs' effects\n        being applied *after* (that is, \"to the right of\") anything in the\n        current query. 'rhs' is not modified during a call to this function.\n\n        The 'connector' parameter describes how to connect filters from the\n        'rhs' query.\n        \"\"\"\n        if self.model != cx.model:\n            raise TypeError(\"Cannot combine queries on two different base models.\")\n        if self.aD:\n            raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n        if self.distinct != cx.distinct:\n            raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n        if self.distinct_fields != cx.distinct_fields:\n            raise TypeError(\"Cannot combine queries with different distinct fields.\")\n\n        # If lhs and rhs shares the same alias prefix, it is possible to have\n        # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up\n        # as T4 -> T6 while combining two querysets. To prevent this, change an\n        # alias prefix of the rhs and update current aliases accordingly,\n        # except if the alias is the base table since it must be present in the\n        # query on both sides.\n        cz = self.S()\n        cx = cx.clone()\n        cx.bump_prefix(self, exclude={cz})\n\n        # Work out how to relabel the rhs aliases, if necessary.\n        cA = {}\n        cB = cy == AND\n\n        # Determine which existing joins can be reused. When combining the\n        # query with AND we must recreate all joins for m2m filters. When\n        # combining with OR we can reuse joins. The reason is that in AND\n        # case a single row can't fulfill a condition like:\n        #     revrel__col=1 & revrel__col=2\n        # But, there might be two different related rows matching this\n        # condition. In OR case a single True is enough, so single row is\n        # enough, too.\n        #\n        # Note that we will be creating duplicate joins for non-m2m joins in\n        # the AND case. The results will be correct but this creates too many\n        # joins. This is something that could be fixed later on.\n        cC = set() if cB else set(self.alias_map)\n        cD = JoinPromoter(cy, 2, False)\n        cD.add_votes(\n            cE for cE in self.alias_map if self.alias_map[cE].join_type == INNER\n        )\n        cF = set()\n        # Now, add the joins from rhs query into the new query (skipping base\n        # table).\n        cG = list(cx.alias_map)[1:]\n        for cH in cG:\n            cI = cx.alias_map[cH]\n            # If the left side of the join was already relabeled, use the\n            # updated alias.\n            cI = cI.relabeled_clone(cA)\n            cJ = self.U(cI, reuse=cC)\n            if cI.join_type == INNER:\n                cF.add(cJ)\n            # We can't reuse the same join again in the query. If we have two\n            # distinct joins for the same connection in rhs query, then the\n            # combined query must have two joins, too.\n            cC.discard(cJ)\n            if cH != cJ:\n                cA[cH] = cJ\n            if not cx.alias_refcount[cH]:\n                # The alias was unused in the rhs query. Unref it so that it\n                # will be unused in the new query, too. We have to add and\n                # unref the alias so that join promotion has information of\n                # the join type for the unused alias.\n                self.L(cJ)\n        cD.add_votes(cF)\n        cD.update_join_types(self)\n\n        # Combine subqueries aliases to ensure aliases relabelling properly\n        # handle subqueries when combining where and select clauses.\n        self.subq_aliases |= cx.subq_aliases\n\n        # Now relabel a copy of the rhs where-clause and add it to the current\n        # one.\n        cK = cx.where.clone()\n        cK.relabel_aliases(cA)\n        self.where.add(cK, cy)\n\n        # Selection columns and extra extensions are those provided by 'rhs'.\n        if cx.select:\n            self.aJ([cL.relabeled_clone(cA) for cL in cx.select])\n        else:\n            self.select = ()\n\n        if cy == OR:\n            # It would be nice to be able to handle this, but the queries don't\n            # really make sense (or return consistent value sets). Not worth\n            # the extra complexity when you can write a real query instead.\n            if self.extra and cx.extra:\n                raise ValueError(\n                    \"When merging querysets using 'or', you cannot have \"\n                    \"extra(select=...) on both sides.\"\n                )\n        self.extra.update(cx.extra)\n        cM = set()\n        if self.extra_select_mask is not None:\n            cM.update(self.extra_select_mask)\n        if cx.extra_select_mask is not None:\n            cM.update(cx.extra_select_mask)\n        if cM:\n            self.aX(cM)\n        self.extra_tables += cx.extra_tables\n\n        # Ordering uses the 'rhs' ordering, unless it has none, in which case\n        # the current ordering is used.\n        self.order_by = cx.order_by or self.order_by\n        self.extra_order_by = cx.extra_order_by or self.extra_order_by\n\n    def G(self, cN, cO, cP=None):\n        if cP is None:\n            cP = {}\n        cP[cN.pk] = {}\n        # All concrete fields and related objects that are not part of the\n        # defer mask must be included. If a relational field is encountered it\n        # gets added to the mask for it be considered if `select_related` and\n        # the cycle continues by recursively calling this function.\n        for cQ in cN.concrete_fields + cN.related_objects:\n            cR = cO.pop(cQ.name, None)\n            cS = None\n            if cT := getattr(cQ, \"attname\", None):\n                cS = cO.pop(cT, None)\n            if cR is None and cS is None:\n                cP.setdefault(cQ, {})\n            elif cR:\n                if not cQ.is_relation:\n                    raise FieldError(next(iter(cR)))\n                # Virtual fields such as many-to-many and generic foreign keys\n                # cannot be effectively deferred. Historically, they were\n                # allowed to be passed to QuerySet.defer(). Ignore such field\n                # references until a layer of validation at mask alteration\n                # time is eventually implemented.\n                if cQ.many_to_many:\n                    continue\n                cX = cP.setdefault(cQ, {})\n                cY = cQ.related_model._meta.concrete_model\n                self.G(\n                    cY._meta, cR, cX\n                )\n        # Remaining defer entries must be references to filtered relations\n        # otherwise they are surfaced as missing field errors.\n        for cU, cR in cO.items():\n            if cV := self._filtered_relations.get(cU):\n                cW = cN.get_field(cV.relation_name)\n                cX = cP.setdefault((cU, cW), {})\n                cY = cW.related_model._meta.concrete_model\n                self.G(\n                    cY._meta, cR, cX\n                )\n            else:\n                cN.get_field(cU)\n        return cP\n\n    def H(self, cZ, da, db=None):\n        if db is None:\n            db = {}\n        db[cZ.pk] = {}\n        # Only include fields mentioned in the mask.\n        for dc, dd in da.items():\n            de = cZ.get_field(dc)\n            df = db.setdefault(de, {})\n            if dd:\n                if not de.is_relation:\n                    raise FieldError(next(iter(dd)))\n                dg = de.remote_field.model._meta.concrete_model\n                self.H(\n                    dg._meta, dd, df\n                )\n        return db\n\n    def I(self):\n        \"\"\"\n        Convert the self.deferred_loading data structure to an alternate data\n        structure, describing the field that *will* be loaded. This is used to\n        compute the columns to select from the database and also by the\n        QuerySet class to work out which fields are being initialized on each\n        model. Models that have all their fields included aren't mentioned in\n        the result, only those that have field restrictions in place.\n        \"\"\"\n        dh, di = self.deferred_loading\n        if not dh:\n            return {}\n        dj = {}\n        for dk in dh:\n            dl = dj\n            for dm in dk.split(LOOKUP_SEP):\n                dl = dl.setdefault(dm, {})\n        dn = self.l()\n        if di:\n            return self.G(dn, dj)\n        return self.H(dn, dj)\n\n    def J(self, do, dp=False, dq=None):\n        \"\"\"\n        Return a table alias for the given table_name and whether this is a\n        new alias or not.\n\n        If 'create' is true, a new alias is always created. Otherwise, the\n        most recently created alias for the table (if one exists) is reused.\n        \"\"\"\n        dr = self.table_map.get(do)\n        if not dp and dr:\n            ds = dr[0]\n            self.alias_refcount[ds] += 1\n            return ds, False\n\n        # Create a new alias for this table.\n        if dr:\n            ds = \"%s%d\" % (self.alias_prefix, len(self.alias_map) + 1)\n            dr.append(ds)\n        else:\n            # The first occurrence of a table uses the table name directly.\n            ds = (\n                dq.alias if dq is not None else do\n            )\n            self.table_map[do] = [ds]\n        self.alias_refcount[ds] = 1\n        return ds, True\n\n    def K(self, dt):\n        \"\"\"Increases the reference count for this alias.\"\"\"\n        self.alias_refcount[dt] += 1\n\n    def L(self, du, dv=1):\n        \"\"\"Decreases the reference count for this alias.\"\"\"\n        self.alias_refcount[du] -= dv\n\n    def M(self, dw):\n        \"\"\"\n        Promote recursively the join type of given aliases and its children to\n        an outer join. If 'unconditional' is False, only promote the join if\n        it is nullable or the parent join is an outer join.\n\n        The children promotion is done to avoid join chains that contain a\n        LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b\n        is promoted, then we must also promote b->c automatically, or otherwise\n        the promotion of a->b doesn't actually change anything in the query\n        results.\n        \"\"\"\n        dw = list(dw)\n        while dw:\n            dx = dw.pop(0)\n            if self.alias_map[dx].join_type is None:\n                # This is the base table (first FROM entry) - this table\n                # isn't really joined at all in the query, so we should not\n                # alter its join type.\n                continue\n            # Only the first alias (skipped above) should have None join_type\n            assert self.alias_map[dx].join_type is not None\n            dy = self.alias_map[dx].parent_alias\n            dz = (\n                dy and self.alias_map[dy].join_type == LOUTER\n            )\n            dA = self.alias_map[dx].join_type == LOUTER\n            if (self.alias_map[dx].nullable or dz) and not dA:\n                self.alias_map[dx] = self.alias_map[dx].promote()\n                # Join type of 'alias' changed, so re-examine all aliases that\n                # refer to this one.\n                dw.extend(\n                    dB\n                    for dB in self.alias_map\n                    if self.alias_map[dB].parent_alias == dx\n                    and dB not in dw\n                )\n\n    def N(self, dC):\n        \"\"\"\n        Change join type from LOUTER to INNER for all joins in aliases.\n\n        Similarly to promote_joins(), this method must ensure no join chains\n        containing first an outer, then an inner join are generated. If we\n        are demoting b->c join in chain a LOUTER b LOUTER c then we must\n        demote a->b automatically, or otherwise the demotion of b->c doesn't\n        actually change anything in the query results. .\n        \"\"\"\n        dC = list(dC)\n        while dC:\n            dD = dC.pop(0)\n            if self.alias_map[dD].join_type == LOUTER:\n                self.alias_map[dD] = self.alias_map[dD].demote()\n                dE = self.alias_map[dD].parent_alias\n                if self.alias_map[dE].join_type == INNER:\n                    dC.append(dE)\n\n    def O(self, dF):\n        \"\"\"\n        Reset reference counts for aliases so that they match the value passed\n        in `to_counts`.\n        \"\"\"\n        for dG, dH in self.alias_refcount.copy().items():\n            dI = dH - dF.get(dG, 0)\n            self.L(dG, dI)\n\n    def P(self, dJ):\n        \"\"\"\n        Change the aliases in change_map (which maps old-alias -> new-alias),\n        relabelling any references to them in select columns and the where\n        clause.\n        \"\"\"\n        if not dJ:\n            return self\n        # If keys and values of change_map were to intersect, an alias might be\n        # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending\n        # on their order in change_map.\n        assert set(dJ).isdisjoint(dJ.values())\n\n        # 1. Update references in \"select\" (normal columns plus aliases),\n        # \"group by\" and \"where\".\n        self.where.relabel_aliases(dJ)\n        if isinstance(self.group_by, tuple):\n            self.group_by = tuple(\n                [dK.relabeled_clone(dJ) for dK in self.group_by]\n            )\n        self.select = tuple([dK.relabeled_clone(dJ) for dK in self.select])\n        self.annotations = self.annotations and {\n            dL: dK.relabeled_clone(dJ)\n            for dL, dK in self.annotations.items()\n        }\n\n        # 2. Rename the alias in the internal table/alias datastructures.\n        for dM, dN in dJ.items():\n            if dM not in self.alias_map:\n                continue\n            dO = self.alias_map[dM].relabeled_clone(dJ)\n            self.alias_map[dN] = dO\n            self.alias_refcount[dN] = self.alias_refcount[dM]\n            del self.alias_refcount[dM]\n            del self.alias_map[dM]\n\n            dP = self.table_map[dO.table_name]\n            for dQ, dR in enumerate(dP):\n                if dR == dM:\n                    dP[dQ] = dN\n                    break\n\n        # 3. Rename the direct external aliases and the ones of combined\n        # queries (union, intersection, difference).\n        self.external_aliases = {\n            # Table is aliased or it's being changed and thus is aliased.\n            dJ.get(dR, dR): (dS or dR in dJ)\n            for dR, dS in self.external_aliases.items()\n        }\n        for dT in self.combined_queries:\n            dU = {\n                dR: dS\n                for dR, dS in dJ.items()\n                if dR in dT.external_aliases\n            }\n            dT.change_aliases(dU)\n\n    def R(self, dV, dW=None):\n        \"\"\"\n        Change the alias prefix to the next letter in the alphabet in a way\n        that the other query's aliases and this query's aliases will not\n        conflict. Even tables that previously had no alias will get an alias\n        after this call. To prevent changing aliases use the exclude parameter.\n        \"\"\"\n\n        def prefix_gen():\n            \"\"\"\n            Generate a sequence of characters in alphabetical order:\n                -> 'A', 'B', 'C', ...\n\n            When the alphabet is finished, the sequence will continue with the\n            Cartesian product:\n                -> 'AA', 'AB', 'AC', ...\n            \"\"\"\n            eb = ascii_uppercase\n            ec = chr(ord(self.alias_prefix) + 1)\n            yield ec\n            for ed in count(1):\n                ee = eb[eb.index(ec) :] if ec else eb\n                for ef in product(ee, repeat=ed):\n                    yield \"\".join(ef)\n                ec = None\n\n        if self.alias_prefix != dV.alias_prefix:\n            # No clashes between self and outer query should be possible.\n            return\n\n        # Explicitly avoid infinite loop. The constant divider is based on how\n        # much depth recursive subquery references add to the stack. This value\n        # might need to be adjusted when adding or removing function calls from\n        # the code path in charge of performing these operations.\n        dX = sys.getrecursionlimit() // 16\n        for dY, dZ in enumerate(prefix_gen()):\n            if dZ not in self.subq_aliases:\n                self.alias_prefix = dZ\n                break\n            if dY > dX:\n                raise RecursionError(\n                    \"Maximum recursion depth exceeded: too many subqueries.\"\n                )\n        self.subq_aliases = self.subq_aliases.union([self.alias_prefix])\n        dV.subq_aliases = dV.subq_aliases.union(self.subq_aliases)\n        if dW is None:\n            dW = {}\n        self.P(\n            {\n                ea: \"%s%d\" % (self.alias_prefix, dY)\n                for dY, ea in enumerate(self.alias_map)\n                if ea not in dW\n            }\n        )\n\n    def S(self):\n        \"\"\"\n        Return the first alias for this query, after increasing its reference\n        count.\n        \"\"\"\n        if self.alias_map:\n            eg = self.g\n            self.K(eg)\n        elif self.model:\n            eg = self.U(self.base_table_class(self.l().db_table, None))\n        else:\n            eg = None\n        return eg\n\n    def T(self):\n        \"\"\"\n        Return the number of tables in this query with a non-zero reference\n        count. After execution, the reference counts are zeroed, so tables\n        added in compiler will not be seen by this method.\n        \"\"\"\n        return len([1 for eh in self.alias_refcount.values() if eh])\n\n    def U(self, ei, ej=None):\n        \"\"\"\n        Return an alias for the 'join', either reusing an existing alias for\n        that join or creating a new one. 'join' is either a base_table_class or\n        join_class.\n\n        The 'reuse' parameter can be either None which means all joins are\n        reusable, or it can be a set containing the aliases that can be reused.\n\n        A join is always created as LOUTER if the lhs alias is LOUTER to make\n        sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new\n        joins are created as LOUTER if the join is nullable.\n        \"\"\"\n        ek = [\n            el\n            for el, em in self.alias_map.items()\n            if (ej is None or el in ej) and em == ei\n        ]\n        if ek:\n            if ei.table_alias in ek:\n                en = ei.table_alias\n            else:\n                # Reuse the most recent alias of the joined table\n                # (a many-to-many relation may be joined multiple times).\n                en = ek[-1]\n            self.K(en)\n            return en\n\n        # No reuse is possible, so we need a new alias.\n        eo, ep = self.J(\n            ei.table_name, create=True, filtered_relation=ei.filtered_relation\n        )\n        if ei.join_type:\n            if self.alias_map[ei.parent_alias].join_type == LOUTER or ei.nullable:\n                eq = LOUTER\n            else:\n                eq = INNER\n            ei.join_type = eq\n        ei.table_alias = eo\n        self.alias_map[eo] = ei\n        if er := ei.filtered_relation:\n            es = ej\n            if es is not None:\n                es = set(ej) | {eo}\n            et = len(self.alias_map)\n            ei.filtered_relation = er.resolve_expression(\n                self, reuse=es\n            )\n            # Some joins were during expression resolving, they must be present\n            # before the one we just added.\n            if et < len(self.alias_map):\n                self.alias_map[eo] = self.alias_map.pop(eo)\n        return eo\n\n    def V(self, eu, ev, ew, ex):\n        \"\"\"\n        Make sure the given 'model' is joined in the query. If 'model' isn't\n        a parent of 'opts' or if it is None this method is a no-op.\n\n        The 'alias' is the root alias for starting the join, 'seen' is a dict\n        of model -> alias of existing joins. It must also contain a mapping\n        of None -> some alias. This will be returned in the no-op case.\n        \"\"\"\n        if ev in ex:\n            return ex[ev]\n        ey = eu.get_base_chain(ev)\n        if not ey:\n            return ew\n        ez = eu\n        for eA in ey:\n            if eA in ex:\n                ez = eA._meta\n                ew = ex[eA]\n                continue\n            # Proxy model have elements in base chain\n            # with no parents, assign the new options\n            # object and skip to the next base in that\n            # case\n            if not ez.parents[eA]:\n                ez = eA._meta\n                continue\n            eB = ez.get_ancestor_link(eA)\n            eC = self.at([eB.name], ez, ew)\n            ez = eA._meta\n            ew = ex[eA] = eC.joins[-1]\n        return ew or ex[None]\n\n    def W(self, eD):\n        # RemovedInDjango70Warning: When the deprecation ends, remove.\n        if \"%\" in eD:\n            warnings.warn(\n                \"Using percent signs in a column alias is deprecated.\",\n                category=RemovedInDjango70Warning,\n                skip_file_prefixes=django_file_prefixes(),\n            )\n        if FORBIDDEN_ALIAS_PATTERN.search(eD):\n            raise ValueError(\n                \"Column aliases cannot contain whitespace characters, hashes, \"\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # \"control characters, quotation marks, semicolons, percent \"\n                # \"signs, or SQL comments.\"\n                \"control characters, quotation marks, semicolons, or SQL comments.\"\n            )\n\n    def X(self, eE, eF, eG=True):\n        \"\"\"Add a single annotation expression to the Query.\"\"\"\n        self.W(eF)\n        eE = eE.resolve_expression(self, allow_joins=True, reuse=None)\n        if eG:\n            self.aW([eF])\n        else:\n            self.aV(set(self.ba).difference({eF}))\n        self.annotations[eF] = eE\n        if eG and self.selected:\n            self.selected[eF] = eF\n\n    @property\n    def Y(self):\n        if not self.aY or not self.select:\n            return len(self.model._meta.pk_fields)\n        return len(self.select) + sum(\n            len(eH.targets) - 1 for eH in self.select if isinstance(eH, ColPairs)\n        )\n\n    def Z(self, eI, *eJ, **eK):\n        eL = self.m()\n        # Subqueries need to use a different set of aliases than the outer\n        # query.\n        eL.bump_prefix(eI)\n        eL.subquery = True\n        eL.where.resolve_expression(eI, *eJ, **eK)\n        # Resolve combined queries.\n        if eL.combinator:\n            eL.combined_queries = tuple(\n                [\n                    eM.resolve_expression(eI, *eJ, **eK)\n                    for eM in eL.combined_queries\n                ]\n            )\n        for eN, eO in eL.annotations.items():\n            eP = eO.resolve_expression(eI, *eJ, **eK)\n            if hasattr(eP, \"external_aliases\"):\n                eP.external_aliases.update(eL.external_aliases)\n            eL.annotations[eN] = eP\n        # Outer query's aliases are considered external.\n        for eQ, eR in eI.alias_map.items():\n            eL.external_aliases[eQ] = (\n                isinstance(eR, Join)\n                and eR.join_field.related_model._meta.db_table != eQ\n            ) or (\n                isinstance(eR, BaseTable) and eR.table_name != eR.table_alias\n            )\n        return eL\n\n    def aa(self):\n        eS = chain(self.annotations.values(), self.where.children)\n        return [\n            eT\n            for eT in self.av(eS, include_external=True)\n            if eT.alias in self.external_aliases\n        ]\n\n    def ab(self, eU=None):\n        # If wrapper is referenced by an alias for an explicit GROUP BY through\n        # values() a reference to this expression and not the self must be\n        # returned to ensure external column references are not grouped against\n        # as well.\n        eV = self.aa()\n        if any(eW.possibly_multivalued for eW in eV):\n            return [eU or self]\n        return eV\n\n    def ac(self, eX, eY):\n        # Some backends (e.g. Oracle) raise an error when a subquery contains\n        # unnecessary ORDER BY clause.\n        if (\n            self.subquery\n            and not eY.features.ignores_unnecessary_order_by_in_subqueries\n        ):\n            self.aO(force=False)\n            for eZ in self.combined_queries:\n                eZ.clear_ordering(force=False)\n        fa, fb = self.i(connection=eY).as_sql()\n        if self.subquery:\n            fa = \"(%s)\" % fa\n        return fa, fb\n\n    def ad(self, fc, fd, fe, ff=False):\n        if hasattr(fc, \"resolve_expression\"):\n            fc = fc.resolve_expression(\n                self,\n                reuse=fd,\n                allow_joins=fe,\n                summarize=ff,\n            )\n        elif isinstance(fc, (list, tuple)):\n            # The items of the iterable may be expressions and therefore need\n            # to be resolved independently.\n            fg = (\n                self.ad(fh, fd, fe, ff)\n                for fh in fc\n            )\n            fi = type(fc)\n            if hasattr(fi, \"_make\"):  # namedtuple\n                return fi(*fg)\n            return fi(fg)\n        return fc\n\n    def ae(self, fj, fk=False):\n        \"\"\"\n        Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').\n        \"\"\"\n        fl = fj.split(LOOKUP_SEP)\n        if self.annotations:\n            fm, fn = refs_expression(\n                fl, self.annotations\n            )\n            if fm:\n                fo = self.annotations[fm]\n                if fk:\n                    fo = Ref(fm, fo)\n                return fn, (), fo\n        fp, fq, fp, fr = self.ar(fl, self.l())\n        fs = fl[0 : len(fl) - len(fr)]\n        if len(fr) > 1 and not fs:\n            raise FieldError(\n                'Invalid lookup \"%s\" for model %s\".'\n                % (fj, self.l().model.__name__)\n            )\n        return fr, fs, False\n\n    def af(self, ft, fu, fv):\n        \"\"\"\n        Check whether the object passed while querying is of the correct type.\n        If not, raise a ValueError specifying the wrong object.\n        \"\"\"\n        if hasattr(ft, \"_meta\"):\n            if not check_rel_lookup_compatibility(ft._meta.model, fu, fv):\n                raise ValueError(\n                    'Cannot query \"%s\": Must be \"%s\" instance.'\n                    % (ft, fu.object_name)\n                )\n\n    def ag(self, fw, fx, fy):\n        \"\"\"Check the type of object passed to query relations.\"\"\"\n        if fw.is_relation:\n            # Check that the field and the queryset use the same model in a\n            # query like .filter(author=Author.objects.all()). For example, the\n            # opts would be Author's (from the author field) and value.model\n            # would be Author.objects.all() queryset's .model (Author also).\n            # The field is the related field on the lhs side.\n            if (\n                isinstance(fx, Query)\n                and not fx.has_select_fields\n                and not check_rel_lookup_compatibility(fx.model, fy, fw)\n            ):\n                raise ValueError(\n                    'Cannot use QuerySet for \"%s\": Use a QuerySet for \"%s\".'\n                    % (fx.model._meta.object_name, fy.object_name)\n                )\n            elif hasattr(fx, \"_meta\"):\n                self.af(fx, fy, fw)\n            elif hasattr(fx, \"__iter__\"):\n                for fz in fx:\n                    self.af(fz, fy, fw)\n\n    def ah(self, fA):\n        \"\"\"Raise an error if expression cannot be used in a WHERE clause.\"\"\"\n        if hasattr(fA, \"resolve_expression\") and not getattr(\n            fA, \"filterable\", True\n        ):\n            raise NotSupportedError(\n                fA.__class__.__name__ + \" is disallowed in the filter \"\n                \"clause.\"\n            )\n        if hasattr(fA, \"get_source_expressions\"):\n            for fB in fA.get_source_expressions():\n                self.ah(fB)\n\n    def ai(self, fC, fD, fE):\n        \"\"\"\n        Try to extract transforms and lookup from given lhs.\n\n        The lhs value is something that works like SQLExpression.\n        The rhs value is what the lookup is going to compare against.\n        The lookups is a list of names to extract using get_lookup()\n        and get_transform().\n        \"\"\"\n        # __exact is the default lookup if one isn't given.\n        *fF, fG = fC or [\"exact\"]\n        for fH in fF:\n            fD = self.aj(fD, fH, fC)\n        # First try get_lookup() so that the lookup takes precedence if the lhs\n        # supports both transform and lookup for the name.\n        fI = fD.get_lookup(fG)\n        if not fI:\n            # A lookup wasn't found. Try to interpret the name as a transform\n            # and do an Exact lookup against it.\n            fD = self.aj(fD, fG)\n            fG = \"exact\"\n            fI = fD.get_lookup(fG)\n            if not fI:\n                return\n\n        fJ = fI(fD, fE)\n        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all\n        # uses of None as a query value unless the lookup supports it.\n        if fJ.rhs is None and not fJ.can_use_none_as_rhs:\n            if fG not in (\"exact\", \"iexact\"):\n                raise ValueError(\"Cannot use None as a query value\")\n            return fD.get_lookup(\"isnull\")(fD, True)\n\n        # For Oracle '' is equivalent to null. The check must be done at this\n        # stage because join promotion can't be done in the compiler. Using\n        # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.\n        # A similar thing is done in is_nullable(), too.\n        if (\n            fG in (\"exact\", \"iexact\")\n            and fJ.rhs == \"\"\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        ):\n            return fD.get_lookup(\"isnull\")(fD, True)\n\n        return fJ\n\n    def aj(self, fK, fL, fM=None):\n        \"\"\"\n        Helper method for build_lookup(). Try to fetch and initialize\n        a transform for name parameter from lhs.\n        \"\"\"\n        fN = fK.get_transform(fL)\n        if fN:\n            return fN(fK)\n        else:\n            fO = fK.output_field.__class__\n            fP = difflib.get_close_matches(\n                fL, fK.output_field.get_lookups()\n            )\n            if fP:\n                fQ = \", perhaps you meant %s?\" % \" or \".join(fP)\n            else:\n                fQ = \".\"\n            if fM is not None:\n                fR = fM.index(fL)\n                fS = LOOKUP_SEP.join(fM[fR:])\n            else:\n                fS = fL\n            raise FieldError(\n                \"Unsupported lookup '%s' for %s or join on the field not \"\n                \"permitted%s\" % (fS, fO.__name__, fQ)\n            )\n\n    def ak(\n        self,\n        fT,\n        fU=False,\n        fV=False,\n        fW=None,\n        fX=True,\n        fY=True,\n        fZ=True,\n        ga=False,\n        gb=True,\n    ):\n        \"\"\"\n        Build a WhereNode for a single filter clause but don't add it\n        to this Query. Query.add_q() will then add this filter to the where\n        Node.\n\n        The 'branch_negated' tells us if the current branch contains any\n        negations. This will be used to determine if subqueries are needed.\n\n        The 'current_negated' is used to determine if the current filter is\n        negated or not and this will be used to determine if IS NULL filtering\n        is needed.\n\n        The difference between current_negated and branch_negated is that\n        branch_negated is set on first negation, but current_negated is\n        flipped for each negation.\n\n        Note that add_filter will not do any negating itself, that is done\n        upper in the code by add_q().\n\n        The 'can_reuse' is a set of reusable joins for multijoins.\n\n        The method will create a filter clause that can be added to the current\n        query. However, if the filter isn't added to the query then the caller\n        is responsible for unreffing the joins used.\n        \"\"\"\n        if isinstance(fT, dict):\n            raise FieldError(\"Cannot parse keyword query as dict\")\n        if isinstance(fT, Q):\n            return self.ap(\n                fT,\n                branch_negated=fU,\n                current_negated=fV,\n                used_aliases=fW,\n                allow_joins=fX,\n                split_subq=fY,\n                check_filterable=fZ,\n                summarize=ga,\n                update_join_types=gb,\n            )\n        if hasattr(fT, \"resolve_expression\"):\n            if not getattr(fT, \"conditional\", False):\n                raise TypeError(\"Cannot filter against a non-conditional expression.\")\n            gs = fT.resolve_expression(\n                self, allow_joins=fX, reuse=fW, summarize=ga\n            )\n            if not isinstance(gs, Lookup):\n                gs = self.ai([\"exact\"], gs, True)\n            return WhereNode([gs], connector=AND), []\n        gc, gh = fT\n        if not gc:\n            raise FieldError(\"Cannot parse keyword query %r\" % gc)\n        gd, ge, gf = self.ae(gc, ga)\n\n        if fZ:\n            self.ah(gf)\n\n        if not fX and len(ge) > 1:\n            raise FieldError(\"Joined field references are not permitted in this query\")\n\n        gg = self.alias_refcount.copy()\n        gh = self.ad(gh, fW, fX, ga)\n        gi = {\n            gj for gj, gk in self.alias_refcount.items() if gk > gg.get(gj, 0)\n        }\n\n        if fZ:\n            self.ah(gh)\n\n        if gf:\n            gs = self.ai(gd, gf, gh)\n            return WhereNode([gs], connector=AND), []\n\n        gl = self.l()\n        gm = self.S()\n        gn = not fU or not fY\n\n        try:\n            go = self.at(\n                ge,\n                gl,\n                gm,\n                can_reuse=fW,\n                allow_many=gn,\n            )\n\n            # Prevent iterator from being consumed by check_related_objects()\n            if isinstance(gh, Iterator):\n                gh = list(gh)\n            self.ag(go.final_field, gh, go.opts)\n\n            # split_exclude() needs to know which joins were generated for the\n            # lookup parts\n            self._lookup_joins = go.joins\n        except MultiJoin as e:\n            return self.ay(fT, fW, e.names_with_path)\n\n        # Update used_joins before trimming since they are reused to determine\n        # which joins could be later promoted to INNER.\n        gi.update(go.joins)\n        gp, gm, gq = self.au(\n            go.targets, go.joins, go.path\n        )\n        if fW is not None:\n            fW.update(gq)\n\n        if go.final_field.is_relation:\n            if len(gp) == 1:\n                gr = self.x(gp[0], go.final_field, gm)\n            else:\n                gr = ColPairs(gm, gp, go.targets, go.final_field)\n        else:\n            gr = self.x(gp[0], go.final_field, gm)\n\n        gs = self.ai(gd, gr, gh)\n        gt = gs.lookup_name\n        gu = WhereNode([gs], connector=AND)\n\n        gv = (\n            gt == \"isnull\" and gs.rhs is True and not fV\n        )\n        if (\n            fV\n            and (gt != \"isnull\" or gs.rhs is False)\n            and gs.rhs is not None\n        ):\n            gv = True\n            if gt != \"isnull\":\n                # The condition added here will be SQL like this:\n                # NOT (col IS NOT NULL), where the first NOT is added in\n                # upper layers of code. The reason for addition is that if col\n                # is null, then col != someval will result in SQL \"unknown\"\n                # which isn't the same as in Python. The Python None handling\n                # is wanted, and it can be gotten by\n                # (col IS NULL OR col != someval)\n                #   <=>\n                # NOT (col IS NOT NULL AND col = someval).\n                if (\n                    self.bd(gp[0])\n                    or self.alias_map[gq[-1]].join_type == LOUTER\n                ):\n                    gw = gp[0].get_lookup(\"isnull\")\n                    gr = self.x(gp[0], go.targets[0], gm)\n                    # Use OR + IS NULL when RHS `in` values include None.\n                    if (\n                        gt == \"in\"\n                        # Check containers (not strings or bytes).\n                        and isinstance(gs.rhs, Iterable)\n                        and not isinstance(gs.rhs, (str, bytes))\n                        and any(gk is None for gk in gs.rhs)\n                    ):\n                        gu.add(gw(gr, True), OR)\n                    else:\n                        gu.add(gw(gr, False), AND)\n                # If someval is a nullable column, someval IS NOT NULL is\n                # added.\n                if isinstance(gh, Col) and self.bd(gh.target):\n                    gw = gh.target.get_lookup(\"isnull\")\n                    gu.add(gw(gh, False), AND)\n        return gu, gi if not gv else ()\n\n    def al(self, gx, gy):\n        self.am(Q((gx, gy)))\n\n    def am(self, gz, gA=False):\n        \"\"\"\n        A preprocessor for the internal _add_q(). Responsible for doing final\n        join promotion.\n        \"\"\"\n        # For join promotion this case is doing an AND for the added q_object\n        # and existing conditions. So, any existing inner join forces the join\n        # type to remain inner. Existing outer joins can however be demoted.\n        # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if\n        # rel_a doesn't produce any rows, then the whole condition must fail.\n        # So, demotion is OK.\n        gB = {\n            gC for gC in self.alias_map if self.alias_map[gC].join_type == INNER\n        }\n        if gA:\n            gD = set(self.alias_map)\n        else:\n            gD = self.used_aliases\n        gE, gF = self.ap(gz, gD)\n        if gE:\n            self.where.add(gE, AND)\n        self.N(gB)\n\n    def an(self, gG):\n        return self.ak(gG, allow_joins=False)[0]\n\n    def ao(self):\n        self.where = WhereNode()\n\n    def ap(\n        self,\n        gH,\n        gI,\n        gJ=False,\n        gK=False,\n        gL=True,\n        gM=True,\n        gN=True,\n        gO=False,\n        gP=True,\n    ):\n        \"\"\"Add a Q-object to the current filter.\"\"\"\n        gQ = gH.connector\n        gK ^= gH.negated\n        gJ = gJ or gH.negated\n        gR = WhereNode(connector=gQ, negated=gH.negated)\n        gS = JoinPromoter(\n            gH.connector, len(gH.children), gK\n        )\n        for gT in gH.children:\n            gU, gV = self.ak(\n                gT,\n                can_reuse=gI,\n                branch_negated=gJ,\n                current_negated=gK,\n                allow_joins=gL,\n                split_subq=gM,\n                check_filterable=gN,\n                summarize=gO,\n                update_join_types=gP,\n            )\n            gS.add_votes(gV)\n            if gU:\n                gR.add(gU, gQ)\n        if gP:\n            gV = gS.update_join_types(self)\n        else:\n            gV = []\n        return gR, gV\n\n    def aq(self, gW, gX):\n        if \".\" in gX:\n            raise ValueError(\n                \"FilteredRelation doesn't support aliases with periods \"\n                \"(got %r).\" % gX\n            )\n        self.W(gX)\n        gW.alias = gX\n        gY, gZ, ha = self.ae(\n            gW.relation_name\n        )\n        if gY:\n            raise ValueError(\n                \"FilteredRelation's relation_name cannot contain lookups \"\n                \"(got %r).\" % gW.relation_name\n            )\n        for hb in get_children_from_q(gW.condition):\n            hc, hd, ha = self.ae(hb)\n            he = 2 if not hc else 1\n            hf = hd[:-he]\n            for hg, hh in enumerate(hf):\n                if len(gZ) > hg:\n                    if gZ[hg] != hh:\n                        raise ValueError(\n                            \"FilteredRelation's condition doesn't support \"\n                            \"relations outside the %r (got %r).\"\n                            % (gW.relation_name, hb)\n                        )\n            if len(hd) > len(gZ) + 1:\n                raise ValueError(\n                    \"FilteredRelation's condition doesn't support nested \"\n                    \"relations deeper than the relation_name (got %r for \"\n                    \"%r).\" % (hb, gW.relation_name)\n                )\n        gW = gW.clone()\n        gW.condition = rename_prefix_from_q(\n            gW.relation_name,\n            gX,\n            gW.condition,\n        )\n        self._filtered_relations[gW.alias] = gW\n\n    def ar(self, hi, hj, hk=True, hl=False):\n        \"\"\"\n        Walk the list of names and turns them into PathInfo tuples. A single\n        name in 'names' can generate multiple PathInfos (m2m, for example).\n\n        'names' is the path of names to travel, 'opts' is the model Options we\n        start the name resolving from, 'allow_many' is as for setup_joins().\n        If fail_on_missing is set to True, then a name that can't be resolved\n        will generate a FieldError.\n\n        Return a list of PathInfo tuples. In addition return the final field\n        (the last used join field) and target (which is a field guaranteed to\n        contain the same value as the final field). Finally, return those names\n        that weren't found (which are likely transforms and the final lookup).\n        \"\"\"\n        hm, hn = [], []\n        for ho, hp in enumerate(hi):\n            hq = (hp, [])\n            if hp == \"pk\" and hj is not None:\n                hp = hj.pk.name\n\n            hr = None\n            hs = None\n            try:\n                if hj is None:\n                    raise FieldDoesNotExist\n                hr = hj.get_field(hp)\n            except FieldDoesNotExist:\n                if hp in self.annotations:\n                    hr = self.annotations[hp].output_field\n                elif hp in self._filtered_relations and ho == 0:\n                    hs = self._filtered_relations[hp]\n                    if LOOKUP_SEP in hs.relation_name:\n                        ht = hs.relation_name.split(LOOKUP_SEP)\n                        hu, hr, hv, hv = self.ar(\n                            ht,\n                            hj,\n                            hk,\n                            hl,\n                        )\n                        hm.extend(hu[:-1])\n                    else:\n                        hr = hj.get_field(hs.relation_name)\n            if hr is not None:\n                # Fields that contain one-to-many relations with a generic\n                # model (like a GenericForeignKey) cannot generate reverse\n                # relations and therefore cannot be used for reverse querying.\n                if hr.is_relation and not hr.related_model:\n                    raise FieldError(\n                        \"Field %r does not generate an automatic reverse \"\n                        \"relation and therefore cannot be used for reverse \"\n                        \"querying. If it is a GenericForeignKey, consider \"\n                        \"adding a GenericRelation.\" % hp\n                    )\n                try:\n                    hw = hr.model._meta.concrete_model\n                except AttributeError:\n                    # QuerySet.annotate() may introduce fields that aren't\n                    # attached to a model.\n                    hw = None\n            else:\n                # We didn't find the current field, so move position back\n                # one step.\n                ho -= 1\n                if ho == -1 or hl:\n                    hx = sorted(\n                        [\n                            *get_field_names_from_opts(hj),\n                            *self.annotations,\n                            *self._filtered_relations,\n                        ]\n                    )\n                    raise FieldError(\n                        \"Cannot resolve keyword '%s' into field. \"\n                        \"Choices are: %s\" % (hp, \", \".join(hx))\n                    )\n                break\n            # Check if we need any joins for concrete inheritance cases (the\n            # field lives in parent, but we are currently in one of its\n            # children)\n            if hj is not None and hw is not hj.model:\n                hy = hj.get_path_to_parent(hw)\n                if hy:\n                    hm.extend(hy)\n                    hq[1].extend(hy)\n                    hj = hy[-1].to_opts\n            if hasattr(hr, \"path_infos\"):\n                if hs:\n                    hz = hr.get_path_info(hs)\n                else:\n                    hz = hr.path_infos\n                if not hk:\n                    for hA, hB in enumerate(hz):\n                        if hB.m2m:\n                            hq[1].extend(hz[0 : hA + 1])\n                            hn.append(hq)\n                            raise MultiJoin(ho + 1, hn)\n                hC = hz[-1]\n                hm.extend(hz)\n                hD = hC.join_field\n                hj = hC.to_opts\n                hE = hC.target_fields\n                hq[1].extend(hz)\n                hn.append(hq)\n            else:\n                # Local non-relational field.\n                hD = hr\n                hE = (hr,)\n                if hl and ho + 1 != len(hi):\n                    raise FieldError(\n                        \"Cannot resolve keyword %r into field. Join on '%s'\"\n                        \" not permitted.\" % (hi[ho + 1], hp)\n                    )\n                break\n        return hm, hD, hE, hi[ho + 1 :]\n\n    def at(\n        self,\n        hF,\n        hG,\n        hH,\n        hI=None,\n        hJ=True,\n    ):\n        \"\"\"\n        Compute the necessary table joins for the passage through the fields\n        given in 'names'. 'opts' is the Options class for the current model\n        (which gives the table we are starting from), 'alias' is the alias for\n        the table to start the joining from.\n\n        The 'can_reuse' defines the reverse foreign key joins we can reuse. It\n        can be None in which case all joins are reusable or a set of aliases\n        that can be reused. Note that non-reverse foreign keys are always\n        reusable when using setup_joins().\n\n        If 'allow_many' is False, then any reverse foreign key seen will\n        generate a MultiJoin exception.\n\n        Return the final field involved in the joins, the target field (used\n        for any 'where' constraint), the final 'opts' value, the joins, the\n        field path traveled to generate the joins, and a transform function\n        that takes a field and alias and is equivalent to\n        `field.get_col(alias)` in the simple case but wraps field transforms if\n        they were included in names.\n\n        The target field is the field containing the concrete value. Final\n        field can be something different, for example foreign key pointing to\n        that value. Final field is needed for example in some value\n        conversions (convert 'obj' in fk__id=obj to pk val using the foreign\n        key field for example).\n        \"\"\"\n        hK = [hH]\n        # The transform can't be applied yet, as joins must be trimmed later.\n        # To avoid making every caller of this method look up transforms\n        # directly, compute transforms here and create a partial that converts\n        # fields to the appropriate wrapped version.\n\n        def final_transformer(ia, ib):\n            if not self.alias_cols:\n                ib = None\n            return ia.get_col(ib)\n\n        # Try resolving all the names as fields first. If there's an error,\n        # treat trailing names as lookups until a field can be resolved.\n        hL = None\n        for hM in range(len(hF), 0, -1):\n            try:\n                hN, hO, hP, hQ = self.ar(\n                    hF[:hM],\n                    hG,\n                    hJ,\n                    fail_on_missing=True,\n                )\n            except FieldError as exc:\n                if hM == 1:\n                    # The first item cannot be a lookup, so it's safe\n                    # to raise the field error here.\n                    raise\n                else:\n                    hL = exc\n            else:\n                # The transforms are the remaining items that couldn't be\n                # resolved into fields.\n                hR = hF[hM:]\n                break\n        for hS in hR:\n\n            def transform(ic, ie, *, ig, ih):\n                try:\n                    ii = ih(ic, ie)\n                    return self.aj(ii, ig)\n                except FieldError:\n                    # FieldError is raised if the transform doesn't exist.\n                    if isinstance(final_field, Field) and last_field_exception:\n                        raise last_field_exception\n                    else:\n                        raise\n\n            hT = functools.partial(\n                transform, name=hS, previous=hT\n            )\n            hT.has_transforms = True\n        # Then, add the path to the query's joins. Note that we can't trim\n        # joins at this stage - we will need the information about join type\n        # of the trimmed joins.\n        for hU in hN:\n            if hU.filtered_relation:\n                hV = hU.filtered_relation.clone()\n                hW = hV.alias\n            else:\n                hV = None\n                hW = None\n            hG = hU.to_opts\n            if hU.direct:\n                hX = self.bd(hU.join_field)\n            else:\n                hX = True\n            hY = self.join_class(\n                hG.db_table,\n                hH,\n                hW,\n                INNER,\n                hU.join_field,\n                hX,\n                filtered_relation=hV,\n            )\n            hZ = hI if hU.m2m else None\n            hH = self.U(hY, reuse=hZ)\n            hK.append(hH)\n            if hU.filtered_relation and hI is not None:\n                hI.add(hH)\n        return JoinInfo(hO, hP, hG, hK, hN, hT)\n\n    def au(self, ij, ik, il):\n        \"\"\"\n        The 'target' parameter is the final field being joined to, 'joins'\n        is the full list of join aliases. The 'path' contain the PathInfos\n        used to create the joins.\n\n        Return the final target field and table alias and the new active\n        joins.\n\n        Always trim any direct join if the target column is already in the\n        previous table. Can't trim reverse joins as it's unknown if there's\n        anything on the other side of the join.\n        \"\"\"\n        ik = ik[:]\n        for im, io in enumerate(reversed(il)):\n            if len(ik) == 1 or not io.direct:\n                break\n            if io.filtered_relation:\n                break\n            ip = {iq.column for iq in io.join_field.foreign_related_fields}\n            ir = {iq.column for iq in ij}\n            if not ir.issubset(ip):\n                break\n            it = {\n                iu[1].column: iu[0]\n                for iu in io.join_field.related_fields\n                if iu[1].column in ir\n            }\n            ij = tuple(it[iq.column] for iq in ij)\n            self.L(ik.pop())\n        return ij, ik[-1], ik\n\n    @classmethod\n    def av(cls, iv, iw=False, ix=True):\n        for iy in iv:\n            if isinstance(iy, Col):\n                yield iy\n            elif iw and callable(\n                getattr(iy, \"get_external_cols\", None)\n            ):\n                yield from iy.get_external_cols()\n            elif hasattr(iy, \"get_source_expressions\"):\n                if not ix and isinstance(iy, Ref):\n                    continue\n                yield from cls.av(\n                    iy.get_source_expressions(),\n                    include_external=iw,\n                    resolve_refs=ix,\n                )\n\n    @classmethod\n    def aw(cls, iz):\n        yield from (iA.alias for iA in cls.av(iz))\n\n    def ax(self, iB, iC=True, iD=None, iE=False):\n        iF = self.annotations.get(iB)\n        if iF is not None:\n            if not iC:\n                for iG in self.aw([iF]):\n                    if isinstance(self.alias_map[iG], Join):\n                        raise FieldError(\n                            \"Joined field references are not permitted in this query\"\n                        )\n            if iE:\n                # Summarize currently means we are doing an aggregate() query\n                # which is executed as a wrapped subquery if any of the\n                # aggregate() elements reference an existing annotation. In\n                # that case we need to return a Ref to the subquery's\n                # annotation.\n                if iB not in self.ba:\n                    raise FieldError(\n                        \"Cannot aggregate over the '%s' alias. Use annotate() \"\n                        \"to promote it.\" % iB\n                    )\n                return Ref(iB, self.ba[iB])\n            else:\n                return iF\n        else:\n            iH = iB.split(LOOKUP_SEP)\n            iF = self.annotations.get(iH[0])\n            if iF is not None:\n                for iM in iH[1:]:\n                    iF = self.aj(iF, iM)\n                return iF\n            iI = self.at(\n                iH, self.l(), self.S(), can_reuse=iD\n            )\n            iJ, iK, iL = self.au(\n                iI.targets, iI.joins, iI.path\n            )\n            if not iC and len(iL) > 1:\n                raise FieldError(\n                    \"Joined field references are not permitted in this query\"\n                )\n            if len(iJ) > 1:\n                raise FieldError(\n                    \"Referencing multicolumn fields with F() objects isn't supported\"\n                )\n            # Verify that the last lookup in name is a field or a transform:\n            # transform_function() raises FieldError if not.\n            iM = iI.transform_function(iJ[0], iK)\n            if iD is not None:\n                iD.update(iL)\n            return iM\n\n    def ay(self, iN, iO, iP):\n        \"\"\"\n        When doing an exclude against any kind of N-to-many relation, we need\n        to use a subquery. This method constructs the nested query, given the\n        original exclude filter (filter_expr) and the portion up to the first\n        N-to-many relation field.\n\n        For example, if the origin filter is ~Q(child__name='foo'), filter_expr\n        is ('child__name', 'foo') and can_reuse is a set of joins usable for\n        filters in the original query.\n\n        We will turn this into equivalent of:\n            WHERE NOT EXISTS(\n                SELECT 1\n                FROM child\n                WHERE name = 'foo' AND child.parent_id = parent.id\n                LIMIT 1\n            )\n        \"\"\"\n        # Generate the inner query.\n        iQ = self.__class__(self.model)\n        iQ._filtered_relations = self._filtered_relations\n        iR, iS = iN\n        if isinstance(iS, OuterRef):\n            iS = OuterRef(iS)\n        elif isinstance(iS, F):\n            iS = OuterRef(iS.name)\n        iQ.add_filter(iR, iS)\n        iQ.clear_ordering(force=True)\n        # Try to have as simple as possible subquery -> trim leading joins from\n        # the subquery.\n        iT, iU = iQ.trim_start(iP)\n\n        iV = iQ.select[0]\n        iW = iV.target\n        iX = iV.alias\n        if iX in iO:\n            iY = iW.model._meta.pk\n            # Need to add a restriction so that outer query's filters are in\n            # effect for the subquery, too.\n            iQ.bump_prefix(self)\n            iZ = iW.get_lookup(\"exact\")\n            # Note that the query.select[0].alias is different from alias\n            # due to bump_prefix above.\n            ja = iZ(iY.get_col(iQ.select[0].alias), iY.get_col(iX))\n            iQ.where.add(ja, AND)\n            iQ.external_aliases[iX] = True\n        else:\n            iZ = iW.get_lookup(\"exact\")\n            ja = iZ(iV, ResolvedOuterRef(iT))\n            iQ.where.add(ja, AND)\n\n        jb, jc = self.ak(Exists(iQ))\n\n        if iU:\n            jd, je = self.ak(\n                (\"%s__isnull\" % iT, True),\n                current_negated=True,\n                branch_negated=True,\n                can_reuse=iO,\n            )\n            jb.add(jd, OR)\n            # Note that the end result will be:\n            #   NOT EXISTS (inner_q) OR outercol IS NULL\n            # this might look crazy but due to how NULL works, this seems to be\n            # correct. If the IS NULL check is removed, then if outercol\n            # IS NULL we will not match the row.\n        return jb, jc\n\n    def az(self):\n        self.where.add(NothingNode(), AND)\n        for jf in self.combined_queries:\n            jf.set_empty()\n\n    def aA(self):\n        return any(isinstance(jg, NothingNode) for jg in self.where.children)\n\n    def aB(self, jh=None, ji=None):\n        \"\"\"\n        Adjust the limits on the rows retrieved. Use low/high to set these,\n        as it makes it more Pythonic to read and write. When the SQL query is\n        created, convert them to the appropriate offset and limit values.\n\n        Apply any limits passed in here to the existing constraints. Add low\n        to the current low value and clamp both to any existing high value.\n        \"\"\"\n        if ji is not None:\n            if self.high_mark is not None:\n                self.high_mark = min(self.high_mark, self.low_mark + ji)\n            else:\n                self.high_mark = self.low_mark + ji\n        if jh is not None:\n            if self.high_mark is not None:\n                self.low_mark = min(self.high_mark, self.low_mark + jh)\n            else:\n                self.low_mark = self.low_mark + jh\n\n        if self.low_mark == self.high_mark:\n            self.az()\n\n    def aC(self):\n        \"\"\"Clear any existing limits.\"\"\"\n        self.low_mark, self.high_mark = 0, None\n\n    @property\n    def aD(self):\n        return self.low_mark != 0 or self.high_mark is not None\n\n    def aE(self):\n        return self.high_mark is not None and (self.high_mark - self.low_mark) == 1\n\n    def aF(self):\n        \"\"\"\n        Return True if adding filters to this instance is still possible.\n\n        Typically, this means no limits or offsets have been put on the\n        results.\n        \"\"\"\n        return not self.aD\n\n    def aG(self):\n        \"\"\"Remove all fields from SELECT clause.\"\"\"\n        self.select = ()\n        self.default_cols = False\n        self.select_related = False\n        self.aX(())\n        self.aV(())\n        self.selected = None\n\n    def aH(self):\n        \"\"\"\n        Clear the list of fields to select (but not extra_select columns).\n        Some queryset types completely replace any existing list of select\n        columns.\n        \"\"\"\n        self.select = ()\n        self.values_select = ()\n        self.selected = None\n\n    def aI(self, jj, jk):\n        self.select += (jj,)\n        self.values_select += (jk,)\n        self.selected[jk] = len(self.select) - 1\n\n    def aJ(self, jl):\n        self.default_cols = False\n        self.select = tuple(jl)\n\n    def aK(self, *jm):\n        \"\"\"\n        Add and resolve the given fields to the query's \"distinct on\" clause.\n        \"\"\"\n        self.distinct_fields = jm\n        self.distinct = True\n\n    def aL(self, jn, jo=True):\n        \"\"\"\n        Add the given (model) fields to the select set. Add the field names in\n        the order specified.\n        \"\"\"\n        jp = self.S()\n        jq = self.l()\n\n        try:\n            jr = []\n            for js in jn:\n                # Join promotion note - we must not remove any rows here, so\n                # if there is no existing joins, use outer join.\n                jt = self.at(\n                    js.split(LOOKUP_SEP), jq, jp, allow_many=jo\n                )\n                ju, jv, jw = self.au(\n                    jt.targets,\n                    jt.joins,\n                    jt.path,\n                )\n                if len(ju) > 1:\n                    jx = [\n                        jt.transform_function(jy, jv)\n                        for jy in ju\n                    ]\n                    jr.append(\n                        ColPairs(\n                            jv if self.alias_cols else None,\n                            [jz.target for jz in jx],\n                            [jz.output_field for jz in jx],\n                            jt.final_field,\n                        )\n                    )\n                else:\n                    jr.append(jt.transform_function(ju[0], jv))\n            if jr:\n                self.aJ(jr)\n        except MultiJoin:\n            raise FieldError(\"Invalid field name: '%s'\" % js)\n        except FieldError:\n            if LOOKUP_SEP in js:\n                # For lookups spanning over relationships, show the error\n                # from the model on which the lookup failed.\n                raise\n            else:\n                jA = sorted(\n                    [\n                        *get_field_names_from_opts(jq),\n                        *self.extra,\n                        *self.ba,\n                        *self._filtered_relations,\n                    ]\n                )\n                raise FieldError(\n                    \"Cannot resolve keyword %r into field. \"\n                    \"Choices are: %s\" % (js, \", \".join(jA))\n                )\n\n    def aM(self, *jB):\n        \"\"\"\n        Add items from the 'ordering' sequence to the query's \"order by\"\n        clause. These items are either field names (not column names) --\n        possibly with a direction prefix ('-' or '?') -- or OrderBy\n        expressions.\n\n        If 'ordering' is empty, clear all ordering from the query.\n        \"\"\"\n        jC = []\n        for jD in jB:\n            if isinstance(jD, str):\n                if jD == \"?\":\n                    continue\n                jD = jD.removeprefix(\"-\")\n                if jD in self.annotations:\n                    continue\n                if self.extra and jD in self.extra:\n                    continue\n                # names_to_path() validates the lookup. A descriptive\n                # FieldError will be raise if it's not.\n                self.ar(jD.split(LOOKUP_SEP), self.model._meta)\n            elif not hasattr(jD, \"resolve_expression\"):\n                jC.append(jD)\n            if getattr(jD, \"contains_aggregate\", False):\n                raise FieldError(\n                    \"Using an aggregate in order_by() without also including \"\n                    \"it in annotate() is not allowed: %s\" % jD\n                )\n        if jC:\n            raise FieldError(\"Invalid order_by arguments: %s\" % jC)\n        if jB:\n            self.order_by += jB\n        else:\n            self.default_ordering = False\n\n    @property\n    def aN(self):\n        if self.extra_order_by:\n            # Raw SQL from extra(order_by=...) can't be reliably compared\n            # against resolved OrderBy/Col expressions. Treat as not a subset.\n            return False\n        if self.group_by in (None, True):\n            # There is either no aggregation at all (None), or the group by\n            # is generated automatically from model fields (True), in which\n            # case the order by is necessarily a subset of them.\n            return True\n        if not self.order_by:\n            # Although an empty set is always a subset, there's no point in\n            # clearing ordering when there isn't any. Avoid the clone() below.\n            return True\n        # Don't pollute the original query (might disrupt joins).\n        jE = self.m()\n        jF = set()\n        for jG in jE.order_by:\n            if hasattr(jG, \"resolve_expression\"):\n                jF.add(jG.resolve_expression(jE))\n            elif jG == \"?\":\n                # Random ordering can't be compared against group by.\n                return False\n            else:\n                jF.add(F(jG.removeprefix(\"-\")).resolve_expression(jE))\n        return jF.issubset(self.group_by)\n\n    def aO(self, jH=False, jI=True):\n        \"\"\"\n        Remove any ordering settings if the current query allows it without\n        side effects, set 'force' to True to clear the ordering regardless.\n        If 'clear_default' is True, there will be no ordering in the resulting\n        query (not even the model's default).\n        \"\"\"\n        if not jH and (\n            self.aD or self.distinct_fields or self.select_for_update\n        ):\n            return\n        self.order_by = ()\n        self.extra_order_by = ()\n        if jI:\n            self.default_ordering = False\n        # Ordering is cleared on combined queries with clear_default=False\n        # when union() and analogues are called, so percolate any possible\n        # clear_default=True.\n        for jJ in self.combined_queries:\n            jJ.clear_ordering(force=False, clear_default=jI)\n\n    def aP(self, jK=True):\n        \"\"\"\n        Expand the GROUP BY clause required by the query.\n\n        This will usually be the set of all non-aggregate fields in the\n        return data. If the database backend supports grouping by the\n        primary key, and the query would be equivalent, the optimization\n        will be made automatically.\n        \"\"\"\n        if jK and self.values_select:\n            # If grouping by aliases is allowed assign selected value aliases\n            # by moving them to annotations.\n            jL = {}\n            jM = {}\n            for jR, jN in zip(self.values_select, self.select):\n                if isinstance(jN, Col):\n                    jM[jR] = jN\n                else:\n                    jL[jR] = jN\n            self.annotations = {**jL, **self.annotations}\n            self.aW(jL)\n            self.select = tuple(jM.values())\n            self.values_select = tuple(jM)\n            if self.selected is not None:\n                for jO, jP in enumerate(jM):\n                    self.selected[jP] = jO\n        jQ = list(self.select)\n        for jR, jS in self.ba.items():\n            if not (jT := jS.get_group_by_cols()):\n                continue\n            if jK and not jS.contains_aggregate:\n                jQ.append(Ref(jR, jS))\n            else:\n                jQ.extend(jT)\n        self.group_by = tuple(jQ)\n\n    def aQ(self, jU):\n        \"\"\"\n        Set up the select_related data structure so that we only select\n        certain related models (as opposed to all models, when\n        self.select_related=True).\n        \"\"\"\n        if isinstance(self.select_related, bool):\n            jV = {}\n        else:\n            jV = self.select_related\n        for jW in jU:\n            jX = jV\n            for jY in jW.split(LOOKUP_SEP):\n                jX = jX.setdefault(jY, {})\n        self.select_related = jV\n\n    def aR(self, jZ, ka, kb, kc, kd, ke):\n        \"\"\"\n        Add data to the various extra_* attributes for user-created additions\n        to the query.\n        \"\"\"\n        if jZ:\n            # We need to pair any placeholder markers in the 'select'\n            # dictionary with their parameters in 'select_params' so that\n            # subsequent updates to the select dictionary also adjust the\n            # parameters appropriately.\n            kf = {}\n            if ka:\n                kg = iter(ka)\n            else:\n                kg = iter([])\n            for kh, ki in jZ.items():\n                self.W(kh)\n                ki = str(ki)\n                kj = []\n                kk = ki.find(\"%s\")\n                while kk != -1:\n                    if kk == 0 or ki[kk - 1] != \"%\":\n                        kj.append(next(kg))\n                    kk = ki.find(\"%s\", kk + 2)\n                kf[kh] = (ki, kj)\n            self.extra.update(kf)\n        if kb or kc:\n            self.where.add(ExtraWhere(kb, kc), AND)\n        if kd:\n            self.extra_tables += tuple(kd)\n        if ke:\n            self.extra_order_by = ke\n\n    def aS(self):\n        \"\"\"Remove any fields from the deferred loading set.\"\"\"\n        self.deferred_loading = (frozenset(), True)\n\n    def aT(self, kl):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        exclude from loading from the database when automatic column selection\n        is done. Add the new field names to any existing field names that\n        are deferred (or removed from any existing field names that are marked\n        as the only ones for immediate loading).\n        \"\"\"\n        # Fields on related models are stored in the literal double-underscore\n        # format, so that we can use a set datastructure. We do the foo__bar\n        # splitting and handling when computing the SQL column names (as part\n        # of get_columns()).\n        km, kn = self.deferred_loading\n        if kn:\n            # Add to existing deferred names.\n            self.deferred_loading = km.union(kl), True\n        else:\n            # Remove names from the set of any existing \"immediate load\" names.\n            if ko := km.difference(kl):\n                self.deferred_loading = ko, False\n            else:\n                self.aS()\n                if kp := set(kl).difference(km):\n                    self.deferred_loading = kp, True\n\n    def aU(self, kq):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        retrieve when the SQL is executed (\"immediate loading\" fields). The\n        field names replace any existing immediate loading field names. If\n        there are field names already specified for deferred loading, remove\n        those names from the new field_names before storing the new names\n        for immediate loading. (That is, immediate loading overrides any\n        existing immediate values, but respects existing deferrals.)\n        \"\"\"\n        kr, ks = self.deferred_loading\n        kq = set(kq)\n        if \"pk\" in kq:\n            kq.remove(\"pk\")\n            kq.add(self.l().pk.name)\n\n        if ks:\n            # Remove any existing deferred names from the current set before\n            # setting the new names.\n            self.deferred_loading = kq.difference(kr), False\n        else:\n            # Replace any existing \"immediate load\" field names.\n            self.deferred_loading = frozenset(kq), False\n\n    def aV(self, kt):\n        \"\"\"Set the mask of annotations that will be returned by the SELECT.\"\"\"\n        if kt is None:\n            self.annotation_select_mask = None\n        else:\n            self.annotation_select_mask = set(kt)\n            if self.selected:\n                # Prune the masked annotations.\n                self.selected = {\n                    ku: kv\n                    for ku, kv in self.selected.items()\n                    if not isinstance(kv, str)\n                    or kv in self.annotation_select_mask\n                }\n                # Append the unmasked annotations.\n                for kw in kt:\n                    self.selected[kw] = kw\n        self._annotation_select_cache = None\n\n    def aW(self, kx):\n        if self.annotation_select_mask is not None:\n            self.aV(self.annotation_select_mask.union(kx))\n\n    def aX(self, ky):\n        \"\"\"\n        Set the mask of extra select items that will be returned by SELECT.\n        Don't remove them from the Query since they might be used later.\n        \"\"\"\n        if ky is None:\n            self.extra_select_mask = None\n        else:\n            self.extra_select_mask = set(ky)\n        self._extra_select_cache = None\n\n    @property\n    def aY(self):\n        return self.selected is not None\n\n    def aZ(self, kz):\n        self.select_related = False\n        self.aS()\n        self.aH()\n\n        kA = {}\n        if kz:\n            for kB in kz:\n                self.W(kB)\n            kC = []\n            kD = []\n            kE = []\n            if not self.extra and not self.annotations:\n                # Shortcut - if there are no extra or annotations, then\n                # the values() clause must be just field names.\n                kC = list(kz)\n                kA = dict(zip(kz, range(len(kz))))\n            else:\n                self.default_cols = False\n                for kF in kz:\n                    if kG := self.bb.get(kF):\n                        kD.append(kF)\n                        kA[kF] = RawSQL(*kG)\n                    elif kF in self.ba:\n                        kE.append(kF)\n                        kA[kF] = kF\n                    elif kF in self.annotations:\n                        if self.ba:\n                            raise FieldError(\n                                f\"Cannot select the '{kF}' alias. It was excluded \"\n                                f\"by a previous values() or values_list() call. \"\n                                f\"Include '{kF}' in that call to select it.\"\n                            )\n                        else:\n                            raise FieldError(\n                                f\"Cannot select the '{kF}' alias. Use annotate() \"\n                                f\"to promote it.\"\n                            )\n                    else:\n                        # Call `names_to_path` to ensure a FieldError including\n                        # annotations about to be masked as valid choices if\n                        # `f` is not resolvable.\n                        if self.ba:\n                            self.ar(kF.split(LOOKUP_SEP), self.model._meta)\n                        kA[kF] = len(kC)\n                        kC.append(kF)\n            self.aX(kD)\n            self.aV(kE)\n        else:\n            kC = [kF.attname for kF in self.model._meta.concrete_fields]\n            kA = dict.fromkeys(kC, None)\n        # Selected annotations must be known before setting the GROUP BY\n        # clause.\n        if self.group_by is True:\n            self.aL(\n                (kF.attname for kF in self.model._meta.concrete_fields), False\n            )\n            # Disable GROUP BY aliases to avoid orphaning references to the\n            # SELECT clause which is about to be cleared.\n            self.aP(allow_aliases=False)\n            self.aH()\n        elif self.group_by:\n            # Resolve GROUP BY annotation references if they are not part of\n            # the selected fields anymore.\n            kH = []\n            for kI in self.group_by:\n                if isinstance(kI, Ref) and kI.refs not in kA:\n                    kI = self.annotations[kI.refs]\n                kH.append(kI)\n            self.group_by = tuple(kH)\n\n        self.values_select = tuple(kC)\n        self.aL(kC, True)\n        self.selected = kA if kz else None\n\n    @property\n    def ba(self):\n        \"\"\"\n        Return the dictionary of aggregate columns that are not masked and\n        should be used in the SELECT clause. Cache this result for performance.\n        \"\"\"\n        if self._annotation_select_cache is not None:\n            return self._annotation_select_cache\n        elif not self.annotations:\n            return {}\n        elif self.annotation_select_mask is not None:\n            self._annotation_select_cache = {\n                kJ: kK\n                for kJ, kK in self.annotations.items()\n                if kJ in self.annotation_select_mask\n            }\n            return self._annotation_select_cache\n        else:\n            return self.annotations\n\n    @property\n    def bb(self):\n        if self._extra_select_cache is not None:\n            return self._extra_select_cache\n        if not self.extra:\n            return {}\n        elif self.extra_select_mask is not None:\n            self._extra_select_cache = {\n                kL: kM for kL, kM in self.extra.items() if kL in self.extra_select_mask\n            }\n            return self._extra_select_cache\n        else:\n            return self.extra\n\n    def bc(self, kN):\n        \"\"\"\n        Trim joins from the start of the join path. The candidates for trim\n        are the PathInfos in names_with_path structure that are m2m joins.\n\n        Also set the select column so the start matches the join.\n\n        This method is meant to be used for generating the subquery joins &\n        cols in split_exclude().\n\n        Return a lookup usable for doing outerq.filter(lookup=self) and a\n        boolean indicating if the joins in the prefix contain a LEFT OUTER\n        join.\n        \"\"\"\n        kO = []\n        for kP, kQ in kN:\n            kO.extend(kQ)\n        kR = False\n        # Trim and operate only on tables that were generated for\n        # the lookup part of the query. That is, avoid trimming\n        # joins generated for F() expressions.\n        kS = [\n            kT for kT in self.alias_map if kT in self._lookup_joins or kT == self.g\n        ]\n        for kU, kV in enumerate(kO):\n            if kV.m2m:\n                break\n            if self.alias_map[kS[kU + 1]].join_type == LOUTER:\n                kR = True\n            kW = kS[kU]\n            self.L(kW)\n        # The path.join_field is a Rel, lets get the other side's field\n        kX = kV.join_field.field\n        # Build the filter prefix.\n        kY = kU\n        kZ = []\n        for la, kV in kN:\n            if kY - len(kV) < 0:\n                break\n            kZ.append(la)\n            kY -= len(kV)\n        kZ.append(kX.foreign_related_fields[0].name)\n        kZ = LOOKUP_SEP.join(kZ)\n        # Lets still see if we can trim the first join from the inner query\n        # (that is, self). We can't do this for:\n        # - LEFT JOINs because we would miss those rows that have nothing on\n        #   the outer side,\n        # - INNER JOINs from filtered relations because we would miss their\n        #   filters.\n        lb = self.alias_map[kS[kU + 1]]\n        if lb.join_type != LOUTER and not lb.filtered_relation:\n            lc = [ld[0] for ld in kX.related_fields]\n            le = kS[kU + 1]\n            self.L(kS[kU])\n            lf = kX.get_extra_restriction(\n                None, kS[kU + 1]\n            )\n            if lf:\n                self.where.add(lf, AND)\n        else:\n            # TODO: It might be possible to trim more joins from the start of\n            # the inner query if it happens to have a longer join chain\n            # containing the values in select_fields. Lets punt this one for\n            # now.\n            lc = [ld[1] for ld in kX.related_fields]\n            le = kS[kU]\n        # The found starting point is likely a join_class instead of a\n        # base_table_class reference. But the first entry in the query's FROM\n        # clause must not be a JOIN.\n        for lg in self.alias_map:\n            if self.alias_refcount[lg] > 0:\n                self.alias_map[lg] = self.base_table_class(\n                    self.alias_map[lg].table_name,\n                    lg,\n                )\n                break\n        self.aJ([lh.get_col(le) for lh in lc])\n        return kZ, kR\n\n    def bd(self, li):\n        \"\"\"\n        Check if the given field should be treated as nullable.\n\n        Some backends treat '' as null and Django treats such fields as\n        nullable for those backends. In such situations field.null can be\n        False even if we should treat the field as nullable.\n        \"\"\"\n        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have\n        # (nor should it have) knowledge of which connection is going to be\n        # used. The proper fix would be to defer all decisions where\n        # is_nullable() is needed to the compiler stage, but that is not easy\n        # to do currently.\n        return li.null or (\n            li.empty_strings_allowed\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-d737c5fea4d295f9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "02a94880c1ef3b222170b7afd8afdf993bdf7ed53d5a620a116e36021b88721e", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 2602, "local_path": "identifiers/garble-identifiers/I04__django__Query__463ba585.py", "order": 4, "original_content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "parent_variant_id": "pyint-82246794d74c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/query.py#L232-L2792", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 2285, "identifiers_declared": 611}, "unit_kind": "class", "unit_name": "Query", "variant_id": "pyint-0e08463ba585-I04", "group_id": "py-d737c5fea4d295f9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 285, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9da1fc70c20e-I05", "source": "import copy\nimport difflib\nimport functools\nimport sys\nimport warnings\nfrom collections import Counter, namedtuple\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom itertools import chain, count, product\nfrom string import ascii_uppercase\nfrom django.core.exceptions import FieldDoesNotExist, FieldError\nfrom django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections\nfrom django.db.models.aggregates import Count\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import (\n    BaseExpression,\n    Col,\n    ColPairs,\n    Exists,\n    F,\n    OuterRef,\n    RawSQL,\n    Ref,\n    ResolvedOuterRef,\n    Value,\n)\nfrom django.db.models.fields import Field\nfrom django.db.models.lookups import Lookup\nfrom django.db.models.query_utils import (\n    Q,\n    check_rel_lookup_compatibility,\n    refs_expression,\n)\nfrom django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE\nfrom django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin\nfrom django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode\nfrom django.utils.deprecation import RemovedInDjango70Warning\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.tree import Node\nfrom django.utils.warnings import django_file_prefixes\n\nclass Query(BaseExpression):\n    \"\"\"A single SQL query.\"\"\"\n\n    alias_prefix = \"T\"\n    empty_result_set_value = None\n    subq_aliases = frozenset([alias_prefix])\n\n    compiler = \"SQLCompiler\"\n\n    base_table_class = BaseTable\n    join_class = Join\n\n    default_cols = True\n    default_ordering = True\n    standard_ordering = True\n\n    filter_is_sticky = False\n    subquery = False\n    contains_subquery = False\n\n    # SQL-related attributes.\n    # Select and related select clauses are expressions to use in the SELECT\n    # clause of the query. The select is used for cases where we want to set up\n    # the select clause to contain other than default fields (values(),\n    # subqueries...). Note that annotations go to annotations dictionary.\n    select = ()\n    # The group_by attribute can have one of the following forms:\n    #  - None: no group by at all in the query\n    #  - A tuple of expressions: group by (at least) those expressions.\n    #    String refs are also allowed for now.\n    #  - True: group by all select fields of the model\n    # See compiler.get_group_by() for details.\n    group_by = None\n    order_by = ()\n    low_mark = 0x0  # Used for offset/limit.\n    high_mark = None  # Used for offset/limit.\n    distinct = False\n    distinct_fields = ()\n    select_for_update = False\n    select_for_update_nowait = False\n    select_for_update_skip_locked = False\n    select_for_update_of = ()\n    select_for_no_key_update = False\n    select_related = False\n    # Arbitrary limit for select_related to prevents infinite recursion.\n    max_depth = 0x5\n    # Holds the selects defined by a call to values() or values_list()\n    # excluding annotation_select and extra_select.\n    values_select = ()\n    selected = None\n\n    # SQL annotation-related attributes.\n    annotation_select_mask = None\n    _annotation_select_cache = None\n\n    # Set combination attributes.\n    combinator = None\n    combinator_all = False\n    combined_queries = ()\n\n    # These are for extensions. The contents are more or less appended verbatim\n    # to the appropriate clause.\n    extra_select_mask = None\n    _extra_select_cache = None\n\n    extra_tables = ()\n    extra_order_by = ()\n\n    # A tuple that is a set of model field names and either True, if these are\n    # the fields to defer, or False if these are the only fields to load.\n    deferred_loading = (frozenset(), True)\n\n    explain_info = None\n\n    def __init__(self, model, alias_cols=True):\n        self.model = model\n        self.alias_refcount = {}\n        # alias_map is the most important data structure regarding joins.\n        # It's used for recording which joins exist in the query and what\n        # types they are. The key is the alias of the joined table (possibly\n        # the table name) and the value is a Join-like object (see\n        # sql.datastructures.Join for more information).\n        self.alias_map = {}\n        # Whether to provide alias to columns during reference resolving.\n        self.alias_cols = alias_cols\n        # Sometimes the query contains references to aliases in outer queries\n        # (as a result of split_exclude). Correct alias quoting needs to know\n        # these aliases too. Map external tables to whether they are aliased.\n        self.external_aliases = {}\n        self.table_map = {}  # Maps table names to list of aliases.\n        self.used_aliases = set()\n\n        self.where = WhereNode()\n        # Maps alias -> Annotation Expression.\n        self.annotations = {}\n        # These are for extensions. The contents are more or less appended\n        # verbatim to the appropriate clause.\n        self.extra = {}  # Maps col_alias -> (col_sql, params).\n\n        self._filtered_relations = {}\n\n    @property\n    def output_field(self):\n        if len(self.select) == 0x1:\n            select = self.select[0x0]\n            return getattr(select, \"target\", None) or select.field\n        elif len(self.annotation_select) == 0x1:\n            return next(iter(self.annotation_select.values())).output_field\n\n    @cached_property\n    def base_table(self):\n        for alias in self.alias_map:\n            return alias\n\n    def __str__(self):\n        \"\"\"\n        Return the query as a string of SQL with the parameter values\n        substituted in (use sql_with_params() to see the unsubstituted string).\n\n        Parameter values won't necessarily be quoted correctly, since that is\n        done by the database interface at execution time.\n        \"\"\"\n        sql, params = self.sql_with_params()\n        return sql % params\n\n    def sql_with_params(self):\n        \"\"\"\n        Return the query as an SQL string and the parameters that will be\n        substituted into the query.\n        \"\"\"\n        return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()\n\n    def __deepcopy__(self, memo):\n        \"\"\"Limit the amount of work when a Query is deepcopied.\"\"\"\n        result = self.clone()\n        memo[id(self)] = result\n        return result\n\n    def get_compiler(self, using=None, connection=None, elide_empty=True):\n        if using is None and connection is None:\n            raise ValueError(\"Need either using or connection\")\n        if using:\n            connection = connections[using]\n        return connection.ops.compiler(self.compiler)(\n            self, connection, using, elide_empty\n        )\n\n    def get_meta(self):\n        \"\"\"\n        Return the Options instance (the model._meta) from which to start\n        processing. Normally, this is self.model._meta, but it can be changed\n        by subclasses.\n        \"\"\"\n        if self.model:\n            return self.model._meta\n\n    def clone(self):\n        \"\"\"\n        Return a copy of the current Query. A lightweight alternative to\n        deepcopy().\n        \"\"\"\n        obj = Empty()\n        obj.__class__ = self.__class__\n        # Copy references to everything.\n        obj.__dict__ = self.__dict__.copy()\n        # Clone attributes that can't use shallow copy.\n        obj.alias_refcount = self.alias_refcount.copy()\n        obj.alias_map = self.alias_map.copy()\n        obj.external_aliases = self.external_aliases.copy()\n        obj.table_map = self.table_map.copy()\n        obj.where = self.where.clone()\n        obj.annotations = self.annotations.copy()\n        if self.annotation_select_mask is not None:\n            obj.annotation_select_mask = self.annotation_select_mask.copy()\n        if self.combined_queries:\n            obj.combined_queries = tuple(\n                [query.clone() for query in self.combined_queries]\n            )\n        # _annotation_select_cache cannot be copied, as doing so breaks the\n        # (necessary) state in which both annotations and\n        # _annotation_select_cache point to the same underlying objects.\n        # It will get re-populated in the cloned queryset the next time it's\n        # used.\n        obj._annotation_select_cache = None\n        obj.extra = self.extra.copy()\n        if self.extra_select_mask is not None:\n            obj.extra_select_mask = self.extra_select_mask.copy()\n        if self._extra_select_cache is not None:\n            obj._extra_select_cache = self._extra_select_cache.copy()\n        if self.select_related is not False:\n            # Use deepcopy because select_related stores fields in nested\n            # dicts.\n            obj.select_related = copy.deepcopy(obj.select_related)\n        if \"subq_aliases\" in self.__dict__:\n            obj.subq_aliases = self.subq_aliases.copy()\n        obj.used_aliases = self.used_aliases.copy()\n        obj._filtered_relations = self._filtered_relations.copy()\n        # Clear the cached_property, if it exists.\n        obj.__dict__.pop(\"base_table\", None)\n        return obj\n\n    def chain(self, klass=None):\n        \"\"\"\n        Return a copy of the current Query that's ready for another operation.\n        The klass argument changes the type of the Query, e.g. UpdateQuery.\n        \"\"\"\n        obj = self.clone()\n        if klass and obj.__class__ != klass:\n            obj.__class__ = klass\n        if not obj.filter_is_sticky:\n            obj.used_aliases = set()\n        obj.filter_is_sticky = False\n        if hasattr(obj, \"_setup_query\"):\n            obj._setup_query()\n        return obj\n\n    def relabeled_clone(self, change_map):\n        clone = self.clone()\n        clone.change_aliases(change_map)\n        return clone\n\n    def _get_col(self, target, field, alias):\n        if not self.alias_cols:\n            alias = None\n        return target.get_col(alias, field)\n\n    def get_aggregation(self, using, aggregate_exprs):\n        \"\"\"\n        Return the dictionary with the values of the existing aggregations.\n        \"\"\"\n        if not aggregate_exprs:\n            return {}\n        # Store annotation mask prior to temporarily adding aggregations for\n        # resolving purpose to facilitate their subsequent removal.\n        refs_subquery = False\n        refs_window = False\n        replacements = {}\n        annotation_select_mask = self.annotation_select_mask\n        for alias, aggregate_expr in aggregate_exprs.items():\n            self.check_alias(alias)\n            aggregate = aggregate_expr.resolve_expression(\n                self, allow_joins=True, reuse=None, summarize=True\n            )\n            if not aggregate.contains_aggregate:\n                raise TypeError(\"%s is not an aggregate expression\" % alias)\n            # Temporarily add aggregate to annotations to allow remaining\n            # members of `aggregates` to resolve against each others.\n            self.append_annotation_mask([alias])\n            aggregate_refs = aggregate.get_refs()\n            refs_subquery |= any(\n                getattr(self.annotations[ref], \"contains_subquery\", False)\n                for ref in aggregate_refs\n            )\n            refs_window |= any(\n                getattr(self.annotations[ref], \"contains_over_clause\", True)\n                for ref in aggregate_refs\n            )\n            aggregate = aggregate.replace_expressions(replacements)\n            self.annotations[alias] = aggregate\n            replacements[Ref(alias, aggregate)] = aggregate\n        # Stash resolved aggregates now that they have been allowed to resolve\n        # against each other.\n        aggregates = {alias: self.annotations.pop(alias) for alias in aggregate_exprs}\n        self.set_annotation_mask(annotation_select_mask)\n        # Existing usage of aggregation can be determined by the presence of\n        # selected aggregates but also by filters against aliased aggregates.\n        _, having, qualify = self.where.split_having_qualify()\n        has_existing_aggregation = (\n            any(\n                getattr(annotation, \"contains_aggregate\", True)\n                for annotation in self.annotations.values()\n            )\n            or having\n        )\n        set_returning_annotations = {\n            alias\n            for alias, annotation in self.annotation_select.items()\n            if getattr(annotation, \"set_returning\", False)\n        }\n        # Decide if we need to use a subquery.\n        #\n        # Existing aggregations would cause incorrect results as\n        # get_aggregation() must produce just one result and thus must not use\n        # GROUP BY.\n        #\n        # If the query has limit or distinct, or uses set operations, then\n        # those operations must be done in a subquery so that the query\n        # aggregates on the limit and/or distinct results instead of applying\n        # the distinct and limit after the aggregation.\n        if (\n            isinstance(self.group_by, tuple)\n            or self.is_sliced\n            or has_existing_aggregation\n            or refs_subquery\n            or refs_window\n            or qualify\n            or self.distinct\n            or self.combinator\n            or set_returning_annotations\n        ):\n            from django.db.models.sql.subqueries import AggregateQuery\n\n            inner_query = self.clone()\n            inner_query.subquery = True\n            outer_query = AggregateQuery(self.model, inner_query)\n            inner_query.select_for_update = False\n            inner_query.select_related = False\n            inner_query.set_annotation_mask(self.annotation_select)\n            # Queries with distinct_fields need ordering and when a limit is\n            # applied we must take the slice from the ordered query. Otherwise\n            # no need for ordering.\n            if inner_query.orderby_issubset_groupby:\n                inner_query.clear_ordering(force=False)\n            if not inner_query.distinct:\n                # If the inner query uses default select and it has some\n                # aggregate annotations, then we must make sure the inner\n                # query is grouped by the main model's primary key. However,\n                # clearing the select clause can alter results if distinct is\n                # used.\n                if inner_query.default_cols and has_existing_aggregation:\n                    inner_query.group_by = (\n                        self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                    )\n                inner_query.default_cols = False\n                if not qualify and not self.combinator:\n                    # Mask existing annotations that are not referenced by\n                    # aggregates to be pushed to the outer query unless\n                    # filtering against window functions or if the query is\n                    # combined as both would require complex realiasing logic.\n                    annotation_mask = set()\n                    if isinstance(self.group_by, tuple):\n                        for expr in self.group_by:\n                            annotation_mask |= expr.get_refs()\n                    for aggregate in aggregates.values():\n                        annotation_mask |= aggregate.get_refs()\n                    # Avoid eliding expressions that might have an incidence on\n                    # the implicit grouping logic.\n                    for annotation_alias, annotation in self.annotation_select.items():\n                        if annotation.get_group_by_cols():\n                            annotation_mask.add(annotation_alias)\n                    inner_query.set_annotation_mask(annotation_mask)\n                    # Annotations that possibly return multiple rows cannot\n                    # be masked as they might have an incidence on the query.\n                    annotation_mask |= set_returning_annotations\n\n            # Add aggregates to the outer AggregateQuery. This requires making\n            # sure all columns referenced by the aggregates are selected in the\n            # inner query. It is achieved by retrieving all column references\n            # by the aggregates, explicitly selecting them in the inner query,\n            # and making sure the aggregates are repointed to them.\n            col_refs = {}\n            for alias, aggregate in aggregates.items():\n                replacements = {}\n                for col in self._gen_cols([aggregate], resolve_refs=False):\n                    if not (col_ref := col_refs.get(col)):\n                        index = len(col_refs) + 0x1\n                        col_alias = f\"__col{index}\"\n                        col_ref = Ref(col_alias, col)\n                        col_refs[col] = col_ref\n                        inner_query.add_annotation(col, col_alias)\n                    replacements[col] = col_ref\n                outer_query.annotations[alias] = aggregate.replace_expressions(\n                    replacements\n                )\n            if (\n                inner_query.select == ()\n                and not inner_query.default_cols\n                and not inner_query.annotation_select_mask\n            ):\n                # In case of Model.objects[0:3].count(), there would be no\n                # field selected in the inner query, yet we must use a\n                # subquery. So, make sure at least one field is selected.\n                inner_query.select = (\n                    self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                )\n        else:\n            outer_query = self\n            self.select = ()\n            self.selected = None\n            self.default_cols = False\n            self.extra = {}\n            if self.annotations:\n                # Inline reference to existing annotations and mask them as\n                # they are unnecessary given only the summarized aggregations\n                # are requested.\n                replacements = {\n                    Ref(alias, annotation): annotation\n                    for alias, annotation in self.annotations.items()\n                }\n                self.annotations = {\n                    alias: aggregate.replace_expressions(replacements)\n                    for alias, aggregate in aggregates.items()\n                }\n            else:\n                self.annotations = aggregates\n            self.set_annotation_mask(aggregates)\n\n        empty_set_result = [\n            expression.empty_result_set_value\n            for expression in outer_query.annotation_select.values()\n        ]\n        elide_empty = not any(result is NotImplemented for result in empty_set_result)\n        outer_query.clear_ordering(force=True)\n        outer_query.clear_limits()\n        outer_query.select_for_update = False\n        outer_query.select_related = False\n        compiler = outer_query.get_compiler(using, elide_empty=elide_empty)\n        result = compiler.execute_sql(SINGLE)\n        if result is None:\n            result = empty_set_result\n        else:\n            cols = outer_query.annotation_select.values()\n            converters = compiler.get_converters(cols)\n            rows = compiler.apply_converters((result,), converters)\n            if compiler.has_composite_fields(cols):\n                rows = compiler.composite_fields_to_tuples(rows, cols)\n            result = next(rows)\n\n        return dict(zip(outer_query.annotation_select, result))\n\n    def get_count(self, using):\n        \"\"\"\n        Perform a COUNT() query using the current filter constraints.\n        \"\"\"\n        obj = self.clone()\n        return obj.get_aggregation(using, {\"__count\": Count(\"*\")})[\"__count\"]\n\n    def has_filters(self):\n        return self.where\n\n    def exists(self, limit=True):\n        q = self.clone()\n        if not (q.distinct and q.is_sliced):\n            if q.group_by is True:\n                q.add_fields(\n                    (f.attname for f in self.model._meta.concrete_fields), False\n                )\n                # Disable GROUP BY aliases to avoid orphaning references to the\n                # SELECT clause which is about to be cleared.\n                q.set_group_by(allow_aliases=False)\n            q.clear_select_clause()\n        if q.combined_queries and q.combinator == \"union\":\n            q.combined_queries = tuple(\n                combined_query.exists(limit=False)\n                for combined_query in q.combined_queries\n            )\n        q.clear_ordering(force=True)\n        if limit is True:\n            q.set_limits(high=0x1)\n        q.add_annotation(Value(0x1), \"a\")\n        return q\n\n    def has_results(self, using):\n        q = self.exists()\n        compiler = q.get_compiler(using=using)\n        return compiler.has_results()\n\n    def explain(self, using, format=None, **options):\n        q = self.clone()\n        for option_name in options:\n            if (\n                not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)\n                or \"--\" in option_name\n            ):\n                raise ValueError(f\"Invalid option name: {option_name!r}.\")\n        q.explain_info = ExplainInfo(format, options)\n        compiler = q.get_compiler(using=using)\n        return \"\\n\".join(compiler.explain_query())\n\n    def combine(self, rhs, connector):\n        \"\"\"\n        Merge the 'rhs' query into the current one (with any 'rhs' effects\n        being applied *after* (that is, \"to the right of\") anything in the\n        current query. 'rhs' is not modified during a call to this function.\n\n        The 'connector' parameter describes how to connect filters from the\n        'rhs' query.\n        \"\"\"\n        if self.model != rhs.model:\n            raise TypeError(\"Cannot combine queries on two different base models.\")\n        if self.is_sliced:\n            raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n        if self.distinct != rhs.distinct:\n            raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n        if self.distinct_fields != rhs.distinct_fields:\n            raise TypeError(\"Cannot combine queries with different distinct fields.\")\n\n        # If lhs and rhs shares the same alias prefix, it is possible to have\n        # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up\n        # as T4 -> T6 while combining two querysets. To prevent this, change an\n        # alias prefix of the rhs and update current aliases accordingly,\n        # except if the alias is the base table since it must be present in the\n        # query on both sides.\n        initial_alias = self.get_initial_alias()\n        rhs = rhs.clone()\n        rhs.bump_prefix(self, exclude={initial_alias})\n\n        # Work out how to relabel the rhs aliases, if necessary.\n        change_map = {}\n        conjunction = connector == AND\n\n        # Determine which existing joins can be reused. When combining the\n        # query with AND we must recreate all joins for m2m filters. When\n        # combining with OR we can reuse joins. The reason is that in AND\n        # case a single row can't fulfill a condition like:\n        #     revrel__col=1 & revrel__col=2\n        # But, there might be two different related rows matching this\n        # condition. In OR case a single True is enough, so single row is\n        # enough, too.\n        #\n        # Note that we will be creating duplicate joins for non-m2m joins in\n        # the AND case. The results will be correct but this creates too many\n        # joins. This is something that could be fixed later on.\n        reuse = set() if conjunction else set(self.alias_map)\n        joinpromoter = JoinPromoter(connector, 0x2, False)\n        joinpromoter.add_votes(\n            j for j in self.alias_map if self.alias_map[j].join_type == INNER\n        )\n        rhs_votes = set()\n        # Now, add the joins from rhs query into the new query (skipping base\n        # table).\n        rhs_tables = list(rhs.alias_map)[0x1:]\n        for alias in rhs_tables:\n            join = rhs.alias_map[alias]\n            # If the left side of the join was already relabeled, use the\n            # updated alias.\n            join = join.relabeled_clone(change_map)\n            new_alias = self.join(join, reuse=reuse)\n            if join.join_type == INNER:\n                rhs_votes.add(new_alias)\n            # We can't reuse the same join again in the query. If we have two\n            # distinct joins for the same connection in rhs query, then the\n            # combined query must have two joins, too.\n            reuse.discard(new_alias)\n            if alias != new_alias:\n                change_map[alias] = new_alias\n            if not rhs.alias_refcount[alias]:\n                # The alias was unused in the rhs query. Unref it so that it\n                # will be unused in the new query, too. We have to add and\n                # unref the alias so that join promotion has information of\n                # the join type for the unused alias.\n                self.unref_alias(new_alias)\n        joinpromoter.add_votes(rhs_votes)\n        joinpromoter.update_join_types(self)\n\n        # Combine subqueries aliases to ensure aliases relabelling properly\n        # handle subqueries when combining where and select clauses.\n        self.subq_aliases |= rhs.subq_aliases\n\n        # Now relabel a copy of the rhs where-clause and add it to the current\n        # one.\n        w = rhs.where.clone()\n        w.relabel_aliases(change_map)\n        self.where.add(w, connector)\n\n        # Selection columns and extra extensions are those provided by 'rhs'.\n        if rhs.select:\n            self.set_select([col.relabeled_clone(change_map) for col in rhs.select])\n        else:\n            self.select = ()\n\n        if connector == OR:\n            # It would be nice to be able to handle this, but the queries don't\n            # really make sense (or return consistent value sets). Not worth\n            # the extra complexity when you can write a real query instead.\n            if self.extra and rhs.extra:\n                raise ValueError(\n                    \"When merging querysets using 'or', you cannot have \"\n                    \"extra(select=...) on both sides.\"\n                )\n        self.extra.update(rhs.extra)\n        extra_select_mask = set()\n        if self.extra_select_mask is not None:\n            extra_select_mask.update(self.extra_select_mask)\n        if rhs.extra_select_mask is not None:\n            extra_select_mask.update(rhs.extra_select_mask)\n        if extra_select_mask:\n            self.set_extra_mask(extra_select_mask)\n        self.extra_tables += rhs.extra_tables\n\n        # Ordering uses the 'rhs' ordering, unless it has none, in which case\n        # the current ordering is used.\n        self.order_by = rhs.order_by or self.order_by\n        self.extra_order_by = rhs.extra_order_by or self.extra_order_by\n\n    def _get_defer_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # All concrete fields and related objects that are not part of the\n        # defer mask must be included. If a relational field is encountered it\n        # gets added to the mask for it be considered if `select_related` and\n        # the cycle continues by recursively calling this function.\n        for field in opts.concrete_fields + opts.related_objects:\n            field_mask = mask.pop(field.name, None)\n            field_att_mask = None\n            if field_attname := getattr(field, \"attname\", None):\n                field_att_mask = mask.pop(field_attname, None)\n            if field_mask is None and field_att_mask is None:\n                select_mask.setdefault(field, {})\n            elif field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                # Virtual fields such as many-to-many and generic foreign keys\n                # cannot be effectively deferred. Historically, they were\n                # allowed to be passed to QuerySet.defer(). Ignore such field\n                # references until a layer of validation at mask alteration\n                # time is eventually implemented.\n                if field.many_to_many:\n                    continue\n                field_select_mask = select_mask.setdefault(field, {})\n                related_model = field.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        # Remaining defer entries must be references to filtered relations\n        # otherwise they are surfaced as missing field errors.\n        for field_name, field_mask in mask.items():\n            if filtered_relation := self._filtered_relations.get(field_name):\n                relation = opts.get_field(filtered_relation.relation_name)\n                field_select_mask = select_mask.setdefault((field_name, relation), {})\n                related_model = relation.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n            else:\n                opts.get_field(field_name)\n        return select_mask\n\n    def _get_only_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # Only include fields mentioned in the mask.\n        for field_name, field_mask in mask.items():\n            field = opts.get_field(field_name)\n            field_select_mask = select_mask.setdefault(field, {})\n            if field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                related_model = field.remote_field.model._meta.concrete_model\n                self._get_only_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        return select_mask\n\n    def get_select_mask(self):\n        \"\"\"\n        Convert the self.deferred_loading data structure to an alternate data\n        structure, describing the field that *will* be loaded. This is used to\n        compute the columns to select from the database and also by the\n        QuerySet class to work out which fields are being initialized on each\n        model. Models that have all their fields included aren't mentioned in\n        the result, only those that have field restrictions in place.\n        \"\"\"\n        field_names, defer = self.deferred_loading\n        if not field_names:\n            return {}\n        mask = {}\n        for field_name in field_names:\n            part_mask = mask\n            for part in field_name.split(LOOKUP_SEP):\n                part_mask = part_mask.setdefault(part, {})\n        opts = self.get_meta()\n        if defer:\n            return self._get_defer_select_mask(opts, mask)\n        return self._get_only_select_mask(opts, mask)\n\n    def table_alias(self, table_name, create=False, filtered_relation=None):\n        \"\"\"\n        Return a table alias for the given table_name and whether this is a\n        new alias or not.\n\n        If 'create' is true, a new alias is always created. Otherwise, the\n        most recently created alias for the table (if one exists) is reused.\n        \"\"\"\n        alias_list = self.table_map.get(table_name)\n        if not create and alias_list:\n            alias = alias_list[0x0]\n            self.alias_refcount[alias] += 0x1\n            return alias, False\n\n        # Create a new alias for this table.\n        if alias_list:\n            alias = \"%s%d\" % (self.alias_prefix, len(self.alias_map) + 0x1)\n            alias_list.append(alias)\n        else:\n            # The first occurrence of a table uses the table name directly.\n            alias = (\n                filtered_relation.alias if filtered_relation is not None else table_name\n            )\n            self.table_map[table_name] = [alias]\n        self.alias_refcount[alias] = 0x1\n        return alias, True\n\n    def ref_alias(self, alias):\n        \"\"\"Increases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] += 0x1\n\n    def unref_alias(self, alias, amount=0x1):\n        \"\"\"Decreases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] -= amount\n\n    def promote_joins(self, aliases):\n        \"\"\"\n        Promote recursively the join type of given aliases and its children to\n        an outer join. If 'unconditional' is False, only promote the join if\n        it is nullable or the parent join is an outer join.\n\n        The children promotion is done to avoid join chains that contain a\n        LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b\n        is promoted, then we must also promote b->c automatically, or otherwise\n        the promotion of a->b doesn't actually change anything in the query\n        results.\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0x0)\n            if self.alias_map[alias].join_type is None:\n                # This is the base table (first FROM entry) - this table\n                # isn't really joined at all in the query, so we should not\n                # alter its join type.\n                continue\n            # Only the first alias (skipped above) should have None join_type\n            assert self.alias_map[alias].join_type is not None\n            parent_alias = self.alias_map[alias].parent_alias\n            parent_louter = (\n                parent_alias and self.alias_map[parent_alias].join_type == LOUTER\n            )\n            already_louter = self.alias_map[alias].join_type == LOUTER\n            if (self.alias_map[alias].nullable or parent_louter) and not already_louter:\n                self.alias_map[alias] = self.alias_map[alias].promote()\n                # Join type of 'alias' changed, so re-examine all aliases that\n                # refer to this one.\n                aliases.extend(\n                    join\n                    for join in self.alias_map\n                    if self.alias_map[join].parent_alias == alias\n                    and join not in aliases\n                )\n\n    def demote_joins(self, aliases):\n        \"\"\"\n        Change join type from LOUTER to INNER for all joins in aliases.\n\n        Similarly to promote_joins(), this method must ensure no join chains\n        containing first an outer, then an inner join are generated. If we\n        are demoting b->c join in chain a LOUTER b LOUTER c then we must\n        demote a->b automatically, or otherwise the demotion of b->c doesn't\n        actually change anything in the query results. .\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0x0)\n            if self.alias_map[alias].join_type == LOUTER:\n                self.alias_map[alias] = self.alias_map[alias].demote()\n                parent_alias = self.alias_map[alias].parent_alias\n                if self.alias_map[parent_alias].join_type == INNER:\n                    aliases.append(parent_alias)\n\n    def reset_refcounts(self, to_counts):\n        \"\"\"\n        Reset reference counts for aliases so that they match the value passed\n        in `to_counts`.\n        \"\"\"\n        for alias, cur_refcount in self.alias_refcount.copy().items():\n            unref_amount = cur_refcount - to_counts.get(alias, 0x0)\n            self.unref_alias(alias, unref_amount)\n\n    def change_aliases(self, change_map):\n        \"\"\"\n        Change the aliases in change_map (which maps old-alias -> new-alias),\n        relabelling any references to them in select columns and the where\n        clause.\n        \"\"\"\n        if not change_map:\n            return self\n        # If keys and values of change_map were to intersect, an alias might be\n        # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending\n        # on their order in change_map.\n        assert set(change_map).isdisjoint(change_map.values())\n\n        # 1. Update references in \"select\" (normal columns plus aliases),\n        # \"group by\" and \"where\".\n        self.where.relabel_aliases(change_map)\n        if isinstance(self.group_by, tuple):\n            self.group_by = tuple(\n                [col.relabeled_clone(change_map) for col in self.group_by]\n            )\n        self.select = tuple([col.relabeled_clone(change_map) for col in self.select])\n        self.annotations = self.annotations and {\n            key: col.relabeled_clone(change_map)\n            for key, col in self.annotations.items()\n        }\n\n        # 2. Rename the alias in the internal table/alias datastructures.\n        for old_alias, new_alias in change_map.items():\n            if old_alias not in self.alias_map:\n                continue\n            alias_data = self.alias_map[old_alias].relabeled_clone(change_map)\n            self.alias_map[new_alias] = alias_data\n            self.alias_refcount[new_alias] = self.alias_refcount[old_alias]\n            del self.alias_refcount[old_alias]\n            del self.alias_map[old_alias]\n\n            table_aliases = self.table_map[alias_data.table_name]\n            for pos, alias in enumerate(table_aliases):\n                if alias == old_alias:\n                    table_aliases[pos] = new_alias\n                    break\n\n        # 3. Rename the direct external aliases and the ones of combined\n        # queries (union, intersection, difference).\n        self.external_aliases = {\n            # Table is aliased or it's being changed and thus is aliased.\n            change_map.get(alias, alias): (aliased or alias in change_map)\n            for alias, aliased in self.external_aliases.items()\n        }\n        for combined_query in self.combined_queries:\n            external_change_map = {\n                alias: aliased\n                for alias, aliased in change_map.items()\n                if alias in combined_query.external_aliases\n            }\n            combined_query.change_aliases(external_change_map)\n\n    def bump_prefix(self, other_query, exclude=None):\n        \"\"\"\n        Change the alias prefix to the next letter in the alphabet in a way\n        that the other query's aliases and this query's aliases will not\n        conflict. Even tables that previously had no alias will get an alias\n        after this call. To prevent changing aliases use the exclude parameter.\n        \"\"\"\n\n        def prefix_gen():\n            \"\"\"\n            Generate a sequence of characters in alphabetical order:\n                -> 'A', 'B', 'C', ...\n\n            When the alphabet is finished, the sequence will continue with the\n            Cartesian product:\n                -> 'AA', 'AB', 'AC', ...\n            \"\"\"\n            alphabet = ascii_uppercase\n            prefix = chr(ord(self.alias_prefix) + 0x1)\n            yield prefix\n            for n in count(0x1):\n                seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet\n                for s in product(seq, repeat=n):\n                    yield \"\".join(s)\n                prefix = None\n\n        if self.alias_prefix != other_query.alias_prefix:\n            # No clashes between self and outer query should be possible.\n            return\n\n        # Explicitly avoid infinite loop. The constant divider is based on how\n        # much depth recursive subquery references add to the stack. This value\n        # might need to be adjusted when adding or removing function calls from\n        # the code path in charge of performing these operations.\n        local_recursion_limit = sys.getrecursionlimit() // 0x10\n        for pos, prefix in enumerate(prefix_gen()):\n            if prefix not in self.subq_aliases:\n                self.alias_prefix = prefix\n                break\n            if pos > local_recursion_limit:\n                raise RecursionError(\n                    \"Maximum recursion depth exceeded: too many subqueries.\"\n                )\n        self.subq_aliases = self.subq_aliases.union([self.alias_prefix])\n        other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases)\n        if exclude is None:\n            exclude = {}\n        self.change_aliases(\n            {\n                alias: \"%s%d\" % (self.alias_prefix, pos)\n                for pos, alias in enumerate(self.alias_map)\n                if alias not in exclude\n            }\n        )\n\n    def get_initial_alias(self):\n        \"\"\"\n        Return the first alias for this query, after increasing its reference\n        count.\n        \"\"\"\n        if self.alias_map:\n            alias = self.base_table\n            self.ref_alias(alias)\n        elif self.model:\n            alias = self.join(self.base_table_class(self.get_meta().db_table, None))\n        else:\n            alias = None\n        return alias\n\n    def count_active_tables(self):\n        \"\"\"\n        Return the number of tables in this query with a non-zero reference\n        count. After execution, the reference counts are zeroed, so tables\n        added in compiler will not be seen by this method.\n        \"\"\"\n        return len([0x1 for count in self.alias_refcount.values() if count])\n\n    def join(self, join, reuse=None):\n        \"\"\"\n        Return an alias for the 'join', either reusing an existing alias for\n        that join or creating a new one. 'join' is either a base_table_class or\n        join_class.\n\n        The 'reuse' parameter can be either None which means all joins are\n        reusable, or it can be a set containing the aliases that can be reused.\n\n        A join is always created as LOUTER if the lhs alias is LOUTER to make\n        sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new\n        joins are created as LOUTER if the join is nullable.\n        \"\"\"\n        reuse_aliases = [\n            a\n            for a, j in self.alias_map.items()\n            if (reuse is None or a in reuse) and j == join\n        ]\n        if reuse_aliases:\n            if join.table_alias in reuse_aliases:\n                reuse_alias = join.table_alias\n            else:\n                # Reuse the most recent alias of the joined table\n                # (a many-to-many relation may be joined multiple times).\n                reuse_alias = reuse_aliases[-0x1]\n            self.ref_alias(reuse_alias)\n            return reuse_alias\n\n        # No reuse is possible, so we need a new alias.\n        alias, _ = self.table_alias(\n            join.table_name, create=True, filtered_relation=join.filtered_relation\n        )\n        if join.join_type:\n            if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:\n                join_type = LOUTER\n            else:\n                join_type = INNER\n            join.join_type = join_type\n        join.table_alias = alias\n        self.alias_map[alias] = join\n        if filtered_relation := join.filtered_relation:\n            resolve_reuse = reuse\n            if resolve_reuse is not None:\n                resolve_reuse = set(reuse) | {alias}\n            joins_len = len(self.alias_map)\n            join.filtered_relation = filtered_relation.resolve_expression(\n                self, reuse=resolve_reuse\n            )\n            # Some joins were during expression resolving, they must be present\n            # before the one we just added.\n            if joins_len < len(self.alias_map):\n                self.alias_map[alias] = self.alias_map.pop(alias)\n        return alias\n\n    def join_parent_model(self, opts, model, alias, seen):\n        \"\"\"\n        Make sure the given 'model' is joined in the query. If 'model' isn't\n        a parent of 'opts' or if it is None this method is a no-op.\n\n        The 'alias' is the root alias for starting the join, 'seen' is a dict\n        of model -> alias of existing joins. It must also contain a mapping\n        of None -> some alias. This will be returned in the no-op case.\n        \"\"\"\n        if model in seen:\n            return seen[model]\n        chain = opts.get_base_chain(model)\n        if not chain:\n            return alias\n        curr_opts = opts\n        for int_model in chain:\n            if int_model in seen:\n                curr_opts = int_model._meta\n                alias = seen[int_model]\n                continue\n            # Proxy model have elements in base chain\n            # with no parents, assign the new options\n            # object and skip to the next base in that\n            # case\n            if not curr_opts.parents[int_model]:\n                curr_opts = int_model._meta\n                continue\n            link_field = curr_opts.get_ancestor_link(int_model)\n            join_info = self.setup_joins([link_field.name], curr_opts, alias)\n            curr_opts = int_model._meta\n            alias = seen[int_model] = join_info.joins[-0x1]\n        return alias or seen[None]\n\n    def check_alias(self, alias):\n        # RemovedInDjango70Warning: When the deprecation ends, remove.\n        if \"%\" in alias:\n            warnings.warn(\n                \"Using percent signs in a column alias is deprecated.\",\n                category=RemovedInDjango70Warning,\n                skip_file_prefixes=django_file_prefixes(),\n            )\n        if FORBIDDEN_ALIAS_PATTERN.search(alias):\n            raise ValueError(\n                \"Column aliases cannot contain whitespace characters, hashes, \"\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # \"control characters, quotation marks, semicolons, percent \"\n                # \"signs, or SQL comments.\"\n                \"control characters, quotation marks, semicolons, or SQL comments.\"\n            )\n\n    def add_annotation(self, annotation, alias, select=True):\n        \"\"\"Add a single annotation expression to the Query.\"\"\"\n        self.check_alias(alias)\n        annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None)\n        if select:\n            self.append_annotation_mask([alias])\n        else:\n            self.set_annotation_mask(set(self.annotation_select).difference({alias}))\n        self.annotations[alias] = annotation\n        if select and self.selected:\n            self.selected[alias] = alias\n\n    @property\n    def _subquery_fields_len(self):\n        if not self.has_select_fields or not self.select:\n            return len(self.model._meta.pk_fields)\n        return len(self.select) + sum(\n            len(expr.targets) - 0x1 for expr in self.select if isinstance(expr, ColPairs)\n        )\n\n    def resolve_expression(self, query, *args, **kwargs):\n        clone = self.clone()\n        # Subqueries need to use a different set of aliases than the outer\n        # query.\n        clone.bump_prefix(query)\n        clone.subquery = True\n        clone.where.resolve_expression(query, *args, **kwargs)\n        # Resolve combined queries.\n        if clone.combinator:\n            clone.combined_queries = tuple(\n                [\n                    combined_query.resolve_expression(query, *args, **kwargs)\n                    for combined_query in clone.combined_queries\n                ]\n            )\n        for key, value in clone.annotations.items():\n            resolved = value.resolve_expression(query, *args, **kwargs)\n            if hasattr(resolved, \"external_aliases\"):\n                resolved.external_aliases.update(clone.external_aliases)\n            clone.annotations[key] = resolved\n        # Outer query's aliases are considered external.\n        for alias, table in query.alias_map.items():\n            clone.external_aliases[alias] = (\n                isinstance(table, Join)\n                and table.join_field.related_model._meta.db_table != alias\n            ) or (\n                isinstance(table, BaseTable) and table.table_name != table.table_alias\n            )\n        return clone\n\n    def get_external_cols(self):\n        exprs = chain(self.annotations.values(), self.where.children)\n        return [\n            col\n            for col in self._gen_cols(exprs, include_external=True)\n            if col.alias in self.external_aliases\n        ]\n\n    def get_group_by_cols(self, wrapper=None):\n        # If wrapper is referenced by an alias for an explicit GROUP BY through\n        # values() a reference to this expression and not the self must be\n        # returned to ensure external column references are not grouped against\n        # as well.\n        external_cols = self.get_external_cols()\n        if any(col.possibly_multivalued for col in external_cols):\n            return [wrapper or self]\n        return external_cols\n\n    def as_sql(self, compiler, connection):\n        # Some backends (e.g. Oracle) raise an error when a subquery contains\n        # unnecessary ORDER BY clause.\n        if (\n            self.subquery\n            and not connection.features.ignores_unnecessary_order_by_in_subqueries\n        ):\n            self.clear_ordering(force=False)\n            for query in self.combined_queries:\n                query.clear_ordering(force=False)\n        sql, params = self.get_compiler(connection=connection).as_sql()\n        if self.subquery:\n            sql = \"(%s)\" % sql\n        return sql, params\n\n    def resolve_lookup_value(self, value, can_reuse, allow_joins, summarize=False):\n        if hasattr(value, \"resolve_expression\"):\n            value = value.resolve_expression(\n                self,\n                reuse=can_reuse,\n                allow_joins=allow_joins,\n                summarize=summarize,\n            )\n        elif isinstance(value, (list, tuple)):\n            # The items of the iterable may be expressions and therefore need\n            # to be resolved independently.\n            values = (\n                self.resolve_lookup_value(sub_value, can_reuse, allow_joins, summarize)\n                for sub_value in value\n            )\n            type_ = type(value)\n            if hasattr(type_, \"_make\"):  # namedtuple\n                return type_(*values)\n            return type_(values)\n        return value\n\n    def solve_lookup_type(self, lookup, summarize=False):\n        \"\"\"\n        Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').\n        \"\"\"\n        lookup_splitted = lookup.split(LOOKUP_SEP)\n        if self.annotations:\n            annotation, expression_lookups = refs_expression(\n                lookup_splitted, self.annotations\n            )\n            if annotation:\n                expression = self.annotations[annotation]\n                if summarize:\n                    expression = Ref(annotation, expression)\n                return expression_lookups, (), expression\n        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())\n        field_parts = lookup_splitted[0x0 : len(lookup_splitted) - len(lookup_parts)]\n        if len(lookup_parts) > 0x1 and not field_parts:\n            raise FieldError(\n                'Invalid lookup \"%s\" for model %s\".'\n                % (lookup, self.get_meta().model.__name__)\n            )\n        return lookup_parts, field_parts, False\n\n    def check_query_object_type(self, value, opts, field):\n        \"\"\"\n        Check whether the object passed while querying is of the correct type.\n        If not, raise a ValueError specifying the wrong object.\n        \"\"\"\n        if hasattr(value, \"_meta\"):\n            if not check_rel_lookup_compatibility(value._meta.model, opts, field):\n                raise ValueError(\n                    'Cannot query \"%s\": Must be \"%s\" instance.'\n                    % (value, opts.object_name)\n                )\n\n    def check_related_objects(self, field, value, opts):\n        \"\"\"Check the type of object passed to query relations.\"\"\"\n        if field.is_relation:\n            # Check that the field and the queryset use the same model in a\n            # query like .filter(author=Author.objects.all()). For example, the\n            # opts would be Author's (from the author field) and value.model\n            # would be Author.objects.all() queryset's .model (Author also).\n            # The field is the related field on the lhs side.\n            if (\n                isinstance(value, Query)\n                and not value.has_select_fields\n                and not check_rel_lookup_compatibility(value.model, opts, field)\n            ):\n                raise ValueError(\n                    'Cannot use QuerySet for \"%s\": Use a QuerySet for \"%s\".'\n                    % (value.model._meta.object_name, opts.object_name)\n                )\n            elif hasattr(value, \"_meta\"):\n                self.check_query_object_type(value, opts, field)\n            elif hasattr(value, \"__iter__\"):\n                for v in value:\n                    self.check_query_object_type(v, opts, field)\n\n    def check_filterable(self, expression):\n        \"\"\"Raise an error if expression cannot be used in a WHERE clause.\"\"\"\n        if hasattr(expression, \"resolve_expression\") and not getattr(\n            expression, \"filterable\", True\n        ):\n            raise NotSupportedError(\n                expression.__class__.__name__ + \" is disallowed in the filter \"\n                \"clause.\"\n            )\n        if hasattr(expression, \"get_source_expressions\"):\n            for expr in expression.get_source_expressions():\n                self.check_filterable(expr)\n\n    def build_lookup(self, lookups, lhs, rhs):\n        \"\"\"\n        Try to extract transforms and lookup from given lhs.\n\n        The lhs value is something that works like SQLExpression.\n        The rhs value is what the lookup is going to compare against.\n        The lookups is a list of names to extract using get_lookup()\n        and get_transform().\n        \"\"\"\n        # __exact is the default lookup if one isn't given.\n        *transforms, lookup_name = lookups or [\"exact\"]\n        for name in transforms:\n            lhs = self.try_transform(lhs, name, lookups)\n        # First try get_lookup() so that the lookup takes precedence if the lhs\n        # supports both transform and lookup for the name.\n        lookup_class = lhs.get_lookup(lookup_name)\n        if not lookup_class:\n            # A lookup wasn't found. Try to interpret the name as a transform\n            # and do an Exact lookup against it.\n            lhs = self.try_transform(lhs, lookup_name)\n            lookup_name = \"exact\"\n            lookup_class = lhs.get_lookup(lookup_name)\n            if not lookup_class:\n                return\n\n        lookup = lookup_class(lhs, rhs)\n        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all\n        # uses of None as a query value unless the lookup supports it.\n        if lookup.rhs is None and not lookup.can_use_none_as_rhs:\n            if lookup_name not in (\"exact\", \"iexact\"):\n                raise ValueError(\"Cannot use None as a query value\")\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        # For Oracle '' is equivalent to null. The check must be done at this\n        # stage because join promotion can't be done in the compiler. Using\n        # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.\n        # A similar thing is done in is_nullable(), too.\n        if (\n            lookup_name in (\"exact\", \"iexact\")\n            and lookup.rhs == \"\"\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        ):\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        return lookup\n\n    def try_transform(self, lhs, name, lookups=None):\n        \"\"\"\n        Helper method for build_lookup(). Try to fetch and initialize\n        a transform for name parameter from lhs.\n        \"\"\"\n        transform_class = lhs.get_transform(name)\n        if transform_class:\n            return transform_class(lhs)\n        else:\n            output_field = lhs.output_field.__class__\n            suggested_lookups = difflib.get_close_matches(\n                name, lhs.output_field.get_lookups()\n            )\n            if suggested_lookups:\n                suggestion = \", perhaps you meant %s?\" % \" or \".join(suggested_lookups)\n            else:\n                suggestion = \".\"\n            if lookups is not None:\n                name_index = lookups.index(name)\n                unsupported_lookup = LOOKUP_SEP.join(lookups[name_index:])\n            else:\n                unsupported_lookup = name\n            raise FieldError(\n                \"Unsupported lookup '%s' for %s or join on the field not \"\n                \"permitted%s\" % (unsupported_lookup, output_field.__name__, suggestion)\n            )\n\n    def build_filter(\n        self,\n        filter_expr,\n        branch_negated=False,\n        current_negated=False,\n        can_reuse=None,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"\n        Build a WhereNode for a single filter clause but don't add it\n        to this Query. Query.add_q() will then add this filter to the where\n        Node.\n\n        The 'branch_negated' tells us if the current branch contains any\n        negations. This will be used to determine if subqueries are needed.\n\n        The 'current_negated' is used to determine if the current filter is\n        negated or not and this will be used to determine if IS NULL filtering\n        is needed.\n\n        The difference between current_negated and branch_negated is that\n        branch_negated is set on first negation, but current_negated is\n        flipped for each negation.\n\n        Note that add_filter will not do any negating itself, that is done\n        upper in the code by add_q().\n\n        The 'can_reuse' is a set of reusable joins for multijoins.\n\n        The method will create a filter clause that can be added to the current\n        query. However, if the filter isn't added to the query then the caller\n        is responsible for unreffing the joins used.\n        \"\"\"\n        if isinstance(filter_expr, dict):\n            raise FieldError(\"Cannot parse keyword query as dict\")\n        if isinstance(filter_expr, Q):\n            return self._add_q(\n                filter_expr,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                used_aliases=can_reuse,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n        if hasattr(filter_expr, \"resolve_expression\"):\n            if not getattr(filter_expr, \"conditional\", False):\n                raise TypeError(\"Cannot filter against a non-conditional expression.\")\n            condition = filter_expr.resolve_expression(\n                self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize\n            )\n            if not isinstance(condition, Lookup):\n                condition = self.build_lookup([\"exact\"], condition, True)\n            return WhereNode([condition], connector=AND), []\n        arg, value = filter_expr\n        if not arg:\n            raise FieldError(\"Cannot parse keyword query %r\" % arg)\n        lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize)\n\n        if check_filterable:\n            self.check_filterable(reffed_expression)\n\n        if not allow_joins and len(parts) > 0x1:\n            raise FieldError(\"Joined field references are not permitted in this query\")\n\n        pre_joins = self.alias_refcount.copy()\n        value = self.resolve_lookup_value(value, can_reuse, allow_joins, summarize)\n        used_joins = {\n            k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0x0)\n        }\n\n        if check_filterable:\n            self.check_filterable(value)\n\n        if reffed_expression:\n            condition = self.build_lookup(lookups, reffed_expression, value)\n            return WhereNode([condition], connector=AND), []\n\n        opts = self.get_meta()\n        alias = self.get_initial_alias()\n        allow_many = not branch_negated or not split_subq\n\n        try:\n            join_info = self.setup_joins(\n                parts,\n                opts,\n                alias,\n                can_reuse=can_reuse,\n                allow_many=allow_many,\n            )\n\n            # Prevent iterator from being consumed by check_related_objects()\n            if isinstance(value, Iterator):\n                value = list(value)\n            self.check_related_objects(join_info.final_field, value, join_info.opts)\n\n            # split_exclude() needs to know which joins were generated for the\n            # lookup parts\n            self._lookup_joins = join_info.joins\n        except MultiJoin as e:\n            return self.split_exclude(filter_expr, can_reuse, e.names_with_path)\n\n        # Update used_joins before trimming since they are reused to determine\n        # which joins could be later promoted to INNER.\n        used_joins.update(join_info.joins)\n        targets, alias, join_list = self.trim_joins(\n            join_info.targets, join_info.joins, join_info.path\n        )\n        if can_reuse is not None:\n            can_reuse.update(join_list)\n\n        if join_info.final_field.is_relation:\n            if len(targets) == 0x1:\n                col = self._get_col(targets[0x0], join_info.final_field, alias)\n            else:\n                col = ColPairs(alias, targets, join_info.targets, join_info.final_field)\n        else:\n            col = self._get_col(targets[0x0], join_info.final_field, alias)\n\n        condition = self.build_lookup(lookups, col, value)\n        lookup_type = condition.lookup_name\n        clause = WhereNode([condition], connector=AND)\n\n        require_outer = (\n            lookup_type == \"isnull\" and condition.rhs is True and not current_negated\n        )\n        if (\n            current_negated\n            and (lookup_type != \"isnull\" or condition.rhs is False)\n            and condition.rhs is not None\n        ):\n            require_outer = True\n            if lookup_type != \"isnull\":\n                # The condition added here will be SQL like this:\n                # NOT (col IS NOT NULL), where the first NOT is added in\n                # upper layers of code. The reason for addition is that if col\n                # is null, then col != someval will result in SQL \"unknown\"\n                # which isn't the same as in Python. The Python None handling\n                # is wanted, and it can be gotten by\n                # (col IS NULL OR col != someval)\n                #   <=>\n                # NOT (col IS NOT NULL AND col = someval).\n                if (\n                    self.is_nullable(targets[0x0])\n                    or self.alias_map[join_list[-0x1]].join_type == LOUTER\n                ):\n                    lookup_class = targets[0x0].get_lookup(\"isnull\")\n                    col = self._get_col(targets[0x0], join_info.targets[0x0], alias)\n                    # Use OR + IS NULL when RHS `in` values include None.\n                    if (\n                        lookup_type == \"in\"\n                        # Check containers (not strings or bytes).\n                        and isinstance(condition.rhs, Iterable)\n                        and not isinstance(condition.rhs, (str, bytes))\n                        and any(v is None for v in condition.rhs)\n                    ):\n                        clause.add(lookup_class(col, True), OR)\n                    else:\n                        clause.add(lookup_class(col, False), AND)\n                # If someval is a nullable column, someval IS NOT NULL is\n                # added.\n                if isinstance(value, Col) and self.is_nullable(value.target):\n                    lookup_class = value.target.get_lookup(\"isnull\")\n                    clause.add(lookup_class(value, False), AND)\n        return clause, used_joins if not require_outer else ()\n\n    def add_filter(self, filter_lhs, filter_rhs):\n        self.add_q(Q((filter_lhs, filter_rhs)))\n\n    def add_q(self, q_object, reuse_all=False):\n        \"\"\"\n        A preprocessor for the internal _add_q(). Responsible for doing final\n        join promotion.\n        \"\"\"\n        # For join promotion this case is doing an AND for the added q_object\n        # and existing conditions. So, any existing inner join forces the join\n        # type to remain inner. Existing outer joins can however be demoted.\n        # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if\n        # rel_a doesn't produce any rows, then the whole condition must fail.\n        # So, demotion is OK.\n        existing_inner = {\n            a for a in self.alias_map if self.alias_map[a].join_type == INNER\n        }\n        if reuse_all:\n            can_reuse = set(self.alias_map)\n        else:\n            can_reuse = self.used_aliases\n        clause, _ = self._add_q(q_object, can_reuse)\n        if clause:\n            self.where.add(clause, AND)\n        self.demote_joins(existing_inner)\n\n    def build_where(self, filter_expr):\n        return self.build_filter(filter_expr, allow_joins=False)[0x0]\n\n    def clear_where(self):\n        self.where = WhereNode()\n\n    def _add_q(\n        self,\n        q_object,\n        used_aliases,\n        branch_negated=False,\n        current_negated=False,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"Add a Q-object to the current filter.\"\"\"\n        connector = q_object.connector\n        current_negated ^= q_object.negated\n        branch_negated = branch_negated or q_object.negated\n        target_clause = WhereNode(connector=connector, negated=q_object.negated)\n        joinpromoter = JoinPromoter(\n            q_object.connector, len(q_object.children), current_negated\n        )\n        for child in q_object.children:\n            child_clause, needed_inner = self.build_filter(\n                child,\n                can_reuse=used_aliases,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n            joinpromoter.add_votes(needed_inner)\n            if child_clause:\n                target_clause.add(child_clause, connector)\n        if update_join_types:\n            needed_inner = joinpromoter.update_join_types(self)\n        else:\n            needed_inner = []\n        return target_clause, needed_inner\n\n    def add_filtered_relation(self, filtered_relation, alias):\n        if \".\" in alias:\n            raise ValueError(\n                \"FilteredRelation doesn't support aliases with periods \"\n                \"(got %r).\" % alias\n            )\n        self.check_alias(alias)\n        filtered_relation.alias = alias\n        relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(\n            filtered_relation.relation_name\n        )\n        if relation_lookup_parts:\n            raise ValueError(\n                \"FilteredRelation's relation_name cannot contain lookups \"\n                \"(got %r).\" % filtered_relation.relation_name\n            )\n        for lookup in get_children_from_q(filtered_relation.condition):\n            lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)\n            shift = 0x2 if not lookup_parts else 0x1\n            lookup_field_path = lookup_field_parts[:-shift]\n            for idx, lookup_field_part in enumerate(lookup_field_path):\n                if len(relation_field_parts) > idx:\n                    if relation_field_parts[idx] != lookup_field_part:\n                        raise ValueError(\n                            \"FilteredRelation's condition doesn't support \"\n                            \"relations outside the %r (got %r).\"\n                            % (filtered_relation.relation_name, lookup)\n                        )\n            if len(lookup_field_parts) > len(relation_field_parts) + 0x1:\n                raise ValueError(\n                    \"FilteredRelation's condition doesn't support nested \"\n                    \"relations deeper than the relation_name (got %r for \"\n                    \"%r).\" % (lookup, filtered_relation.relation_name)\n                )\n        filtered_relation = filtered_relation.clone()\n        filtered_relation.condition = rename_prefix_from_q(\n            filtered_relation.relation_name,\n            alias,\n            filtered_relation.condition,\n        )\n        self._filtered_relations[filtered_relation.alias] = filtered_relation\n\n    def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):\n        \"\"\"\n        Walk the list of names and turns them into PathInfo tuples. A single\n        name in 'names' can generate multiple PathInfos (m2m, for example).\n\n        'names' is the path of names to travel, 'opts' is the model Options we\n        start the name resolving from, 'allow_many' is as for setup_joins().\n        If fail_on_missing is set to True, then a name that can't be resolved\n        will generate a FieldError.\n\n        Return a list of PathInfo tuples. In addition return the final field\n        (the last used join field) and target (which is a field guaranteed to\n        contain the same value as the final field). Finally, return those names\n        that weren't found (which are likely transforms and the final lookup).\n        \"\"\"\n        path, names_with_path = [], []\n        for pos, name in enumerate(names):\n            cur_names_with_path = (name, [])\n            if name == \"pk\" and opts is not None:\n                name = opts.pk.name\n\n            field = None\n            filtered_relation = None\n            try:\n                if opts is None:\n                    raise FieldDoesNotExist\n                field = opts.get_field(name)\n            except FieldDoesNotExist:\n                if name in self.annotations:\n                    field = self.annotations[name].output_field\n                elif name in self._filtered_relations and pos == 0x0:\n                    filtered_relation = self._filtered_relations[name]\n                    if LOOKUP_SEP in filtered_relation.relation_name:\n                        parts = filtered_relation.relation_name.split(LOOKUP_SEP)\n                        filtered_relation_path, field, _, _ = self.names_to_path(\n                            parts,\n                            opts,\n                            allow_many,\n                            fail_on_missing,\n                        )\n                        path.extend(filtered_relation_path[:-0x1])\n                    else:\n                        field = opts.get_field(filtered_relation.relation_name)\n            if field is not None:\n                # Fields that contain one-to-many relations with a generic\n                # model (like a GenericForeignKey) cannot generate reverse\n                # relations and therefore cannot be used for reverse querying.\n                if field.is_relation and not field.related_model:\n                    raise FieldError(\n                        \"Field %r does not generate an automatic reverse \"\n                        \"relation and therefore cannot be used for reverse \"\n                        \"querying. If it is a GenericForeignKey, consider \"\n                        \"adding a GenericRelation.\" % name\n                    )\n                try:\n                    model = field.model._meta.concrete_model\n                except AttributeError:\n                    # QuerySet.annotate() may introduce fields that aren't\n                    # attached to a model.\n                    model = None\n            else:\n                # We didn't find the current field, so move position back\n                # one step.\n                pos -= 0x1\n                if pos == -0x1 or fail_on_missing:\n                    available = sorted(\n                        [\n                            *get_field_names_from_opts(opts),\n                            *self.annotations,\n                            *self._filtered_relations,\n                        ]\n                    )\n                    raise FieldError(\n                        \"Cannot resolve keyword '%s' into field. \"\n                        \"Choices are: %s\" % (name, \", \".join(available))\n                    )\n                break\n            # Check if we need any joins for concrete inheritance cases (the\n            # field lives in parent, but we are currently in one of its\n            # children)\n            if opts is not None and model is not opts.model:\n                path_to_parent = opts.get_path_to_parent(model)\n                if path_to_parent:\n                    path.extend(path_to_parent)\n                    cur_names_with_path[0x1].extend(path_to_parent)\n                    opts = path_to_parent[-0x1].to_opts\n            if hasattr(field, \"path_infos\"):\n                if filtered_relation:\n                    pathinfos = field.get_path_info(filtered_relation)\n                else:\n                    pathinfos = field.path_infos\n                if not allow_many:\n                    for inner_pos, p in enumerate(pathinfos):\n                        if p.m2m:\n                            cur_names_with_path[0x1].extend(pathinfos[0x0 : inner_pos + 0x1])\n                            names_with_path.append(cur_names_with_path)\n                            raise MultiJoin(pos + 0x1, names_with_path)\n                last = pathinfos[-0x1]\n                path.extend(pathinfos)\n                final_field = last.join_field\n                opts = last.to_opts\n                targets = last.target_fields\n                cur_names_with_path[0x1].extend(pathinfos)\n                names_with_path.append(cur_names_with_path)\n            else:\n                # Local non-relational field.\n                final_field = field\n                targets = (field,)\n                if fail_on_missing and pos + 0x1 != len(names):\n                    raise FieldError(\n                        \"Cannot resolve keyword %r into field. Join on '%s'\"\n                        \" not permitted.\" % (names[pos + 0x1], name)\n                    )\n                break\n        return path, final_field, targets, names[pos + 0x1 :]\n\n    def setup_joins(\n        self,\n        names,\n        opts,\n        alias,\n        can_reuse=None,\n        allow_many=True,\n    ):\n        \"\"\"\n        Compute the necessary table joins for the passage through the fields\n        given in 'names'. 'opts' is the Options class for the current model\n        (which gives the table we are starting from), 'alias' is the alias for\n        the table to start the joining from.\n\n        The 'can_reuse' defines the reverse foreign key joins we can reuse. It\n        can be None in which case all joins are reusable or a set of aliases\n        that can be reused. Note that non-reverse foreign keys are always\n        reusable when using setup_joins().\n\n        If 'allow_many' is False, then any reverse foreign key seen will\n        generate a MultiJoin exception.\n\n        Return the final field involved in the joins, the target field (used\n        for any 'where' constraint), the final 'opts' value, the joins, the\n        field path traveled to generate the joins, and a transform function\n        that takes a field and alias and is equivalent to\n        `field.get_col(alias)` in the simple case but wraps field transforms if\n        they were included in names.\n\n        The target field is the field containing the concrete value. Final\n        field can be something different, for example foreign key pointing to\n        that value. Final field is needed for example in some value\n        conversions (convert 'obj' in fk__id=obj to pk val using the foreign\n        key field for example).\n        \"\"\"\n        joins = [alias]\n        # The transform can't be applied yet, as joins must be trimmed later.\n        # To avoid making every caller of this method look up transforms\n        # directly, compute transforms here and create a partial that converts\n        # fields to the appropriate wrapped version.\n\n        def final_transformer(field, alias):\n            if not self.alias_cols:\n                alias = None\n            return field.get_col(alias)\n\n        # Try resolving all the names as fields first. If there's an error,\n        # treat trailing names as lookups until a field can be resolved.\n        last_field_exception = None\n        for pivot in range(len(names), 0x0, -0x1):\n            try:\n                path, final_field, targets, rest = self.names_to_path(\n                    names[:pivot],\n                    opts,\n                    allow_many,\n                    fail_on_missing=True,\n                )\n            except FieldError as exc:\n                if pivot == 0x1:\n                    # The first item cannot be a lookup, so it's safe\n                    # to raise the field error here.\n                    raise\n                else:\n                    last_field_exception = exc\n            else:\n                # The transforms are the remaining items that couldn't be\n                # resolved into fields.\n                transforms = names[pivot:]\n                break\n        for name in transforms:\n\n            def transform(field, alias, *, name, previous):\n                try:\n                    wrapped = previous(field, alias)\n                    return self.try_transform(wrapped, name)\n                except FieldError:\n                    # FieldError is raised if the transform doesn't exist.\n                    if isinstance(final_field, Field) and last_field_exception:\n                        raise last_field_exception\n                    else:\n                        raise\n\n            final_transformer = functools.partial(\n                transform, name=name, previous=final_transformer\n            )\n            final_transformer.has_transforms = True\n        # Then, add the path to the query's joins. Note that we can't trim\n        # joins at this stage - we will need the information about join type\n        # of the trimmed joins.\n        for join in path:\n            if join.filtered_relation:\n                filtered_relation = join.filtered_relation.clone()\n                table_alias = filtered_relation.alias\n            else:\n                filtered_relation = None\n                table_alias = None\n            opts = join.to_opts\n            if join.direct:\n                nullable = self.is_nullable(join.join_field)\n            else:\n                nullable = True\n            connection = self.join_class(\n                opts.db_table,\n                alias,\n                table_alias,\n                INNER,\n                join.join_field,\n                nullable,\n                filtered_relation=filtered_relation,\n            )\n            reuse = can_reuse if join.m2m else None\n            alias = self.join(connection, reuse=reuse)\n            joins.append(alias)\n            if join.filtered_relation and can_reuse is not None:\n                can_reuse.add(alias)\n        return JoinInfo(final_field, targets, opts, joins, path, final_transformer)\n\n    def trim_joins(self, targets, joins, path):\n        \"\"\"\n        The 'target' parameter is the final field being joined to, 'joins'\n        is the full list of join aliases. The 'path' contain the PathInfos\n        used to create the joins.\n\n        Return the final target field and table alias and the new active\n        joins.\n\n        Always trim any direct join if the target column is already in the\n        previous table. Can't trim reverse joins as it's unknown if there's\n        anything on the other side of the join.\n        \"\"\"\n        joins = joins[:]\n        for pos, info in enumerate(reversed(path)):\n            if len(joins) == 0x1 or not info.direct:\n                break\n            if info.filtered_relation:\n                break\n            join_targets = {t.column for t in info.join_field.foreign_related_fields}\n            cur_targets = {t.column for t in targets}\n            if not cur_targets.issubset(join_targets):\n                break\n            targets_dict = {\n                r[0x1].column: r[0x0]\n                for r in info.join_field.related_fields\n                if r[0x1].column in cur_targets\n            }\n            targets = tuple(targets_dict[t.column] for t in targets)\n            self.unref_alias(joins.pop())\n        return targets, joins[-0x1], joins\n\n    @classmethod\n    def _gen_cols(cls, exprs, include_external=False, resolve_refs=True):\n        for expr in exprs:\n            if isinstance(expr, Col):\n                yield expr\n            elif include_external and callable(\n                getattr(expr, \"get_external_cols\", None)\n            ):\n                yield from expr.get_external_cols()\n            elif hasattr(expr, \"get_source_expressions\"):\n                if not resolve_refs and isinstance(expr, Ref):\n                    continue\n                yield from cls._gen_cols(\n                    expr.get_source_expressions(),\n                    include_external=include_external,\n                    resolve_refs=resolve_refs,\n                )\n\n    @classmethod\n    def _gen_col_aliases(cls, exprs):\n        yield from (expr.alias for expr in cls._gen_cols(exprs))\n\n    def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):\n        annotation = self.annotations.get(name)\n        if annotation is not None:\n            if not allow_joins:\n                for alias in self._gen_col_aliases([annotation]):\n                    if isinstance(self.alias_map[alias], Join):\n                        raise FieldError(\n                            \"Joined field references are not permitted in this query\"\n                        )\n            if summarize:\n                # Summarize currently means we are doing an aggregate() query\n                # which is executed as a wrapped subquery if any of the\n                # aggregate() elements reference an existing annotation. In\n                # that case we need to return a Ref to the subquery's\n                # annotation.\n                if name not in self.annotation_select:\n                    raise FieldError(\n                        \"Cannot aggregate over the '%s' alias. Use annotate() \"\n                        \"to promote it.\" % name\n                    )\n                return Ref(name, self.annotation_select[name])\n            else:\n                return annotation\n        else:\n            field_list = name.split(LOOKUP_SEP)\n            annotation = self.annotations.get(field_list[0x0])\n            if annotation is not None:\n                for transform in field_list[0x1:]:\n                    annotation = self.try_transform(annotation, transform)\n                return annotation\n            join_info = self.setup_joins(\n                field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse\n            )\n            targets, final_alias, join_list = self.trim_joins(\n                join_info.targets, join_info.joins, join_info.path\n            )\n            if not allow_joins and len(join_list) > 0x1:\n                raise FieldError(\n                    \"Joined field references are not permitted in this query\"\n                )\n            if len(targets) > 0x1:\n                raise FieldError(\n                    \"Referencing multicolumn fields with F() objects isn't supported\"\n                )\n            # Verify that the last lookup in name is a field or a transform:\n            # transform_function() raises FieldError if not.\n            transform = join_info.transform_function(targets[0x0], final_alias)\n            if reuse is not None:\n                reuse.update(join_list)\n            return transform\n\n    def split_exclude(self, filter_expr, can_reuse, names_with_path):\n        \"\"\"\n        When doing an exclude against any kind of N-to-many relation, we need\n        to use a subquery. This method constructs the nested query, given the\n        original exclude filter (filter_expr) and the portion up to the first\n        N-to-many relation field.\n\n        For example, if the origin filter is ~Q(child__name='foo'), filter_expr\n        is ('child__name', 'foo') and can_reuse is a set of joins usable for\n        filters in the original query.\n\n        We will turn this into equivalent of:\n            WHERE NOT EXISTS(\n                SELECT 1\n                FROM child\n                WHERE name = 'foo' AND child.parent_id = parent.id\n                LIMIT 1\n            )\n        \"\"\"\n        # Generate the inner query.\n        query = self.__class__(self.model)\n        query._filtered_relations = self._filtered_relations\n        filter_lhs, filter_rhs = filter_expr\n        if isinstance(filter_rhs, OuterRef):\n            filter_rhs = OuterRef(filter_rhs)\n        elif isinstance(filter_rhs, F):\n            filter_rhs = OuterRef(filter_rhs.name)\n        query.add_filter(filter_lhs, filter_rhs)\n        query.clear_ordering(force=True)\n        # Try to have as simple as possible subquery -> trim leading joins from\n        # the subquery.\n        trimmed_prefix, contains_louter = query.trim_start(names_with_path)\n\n        col = query.select[0x0]\n        select_field = col.target\n        alias = col.alias\n        if alias in can_reuse:\n            pk = select_field.model._meta.pk\n            # Need to add a restriction so that outer query's filters are in\n            # effect for the subquery, too.\n            query.bump_prefix(self)\n            lookup_class = select_field.get_lookup(\"exact\")\n            # Note that the query.select[0].alias is different from alias\n            # due to bump_prefix above.\n            lookup = lookup_class(pk.get_col(query.select[0x0].alias), pk.get_col(alias))\n            query.where.add(lookup, AND)\n            query.external_aliases[alias] = True\n        else:\n            lookup_class = select_field.get_lookup(\"exact\")\n            lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix))\n            query.where.add(lookup, AND)\n\n        condition, needed_inner = self.build_filter(Exists(query))\n\n        if contains_louter:\n            or_null_condition, _ = self.build_filter(\n                (\"%s__isnull\" % trimmed_prefix, True),\n                current_negated=True,\n                branch_negated=True,\n                can_reuse=can_reuse,\n            )\n            condition.add(or_null_condition, OR)\n            # Note that the end result will be:\n            #   NOT EXISTS (inner_q) OR outercol IS NULL\n            # this might look crazy but due to how NULL works, this seems to be\n            # correct. If the IS NULL check is removed, then if outercol\n            # IS NULL we will not match the row.\n        return condition, needed_inner\n\n    def set_empty(self):\n        self.where.add(NothingNode(), AND)\n        for query in self.combined_queries:\n            query.set_empty()\n\n    def is_empty(self):\n        return any(isinstance(c, NothingNode) for c in self.where.children)\n\n    def set_limits(self, low=None, high=None):\n        \"\"\"\n        Adjust the limits on the rows retrieved. Use low/high to set these,\n        as it makes it more Pythonic to read and write. When the SQL query is\n        created, convert them to the appropriate offset and limit values.\n\n        Apply any limits passed in here to the existing constraints. Add low\n        to the current low value and clamp both to any existing high value.\n        \"\"\"\n        if high is not None:\n            if self.high_mark is not None:\n                self.high_mark = min(self.high_mark, self.low_mark + high)\n            else:\n                self.high_mark = self.low_mark + high\n        if low is not None:\n            if self.high_mark is not None:\n                self.low_mark = min(self.high_mark, self.low_mark + low)\n            else:\n                self.low_mark = self.low_mark + low\n\n        if self.low_mark == self.high_mark:\n            self.set_empty()\n\n    def clear_limits(self):\n        \"\"\"Clear any existing limits.\"\"\"\n        self.low_mark, self.high_mark = 0x0, None\n\n    @property\n    def is_sliced(self):\n        return self.low_mark != 0x0 or self.high_mark is not None\n\n    def has_limit_one(self):\n        return self.high_mark is not None and (self.high_mark - self.low_mark) == 0x1\n\n    def can_filter(self):\n        \"\"\"\n        Return True if adding filters to this instance is still possible.\n\n        Typically, this means no limits or offsets have been put on the\n        results.\n        \"\"\"\n        return not self.is_sliced\n\n    def clear_select_clause(self):\n        \"\"\"Remove all fields from SELECT clause.\"\"\"\n        self.select = ()\n        self.default_cols = False\n        self.select_related = False\n        self.set_extra_mask(())\n        self.set_annotation_mask(())\n        self.selected = None\n\n    def clear_select_fields(self):\n        \"\"\"\n        Clear the list of fields to select (but not extra_select columns).\n        Some queryset types completely replace any existing list of select\n        columns.\n        \"\"\"\n        self.select = ()\n        self.values_select = ()\n        self.selected = None\n\n    def add_select_col(self, col, name):\n        self.select += (col,)\n        self.values_select += (name,)\n        self.selected[name] = len(self.select) - 0x1\n\n    def set_select(self, cols):\n        self.default_cols = False\n        self.select = tuple(cols)\n\n    def add_distinct_fields(self, *field_names):\n        \"\"\"\n        Add and resolve the given fields to the query's \"distinct on\" clause.\n        \"\"\"\n        self.distinct_fields = field_names\n        self.distinct = True\n\n    def add_fields(self, field_names, allow_m2m=True):\n        \"\"\"\n        Add the given (model) fields to the select set. Add the field names in\n        the order specified.\n        \"\"\"\n        alias = self.get_initial_alias()\n        opts = self.get_meta()\n\n        try:\n            cols = []\n            for name in field_names:\n                # Join promotion note - we must not remove any rows here, so\n                # if there is no existing joins, use outer join.\n                join_info = self.setup_joins(\n                    name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m\n                )\n                targets, final_alias, joins = self.trim_joins(\n                    join_info.targets,\n                    join_info.joins,\n                    join_info.path,\n                )\n                if len(targets) > 0x1:\n                    transformed_targets = [\n                        join_info.transform_function(target, final_alias)\n                        for target in targets\n                    ]\n                    cols.append(\n                        ColPairs(\n                            final_alias if self.alias_cols else None,\n                            [col.target for col in transformed_targets],\n                            [col.output_field for col in transformed_targets],\n                            join_info.final_field,\n                        )\n                    )\n                else:\n                    cols.append(join_info.transform_function(targets[0x0], final_alias))\n            if cols:\n                self.set_select(cols)\n        except MultiJoin:\n            raise FieldError(\"Invalid field name: '%s'\" % name)\n        except FieldError:\n            if LOOKUP_SEP in name:\n                # For lookups spanning over relationships, show the error\n                # from the model on which the lookup failed.\n                raise\n            else:\n                names = sorted(\n                    [\n                        *get_field_names_from_opts(opts),\n                        *self.extra,\n                        *self.annotation_select,\n                        *self._filtered_relations,\n                    ]\n                )\n                raise FieldError(\n                    \"Cannot resolve keyword %r into field. \"\n                    \"Choices are: %s\" % (name, \", \".join(names))\n                )\n\n    def add_ordering(self, *ordering):\n        \"\"\"\n        Add items from the 'ordering' sequence to the query's \"order by\"\n        clause. These items are either field names (not column names) --\n        possibly with a direction prefix ('-' or '?') -- or OrderBy\n        expressions.\n\n        If 'ordering' is empty, clear all ordering from the query.\n        \"\"\"\n        errors = []\n        for item in ordering:\n            if isinstance(item, str):\n                if item == \"?\":\n                    continue\n                item = item.removeprefix(\"-\")\n                if item in self.annotations:\n                    continue\n                if self.extra and item in self.extra:\n                    continue\n                # names_to_path() validates the lookup. A descriptive\n                # FieldError will be raise if it's not.\n                self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)\n            elif not hasattr(item, \"resolve_expression\"):\n                errors.append(item)\n            if getattr(item, \"contains_aggregate\", False):\n                raise FieldError(\n                    \"Using an aggregate in order_by() without also including \"\n                    \"it in annotate() is not allowed: %s\" % item\n                )\n        if errors:\n            raise FieldError(\"Invalid order_by arguments: %s\" % errors)\n        if ordering:\n            self.order_by += ordering\n        else:\n            self.default_ordering = False\n\n    @property\n    def orderby_issubset_groupby(self):\n        if self.extra_order_by:\n            # Raw SQL from extra(order_by=...) can't be reliably compared\n            # against resolved OrderBy/Col expressions. Treat as not a subset.\n            return False\n        if self.group_by in (None, True):\n            # There is either no aggregation at all (None), or the group by\n            # is generated automatically from model fields (True), in which\n            # case the order by is necessarily a subset of them.\n            return True\n        if not self.order_by:\n            # Although an empty set is always a subset, there's no point in\n            # clearing ordering when there isn't any. Avoid the clone() below.\n            return True\n        # Don't pollute the original query (might disrupt joins).\n        q = self.clone()\n        order_by_set = set()\n        for order_by in q.order_by:\n            if hasattr(order_by, \"resolve_expression\"):\n                order_by_set.add(order_by.resolve_expression(q))\n            elif order_by == \"?\":\n                # Random ordering can't be compared against group by.\n                return False\n            else:\n                order_by_set.add(F(order_by.removeprefix(\"-\")).resolve_expression(q))\n        return order_by_set.issubset(self.group_by)\n\n    def clear_ordering(self, force=False, clear_default=True):\n        \"\"\"\n        Remove any ordering settings if the current query allows it without\n        side effects, set 'force' to True to clear the ordering regardless.\n        If 'clear_default' is True, there will be no ordering in the resulting\n        query (not even the model's default).\n        \"\"\"\n        if not force and (\n            self.is_sliced or self.distinct_fields or self.select_for_update\n        ):\n            return\n        self.order_by = ()\n        self.extra_order_by = ()\n        if clear_default:\n            self.default_ordering = False\n        # Ordering is cleared on combined queries with clear_default=False\n        # when union() and analogues are called, so percolate any possible\n        # clear_default=True.\n        for query in self.combined_queries:\n            query.clear_ordering(force=False, clear_default=clear_default)\n\n    def set_group_by(self, allow_aliases=True):\n        \"\"\"\n        Expand the GROUP BY clause required by the query.\n\n        This will usually be the set of all non-aggregate fields in the\n        return data. If the database backend supports grouping by the\n        primary key, and the query would be equivalent, the optimization\n        will be made automatically.\n        \"\"\"\n        if allow_aliases and self.values_select:\n            # If grouping by aliases is allowed assign selected value aliases\n            # by moving them to annotations.\n            group_by_annotations = {}\n            values_select = {}\n            for alias, expr in zip(self.values_select, self.select):\n                if isinstance(expr, Col):\n                    values_select[alias] = expr\n                else:\n                    group_by_annotations[alias] = expr\n            self.annotations = {**group_by_annotations, **self.annotations}\n            self.append_annotation_mask(group_by_annotations)\n            self.select = tuple(values_select.values())\n            self.values_select = tuple(values_select)\n            if self.selected is not None:\n                for index, value_select in enumerate(values_select):\n                    self.selected[value_select] = index\n        group_by = list(self.select)\n        for alias, annotation in self.annotation_select.items():\n            if not (group_by_cols := annotation.get_group_by_cols()):\n                continue\n            if allow_aliases and not annotation.contains_aggregate:\n                group_by.append(Ref(alias, annotation))\n            else:\n                group_by.extend(group_by_cols)\n        self.group_by = tuple(group_by)\n\n    def add_select_related(self, fields):\n        \"\"\"\n        Set up the select_related data structure so that we only select\n        certain related models (as opposed to all models, when\n        self.select_related=True).\n        \"\"\"\n        if isinstance(self.select_related, bool):\n            field_dict = {}\n        else:\n            field_dict = self.select_related\n        for field in fields:\n            d = field_dict\n            for part in field.split(LOOKUP_SEP):\n                d = d.setdefault(part, {})\n        self.select_related = field_dict\n\n    def add_extra(self, select, select_params, where, params, tables, order_by):\n        \"\"\"\n        Add data to the various extra_* attributes for user-created additions\n        to the query.\n        \"\"\"\n        if select:\n            # We need to pair any placeholder markers in the 'select'\n            # dictionary with their parameters in 'select_params' so that\n            # subsequent updates to the select dictionary also adjust the\n            # parameters appropriately.\n            select_pairs = {}\n            if select_params:\n                param_iter = iter(select_params)\n            else:\n                param_iter = iter([])\n            for name, entry in select.items():\n                self.check_alias(name)\n                entry = str(entry)\n                entry_params = []\n                pos = entry.find(\"%s\")\n                while pos != -0x1:\n                    if pos == 0x0 or entry[pos - 0x1] != \"%\":\n                        entry_params.append(next(param_iter))\n                    pos = entry.find(\"%s\", pos + 0x2)\n                select_pairs[name] = (entry, entry_params)\n            self.extra.update(select_pairs)\n        if where or params:\n            self.where.add(ExtraWhere(where, params), AND)\n        if tables:\n            self.extra_tables += tuple(tables)\n        if order_by:\n            self.extra_order_by = order_by\n\n    def clear_deferred_loading(self):\n        \"\"\"Remove any fields from the deferred loading set.\"\"\"\n        self.deferred_loading = (frozenset(), True)\n\n    def add_deferred_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        exclude from loading from the database when automatic column selection\n        is done. Add the new field names to any existing field names that\n        are deferred (or removed from any existing field names that are marked\n        as the only ones for immediate loading).\n        \"\"\"\n        # Fields on related models are stored in the literal double-underscore\n        # format, so that we can use a set datastructure. We do the foo__bar\n        # splitting and handling when computing the SQL column names (as part\n        # of get_columns()).\n        existing, defer = self.deferred_loading\n        if defer:\n            # Add to existing deferred names.\n            self.deferred_loading = existing.union(field_names), True\n        else:\n            # Remove names from the set of any existing \"immediate load\" names.\n            if new_existing := existing.difference(field_names):\n                self.deferred_loading = new_existing, False\n            else:\n                self.clear_deferred_loading()\n                if new_only := set(field_names).difference(existing):\n                    self.deferred_loading = new_only, True\n\n    def add_immediate_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        retrieve when the SQL is executed (\"immediate loading\" fields). The\n        field names replace any existing immediate loading field names. If\n        there are field names already specified for deferred loading, remove\n        those names from the new field_names before storing the new names\n        for immediate loading. (That is, immediate loading overrides any\n        existing immediate values, but respects existing deferrals.)\n        \"\"\"\n        existing, defer = self.deferred_loading\n        field_names = set(field_names)\n        if \"pk\" in field_names:\n            field_names.remove(\"pk\")\n            field_names.add(self.get_meta().pk.name)\n\n        if defer:\n            # Remove any existing deferred names from the current set before\n            # setting the new names.\n            self.deferred_loading = field_names.difference(existing), False\n        else:\n            # Replace any existing \"immediate load\" field names.\n            self.deferred_loading = frozenset(field_names), False\n\n    def set_annotation_mask(self, names):\n        \"\"\"Set the mask of annotations that will be returned by the SELECT.\"\"\"\n        if names is None:\n            self.annotation_select_mask = None\n        else:\n            self.annotation_select_mask = set(names)\n            if self.selected:\n                # Prune the masked annotations.\n                self.selected = {\n                    key: value\n                    for key, value in self.selected.items()\n                    if not isinstance(value, str)\n                    or value in self.annotation_select_mask\n                }\n                # Append the unmasked annotations.\n                for name in names:\n                    self.selected[name] = name\n        self._annotation_select_cache = None\n\n    def append_annotation_mask(self, names):\n        if self.annotation_select_mask is not None:\n            self.set_annotation_mask(self.annotation_select_mask.union(names))\n\n    def set_extra_mask(self, names):\n        \"\"\"\n        Set the mask of extra select items that will be returned by SELECT.\n        Don't remove them from the Query since they might be used later.\n        \"\"\"\n        if names is None:\n            self.extra_select_mask = None\n        else:\n            self.extra_select_mask = set(names)\n        self._extra_select_cache = None\n\n    @property\n    def has_select_fields(self):\n        return self.selected is not None\n\n    def set_values(self, fields):\n        self.select_related = False\n        self.clear_deferred_loading()\n        self.clear_select_fields()\n\n        selected = {}\n        if fields:\n            for field in fields:\n                self.check_alias(field)\n            field_names = []\n            extra_names = []\n            annotation_names = []\n            if not self.extra and not self.annotations:\n                # Shortcut - if there are no extra or annotations, then\n                # the values() clause must be just field names.\n                field_names = list(fields)\n                selected = dict(zip(fields, range(len(fields))))\n            else:\n                self.default_cols = False\n                for f in fields:\n                    if extra := self.extra_select.get(f):\n                        extra_names.append(f)\n                        selected[f] = RawSQL(*extra)\n                    elif f in self.annotation_select:\n                        annotation_names.append(f)\n                        selected[f] = f\n                    elif f in self.annotations:\n                        if self.annotation_select:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. It was excluded \"\n                                f\"by a previous values() or values_list() call. \"\n                                f\"Include '{f}' in that call to select it.\"\n                            )\n                        else:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. Use annotate() \"\n                                f\"to promote it.\"\n                            )\n                    else:\n                        # Call `names_to_path` to ensure a FieldError including\n                        # annotations about to be masked as valid choices if\n                        # `f` is not resolvable.\n                        if self.annotation_select:\n                            self.names_to_path(f.split(LOOKUP_SEP), self.model._meta)\n                        selected[f] = len(field_names)\n                        field_names.append(f)\n            self.set_extra_mask(extra_names)\n            self.set_annotation_mask(annotation_names)\n        else:\n            field_names = [f.attname for f in self.model._meta.concrete_fields]\n            selected = dict.fromkeys(field_names, None)\n        # Selected annotations must be known before setting the GROUP BY\n        # clause.\n        if self.group_by is True:\n            self.add_fields(\n                (f.attname for f in self.model._meta.concrete_fields), False\n            )\n            # Disable GROUP BY aliases to avoid orphaning references to the\n            # SELECT clause which is about to be cleared.\n            self.set_group_by(allow_aliases=False)\n            self.clear_select_fields()\n        elif self.group_by:\n            # Resolve GROUP BY annotation references if they are not part of\n            # the selected fields anymore.\n            group_by = []\n            for expr in self.group_by:\n                if isinstance(expr, Ref) and expr.refs not in selected:\n                    expr = self.annotations[expr.refs]\n                group_by.append(expr)\n            self.group_by = tuple(group_by)\n\n        self.values_select = tuple(field_names)\n        self.add_fields(field_names, True)\n        self.selected = selected if fields else None\n\n    @property\n    def annotation_select(self):\n        \"\"\"\n        Return the dictionary of aggregate columns that are not masked and\n        should be used in the SELECT clause. Cache this result for performance.\n        \"\"\"\n        if self._annotation_select_cache is not None:\n            return self._annotation_select_cache\n        elif not self.annotations:\n            return {}\n        elif self.annotation_select_mask is not None:\n            self._annotation_select_cache = {\n                k: v\n                for k, v in self.annotations.items()\n                if k in self.annotation_select_mask\n            }\n            return self._annotation_select_cache\n        else:\n            return self.annotations\n\n    @property\n    def extra_select(self):\n        if self._extra_select_cache is not None:\n            return self._extra_select_cache\n        if not self.extra:\n            return {}\n        elif self.extra_select_mask is not None:\n            self._extra_select_cache = {\n                k: v for k, v in self.extra.items() if k in self.extra_select_mask\n            }\n            return self._extra_select_cache\n        else:\n            return self.extra\n\n    def trim_start(self, names_with_path):\n        \"\"\"\n        Trim joins from the start of the join path. The candidates for trim\n        are the PathInfos in names_with_path structure that are m2m joins.\n\n        Also set the select column so the start matches the join.\n\n        This method is meant to be used for generating the subquery joins &\n        cols in split_exclude().\n\n        Return a lookup usable for doing outerq.filter(lookup=self) and a\n        boolean indicating if the joins in the prefix contain a LEFT OUTER\n        join.\n        \"\"\"\n        all_paths = []\n        for _, paths in names_with_path:\n            all_paths.extend(paths)\n        contains_louter = False\n        # Trim and operate only on tables that were generated for\n        # the lookup part of the query. That is, avoid trimming\n        # joins generated for F() expressions.\n        lookup_tables = [\n            t for t in self.alias_map if t in self._lookup_joins or t == self.base_table\n        ]\n        for trimmed_paths, path in enumerate(all_paths):\n            if path.m2m:\n                break\n            if self.alias_map[lookup_tables[trimmed_paths + 0x1]].join_type == LOUTER:\n                contains_louter = True\n            alias = lookup_tables[trimmed_paths]\n            self.unref_alias(alias)\n        # The path.join_field is a Rel, lets get the other side's field\n        join_field = path.join_field.field\n        # Build the filter prefix.\n        paths_in_prefix = trimmed_paths\n        trimmed_prefix = []\n        for name, path in names_with_path:\n            if paths_in_prefix - len(path) < 0x0:\n                break\n            trimmed_prefix.append(name)\n            paths_in_prefix -= len(path)\n        trimmed_prefix.append(join_field.foreign_related_fields[0x0].name)\n        trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)\n        # Lets still see if we can trim the first join from the inner query\n        # (that is, self). We can't do this for:\n        # - LEFT JOINs because we would miss those rows that have nothing on\n        #   the outer side,\n        # - INNER JOINs from filtered relations because we would miss their\n        #   filters.\n        first_join = self.alias_map[lookup_tables[trimmed_paths + 0x1]]\n        if first_join.join_type != LOUTER and not first_join.filtered_relation:\n            select_fields = [r[0x0] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths + 0x1]\n            self.unref_alias(lookup_tables[trimmed_paths])\n            extra_restriction = join_field.get_extra_restriction(\n                None, lookup_tables[trimmed_paths + 0x1]\n            )\n            if extra_restriction:\n                self.where.add(extra_restriction, AND)\n        else:\n            # TODO: It might be possible to trim more joins from the start of\n            # the inner query if it happens to have a longer join chain\n            # containing the values in select_fields. Lets punt this one for\n            # now.\n            select_fields = [r[0x1] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths]\n        # The found starting point is likely a join_class instead of a\n        # base_table_class reference. But the first entry in the query's FROM\n        # clause must not be a JOIN.\n        for table in self.alias_map:\n            if self.alias_refcount[table] > 0x0:\n                self.alias_map[table] = self.base_table_class(\n                    self.alias_map[table].table_name,\n                    table,\n                )\n                break\n        self.set_select([f.get_col(select_alias) for f in select_fields])\n        return trimmed_prefix, contains_louter\n\n    def is_nullable(self, field):\n        \"\"\"\n        Check if the given field should be treated as nullable.\n\n        Some backends treat '' as null and Django treats such fields as\n        nullable for those backends. In such situations field.null can be\n        False even if we should treat the field as nullable.\n        \"\"\"\n        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have\n        # (nor should it have) knowledge of which connection is going to be\n        # used. The proper fix would be to defer all decisions where\n        # is_nullable() is needed to the compiler stage, but that is not easy\n        # to do currently.\n        return field.null or (\n            field.empty_strings_allowed\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-d737c5fea4d295f9", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "1e873c47c4fea59b575ffb6fe226ce9cd4edd647ebd1d9feedba35fc5817c0e2", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 2602, "local_path": "expressions/encode-integer-literals/I05__django__Query__fc70c20e.py", "order": 5, "original_content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "parent_variant_id": "pyint-82246794d74c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/query.py#L232-L2792", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 91}, "unit_kind": "class", "unit_name": "Query", "variant_id": "pyint-9da1fc70c20e-I05", "group_id": "py-d737c5fea4d295f9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 286, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8513a17a76e9-I06", "source": "import copy\nimport difflib\nimport functools\nimport sys\nimport warnings\nfrom collections import Counter, namedtuple\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom itertools import chain, count, product\nfrom string import ascii_uppercase\nfrom django.core.exceptions import FieldDoesNotExist, FieldError\nfrom django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections\nfrom django.db.models.aggregates import Count\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import (\n    BaseExpression,\n    Col,\n    ColPairs,\n    Exists,\n    F,\n    OuterRef,\n    RawSQL,\n    Ref,\n    ResolvedOuterRef,\n    Value,\n)\nfrom django.db.models.fields import Field\nfrom django.db.models.lookups import Lookup\nfrom django.db.models.query_utils import (\n    Q,\n    check_rel_lookup_compatibility,\n    refs_expression,\n)\nfrom django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE\nfrom django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin\nfrom django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode\nfrom django.utils.deprecation import RemovedInDjango70Warning\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.tree import Node\nfrom django.utils.warnings import django_file_prefixes\n\nclass Query(BaseExpression):\n    \"\"\"A single SQL query.\"\"\"\n\n    alias_prefix = \"T\"\n    empty_result_set_value = None\n    subq_aliases = frozenset([alias_prefix])\n\n    compiler = \"SQLCompiler\"\n\n    base_table_class = BaseTable\n    join_class = Join\n\n    default_cols = True\n    default_ordering = True\n    standard_ordering = True\n\n    filter_is_sticky = False\n    subquery = False\n    contains_subquery = False\n\n    # SQL-related attributes.\n    # Select and related select clauses are expressions to use in the SELECT\n    # clause of the query. The select is used for cases where we want to set up\n    # the select clause to contain other than default fields (values(),\n    # subqueries...). Note that annotations go to annotations dictionary.\n    select = ()\n    # The group_by attribute can have one of the following forms:\n    #  - None: no group by at all in the query\n    #  - A tuple of expressions: group by (at least) those expressions.\n    #    String refs are also allowed for now.\n    #  - True: group by all select fields of the model\n    # See compiler.get_group_by() for details.\n    group_by = None\n    order_by = ()\n    low_mark = 0  # Used for offset/limit.\n    high_mark = None  # Used for offset/limit.\n    distinct = False\n    distinct_fields = ()\n    select_for_update = False\n    select_for_update_nowait = False\n    select_for_update_skip_locked = False\n    select_for_update_of = ()\n    select_for_no_key_update = False\n    select_related = False\n    # Arbitrary limit for select_related to prevents infinite recursion.\n    max_depth = 5\n    # Holds the selects defined by a call to values() or values_list()\n    # excluding annotation_select and extra_select.\n    values_select = ()\n    selected = None\n\n    # SQL annotation-related attributes.\n    annotation_select_mask = None\n    _annotation_select_cache = None\n\n    # Set combination attributes.\n    combinator = None\n    combinator_all = False\n    combined_queries = ()\n\n    # These are for extensions. The contents are more or less appended verbatim\n    # to the appropriate clause.\n    extra_select_mask = None\n    _extra_select_cache = None\n\n    extra_tables = ()\n    extra_order_by = ()\n\n    # A tuple that is a set of model field names and either True, if these are\n    # the fields to defer, or False if these are the only fields to load.\n    deferred_loading = (frozenset(), True)\n\n    explain_info = None\n\n    def __init__(self, model, alias_cols=True):\n        self.model = model\n        self.alias_refcount = {}\n        # alias_map is the most important data structure regarding joins.\n        # It's used for recording which joins exist in the query and what\n        # types they are. The key is the alias of the joined table (possibly\n        # the table name) and the value is a Join-like object (see\n        # sql.datastructures.Join for more information).\n        self.alias_map = {}\n        # Whether to provide alias to columns during reference resolving.\n        self.alias_cols = alias_cols\n        # Sometimes the query contains references to aliases in outer queries\n        # (as a result of split_exclude). Correct alias quoting needs to know\n        # these aliases too. Map external tables to whether they are aliased.\n        self.external_aliases = {}\n        self.table_map = {}  # Maps table names to list of aliases.\n        self.used_aliases = set()\n\n        self.where = WhereNode()\n        # Maps alias -> Annotation Expression.\n        self.annotations = {}\n        # These are for extensions. The contents are more or less appended\n        # verbatim to the appropriate clause.\n        self.extra = {}  # Maps col_alias -> (col_sql, params).\n\n        self._filtered_relations = {}\n\n    @property\n    def output_field(self):\n        if len(self.select) == 1:\n            select = self.select[0]\n            return getattr(select, \"target\", None) or select.field\n        elif len(self.annotation_select) == 1:\n            return next(iter(self.annotation_select.values())).output_field\n\n    @cached_property\n    def base_table(self):\n        for alias in self.alias_map:\n            return alias\n\n    def __str__(self):\n        \"\"\"\n        Return the query as a string of SQL with the parameter values\n        substituted in (use sql_with_params() to see the unsubstituted string).\n\n        Parameter values won't necessarily be quoted correctly, since that is\n        done by the database interface at execution time.\n        \"\"\"\n        sql, params = self.sql_with_params()\n        return sql % params\n\n    def sql_with_params(self):\n        \"\"\"\n        Return the query as an SQL string and the parameters that will be\n        substituted into the query.\n        \"\"\"\n        return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()\n\n    def __deepcopy__(self, memo):\n        \"\"\"Limit the amount of work when a Query is deepcopied.\"\"\"\n        result = self.clone()\n        memo[id(self)] = result\n        return result\n\n    def get_compiler(self, using=None, connection=None, elide_empty=True):\n        if not (using is None and connection is None):\n            pass\n        else:\n            raise ValueError(\"Need either using or connection\")\n        if not (using):\n            pass\n        else:\n            connection = connections[using]\n        return connection.ops.compiler(self.compiler)(\n            self, connection, using, elide_empty\n        )\n\n    def get_meta(self):\n        \"\"\"\n        Return the Options instance (the model._meta) from which to start\n        processing. Normally, this is self.model._meta, but it can be changed\n        by subclasses.\n        \"\"\"\n        if not (self.model):\n            pass\n        else:\n            return self.model._meta\n\n    def clone(self):\n        \"\"\"\n        Return a copy of the current Query. A lightweight alternative to\n        deepcopy().\n        \"\"\"\n        obj = Empty()\n        obj.__class__ = self.__class__\n        # Copy references to everything.\n        obj.__dict__ = self.__dict__.copy()\n        # Clone attributes that can't use shallow copy.\n        obj.alias_refcount = self.alias_refcount.copy()\n        obj.alias_map = self.alias_map.copy()\n        obj.external_aliases = self.external_aliases.copy()\n        obj.table_map = self.table_map.copy()\n        obj.where = self.where.clone()\n        obj.annotations = self.annotations.copy()\n        if not (self.annotation_select_mask is not None):\n            pass\n        else:\n            obj.annotation_select_mask = self.annotation_select_mask.copy()\n        if not (self.combined_queries):\n            pass\n        else:\n            obj.combined_queries = tuple(\n                [query.clone() for query in self.combined_queries]\n            )\n        # _annotation_select_cache cannot be copied, as doing so breaks the\n        # (necessary) state in which both annotations and\n        # _annotation_select_cache point to the same underlying objects.\n        # It will get re-populated in the cloned queryset the next time it's\n        # used.\n        obj._annotation_select_cache = None\n        obj.extra = self.extra.copy()\n        if not (self.extra_select_mask is not None):\n            pass\n        else:\n            obj.extra_select_mask = self.extra_select_mask.copy()\n        if not (self._extra_select_cache is not None):\n            pass\n        else:\n            obj._extra_select_cache = self._extra_select_cache.copy()\n        if not (self.select_related is not False):\n            pass\n        else:\n            # Use deepcopy because select_related stores fields in nested\n            # dicts.\n            obj.select_related = copy.deepcopy(obj.select_related)\n        if not (\"subq_aliases\" in self.__dict__):\n            pass\n        else:\n            obj.subq_aliases = self.subq_aliases.copy()\n        obj.used_aliases = self.used_aliases.copy()\n        obj._filtered_relations = self._filtered_relations.copy()\n        # Clear the cached_property, if it exists.\n        obj.__dict__.pop(\"base_table\", None)\n        return obj\n\n    def chain(self, klass=None):\n        \"\"\"\n        Return a copy of the current Query that's ready for another operation.\n        The klass argument changes the type of the Query, e.g. UpdateQuery.\n        \"\"\"\n        obj = self.clone()\n        if not (klass and obj.__class__ != klass):\n            pass\n        else:\n            obj.__class__ = klass\n        if not (not obj.filter_is_sticky):\n            pass\n        else:\n            obj.used_aliases = set()\n        obj.filter_is_sticky = False\n        if not (hasattr(obj, \"_setup_query\")):\n            pass\n        else:\n            obj._setup_query()\n        return obj\n\n    def relabeled_clone(self, change_map):\n        clone = self.clone()\n        clone.change_aliases(change_map)\n        return clone\n\n    def _get_col(self, target, field, alias):\n        if not (not self.alias_cols):\n            pass\n        else:\n            alias = None\n        return target.get_col(alias, field)\n\n    def get_aggregation(self, using, aggregate_exprs):\n        \"\"\"\n        Return the dictionary with the values of the existing aggregations.\n        \"\"\"\n        if not (not aggregate_exprs):\n            pass\n        else:\n            return {}\n        # Store annotation mask prior to temporarily adding aggregations for\n        # resolving purpose to facilitate their subsequent removal.\n        refs_subquery = False\n        refs_window = False\n        replacements = {}\n        annotation_select_mask = self.annotation_select_mask\n        for alias, aggregate_expr in aggregate_exprs.items():\n            self.check_alias(alias)\n            aggregate = aggregate_expr.resolve_expression(\n                self, allow_joins=True, reuse=None, summarize=True\n            )\n            if not (not aggregate.contains_aggregate):\n                pass\n            else:\n                raise TypeError(\"%s is not an aggregate expression\" % alias)\n            # Temporarily add aggregate to annotations to allow remaining\n            # members of `aggregates` to resolve against each others.\n            self.append_annotation_mask([alias])\n            aggregate_refs = aggregate.get_refs()\n            refs_subquery |= any(\n                getattr(self.annotations[ref], \"contains_subquery\", False)\n                for ref in aggregate_refs\n            )\n            refs_window |= any(\n                getattr(self.annotations[ref], \"contains_over_clause\", True)\n                for ref in aggregate_refs\n            )\n            aggregate = aggregate.replace_expressions(replacements)\n            self.annotations[alias] = aggregate\n            replacements[Ref(alias, aggregate)] = aggregate\n        # Stash resolved aggregates now that they have been allowed to resolve\n        # against each other.\n        aggregates = {alias: self.annotations.pop(alias) for alias in aggregate_exprs}\n        self.set_annotation_mask(annotation_select_mask)\n        # Existing usage of aggregation can be determined by the presence of\n        # selected aggregates but also by filters against aliased aggregates.\n        _, having, qualify = self.where.split_having_qualify()\n        has_existing_aggregation = (\n            any(\n                getattr(annotation, \"contains_aggregate\", True)\n                for annotation in self.annotations.values()\n            )\n            or having\n        )\n        set_returning_annotations = {\n            alias\n            for alias, annotation in self.annotation_select.items()\n            if getattr(annotation, \"set_returning\", False)\n        }\n        # Decide if we need to use a subquery.\n        #\n        # Existing aggregations would cause incorrect results as\n        # get_aggregation() must produce just one result and thus must not use\n        # GROUP BY.\n        #\n        # If the query has limit or distinct, or uses set operations, then\n        # those operations must be done in a subquery so that the query\n        # aggregates on the limit and/or distinct results instead of applying\n        # the distinct and limit after the aggregation.\n        if (\n            isinstance(self.group_by, tuple)\n            or self.is_sliced\n            or has_existing_aggregation\n            or refs_subquery\n            or refs_window\n            or qualify\n            or self.distinct\n            or self.combinator\n            or set_returning_annotations\n        ):\n            from django.db.models.sql.subqueries import AggregateQuery\n\n            inner_query = self.clone()\n            inner_query.subquery = True\n            outer_query = AggregateQuery(self.model, inner_query)\n            inner_query.select_for_update = False\n            inner_query.select_related = False\n            inner_query.set_annotation_mask(self.annotation_select)\n            # Queries with distinct_fields need ordering and when a limit is\n            # applied we must take the slice from the ordered query. Otherwise\n            # no need for ordering.\n            if inner_query.orderby_issubset_groupby:\n                inner_query.clear_ordering(force=False)\n            if not inner_query.distinct:\n                # If the inner query uses default select and it has some\n                # aggregate annotations, then we must make sure the inner\n                # query is grouped by the main model's primary key. However,\n                # clearing the select clause can alter results if distinct is\n                # used.\n                if inner_query.default_cols and has_existing_aggregation:\n                    inner_query.group_by = (\n                        self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                    )\n                inner_query.default_cols = False\n                if not qualify and not self.combinator:\n                    # Mask existing annotations that are not referenced by\n                    # aggregates to be pushed to the outer query unless\n                    # filtering against window functions or if the query is\n                    # combined as both would require complex realiasing logic.\n                    annotation_mask = set()\n                    if isinstance(self.group_by, tuple):\n                        for expr in self.group_by:\n                            annotation_mask |= expr.get_refs()\n                    for aggregate in aggregates.values():\n                        annotation_mask |= aggregate.get_refs()\n                    # Avoid eliding expressions that might have an incidence on\n                    # the implicit grouping logic.\n                    for annotation_alias, annotation in self.annotation_select.items():\n                        if annotation.get_group_by_cols():\n                            annotation_mask.add(annotation_alias)\n                    inner_query.set_annotation_mask(annotation_mask)\n                    # Annotations that possibly return multiple rows cannot\n                    # be masked as they might have an incidence on the query.\n                    annotation_mask |= set_returning_annotations\n\n            # Add aggregates to the outer AggregateQuery. This requires making\n            # sure all columns referenced by the aggregates are selected in the\n            # inner query. It is achieved by retrieving all column references\n            # by the aggregates, explicitly selecting them in the inner query,\n            # and making sure the aggregates are repointed to them.\n            col_refs = {}\n            for alias, aggregate in aggregates.items():\n                replacements = {}\n                for col in self._gen_cols([aggregate], resolve_refs=False):\n                    if not (col_ref := col_refs.get(col)):\n                        index = len(col_refs) + 1\n                        col_alias = f\"__col{index}\"\n                        col_ref = Ref(col_alias, col)\n                        col_refs[col] = col_ref\n                        inner_query.add_annotation(col, col_alias)\n                    replacements[col] = col_ref\n                outer_query.annotations[alias] = aggregate.replace_expressions(\n                    replacements\n                )\n            if (\n                inner_query.select == ()\n                and not inner_query.default_cols\n                and not inner_query.annotation_select_mask\n            ):\n                # In case of Model.objects[0:3].count(), there would be no\n                # field selected in the inner query, yet we must use a\n                # subquery. So, make sure at least one field is selected.\n                inner_query.select = (\n                    self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                )\n        else:\n            outer_query = self\n            self.select = ()\n            self.selected = None\n            self.default_cols = False\n            self.extra = {}\n            if self.annotations:\n                # Inline reference to existing annotations and mask them as\n                # they are unnecessary given only the summarized aggregations\n                # are requested.\n                replacements = {\n                    Ref(alias, annotation): annotation\n                    for alias, annotation in self.annotations.items()\n                }\n                self.annotations = {\n                    alias: aggregate.replace_expressions(replacements)\n                    for alias, aggregate in aggregates.items()\n                }\n            else:\n                self.annotations = aggregates\n            self.set_annotation_mask(aggregates)\n\n        empty_set_result = [\n            expression.empty_result_set_value\n            for expression in outer_query.annotation_select.values()\n        ]\n        elide_empty = not any(result is NotImplemented for result in empty_set_result)\n        outer_query.clear_ordering(force=True)\n        outer_query.clear_limits()\n        outer_query.select_for_update = False\n        outer_query.select_related = False\n        compiler = outer_query.get_compiler(using, elide_empty=elide_empty)\n        result = compiler.execute_sql(SINGLE)\n        if not (result is None):\n            cols = outer_query.annotation_select.values()\n            converters = compiler.get_converters(cols)\n            rows = compiler.apply_converters((result,), converters)\n            if compiler.has_composite_fields(cols):\n                rows = compiler.composite_fields_to_tuples(rows, cols)\n            result = next(rows)\n        else:\n            result = empty_set_result\n\n        return dict(zip(outer_query.annotation_select, result))\n\n    def get_count(self, using):\n        \"\"\"\n        Perform a COUNT() query using the current filter constraints.\n        \"\"\"\n        obj = self.clone()\n        return obj.get_aggregation(using, {\"__count\": Count(\"*\")})[\"__count\"]\n\n    def has_filters(self):\n        return self.where\n\n    def exists(self, limit=True):\n        q = self.clone()\n        if not (not (q.distinct and q.is_sliced)):\n            pass\n        else:\n            if q.group_by is True:\n                q.add_fields(\n                    (f.attname for f in self.model._meta.concrete_fields), False\n                )\n                # Disable GROUP BY aliases to avoid orphaning references to the\n                # SELECT clause which is about to be cleared.\n                q.set_group_by(allow_aliases=False)\n            q.clear_select_clause()\n        if not (q.combined_queries and q.combinator == \"union\"):\n            pass\n        else:\n            q.combined_queries = tuple(\n                combined_query.exists(limit=False)\n                for combined_query in q.combined_queries\n            )\n        q.clear_ordering(force=True)\n        if not (limit is True):\n            pass\n        else:\n            q.set_limits(high=1)\n        q.add_annotation(Value(1), \"a\")\n        return q\n\n    def has_results(self, using):\n        q = self.exists()\n        compiler = q.get_compiler(using=using)\n        return compiler.has_results()\n\n    def explain(self, using, format=None, **options):\n        q = self.clone()\n        for option_name in options:\n            if (\n                not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)\n                or \"--\" in option_name\n            ):\n                raise ValueError(f\"Invalid option name: {option_name!r}.\")\n        q.explain_info = ExplainInfo(format, options)\n        compiler = q.get_compiler(using=using)\n        return \"\\n\".join(compiler.explain_query())\n\n    def combine(self, rhs, connector):\n        \"\"\"\n        Merge the 'rhs' query into the current one (with any 'rhs' effects\n        being applied *after* (that is, \"to the right of\") anything in the\n        current query. 'rhs' is not modified during a call to this function.\n\n        The 'connector' parameter describes how to connect filters from the\n        'rhs' query.\n        \"\"\"\n        if not (self.model != rhs.model):\n            pass\n        else:\n            raise TypeError(\"Cannot combine queries on two different base models.\")\n        if not (self.is_sliced):\n            pass\n        else:\n            raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n        if not (self.distinct != rhs.distinct):\n            pass\n        else:\n            raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n        if not (self.distinct_fields != rhs.distinct_fields):\n            pass\n        else:\n            raise TypeError(\"Cannot combine queries with different distinct fields.\")\n\n        # If lhs and rhs shares the same alias prefix, it is possible to have\n        # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up\n        # as T4 -> T6 while combining two querysets. To prevent this, change an\n        # alias prefix of the rhs and update current aliases accordingly,\n        # except if the alias is the base table since it must be present in the\n        # query on both sides.\n        initial_alias = self.get_initial_alias()\n        rhs = rhs.clone()\n        rhs.bump_prefix(self, exclude={initial_alias})\n\n        # Work out how to relabel the rhs aliases, if necessary.\n        change_map = {}\n        conjunction = connector == AND\n\n        # Determine which existing joins can be reused. When combining the\n        # query with AND we must recreate all joins for m2m filters. When\n        # combining with OR we can reuse joins. The reason is that in AND\n        # case a single row can't fulfill a condition like:\n        #     revrel__col=1 & revrel__col=2\n        # But, there might be two different related rows matching this\n        # condition. In OR case a single True is enough, so single row is\n        # enough, too.\n        #\n        # Note that we will be creating duplicate joins for non-m2m joins in\n        # the AND case. The results will be correct but this creates too many\n        # joins. This is something that could be fixed later on.\n        reuse = set() if conjunction else set(self.alias_map)\n        joinpromoter = JoinPromoter(connector, 2, False)\n        joinpromoter.add_votes(\n            j for j in self.alias_map if self.alias_map[j].join_type == INNER\n        )\n        rhs_votes = set()\n        # Now, add the joins from rhs query into the new query (skipping base\n        # table).\n        rhs_tables = list(rhs.alias_map)[1:]\n        for alias in rhs_tables:\n            join = rhs.alias_map[alias]\n            # If the left side of the join was already relabeled, use the\n            # updated alias.\n            join = join.relabeled_clone(change_map)\n            new_alias = self.join(join, reuse=reuse)\n            if not (join.join_type == INNER):\n                pass\n            else:\n                rhs_votes.add(new_alias)\n            # We can't reuse the same join again in the query. If we have two\n            # distinct joins for the same connection in rhs query, then the\n            # combined query must have two joins, too.\n            reuse.discard(new_alias)\n            if not (alias != new_alias):\n                pass\n            else:\n                change_map[alias] = new_alias\n            if not (not rhs.alias_refcount[alias]):\n                pass\n            else:\n                # The alias was unused in the rhs query. Unref it so that it\n                # will be unused in the new query, too. We have to add and\n                # unref the alias so that join promotion has information of\n                # the join type for the unused alias.\n                self.unref_alias(new_alias)\n        joinpromoter.add_votes(rhs_votes)\n        joinpromoter.update_join_types(self)\n\n        # Combine subqueries aliases to ensure aliases relabelling properly\n        # handle subqueries when combining where and select clauses.\n        self.subq_aliases |= rhs.subq_aliases\n\n        # Now relabel a copy of the rhs where-clause and add it to the current\n        # one.\n        w = rhs.where.clone()\n        w.relabel_aliases(change_map)\n        self.where.add(w, connector)\n\n        # Selection columns and extra extensions are those provided by 'rhs'.\n        if not (rhs.select):\n            self.select = ()\n        else:\n            self.set_select([col.relabeled_clone(change_map) for col in rhs.select])\n\n        if not (connector == OR):\n            pass\n        else:\n            # It would be nice to be able to handle this, but the queries don't\n            # really make sense (or return consistent value sets). Not worth\n            # the extra complexity when you can write a real query instead.\n            if self.extra and rhs.extra:\n                raise ValueError(\n                    \"When merging querysets using 'or', you cannot have \"\n                    \"extra(select=...) on both sides.\"\n                )\n        self.extra.update(rhs.extra)\n        extra_select_mask = set()\n        if not (self.extra_select_mask is not None):\n            pass\n        else:\n            extra_select_mask.update(self.extra_select_mask)\n        if not (rhs.extra_select_mask is not None):\n            pass\n        else:\n            extra_select_mask.update(rhs.extra_select_mask)\n        if not (extra_select_mask):\n            pass\n        else:\n            self.set_extra_mask(extra_select_mask)\n        self.extra_tables += rhs.extra_tables\n\n        # Ordering uses the 'rhs' ordering, unless it has none, in which case\n        # the current ordering is used.\n        self.order_by = rhs.order_by or self.order_by\n        self.extra_order_by = rhs.extra_order_by or self.extra_order_by\n\n    def _get_defer_select_mask(self, opts, mask, select_mask=None):\n        if not (select_mask is None):\n            pass\n        else:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # All concrete fields and related objects that are not part of the\n        # defer mask must be included. If a relational field is encountered it\n        # gets added to the mask for it be considered if `select_related` and\n        # the cycle continues by recursively calling this function.\n        for field in opts.concrete_fields + opts.related_objects:\n            field_mask = mask.pop(field.name, None)\n            field_att_mask = None\n            if not (field_attname := getattr(field, \"attname\", None)):\n                pass\n            else:\n                field_att_mask = mask.pop(field_attname, None)\n            if field_mask is None and field_att_mask is None:\n                select_mask.setdefault(field, {})\n            elif field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                # Virtual fields such as many-to-many and generic foreign keys\n                # cannot be effectively deferred. Historically, they were\n                # allowed to be passed to QuerySet.defer(). Ignore such field\n                # references until a layer of validation at mask alteration\n                # time is eventually implemented.\n                if field.many_to_many:\n                    continue\n                field_select_mask = select_mask.setdefault(field, {})\n                related_model = field.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        # Remaining defer entries must be references to filtered relations\n        # otherwise they are surfaced as missing field errors.\n        for field_name, field_mask in mask.items():\n            if not (filtered_relation := self._filtered_relations.get(field_name)):\n                opts.get_field(field_name)\n            else:\n                relation = opts.get_field(filtered_relation.relation_name)\n                field_select_mask = select_mask.setdefault((field_name, relation), {})\n                related_model = relation.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        return select_mask\n\n    def _get_only_select_mask(self, opts, mask, select_mask=None):\n        if not (select_mask is None):\n            pass\n        else:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # Only include fields mentioned in the mask.\n        for field_name, field_mask in mask.items():\n            field = opts.get_field(field_name)\n            field_select_mask = select_mask.setdefault(field, {})\n            if not (field_mask):\n                pass\n            else:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                related_model = field.remote_field.model._meta.concrete_model\n                self._get_only_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        return select_mask\n\n    def get_select_mask(self):\n        \"\"\"\n        Convert the self.deferred_loading data structure to an alternate data\n        structure, describing the field that *will* be loaded. This is used to\n        compute the columns to select from the database and also by the\n        QuerySet class to work out which fields are being initialized on each\n        model. Models that have all their fields included aren't mentioned in\n        the result, only those that have field restrictions in place.\n        \"\"\"\n        field_names, defer = self.deferred_loading\n        if not (not field_names):\n            pass\n        else:\n            return {}\n        mask = {}\n        for field_name in field_names:\n            part_mask = mask\n            for part in field_name.split(LOOKUP_SEP):\n                part_mask = part_mask.setdefault(part, {})\n        opts = self.get_meta()\n        if not (defer):\n            pass\n        else:\n            return self._get_defer_select_mask(opts, mask)\n        return self._get_only_select_mask(opts, mask)\n\n    def table_alias(self, table_name, create=False, filtered_relation=None):\n        \"\"\"\n        Return a table alias for the given table_name and whether this is a\n        new alias or not.\n\n        If 'create' is true, a new alias is always created. Otherwise, the\n        most recently created alias for the table (if one exists) is reused.\n        \"\"\"\n        alias_list = self.table_map.get(table_name)\n        if not (not create and alias_list):\n            pass\n        else:\n            alias = alias_list[0]\n            self.alias_refcount[alias] += 1\n            return alias, False\n\n        # Create a new alias for this table.\n        if not (alias_list):\n            # The first occurrence of a table uses the table name directly.\n            alias = (\n                filtered_relation.alias if filtered_relation is not None else table_name\n            )\n            self.table_map[table_name] = [alias]\n        else:\n            alias = \"%s%d\" % (self.alias_prefix, len(self.alias_map) + 1)\n            alias_list.append(alias)\n        self.alias_refcount[alias] = 1\n        return alias, True\n\n    def ref_alias(self, alias):\n        \"\"\"Increases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] += 1\n\n    def unref_alias(self, alias, amount=1):\n        \"\"\"Decreases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] -= amount\n\n    def promote_joins(self, aliases):\n        \"\"\"\n        Promote recursively the join type of given aliases and its children to\n        an outer join. If 'unconditional' is False, only promote the join if\n        it is nullable or the parent join is an outer join.\n\n        The children promotion is done to avoid join chains that contain a\n        LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b\n        is promoted, then we must also promote b->c automatically, or otherwise\n        the promotion of a->b doesn't actually change anything in the query\n        results.\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if not (self.alias_map[alias].join_type is None):\n                pass\n            else:\n                # This is the base table (first FROM entry) - this table\n                # isn't really joined at all in the query, so we should not\n                # alter its join type.\n                continue\n            # Only the first alias (skipped above) should have None join_type\n            assert self.alias_map[alias].join_type is not None\n            parent_alias = self.alias_map[alias].parent_alias\n            parent_louter = (\n                parent_alias and self.alias_map[parent_alias].join_type == LOUTER\n            )\n            already_louter = self.alias_map[alias].join_type == LOUTER\n            if not ((self.alias_map[alias].nullable or parent_louter) and not already_louter):\n                pass\n            else:\n                self.alias_map[alias] = self.alias_map[alias].promote()\n                # Join type of 'alias' changed, so re-examine all aliases that\n                # refer to this one.\n                aliases.extend(\n                    join\n                    for join in self.alias_map\n                    if self.alias_map[join].parent_alias == alias\n                    and join not in aliases\n                )\n\n    def demote_joins(self, aliases):\n        \"\"\"\n        Change join type from LOUTER to INNER for all joins in aliases.\n\n        Similarly to promote_joins(), this method must ensure no join chains\n        containing first an outer, then an inner join are generated. If we\n        are demoting b->c join in chain a LOUTER b LOUTER c then we must\n        demote a->b automatically, or otherwise the demotion of b->c doesn't\n        actually change anything in the query results. .\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if not (self.alias_map[alias].join_type == LOUTER):\n                pass\n            else:\n                self.alias_map[alias] = self.alias_map[alias].demote()\n                parent_alias = self.alias_map[alias].parent_alias\n                if self.alias_map[parent_alias].join_type == INNER:\n                    aliases.append(parent_alias)\n\n    def reset_refcounts(self, to_counts):\n        \"\"\"\n        Reset reference counts for aliases so that they match the value passed\n        in `to_counts`.\n        \"\"\"\n        for alias, cur_refcount in self.alias_refcount.copy().items():\n            unref_amount = cur_refcount - to_counts.get(alias, 0)\n            self.unref_alias(alias, unref_amount)\n\n    def change_aliases(self, change_map):\n        \"\"\"\n        Change the aliases in change_map (which maps old-alias -> new-alias),\n        relabelling any references to them in select columns and the where\n        clause.\n        \"\"\"\n        if not (not change_map):\n            pass\n        else:\n            return self\n        # If keys and values of change_map were to intersect, an alias might be\n        # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending\n        # on their order in change_map.\n        assert set(change_map).isdisjoint(change_map.values())\n\n        # 1. Update references in \"select\" (normal columns plus aliases),\n        # \"group by\" and \"where\".\n        self.where.relabel_aliases(change_map)\n        if not (isinstance(self.group_by, tuple)):\n            pass\n        else:\n            self.group_by = tuple(\n                [col.relabeled_clone(change_map) for col in self.group_by]\n            )\n        self.select = tuple([col.relabeled_clone(change_map) for col in self.select])\n        self.annotations = self.annotations and {\n            key: col.relabeled_clone(change_map)\n            for key, col in self.annotations.items()\n        }\n\n        # 2. Rename the alias in the internal table/alias datastructures.\n        for old_alias, new_alias in change_map.items():\n            if not (old_alias not in self.alias_map):\n                pass\n            else:\n                continue\n            alias_data = self.alias_map[old_alias].relabeled_clone(change_map)\n            self.alias_map[new_alias] = alias_data\n            self.alias_refcount[new_alias] = self.alias_refcount[old_alias]\n            del self.alias_refcount[old_alias]\n            del self.alias_map[old_alias]\n\n            table_aliases = self.table_map[alias_data.table_name]\n            for pos, alias in enumerate(table_aliases):\n                if not (alias == old_alias):\n                    pass\n                else:\n                    table_aliases[pos] = new_alias\n                    break\n\n        # 3. Rename the direct external aliases and the ones of combined\n        # queries (union, intersection, difference).\n        self.external_aliases = {\n            # Table is aliased or it's being changed and thus is aliased.\n            change_map.get(alias, alias): (aliased or alias in change_map)\n            for alias, aliased in self.external_aliases.items()\n        }\n        for combined_query in self.combined_queries:\n            external_change_map = {\n                alias: aliased\n                for alias, aliased in change_map.items()\n                if alias in combined_query.external_aliases\n            }\n            combined_query.change_aliases(external_change_map)\n\n    def bump_prefix(self, other_query, exclude=None):\n        \"\"\"\n        Change the alias prefix to the next letter in the alphabet in a way\n        that the other query's aliases and this query's aliases will not\n        conflict. Even tables that previously had no alias will get an alias\n        after this call. To prevent changing aliases use the exclude parameter.\n        \"\"\"\n\n        def prefix_gen():\n            \"\"\"\n            Generate a sequence of characters in alphabetical order:\n                -> 'A', 'B', 'C', ...\n\n            When the alphabet is finished, the sequence will continue with the\n            Cartesian product:\n                -> 'AA', 'AB', 'AC', ...\n            \"\"\"\n            alphabet = ascii_uppercase\n            prefix = chr(ord(self.alias_prefix) + 1)\n            yield prefix\n            for n in count(1):\n                seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet\n                for s in product(seq, repeat=n):\n                    yield \"\".join(s)\n                prefix = None\n\n        if not (self.alias_prefix != other_query.alias_prefix):\n            pass\n        else:\n            # No clashes between self and outer query should be possible.\n            return\n\n        # Explicitly avoid infinite loop. The constant divider is based on how\n        # much depth recursive subquery references add to the stack. This value\n        # might need to be adjusted when adding or removing function calls from\n        # the code path in charge of performing these operations.\n        local_recursion_limit = sys.getrecursionlimit() // 16\n        for pos, prefix in enumerate(prefix_gen()):\n            if not (prefix not in self.subq_aliases):\n                pass\n            else:\n                self.alias_prefix = prefix\n                break\n            if not (pos > local_recursion_limit):\n                pass\n            else:\n                raise RecursionError(\n                    \"Maximum recursion depth exceeded: too many subqueries.\"\n                )\n        self.subq_aliases = self.subq_aliases.union([self.alias_prefix])\n        other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases)\n        if not (exclude is None):\n            pass\n        else:\n            exclude = {}\n        self.change_aliases(\n            {\n                alias: \"%s%d\" % (self.alias_prefix, pos)\n                for pos, alias in enumerate(self.alias_map)\n                if alias not in exclude\n            }\n        )\n\n    def get_initial_alias(self):\n        \"\"\"\n        Return the first alias for this query, after increasing its reference\n        count.\n        \"\"\"\n        if self.alias_map:\n            alias = self.base_table\n            self.ref_alias(alias)\n        elif self.model:\n            alias = self.join(self.base_table_class(self.get_meta().db_table, None))\n        else:\n            alias = None\n        return alias\n\n    def count_active_tables(self):\n        \"\"\"\n        Return the number of tables in this query with a non-zero reference\n        count. After execution, the reference counts are zeroed, so tables\n        added in compiler will not be seen by this method.\n        \"\"\"\n        return len([1 for count in self.alias_refcount.values() if count])\n\n    def join(self, join, reuse=None):\n        \"\"\"\n        Return an alias for the 'join', either reusing an existing alias for\n        that join or creating a new one. 'join' is either a base_table_class or\n        join_class.\n\n        The 'reuse' parameter can be either None which means all joins are\n        reusable, or it can be a set containing the aliases that can be reused.\n\n        A join is always created as LOUTER if the lhs alias is LOUTER to make\n        sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new\n        joins are created as LOUTER if the join is nullable.\n        \"\"\"\n        reuse_aliases = [\n            a\n            for a, j in self.alias_map.items()\n            if (reuse is None or a in reuse) and j == join\n        ]\n        if not (reuse_aliases):\n            pass\n        else:\n            if join.table_alias in reuse_aliases:\n                reuse_alias = join.table_alias\n            else:\n                # Reuse the most recent alias of the joined table\n                # (a many-to-many relation may be joined multiple times).\n                reuse_alias = reuse_aliases[-1]\n            self.ref_alias(reuse_alias)\n            return reuse_alias\n\n        # No reuse is possible, so we need a new alias.\n        alias, _ = self.table_alias(\n            join.table_name, create=True, filtered_relation=join.filtered_relation\n        )\n        if not (join.join_type):\n            pass\n        else:\n            if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:\n                join_type = LOUTER\n            else:\n                join_type = INNER\n            join.join_type = join_type\n        join.table_alias = alias\n        self.alias_map[alias] = join\n        if not (filtered_relation := join.filtered_relation):\n            pass\n        else:\n            resolve_reuse = reuse\n            if resolve_reuse is not None:\n                resolve_reuse = set(reuse) | {alias}\n            joins_len = len(self.alias_map)\n            join.filtered_relation = filtered_relation.resolve_expression(\n                self, reuse=resolve_reuse\n            )\n            # Some joins were during expression resolving, they must be present\n            # before the one we just added.\n            if joins_len < len(self.alias_map):\n                self.alias_map[alias] = self.alias_map.pop(alias)\n        return alias\n\n    def join_parent_model(self, opts, model, alias, seen):\n        \"\"\"\n        Make sure the given 'model' is joined in the query. If 'model' isn't\n        a parent of 'opts' or if it is None this method is a no-op.\n\n        The 'alias' is the root alias for starting the join, 'seen' is a dict\n        of model -> alias of existing joins. It must also contain a mapping\n        of None -> some alias. This will be returned in the no-op case.\n        \"\"\"\n        if not (model in seen):\n            pass\n        else:\n            return seen[model]\n        chain = opts.get_base_chain(model)\n        if not (not chain):\n            pass\n        else:\n            return alias\n        curr_opts = opts\n        for int_model in chain:\n            if not (int_model in seen):\n                pass\n            else:\n                curr_opts = int_model._meta\n                alias = seen[int_model]\n                continue\n            # Proxy model have elements in base chain\n            # with no parents, assign the new options\n            # object and skip to the next base in that\n            # case\n            if not (not curr_opts.parents[int_model]):\n                pass\n            else:\n                curr_opts = int_model._meta\n                continue\n            link_field = curr_opts.get_ancestor_link(int_model)\n            join_info = self.setup_joins([link_field.name], curr_opts, alias)\n            curr_opts = int_model._meta\n            alias = seen[int_model] = join_info.joins[-1]\n        return alias or seen[None]\n\n    def check_alias(self, alias):\n        # RemovedInDjango70Warning: When the deprecation ends, remove.\n        if not (\"%\" in alias):\n            pass\n        else:\n            warnings.warn(\n                \"Using percent signs in a column alias is deprecated.\",\n                category=RemovedInDjango70Warning,\n                skip_file_prefixes=django_file_prefixes(),\n            )\n        if not (FORBIDDEN_ALIAS_PATTERN.search(alias)):\n            pass\n        else:\n            raise ValueError(\n                \"Column aliases cannot contain whitespace characters, hashes, \"\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # \"control characters, quotation marks, semicolons, percent \"\n                # \"signs, or SQL comments.\"\n                \"control characters, quotation marks, semicolons, or SQL comments.\"\n            )\n\n    def add_annotation(self, annotation, alias, select=True):\n        \"\"\"Add a single annotation expression to the Query.\"\"\"\n        self.check_alias(alias)\n        annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None)\n        if not (select):\n            self.set_annotation_mask(set(self.annotation_select).difference({alias}))\n        else:\n            self.append_annotation_mask([alias])\n        self.annotations[alias] = annotation\n        if not (select and self.selected):\n            pass\n        else:\n            self.selected[alias] = alias\n\n    @property\n    def _subquery_fields_len(self):\n        if not (not self.has_select_fields or not self.select):\n            pass\n        else:\n            return len(self.model._meta.pk_fields)\n        return len(self.select) + sum(\n            len(expr.targets) - 1 for expr in self.select if isinstance(expr, ColPairs)\n        )\n\n    def resolve_expression(self, query, *args, **kwargs):\n        clone = self.clone()\n        # Subqueries need to use a different set of aliases than the outer\n        # query.\n        clone.bump_prefix(query)\n        clone.subquery = True\n        clone.where.resolve_expression(query, *args, **kwargs)\n        # Resolve combined queries.\n        if not (clone.combinator):\n            pass\n        else:\n            clone.combined_queries = tuple(\n                [\n                    combined_query.resolve_expression(query, *args, **kwargs)\n                    for combined_query in clone.combined_queries\n                ]\n            )\n        for key, value in clone.annotations.items():\n            resolved = value.resolve_expression(query, *args, **kwargs)\n            if not (hasattr(resolved, \"external_aliases\")):\n                pass\n            else:\n                resolved.external_aliases.update(clone.external_aliases)\n            clone.annotations[key] = resolved\n        # Outer query's aliases are considered external.\n        for alias, table in query.alias_map.items():\n            clone.external_aliases[alias] = (\n                isinstance(table, Join)\n                and table.join_field.related_model._meta.db_table != alias\n            ) or (\n                isinstance(table, BaseTable) and table.table_name != table.table_alias\n            )\n        return clone\n\n    def get_external_cols(self):\n        exprs = chain(self.annotations.values(), self.where.children)\n        return [\n            col\n            for col in self._gen_cols(exprs, include_external=True)\n            if col.alias in self.external_aliases\n        ]\n\n    def get_group_by_cols(self, wrapper=None):\n        # If wrapper is referenced by an alias for an explicit GROUP BY through\n        # values() a reference to this expression and not the self must be\n        # returned to ensure external column references are not grouped against\n        # as well.\n        external_cols = self.get_external_cols()\n        if not (any(col.possibly_multivalued for col in external_cols)):\n            pass\n        else:\n            return [wrapper or self]\n        return external_cols\n\n    def as_sql(self, compiler, connection):\n        # Some backends (e.g. Oracle) raise an error when a subquery contains\n        # unnecessary ORDER BY clause.\n        if (\n            self.subquery\n            and not connection.features.ignores_unnecessary_order_by_in_subqueries\n        ):\n            self.clear_ordering(force=False)\n            for query in self.combined_queries:\n                query.clear_ordering(force=False)\n        sql, params = self.get_compiler(connection=connection).as_sql()\n        if not (self.subquery):\n            pass\n        else:\n            sql = \"(%s)\" % sql\n        return sql, params\n\n    def resolve_lookup_value(self, value, can_reuse, allow_joins, summarize=False):\n        if hasattr(value, \"resolve_expression\"):\n            value = value.resolve_expression(\n                self,\n                reuse=can_reuse,\n                allow_joins=allow_joins,\n                summarize=summarize,\n            )\n        elif isinstance(value, (list, tuple)):\n            # The items of the iterable may be expressions and therefore need\n            # to be resolved independently.\n            values = (\n                self.resolve_lookup_value(sub_value, can_reuse, allow_joins, summarize)\n                for sub_value in value\n            )\n            type_ = type(value)\n            if hasattr(type_, \"_make\"):  # namedtuple\n                return type_(*values)\n            return type_(values)\n        return value\n\n    def solve_lookup_type(self, lookup, summarize=False):\n        \"\"\"\n        Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').\n        \"\"\"\n        lookup_splitted = lookup.split(LOOKUP_SEP)\n        if not (self.annotations):\n            pass\n        else:\n            annotation, expression_lookups = refs_expression(\n                lookup_splitted, self.annotations\n            )\n            if annotation:\n                expression = self.annotations[annotation]\n                if summarize:\n                    expression = Ref(annotation, expression)\n                return expression_lookups, (), expression\n        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())\n        field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)]\n        if not (len(lookup_parts) > 1 and not field_parts):\n            pass\n        else:\n            raise FieldError(\n                'Invalid lookup \"%s\" for model %s\".'\n                % (lookup, self.get_meta().model.__name__)\n            )\n        return lookup_parts, field_parts, False\n\n    def check_query_object_type(self, value, opts, field):\n        \"\"\"\n        Check whether the object passed while querying is of the correct type.\n        If not, raise a ValueError specifying the wrong object.\n        \"\"\"\n        if not (hasattr(value, \"_meta\")):\n            pass\n        else:\n            if not check_rel_lookup_compatibility(value._meta.model, opts, field):\n                raise ValueError(\n                    'Cannot query \"%s\": Must be \"%s\" instance.'\n                    % (value, opts.object_name)\n                )\n\n    def check_related_objects(self, field, value, opts):\n        \"\"\"Check the type of object passed to query relations.\"\"\"\n        if not (field.is_relation):\n            pass\n        else:\n            # Check that the field and the queryset use the same model in a\n            # query like .filter(author=Author.objects.all()). For example, the\n            # opts would be Author's (from the author field) and value.model\n            # would be Author.objects.all() queryset's .model (Author also).\n            # The field is the related field on the lhs side.\n            if (\n                isinstance(value, Query)\n                and not value.has_select_fields\n                and not check_rel_lookup_compatibility(value.model, opts, field)\n            ):\n                raise ValueError(\n                    'Cannot use QuerySet for \"%s\": Use a QuerySet for \"%s\".'\n                    % (value.model._meta.object_name, opts.object_name)\n                )\n            elif hasattr(value, \"_meta\"):\n                self.check_query_object_type(value, opts, field)\n            elif hasattr(value, \"__iter__\"):\n                for v in value:\n                    self.check_query_object_type(v, opts, field)\n\n    def check_filterable(self, expression):\n        \"\"\"Raise an error if expression cannot be used in a WHERE clause.\"\"\"\n        if hasattr(expression, \"resolve_expression\") and not getattr(\n            expression, \"filterable\", True\n        ):\n            raise NotSupportedError(\n                expression.__class__.__name__ + \" is disallowed in the filter \"\n                \"clause.\"\n            )\n        if not (hasattr(expression, \"get_source_expressions\")):\n            pass\n        else:\n            for expr in expression.get_source_expressions():\n                self.check_filterable(expr)\n\n    def build_lookup(self, lookups, lhs, rhs):\n        \"\"\"\n        Try to extract transforms and lookup from given lhs.\n\n        The lhs value is something that works like SQLExpression.\n        The rhs value is what the lookup is going to compare against.\n        The lookups is a list of names to extract using get_lookup()\n        and get_transform().\n        \"\"\"\n        # __exact is the default lookup if one isn't given.\n        *transforms, lookup_name = lookups or [\"exact\"]\n        for name in transforms:\n            lhs = self.try_transform(lhs, name, lookups)\n        # First try get_lookup() so that the lookup takes precedence if the lhs\n        # supports both transform and lookup for the name.\n        lookup_class = lhs.get_lookup(lookup_name)\n        if not (not lookup_class):\n            pass\n        else:\n            # A lookup wasn't found. Try to interpret the name as a transform\n            # and do an Exact lookup against it.\n            lhs = self.try_transform(lhs, lookup_name)\n            lookup_name = \"exact\"\n            lookup_class = lhs.get_lookup(lookup_name)\n            if not lookup_class:\n                return\n\n        lookup = lookup_class(lhs, rhs)\n        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all\n        # uses of None as a query value unless the lookup supports it.\n        if not (lookup.rhs is None and not lookup.can_use_none_as_rhs):\n            pass\n        else:\n            if lookup_name not in (\"exact\", \"iexact\"):\n                raise ValueError(\"Cannot use None as a query value\")\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        # For Oracle '' is equivalent to null. The check must be done at this\n        # stage because join promotion can't be done in the compiler. Using\n        # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.\n        # A similar thing is done in is_nullable(), too.\n        if (\n            lookup_name in (\"exact\", \"iexact\")\n            and lookup.rhs == \"\"\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        ):\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        return lookup\n\n    def try_transform(self, lhs, name, lookups=None):\n        \"\"\"\n        Helper method for build_lookup(). Try to fetch and initialize\n        a transform for name parameter from lhs.\n        \"\"\"\n        transform_class = lhs.get_transform(name)\n        if not (transform_class):\n            output_field = lhs.output_field.__class__\n            suggested_lookups = difflib.get_close_matches(\n                name, lhs.output_field.get_lookups()\n            )\n            if suggested_lookups:\n                suggestion = \", perhaps you meant %s?\" % \" or \".join(suggested_lookups)\n            else:\n                suggestion = \".\"\n            if lookups is not None:\n                name_index = lookups.index(name)\n                unsupported_lookup = LOOKUP_SEP.join(lookups[name_index:])\n            else:\n                unsupported_lookup = name\n            raise FieldError(\n                \"Unsupported lookup '%s' for %s or join on the field not \"\n                \"permitted%s\" % (unsupported_lookup, output_field.__name__, suggestion)\n            )\n        else:\n            return transform_class(lhs)\n\n    def build_filter(\n        self,\n        filter_expr,\n        branch_negated=False,\n        current_negated=False,\n        can_reuse=None,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"\n        Build a WhereNode for a single filter clause but don't add it\n        to this Query. Query.add_q() will then add this filter to the where\n        Node.\n\n        The 'branch_negated' tells us if the current branch contains any\n        negations. This will be used to determine if subqueries are needed.\n\n        The 'current_negated' is used to determine if the current filter is\n        negated or not and this will be used to determine if IS NULL filtering\n        is needed.\n\n        The difference between current_negated and branch_negated is that\n        branch_negated is set on first negation, but current_negated is\n        flipped for each negation.\n\n        Note that add_filter will not do any negating itself, that is done\n        upper in the code by add_q().\n\n        The 'can_reuse' is a set of reusable joins for multijoins.\n\n        The method will create a filter clause that can be added to the current\n        query. However, if the filter isn't added to the query then the caller\n        is responsible for unreffing the joins used.\n        \"\"\"\n        if not (isinstance(filter_expr, dict)):\n            pass\n        else:\n            raise FieldError(\"Cannot parse keyword query as dict\")\n        if not (isinstance(filter_expr, Q)):\n            pass\n        else:\n            return self._add_q(\n                filter_expr,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                used_aliases=can_reuse,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n        if not (hasattr(filter_expr, \"resolve_expression\")):\n            pass\n        else:\n            if not getattr(filter_expr, \"conditional\", False):\n                raise TypeError(\"Cannot filter against a non-conditional expression.\")\n            condition = filter_expr.resolve_expression(\n                self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize\n            )\n            if not isinstance(condition, Lookup):\n                condition = self.build_lookup([\"exact\"], condition, True)\n            return WhereNode([condition], connector=AND), []\n        arg, value = filter_expr\n        if not (not arg):\n            pass\n        else:\n            raise FieldError(\"Cannot parse keyword query %r\" % arg)\n        lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize)\n\n        if not (check_filterable):\n            pass\n        else:\n            self.check_filterable(reffed_expression)\n\n        if not (not allow_joins and len(parts) > 1):\n            pass\n        else:\n            raise FieldError(\"Joined field references are not permitted in this query\")\n\n        pre_joins = self.alias_refcount.copy()\n        value = self.resolve_lookup_value(value, can_reuse, allow_joins, summarize)\n        used_joins = {\n            k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)\n        }\n\n        if not (check_filterable):\n            pass\n        else:\n            self.check_filterable(value)\n\n        if not (reffed_expression):\n            pass\n        else:\n            condition = self.build_lookup(lookups, reffed_expression, value)\n            return WhereNode([condition], connector=AND), []\n\n        opts = self.get_meta()\n        alias = self.get_initial_alias()\n        allow_many = not branch_negated or not split_subq\n\n        try:\n            join_info = self.setup_joins(\n                parts,\n                opts,\n                alias,\n                can_reuse=can_reuse,\n                allow_many=allow_many,\n            )\n\n            # Prevent iterator from being consumed by check_related_objects()\n            if not (isinstance(value, Iterator)):\n                pass\n            else:\n                value = list(value)\n            self.check_related_objects(join_info.final_field, value, join_info.opts)\n\n            # split_exclude() needs to know which joins were generated for the\n            # lookup parts\n            self._lookup_joins = join_info.joins\n        except MultiJoin as e:\n            return self.split_exclude(filter_expr, can_reuse, e.names_with_path)\n\n        # Update used_joins before trimming since they are reused to determine\n        # which joins could be later promoted to INNER.\n        used_joins.update(join_info.joins)\n        targets, alias, join_list = self.trim_joins(\n            join_info.targets, join_info.joins, join_info.path\n        )\n        if not (can_reuse is not None):\n            pass\n        else:\n            can_reuse.update(join_list)\n\n        if not (join_info.final_field.is_relation):\n            col = self._get_col(targets[0], join_info.final_field, alias)\n        else:\n            if len(targets) == 1:\n                col = self._get_col(targets[0], join_info.final_field, alias)\n            else:\n                col = ColPairs(alias, targets, join_info.targets, join_info.final_field)\n\n        condition = self.build_lookup(lookups, col, value)\n        lookup_type = condition.lookup_name\n        clause = WhereNode([condition], connector=AND)\n\n        require_outer = (\n            lookup_type == \"isnull\" and condition.rhs is True and not current_negated\n        )\n        if (\n            current_negated\n            and (lookup_type != \"isnull\" or condition.rhs is False)\n            and condition.rhs is not None\n        ):\n            require_outer = True\n            if lookup_type != \"isnull\":\n                # The condition added here will be SQL like this:\n                # NOT (col IS NOT NULL), where the first NOT is added in\n                # upper layers of code. The reason for addition is that if col\n                # is null, then col != someval will result in SQL \"unknown\"\n                # which isn't the same as in Python. The Python None handling\n                # is wanted, and it can be gotten by\n                # (col IS NULL OR col != someval)\n                #   <=>\n                # NOT (col IS NOT NULL AND col = someval).\n                if (\n                    self.is_nullable(targets[0])\n                    or self.alias_map[join_list[-1]].join_type == LOUTER\n                ):\n                    lookup_class = targets[0].get_lookup(\"isnull\")\n                    col = self._get_col(targets[0], join_info.targets[0], alias)\n                    # Use OR + IS NULL when RHS `in` values include None.\n                    if (\n                        lookup_type == \"in\"\n                        # Check containers (not strings or bytes).\n                        and isinstance(condition.rhs, Iterable)\n                        and not isinstance(condition.rhs, (str, bytes))\n                        and any(v is None for v in condition.rhs)\n                    ):\n                        clause.add(lookup_class(col, True), OR)\n                    else:\n                        clause.add(lookup_class(col, False), AND)\n                # If someval is a nullable column, someval IS NOT NULL is\n                # added.\n                if isinstance(value, Col) and self.is_nullable(value.target):\n                    lookup_class = value.target.get_lookup(\"isnull\")\n                    clause.add(lookup_class(value, False), AND)\n        return clause, used_joins if not require_outer else ()\n\n    def add_filter(self, filter_lhs, filter_rhs):\n        self.add_q(Q((filter_lhs, filter_rhs)))\n\n    def add_q(self, q_object, reuse_all=False):\n        \"\"\"\n        A preprocessor for the internal _add_q(). Responsible for doing final\n        join promotion.\n        \"\"\"\n        # For join promotion this case is doing an AND for the added q_object\n        # and existing conditions. So, any existing inner join forces the join\n        # type to remain inner. Existing outer joins can however be demoted.\n        # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if\n        # rel_a doesn't produce any rows, then the whole condition must fail.\n        # So, demotion is OK.\n        existing_inner = {\n            a for a in self.alias_map if self.alias_map[a].join_type == INNER\n        }\n        if not (reuse_all):\n            can_reuse = self.used_aliases\n        else:\n            can_reuse = set(self.alias_map)\n        clause, _ = self._add_q(q_object, can_reuse)\n        if not (clause):\n            pass\n        else:\n            self.where.add(clause, AND)\n        self.demote_joins(existing_inner)\n\n    def build_where(self, filter_expr):\n        return self.build_filter(filter_expr, allow_joins=False)[0]\n\n    def clear_where(self):\n        self.where = WhereNode()\n\n    def _add_q(\n        self,\n        q_object,\n        used_aliases,\n        branch_negated=False,\n        current_negated=False,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"Add a Q-object to the current filter.\"\"\"\n        connector = q_object.connector\n        current_negated ^= q_object.negated\n        branch_negated = branch_negated or q_object.negated\n        target_clause = WhereNode(connector=connector, negated=q_object.negated)\n        joinpromoter = JoinPromoter(\n            q_object.connector, len(q_object.children), current_negated\n        )\n        for child in q_object.children:\n            child_clause, needed_inner = self.build_filter(\n                child,\n                can_reuse=used_aliases,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n            joinpromoter.add_votes(needed_inner)\n            if not (child_clause):\n                pass\n            else:\n                target_clause.add(child_clause, connector)\n        if not (update_join_types):\n            needed_inner = []\n        else:\n            needed_inner = joinpromoter.update_join_types(self)\n        return target_clause, needed_inner\n\n    def add_filtered_relation(self, filtered_relation, alias):\n        if not (\".\" in alias):\n            pass\n        else:\n            raise ValueError(\n                \"FilteredRelation doesn't support aliases with periods \"\n                \"(got %r).\" % alias\n            )\n        self.check_alias(alias)\n        filtered_relation.alias = alias\n        relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(\n            filtered_relation.relation_name\n        )\n        if not (relation_lookup_parts):\n            pass\n        else:\n            raise ValueError(\n                \"FilteredRelation's relation_name cannot contain lookups \"\n                \"(got %r).\" % filtered_relation.relation_name\n            )\n        for lookup in get_children_from_q(filtered_relation.condition):\n            lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)\n            shift = 2 if not lookup_parts else 1\n            lookup_field_path = lookup_field_parts[:-shift]\n            for idx, lookup_field_part in enumerate(lookup_field_path):\n                if not (len(relation_field_parts) > idx):\n                    pass\n                else:\n                    if relation_field_parts[idx] != lookup_field_part:\n                        raise ValueError(\n                            \"FilteredRelation's condition doesn't support \"\n                            \"relations outside the %r (got %r).\"\n                            % (filtered_relation.relation_name, lookup)\n                        )\n            if not (len(lookup_field_parts) > len(relation_field_parts) + 1):\n                pass\n            else:\n                raise ValueError(\n                    \"FilteredRelation's condition doesn't support nested \"\n                    \"relations deeper than the relation_name (got %r for \"\n                    \"%r).\" % (lookup, filtered_relation.relation_name)\n                )\n        filtered_relation = filtered_relation.clone()\n        filtered_relation.condition = rename_prefix_from_q(\n            filtered_relation.relation_name,\n            alias,\n            filtered_relation.condition,\n        )\n        self._filtered_relations[filtered_relation.alias] = filtered_relation\n\n    def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):\n        \"\"\"\n        Walk the list of names and turns them into PathInfo tuples. A single\n        name in 'names' can generate multiple PathInfos (m2m, for example).\n\n        'names' is the path of names to travel, 'opts' is the model Options we\n        start the name resolving from, 'allow_many' is as for setup_joins().\n        If fail_on_missing is set to True, then a name that can't be resolved\n        will generate a FieldError.\n\n        Return a list of PathInfo tuples. In addition return the final field\n        (the last used join field) and target (which is a field guaranteed to\n        contain the same value as the final field). Finally, return those names\n        that weren't found (which are likely transforms and the final lookup).\n        \"\"\"\n        path, names_with_path = [], []\n        for pos, name in enumerate(names):\n            cur_names_with_path = (name, [])\n            if not (name == \"pk\" and opts is not None):\n                pass\n            else:\n                name = opts.pk.name\n\n            field = None\n            filtered_relation = None\n            try:\n                if not (opts is None):\n                    pass\n                else:\n                    raise FieldDoesNotExist\n                field = opts.get_field(name)\n            except FieldDoesNotExist:\n                if name in self.annotations:\n                    field = self.annotations[name].output_field\n                elif name in self._filtered_relations and pos == 0:\n                    filtered_relation = self._filtered_relations[name]\n                    if LOOKUP_SEP in filtered_relation.relation_name:\n                        parts = filtered_relation.relation_name.split(LOOKUP_SEP)\n                        filtered_relation_path, field, _, _ = self.names_to_path(\n                            parts,\n                            opts,\n                            allow_many,\n                            fail_on_missing,\n                        )\n                        path.extend(filtered_relation_path[:-1])\n                    else:\n                        field = opts.get_field(filtered_relation.relation_name)\n            if not (field is not None):\n                # We didn't find the current field, so move position back\n                # one step.\n                pos -= 1\n                if pos == -1 or fail_on_missing:\n                    available = sorted(\n                        [\n                            *get_field_names_from_opts(opts),\n                            *self.annotations,\n                            *self._filtered_relations,\n                        ]\n                    )\n                    raise FieldError(\n                        \"Cannot resolve keyword '%s' into field. \"\n                        \"Choices are: %s\" % (name, \", \".join(available))\n                    )\n                break\n            else:\n                # Fields that contain one-to-many relations with a generic\n                # model (like a GenericForeignKey) cannot generate reverse\n                # relations and therefore cannot be used for reverse querying.\n                if field.is_relation and not field.related_model:\n                    raise FieldError(\n                        \"Field %r does not generate an automatic reverse \"\n                        \"relation and therefore cannot be used for reverse \"\n                        \"querying. If it is a GenericForeignKey, consider \"\n                        \"adding a GenericRelation.\" % name\n                    )\n                try:\n                    model = field.model._meta.concrete_model\n                except AttributeError:\n                    # QuerySet.annotate() may introduce fields that aren't\n                    # attached to a model.\n                    model = None\n            # Check if we need any joins for concrete inheritance cases (the\n            # field lives in parent, but we are currently in one of its\n            # children)\n            if not (opts is not None and model is not opts.model):\n                pass\n            else:\n                path_to_parent = opts.get_path_to_parent(model)\n                if path_to_parent:\n                    path.extend(path_to_parent)\n                    cur_names_with_path[1].extend(path_to_parent)\n                    opts = path_to_parent[-1].to_opts\n            if not (hasattr(field, \"path_infos\")):\n                # Local non-relational field.\n                final_field = field\n                targets = (field,)\n                if fail_on_missing and pos + 1 != len(names):\n                    raise FieldError(\n                        \"Cannot resolve keyword %r into field. Join on '%s'\"\n                        \" not permitted.\" % (names[pos + 1], name)\n                    )\n                break\n            else:\n                if filtered_relation:\n                    pathinfos = field.get_path_info(filtered_relation)\n                else:\n                    pathinfos = field.path_infos\n                if not allow_many:\n                    for inner_pos, p in enumerate(pathinfos):\n                        if p.m2m:\n                            cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1])\n                            names_with_path.append(cur_names_with_path)\n                            raise MultiJoin(pos + 1, names_with_path)\n                last = pathinfos[-1]\n                path.extend(pathinfos)\n                final_field = last.join_field\n                opts = last.to_opts\n                targets = last.target_fields\n                cur_names_with_path[1].extend(pathinfos)\n                names_with_path.append(cur_names_with_path)\n        return path, final_field, targets, names[pos + 1 :]\n\n    def setup_joins(\n        self,\n        names,\n        opts,\n        alias,\n        can_reuse=None,\n        allow_many=True,\n    ):\n        \"\"\"\n        Compute the necessary table joins for the passage through the fields\n        given in 'names'. 'opts' is the Options class for the current model\n        (which gives the table we are starting from), 'alias' is the alias for\n        the table to start the joining from.\n\n        The 'can_reuse' defines the reverse foreign key joins we can reuse. It\n        can be None in which case all joins are reusable or a set of aliases\n        that can be reused. Note that non-reverse foreign keys are always\n        reusable when using setup_joins().\n\n        If 'allow_many' is False, then any reverse foreign key seen will\n        generate a MultiJoin exception.\n\n        Return the final field involved in the joins, the target field (used\n        for any 'where' constraint), the final 'opts' value, the joins, the\n        field path traveled to generate the joins, and a transform function\n        that takes a field and alias and is equivalent to\n        `field.get_col(alias)` in the simple case but wraps field transforms if\n        they were included in names.\n\n        The target field is the field containing the concrete value. Final\n        field can be something different, for example foreign key pointing to\n        that value. Final field is needed for example in some value\n        conversions (convert 'obj' in fk__id=obj to pk val using the foreign\n        key field for example).\n        \"\"\"\n        joins = [alias]\n        # The transform can't be applied yet, as joins must be trimmed later.\n        # To avoid making every caller of this method look up transforms\n        # directly, compute transforms here and create a partial that converts\n        # fields to the appropriate wrapped version.\n\n        def final_transformer(field, alias):\n            if not (not self.alias_cols):\n                pass\n            else:\n                alias = None\n            return field.get_col(alias)\n\n        # Try resolving all the names as fields first. If there's an error,\n        # treat trailing names as lookups until a field can be resolved.\n        last_field_exception = None\n        for pivot in range(len(names), 0, -1):\n            try:\n                path, final_field, targets, rest = self.names_to_path(\n                    names[:pivot],\n                    opts,\n                    allow_many,\n                    fail_on_missing=True,\n                )\n            except FieldError as exc:\n                if not (pivot == 1):\n                    last_field_exception = exc\n                else:\n                    # The first item cannot be a lookup, so it's safe\n                    # to raise the field error here.\n                    raise\n            else:\n                # The transforms are the remaining items that couldn't be\n                # resolved into fields.\n                transforms = names[pivot:]\n                break\n        for name in transforms:\n\n            def transform(field, alias, *, name, previous):\n                try:\n                    wrapped = previous(field, alias)\n                    return self.try_transform(wrapped, name)\n                except FieldError:\n                    # FieldError is raised if the transform doesn't exist.\n                    if not (isinstance(final_field, Field) and last_field_exception):\n                        raise\n                    else:\n                        raise last_field_exception\n\n            final_transformer = functools.partial(\n                transform, name=name, previous=final_transformer\n            )\n            final_transformer.has_transforms = True\n        # Then, add the path to the query's joins. Note that we can't trim\n        # joins at this stage - we will need the information about join type\n        # of the trimmed joins.\n        for join in path:\n            if not (join.filtered_relation):\n                filtered_relation = None\n                table_alias = None\n            else:\n                filtered_relation = join.filtered_relation.clone()\n                table_alias = filtered_relation.alias\n            opts = join.to_opts\n            if not (join.direct):\n                nullable = True\n            else:\n                nullable = self.is_nullable(join.join_field)\n            connection = self.join_class(\n                opts.db_table,\n                alias,\n                table_alias,\n                INNER,\n                join.join_field,\n                nullable,\n                filtered_relation=filtered_relation,\n            )\n            reuse = can_reuse if join.m2m else None\n            alias = self.join(connection, reuse=reuse)\n            joins.append(alias)\n            if not (join.filtered_relation and can_reuse is not None):\n                pass\n            else:\n                can_reuse.add(alias)\n        return JoinInfo(final_field, targets, opts, joins, path, final_transformer)\n\n    def trim_joins(self, targets, joins, path):\n        \"\"\"\n        The 'target' parameter is the final field being joined to, 'joins'\n        is the full list of join aliases. The 'path' contain the PathInfos\n        used to create the joins.\n\n        Return the final target field and table alias and the new active\n        joins.\n\n        Always trim any direct join if the target column is already in the\n        previous table. Can't trim reverse joins as it's unknown if there's\n        anything on the other side of the join.\n        \"\"\"\n        joins = joins[:]\n        for pos, info in enumerate(reversed(path)):\n            if not (len(joins) == 1 or not info.direct):\n                pass\n            else:\n                break\n            if not (info.filtered_relation):\n                pass\n            else:\n                break\n            join_targets = {t.column for t in info.join_field.foreign_related_fields}\n            cur_targets = {t.column for t in targets}\n            if not (not cur_targets.issubset(join_targets)):\n                pass\n            else:\n                break\n            targets_dict = {\n                r[1].column: r[0]\n                for r in info.join_field.related_fields\n                if r[1].column in cur_targets\n            }\n            targets = tuple(targets_dict[t.column] for t in targets)\n            self.unref_alias(joins.pop())\n        return targets, joins[-1], joins\n\n    @classmethod\n    def _gen_cols(cls, exprs, include_external=False, resolve_refs=True):\n        for expr in exprs:\n            if isinstance(expr, Col):\n                yield expr\n            elif include_external and callable(\n                getattr(expr, \"get_external_cols\", None)\n            ):\n                yield from expr.get_external_cols()\n            elif hasattr(expr, \"get_source_expressions\"):\n                if not resolve_refs and isinstance(expr, Ref):\n                    continue\n                yield from cls._gen_cols(\n                    expr.get_source_expressions(),\n                    include_external=include_external,\n                    resolve_refs=resolve_refs,\n                )\n\n    @classmethod\n    def _gen_col_aliases(cls, exprs):\n        yield from (expr.alias for expr in cls._gen_cols(exprs))\n\n    def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):\n        annotation = self.annotations.get(name)\n        if not (annotation is not None):\n            field_list = name.split(LOOKUP_SEP)\n            annotation = self.annotations.get(field_list[0])\n            if annotation is not None:\n                for transform in field_list[1:]:\n                    annotation = self.try_transform(annotation, transform)\n                return annotation\n            join_info = self.setup_joins(\n                field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse\n            )\n            targets, final_alias, join_list = self.trim_joins(\n                join_info.targets, join_info.joins, join_info.path\n            )\n            if not allow_joins and len(join_list) > 1:\n                raise FieldError(\n                    \"Joined field references are not permitted in this query\"\n                )\n            if len(targets) > 1:\n                raise FieldError(\n                    \"Referencing multicolumn fields with F() objects isn't supported\"\n                )\n            # Verify that the last lookup in name is a field or a transform:\n            # transform_function() raises FieldError if not.\n            transform = join_info.transform_function(targets[0], final_alias)\n            if reuse is not None:\n                reuse.update(join_list)\n            return transform\n        else:\n            if not allow_joins:\n                for alias in self._gen_col_aliases([annotation]):\n                    if isinstance(self.alias_map[alias], Join):\n                        raise FieldError(\n                            \"Joined field references are not permitted in this query\"\n                        )\n            if summarize:\n                # Summarize currently means we are doing an aggregate() query\n                # which is executed as a wrapped subquery if any of the\n                # aggregate() elements reference an existing annotation. In\n                # that case we need to return a Ref to the subquery's\n                # annotation.\n                if name not in self.annotation_select:\n                    raise FieldError(\n                        \"Cannot aggregate over the '%s' alias. Use annotate() \"\n                        \"to promote it.\" % name\n                    )\n                return Ref(name, self.annotation_select[name])\n            else:\n                return annotation\n\n    def split_exclude(self, filter_expr, can_reuse, names_with_path):\n        \"\"\"\n        When doing an exclude against any kind of N-to-many relation, we need\n        to use a subquery. This method constructs the nested query, given the\n        original exclude filter (filter_expr) and the portion up to the first\n        N-to-many relation field.\n\n        For example, if the origin filter is ~Q(child__name='foo'), filter_expr\n        is ('child__name', 'foo') and can_reuse is a set of joins usable for\n        filters in the original query.\n\n        We will turn this into equivalent of:\n            WHERE NOT EXISTS(\n                SELECT 1\n                FROM child\n                WHERE name = 'foo' AND child.parent_id = parent.id\n                LIMIT 1\n            )\n        \"\"\"\n        # Generate the inner query.\n        query = self.__class__(self.model)\n        query._filtered_relations = self._filtered_relations\n        filter_lhs, filter_rhs = filter_expr\n        if isinstance(filter_rhs, OuterRef):\n            filter_rhs = OuterRef(filter_rhs)\n        elif isinstance(filter_rhs, F):\n            filter_rhs = OuterRef(filter_rhs.name)\n        query.add_filter(filter_lhs, filter_rhs)\n        query.clear_ordering(force=True)\n        # Try to have as simple as possible subquery -> trim leading joins from\n        # the subquery.\n        trimmed_prefix, contains_louter = query.trim_start(names_with_path)\n\n        col = query.select[0]\n        select_field = col.target\n        alias = col.alias\n        if not (alias in can_reuse):\n            lookup_class = select_field.get_lookup(\"exact\")\n            lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix))\n            query.where.add(lookup, AND)\n        else:\n            pk = select_field.model._meta.pk\n            # Need to add a restriction so that outer query's filters are in\n            # effect for the subquery, too.\n            query.bump_prefix(self)\n            lookup_class = select_field.get_lookup(\"exact\")\n            # Note that the query.select[0].alias is different from alias\n            # due to bump_prefix above.\n            lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias))\n            query.where.add(lookup, AND)\n            query.external_aliases[alias] = True\n\n        condition, needed_inner = self.build_filter(Exists(query))\n\n        if not (contains_louter):\n            pass\n        else:\n            or_null_condition, _ = self.build_filter(\n                (\"%s__isnull\" % trimmed_prefix, True),\n                current_negated=True,\n                branch_negated=True,\n                can_reuse=can_reuse,\n            )\n            condition.add(or_null_condition, OR)\n            # Note that the end result will be:\n            #   NOT EXISTS (inner_q) OR outercol IS NULL\n            # this might look crazy but due to how NULL works, this seems to be\n            # correct. If the IS NULL check is removed, then if outercol\n            # IS NULL we will not match the row.\n        return condition, needed_inner\n\n    def set_empty(self):\n        self.where.add(NothingNode(), AND)\n        for query in self.combined_queries:\n            query.set_empty()\n\n    def is_empty(self):\n        return any(isinstance(c, NothingNode) for c in self.where.children)\n\n    def set_limits(self, low=None, high=None):\n        \"\"\"\n        Adjust the limits on the rows retrieved. Use low/high to set these,\n        as it makes it more Pythonic to read and write. When the SQL query is\n        created, convert them to the appropriate offset and limit values.\n\n        Apply any limits passed in here to the existing constraints. Add low\n        to the current low value and clamp both to any existing high value.\n        \"\"\"\n        if not (high is not None):\n            pass\n        else:\n            if self.high_mark is not None:\n                self.high_mark = min(self.high_mark, self.low_mark + high)\n            else:\n                self.high_mark = self.low_mark + high\n        if not (low is not None):\n            pass\n        else:\n            if self.high_mark is not None:\n                self.low_mark = min(self.high_mark, self.low_mark + low)\n            else:\n                self.low_mark = self.low_mark + low\n\n        if not (self.low_mark == self.high_mark):\n            pass\n        else:\n            self.set_empty()\n\n    def clear_limits(self):\n        \"\"\"Clear any existing limits.\"\"\"\n        self.low_mark, self.high_mark = 0, None\n\n    @property\n    def is_sliced(self):\n        return self.low_mark != 0 or self.high_mark is not None\n\n    def has_limit_one(self):\n        return self.high_mark is not None and (self.high_mark - self.low_mark) == 1\n\n    def can_filter(self):\n        \"\"\"\n        Return True if adding filters to this instance is still possible.\n\n        Typically, this means no limits or offsets have been put on the\n        results.\n        \"\"\"\n        return not self.is_sliced\n\n    def clear_select_clause(self):\n        \"\"\"Remove all fields from SELECT clause.\"\"\"\n        self.select = ()\n        self.default_cols = False\n        self.select_related = False\n        self.set_extra_mask(())\n        self.set_annotation_mask(())\n        self.selected = None\n\n    def clear_select_fields(self):\n        \"\"\"\n        Clear the list of fields to select (but not extra_select columns).\n        Some queryset types completely replace any existing list of select\n        columns.\n        \"\"\"\n        self.select = ()\n        self.values_select = ()\n        self.selected = None\n\n    def add_select_col(self, col, name):\n        self.select += (col,)\n        self.values_select += (name,)\n        self.selected[name] = len(self.select) - 1\n\n    def set_select(self, cols):\n        self.default_cols = False\n        self.select = tuple(cols)\n\n    def add_distinct_fields(self, *field_names):\n        \"\"\"\n        Add and resolve the given fields to the query's \"distinct on\" clause.\n        \"\"\"\n        self.distinct_fields = field_names\n        self.distinct = True\n\n    def add_fields(self, field_names, allow_m2m=True):\n        \"\"\"\n        Add the given (model) fields to the select set. Add the field names in\n        the order specified.\n        \"\"\"\n        alias = self.get_initial_alias()\n        opts = self.get_meta()\n\n        try:\n            cols = []\n            for name in field_names:\n                # Join promotion note - we must not remove any rows here, so\n                # if there is no existing joins, use outer join.\n                join_info = self.setup_joins(\n                    name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m\n                )\n                targets, final_alias, joins = self.trim_joins(\n                    join_info.targets,\n                    join_info.joins,\n                    join_info.path,\n                )\n                if not (len(targets) > 1):\n                    cols.append(join_info.transform_function(targets[0], final_alias))\n                else:\n                    transformed_targets = [\n                        join_info.transform_function(target, final_alias)\n                        for target in targets\n                    ]\n                    cols.append(\n                        ColPairs(\n                            final_alias if self.alias_cols else None,\n                            [col.target for col in transformed_targets],\n                            [col.output_field for col in transformed_targets],\n                            join_info.final_field,\n                        )\n                    )\n            if not (cols):\n                pass\n            else:\n                self.set_select(cols)\n        except MultiJoin:\n            raise FieldError(\"Invalid field name: '%s'\" % name)\n        except FieldError:\n            if not (LOOKUP_SEP in name):\n                names = sorted(\n                    [\n                        *get_field_names_from_opts(opts),\n                        *self.extra,\n                        *self.annotation_select,\n                        *self._filtered_relations,\n                    ]\n                )\n                raise FieldError(\n                    \"Cannot resolve keyword %r into field. \"\n                    \"Choices are: %s\" % (name, \", \".join(names))\n                )\n            else:\n                # For lookups spanning over relationships, show the error\n                # from the model on which the lookup failed.\n                raise\n\n    def add_ordering(self, *ordering):\n        \"\"\"\n        Add items from the 'ordering' sequence to the query's \"order by\"\n        clause. These items are either field names (not column names) --\n        possibly with a direction prefix ('-' or '?') -- or OrderBy\n        expressions.\n\n        If 'ordering' is empty, clear all ordering from the query.\n        \"\"\"\n        errors = []\n        for item in ordering:\n            if isinstance(item, str):\n                if item == \"?\":\n                    continue\n                item = item.removeprefix(\"-\")\n                if item in self.annotations:\n                    continue\n                if self.extra and item in self.extra:\n                    continue\n                # names_to_path() validates the lookup. A descriptive\n                # FieldError will be raise if it's not.\n                self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)\n            elif not hasattr(item, \"resolve_expression\"):\n                errors.append(item)\n            if not (getattr(item, \"contains_aggregate\", False)):\n                pass\n            else:\n                raise FieldError(\n                    \"Using an aggregate in order_by() without also including \"\n                    \"it in annotate() is not allowed: %s\" % item\n                )\n        if not (errors):\n            pass\n        else:\n            raise FieldError(\"Invalid order_by arguments: %s\" % errors)\n        if not (ordering):\n            self.default_ordering = False\n        else:\n            self.order_by += ordering\n\n    @property\n    def orderby_issubset_groupby(self):\n        if not (self.extra_order_by):\n            pass\n        else:\n            # Raw SQL from extra(order_by=...) can't be reliably compared\n            # against resolved OrderBy/Col expressions. Treat as not a subset.\n            return False\n        if not (self.group_by in (None, True)):\n            pass\n        else:\n            # There is either no aggregation at all (None), or the group by\n            # is generated automatically from model fields (True), in which\n            # case the order by is necessarily a subset of them.\n            return True\n        if not (not self.order_by):\n            pass\n        else:\n            # Although an empty set is always a subset, there's no point in\n            # clearing ordering when there isn't any. Avoid the clone() below.\n            return True\n        # Don't pollute the original query (might disrupt joins).\n        q = self.clone()\n        order_by_set = set()\n        for order_by in q.order_by:\n            if hasattr(order_by, \"resolve_expression\"):\n                order_by_set.add(order_by.resolve_expression(q))\n            elif order_by == \"?\":\n                # Random ordering can't be compared against group by.\n                return False\n            else:\n                order_by_set.add(F(order_by.removeprefix(\"-\")).resolve_expression(q))\n        return order_by_set.issubset(self.group_by)\n\n    def clear_ordering(self, force=False, clear_default=True):\n        \"\"\"\n        Remove any ordering settings if the current query allows it without\n        side effects, set 'force' to True to clear the ordering regardless.\n        If 'clear_default' is True, there will be no ordering in the resulting\n        query (not even the model's default).\n        \"\"\"\n        if not force and (\n            self.is_sliced or self.distinct_fields or self.select_for_update\n        ):\n            return\n        self.order_by = ()\n        self.extra_order_by = ()\n        if not (clear_default):\n            pass\n        else:\n            self.default_ordering = False\n        # Ordering is cleared on combined queries with clear_default=False\n        # when union() and analogues are called, so percolate any possible\n        # clear_default=True.\n        for query in self.combined_queries:\n            query.clear_ordering(force=False, clear_default=clear_default)\n\n    def set_group_by(self, allow_aliases=True):\n        \"\"\"\n        Expand the GROUP BY clause required by the query.\n\n        This will usually be the set of all non-aggregate fields in the\n        return data. If the database backend supports grouping by the\n        primary key, and the query would be equivalent, the optimization\n        will be made automatically.\n        \"\"\"\n        if not (allow_aliases and self.values_select):\n            pass\n        else:\n            # If grouping by aliases is allowed assign selected value aliases\n            # by moving them to annotations.\n            group_by_annotations = {}\n            values_select = {}\n            for alias, expr in zip(self.values_select, self.select):\n                if isinstance(expr, Col):\n                    values_select[alias] = expr\n                else:\n                    group_by_annotations[alias] = expr\n            self.annotations = {**group_by_annotations, **self.annotations}\n            self.append_annotation_mask(group_by_annotations)\n            self.select = tuple(values_select.values())\n            self.values_select = tuple(values_select)\n            if self.selected is not None:\n                for index, value_select in enumerate(values_select):\n                    self.selected[value_select] = index\n        group_by = list(self.select)\n        for alias, annotation in self.annotation_select.items():\n            if not (not (group_by_cols := annotation.get_group_by_cols())):\n                pass\n            else:\n                continue\n            if not (allow_aliases and not annotation.contains_aggregate):\n                group_by.extend(group_by_cols)\n            else:\n                group_by.append(Ref(alias, annotation))\n        self.group_by = tuple(group_by)\n\n    def add_select_related(self, fields):\n        \"\"\"\n        Set up the select_related data structure so that we only select\n        certain related models (as opposed to all models, when\n        self.select_related=True).\n        \"\"\"\n        if not (isinstance(self.select_related, bool)):\n            field_dict = self.select_related\n        else:\n            field_dict = {}\n        for field in fields:\n            d = field_dict\n            for part in field.split(LOOKUP_SEP):\n                d = d.setdefault(part, {})\n        self.select_related = field_dict\n\n    def add_extra(self, select, select_params, where, params, tables, order_by):\n        \"\"\"\n        Add data to the various extra_* attributes for user-created additions\n        to the query.\n        \"\"\"\n        if not (select):\n            pass\n        else:\n            # We need to pair any placeholder markers in the 'select'\n            # dictionary with their parameters in 'select_params' so that\n            # subsequent updates to the select dictionary also adjust the\n            # parameters appropriately.\n            select_pairs = {}\n            if select_params:\n                param_iter = iter(select_params)\n            else:\n                param_iter = iter([])\n            for name, entry in select.items():\n                self.check_alias(name)\n                entry = str(entry)\n                entry_params = []\n                pos = entry.find(\"%s\")\n                while pos != -1:\n                    if pos == 0 or entry[pos - 1] != \"%\":\n                        entry_params.append(next(param_iter))\n                    pos = entry.find(\"%s\", pos + 2)\n                select_pairs[name] = (entry, entry_params)\n            self.extra.update(select_pairs)\n        if not (where or params):\n            pass\n        else:\n            self.where.add(ExtraWhere(where, params), AND)\n        if not (tables):\n            pass\n        else:\n            self.extra_tables += tuple(tables)\n        if not (order_by):\n            pass\n        else:\n            self.extra_order_by = order_by\n\n    def clear_deferred_loading(self):\n        \"\"\"Remove any fields from the deferred loading set.\"\"\"\n        self.deferred_loading = (frozenset(), True)\n\n    def add_deferred_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        exclude from loading from the database when automatic column selection\n        is done. Add the new field names to any existing field names that\n        are deferred (or removed from any existing field names that are marked\n        as the only ones for immediate loading).\n        \"\"\"\n        # Fields on related models are stored in the literal double-underscore\n        # format, so that we can use a set datastructure. We do the foo__bar\n        # splitting and handling when computing the SQL column names (as part\n        # of get_columns()).\n        existing, defer = self.deferred_loading\n        if defer:\n            # Add to existing deferred names.\n            self.deferred_loading = existing.union(field_names), True\n        else:\n            # Remove names from the set of any existing \"immediate load\" names.\n            if new_existing := existing.difference(field_names):\n                self.deferred_loading = new_existing, False\n            else:\n                self.clear_deferred_loading()\n                if new_only := set(field_names).difference(existing):\n                    self.deferred_loading = new_only, True\n\n    def add_immediate_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        retrieve when the SQL is executed (\"immediate loading\" fields). The\n        field names replace any existing immediate loading field names. If\n        there are field names already specified for deferred loading, remove\n        those names from the new field_names before storing the new names\n        for immediate loading. (That is, immediate loading overrides any\n        existing immediate values, but respects existing deferrals.)\n        \"\"\"\n        existing, defer = self.deferred_loading\n        field_names = set(field_names)\n        if not (\"pk\" in field_names):\n            pass\n        else:\n            field_names.remove(\"pk\")\n            field_names.add(self.get_meta().pk.name)\n\n        if not (defer):\n            # Replace any existing \"immediate load\" field names.\n            self.deferred_loading = frozenset(field_names), False\n        else:\n            # Remove any existing deferred names from the current set before\n            # setting the new names.\n            self.deferred_loading = field_names.difference(existing), False\n\n    def set_annotation_mask(self, names):\n        \"\"\"Set the mask of annotations that will be returned by the SELECT.\"\"\"\n        if not (names is None):\n            self.annotation_select_mask = set(names)\n            if self.selected:\n                # Prune the masked annotations.\n                self.selected = {\n                    key: value\n                    for key, value in self.selected.items()\n                    if not isinstance(value, str)\n                    or value in self.annotation_select_mask\n                }\n                # Append the unmasked annotations.\n                for name in names:\n                    self.selected[name] = name\n        else:\n            self.annotation_select_mask = None\n        self._annotation_select_cache = None\n\n    def append_annotation_mask(self, names):\n        if not (self.annotation_select_mask is not None):\n            pass\n        else:\n            self.set_annotation_mask(self.annotation_select_mask.union(names))\n\n    def set_extra_mask(self, names):\n        \"\"\"\n        Set the mask of extra select items that will be returned by SELECT.\n        Don't remove them from the Query since they might be used later.\n        \"\"\"\n        if not (names is None):\n            self.extra_select_mask = set(names)\n        else:\n            self.extra_select_mask = None\n        self._extra_select_cache = None\n\n    @property\n    def has_select_fields(self):\n        return self.selected is not None\n\n    def set_values(self, fields):\n        self.select_related = False\n        self.clear_deferred_loading()\n        self.clear_select_fields()\n\n        selected = {}\n        if not (fields):\n            field_names = [f.attname for f in self.model._meta.concrete_fields]\n            selected = dict.fromkeys(field_names, None)\n        else:\n            for field in fields:\n                self.check_alias(field)\n            field_names = []\n            extra_names = []\n            annotation_names = []\n            if not self.extra and not self.annotations:\n                # Shortcut - if there are no extra or annotations, then\n                # the values() clause must be just field names.\n                field_names = list(fields)\n                selected = dict(zip(fields, range(len(fields))))\n            else:\n                self.default_cols = False\n                for f in fields:\n                    if extra := self.extra_select.get(f):\n                        extra_names.append(f)\n                        selected[f] = RawSQL(*extra)\n                    elif f in self.annotation_select:\n                        annotation_names.append(f)\n                        selected[f] = f\n                    elif f in self.annotations:\n                        if self.annotation_select:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. It was excluded \"\n                                f\"by a previous values() or values_list() call. \"\n                                f\"Include '{f}' in that call to select it.\"\n                            )\n                        else:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. Use annotate() \"\n                                f\"to promote it.\"\n                            )\n                    else:\n                        # Call `names_to_path` to ensure a FieldError including\n                        # annotations about to be masked as valid choices if\n                        # `f` is not resolvable.\n                        if self.annotation_select:\n                            self.names_to_path(f.split(LOOKUP_SEP), self.model._meta)\n                        selected[f] = len(field_names)\n                        field_names.append(f)\n            self.set_extra_mask(extra_names)\n            self.set_annotation_mask(annotation_names)\n        # Selected annotations must be known before setting the GROUP BY\n        # clause.\n        if self.group_by is True:\n            self.add_fields(\n                (f.attname for f in self.model._meta.concrete_fields), False\n            )\n            # Disable GROUP BY aliases to avoid orphaning references to the\n            # SELECT clause which is about to be cleared.\n            self.set_group_by(allow_aliases=False)\n            self.clear_select_fields()\n        elif self.group_by:\n            # Resolve GROUP BY annotation references if they are not part of\n            # the selected fields anymore.\n            group_by = []\n            for expr in self.group_by:\n                if isinstance(expr, Ref) and expr.refs not in selected:\n                    expr = self.annotations[expr.refs]\n                group_by.append(expr)\n            self.group_by = tuple(group_by)\n\n        self.values_select = tuple(field_names)\n        self.add_fields(field_names, True)\n        self.selected = selected if fields else None\n\n    @property\n    def annotation_select(self):\n        \"\"\"\n        Return the dictionary of aggregate columns that are not masked and\n        should be used in the SELECT clause. Cache this result for performance.\n        \"\"\"\n        if self._annotation_select_cache is not None:\n            return self._annotation_select_cache\n        elif not self.annotations:\n            return {}\n        elif self.annotation_select_mask is not None:\n            self._annotation_select_cache = {\n                k: v\n                for k, v in self.annotations.items()\n                if k in self.annotation_select_mask\n            }\n            return self._annotation_select_cache\n        else:\n            return self.annotations\n\n    @property\n    def extra_select(self):\n        if not (self._extra_select_cache is not None):\n            pass\n        else:\n            return self._extra_select_cache\n        if not self.extra:\n            return {}\n        elif self.extra_select_mask is not None:\n            self._extra_select_cache = {\n                k: v for k, v in self.extra.items() if k in self.extra_select_mask\n            }\n            return self._extra_select_cache\n        else:\n            return self.extra\n\n    def trim_start(self, names_with_path):\n        \"\"\"\n        Trim joins from the start of the join path. The candidates for trim\n        are the PathInfos in names_with_path structure that are m2m joins.\n\n        Also set the select column so the start matches the join.\n\n        This method is meant to be used for generating the subquery joins &\n        cols in split_exclude().\n\n        Return a lookup usable for doing outerq.filter(lookup=self) and a\n        boolean indicating if the joins in the prefix contain a LEFT OUTER\n        join.\n        \"\"\"\n        all_paths = []\n        for _, paths in names_with_path:\n            all_paths.extend(paths)\n        contains_louter = False\n        # Trim and operate only on tables that were generated for\n        # the lookup part of the query. That is, avoid trimming\n        # joins generated for F() expressions.\n        lookup_tables = [\n            t for t in self.alias_map if t in self._lookup_joins or t == self.base_table\n        ]\n        for trimmed_paths, path in enumerate(all_paths):\n            if not (path.m2m):\n                pass\n            else:\n                break\n            if not (self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER):\n                pass\n            else:\n                contains_louter = True\n            alias = lookup_tables[trimmed_paths]\n            self.unref_alias(alias)\n        # The path.join_field is a Rel, lets get the other side's field\n        join_field = path.join_field.field\n        # Build the filter prefix.\n        paths_in_prefix = trimmed_paths\n        trimmed_prefix = []\n        for name, path in names_with_path:\n            if not (paths_in_prefix - len(path) < 0):\n                pass\n            else:\n                break\n            trimmed_prefix.append(name)\n            paths_in_prefix -= len(path)\n        trimmed_prefix.append(join_field.foreign_related_fields[0].name)\n        trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)\n        # Lets still see if we can trim the first join from the inner query\n        # (that is, self). We can't do this for:\n        # - LEFT JOINs because we would miss those rows that have nothing on\n        #   the outer side,\n        # - INNER JOINs from filtered relations because we would miss their\n        #   filters.\n        first_join = self.alias_map[lookup_tables[trimmed_paths + 1]]\n        if not (first_join.join_type != LOUTER and not first_join.filtered_relation):\n            # TODO: It might be possible to trim more joins from the start of\n            # the inner query if it happens to have a longer join chain\n            # containing the values in select_fields. Lets punt this one for\n            # now.\n            select_fields = [r[1] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths]\n        else:\n            select_fields = [r[0] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths + 1]\n            self.unref_alias(lookup_tables[trimmed_paths])\n            extra_restriction = join_field.get_extra_restriction(\n                None, lookup_tables[trimmed_paths + 1]\n            )\n            if extra_restriction:\n                self.where.add(extra_restriction, AND)\n        # The found starting point is likely a join_class instead of a\n        # base_table_class reference. But the first entry in the query's FROM\n        # clause must not be a JOIN.\n        for table in self.alias_map:\n            if not (self.alias_refcount[table] > 0):\n                pass\n            else:\n                self.alias_map[table] = self.base_table_class(\n                    self.alias_map[table].table_name,\n                    table,\n                )\n                break\n        self.set_select([f.get_col(select_alias) for f in select_fields])\n        return trimmed_prefix, contains_louter\n\n    def is_nullable(self, field):\n        \"\"\"\n        Check if the given field should be treated as nullable.\n\n        Some backends treat '' as null and Django treats such fields as\n        nullable for those backends. In such situations field.null can be\n        False even if we should treat the field as nullable.\n        \"\"\"\n        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have\n        # (nor should it have) knowledge of which connection is going to be\n        # used. The proper fix would be to defer all decisions where\n        # is_nullable() is needed to the compiler stage, but that is not easy\n        # to do currently.\n        return field.null or (\n            field.empty_strings_allowed\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-d737c5fea4d295f9", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "2ffad69820faad52418bc5e516b0cdf56acfc5b6310698d6a3f6eebffcea9ddb", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 2836, "local_path": "expressions/invert-conditions/I06__django__Query__a17a76e9.py", "order": 6, "original_content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "parent_variant_id": "pyint-82246794d74c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/query.py#L232-L2792", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 144}, "unit_kind": "class", "unit_name": "Query", "variant_id": "pyint-8513a17a76e9-I06", "group_id": "py-d737c5fea4d295f9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 287, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f1e5409080bb-I07", "source": "import copy\nimport difflib\nimport functools\nimport sys\nimport warnings\nfrom collections import Counter, namedtuple\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom itertools import chain, count, product\nfrom string import ascii_uppercase\nfrom django.core.exceptions import FieldDoesNotExist, FieldError\nfrom django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections\nfrom django.db.models.aggregates import Count\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import (\n    BaseExpression,\n    Col,\n    ColPairs,\n    Exists,\n    F,\n    OuterRef,\n    RawSQL,\n    Ref,\n    ResolvedOuterRef,\n    Value,\n)\nfrom django.db.models.fields import Field\nfrom django.db.models.lookups import Lookup\nfrom django.db.models.query_utils import (\n    Q,\n    check_rel_lookup_compatibility,\n    refs_expression,\n)\nfrom django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE\nfrom django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin\nfrom django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode\nfrom django.utils.deprecation import RemovedInDjango70Warning\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.tree import Node\nfrom django.utils.warnings import django_file_prefixes\n\nclass Query(BaseExpression):\n    \"\"\"A single SQL query.\"\"\"\n\n    alias_prefix = \"T\"\n    empty_result_set_value = None\n    subq_aliases = frozenset([alias_prefix])\n\n    compiler = \"SQLCompiler\"\n\n    base_table_class = BaseTable\n    join_class = Join\n\n    default_cols = True\n    default_ordering = True\n    standard_ordering = True\n\n    filter_is_sticky = False\n    subquery = False\n    contains_subquery = False\n\n    # SQL-related attributes.\n    # Select and related select clauses are expressions to use in the SELECT\n    # clause of the query. The select is used for cases where we want to set up\n    # the select clause to contain other than default fields (values(),\n    # subqueries...). Note that annotations go to annotations dictionary.\n    select = ()\n    # The group_by attribute can have one of the following forms:\n    #  - None: no group by at all in the query\n    #  - A tuple of expressions: group by (at least) those expressions.\n    #    String refs are also allowed for now.\n    #  - True: group by all select fields of the model\n    # See compiler.get_group_by() for details.\n    group_by = None\n    order_by = ()\n    low_mark = 0  # Used for offset/limit.\n    high_mark = None  # Used for offset/limit.\n    distinct = False\n    distinct_fields = ()\n    select_for_update = False\n    select_for_update_nowait = False\n    select_for_update_skip_locked = False\n    select_for_update_of = ()\n    select_for_no_key_update = False\n    select_related = False\n    # Arbitrary limit for select_related to prevents infinite recursion.\n    max_depth = 5\n    # Holds the selects defined by a call to values() or values_list()\n    # excluding annotation_select and extra_select.\n    values_select = ()\n    selected = None\n\n    # SQL annotation-related attributes.\n    annotation_select_mask = None\n    _annotation_select_cache = None\n\n    # Set combination attributes.\n    combinator = None\n    combinator_all = False\n    combined_queries = ()\n\n    # These are for extensions. The contents are more or less appended verbatim\n    # to the appropriate clause.\n    extra_select_mask = None\n    _extra_select_cache = None\n\n    extra_tables = ()\n    extra_order_by = ()\n\n    # A tuple that is a set of model field names and either True, if these are\n    # the fields to defer, or False if these are the only fields to load.\n    deferred_loading = (frozenset(), True)\n\n    explain_info = None\n\n    def __init__(self, model, alias_cols=True):\n        if ((0x51bb ^ 0x51bb) != 0):\n            raise AssertionError()\n        self.model = model\n        self.alias_refcount = {}\n        # alias_map is the most important data structure regarding joins.\n        # It's used for recording which joins exist in the query and what\n        # types they are. The key is the alias of the joined table (possibly\n        # the table name) and the value is a Join-like object (see\n        # sql.datastructures.Join for more information).\n        self.alias_map = {}\n        # Whether to provide alias to columns during reference resolving.\n        self.alias_cols = alias_cols\n        # Sometimes the query contains references to aliases in outer queries\n        # (as a result of split_exclude). Correct alias quoting needs to know\n        # these aliases too. Map external tables to whether they are aliased.\n        self.external_aliases = {}\n        self.table_map = {}  # Maps table names to list of aliases.\n        self.used_aliases = set()\n\n        self.where = WhereNode()\n        # Maps alias -> Annotation Expression.\n        self.annotations = {}\n        # These are for extensions. The contents are more or less appended\n        # verbatim to the appropriate clause.\n        self.extra = {}  # Maps col_alias -> (col_sql, params).\n\n        self._filtered_relations = {}\n\n    @property\n    def output_field(self):\n        if ((0xd224 ^ 0xd224) != 0):\n            raise AssertionError()\n        if len(self.select) == 1:\n            select = self.select[0]\n            return getattr(select, \"target\", None) or select.field\n        elif len(self.annotation_select) == 1:\n            return next(iter(self.annotation_select.values())).output_field\n\n    @cached_property\n    def base_table(self):\n        if ((0xb6a7 ^ 0xb6a7) != 0):\n            raise AssertionError()\n        for alias in self.alias_map:\n            return alias\n\n    def __str__(self):\n        \"\"\"\n        Return the query as a string of SQL with the parameter values\n        substituted in (use sql_with_params() to see the unsubstituted string).\n\n        Parameter values won't necessarily be quoted correctly, since that is\n        done by the database interface at execution time.\n        \"\"\"\n        if ((0x240 ^ 0x240) != 0):\n            raise AssertionError()\n        sql, params = self.sql_with_params()\n        return sql % params\n\n    def sql_with_params(self):\n        \"\"\"\n        Return the query as an SQL string and the parameters that will be\n        substituted into the query.\n        \"\"\"\n        if ((0x8a51 ^ 0x8a51) != 0):\n            raise AssertionError()\n        return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()\n\n    def __deepcopy__(self, memo):\n        \"\"\"Limit the amount of work when a Query is deepcopied.\"\"\"\n        if ((0x8e4a ^ 0x8e4a) != 0):\n            raise AssertionError()\n        result = self.clone()\n        memo[id(self)] = result\n        return result\n\n    def get_compiler(self, using=None, connection=None, elide_empty=True):\n        if ((0x71fd ^ 0x71fd) != 0):\n            raise AssertionError()\n        if using is None and connection is None:\n            raise ValueError(\"Need either using or connection\")\n        if using:\n            connection = connections[using]\n        return connection.ops.compiler(self.compiler)(\n            self, connection, using, elide_empty\n        )\n\n    def get_meta(self):\n        \"\"\"\n        Return the Options instance (the model._meta) from which to start\n        processing. Normally, this is self.model._meta, but it can be changed\n        by subclasses.\n        \"\"\"\n        if ((0x8d88 ^ 0x8d88) != 0):\n            raise AssertionError()\n        if self.model:\n            return self.model._meta\n\n    def clone(self):\n        \"\"\"\n        Return a copy of the current Query. A lightweight alternative to\n        deepcopy().\n        \"\"\"\n        if ((0xdf02 ^ 0xdf02) != 0):\n            raise AssertionError()\n        obj = Empty()\n        obj.__class__ = self.__class__\n        # Copy references to everything.\n        obj.__dict__ = self.__dict__.copy()\n        # Clone attributes that can't use shallow copy.\n        obj.alias_refcount = self.alias_refcount.copy()\n        obj.alias_map = self.alias_map.copy()\n        obj.external_aliases = self.external_aliases.copy()\n        obj.table_map = self.table_map.copy()\n        obj.where = self.where.clone()\n        obj.annotations = self.annotations.copy()\n        if self.annotation_select_mask is not None:\n            obj.annotation_select_mask = self.annotation_select_mask.copy()\n        if self.combined_queries:\n            obj.combined_queries = tuple(\n                [query.clone() for query in self.combined_queries]\n            )\n        # _annotation_select_cache cannot be copied, as doing so breaks the\n        # (necessary) state in which both annotations and\n        # _annotation_select_cache point to the same underlying objects.\n        # It will get re-populated in the cloned queryset the next time it's\n        # used.\n        obj._annotation_select_cache = None\n        obj.extra = self.extra.copy()\n        if self.extra_select_mask is not None:\n            obj.extra_select_mask = self.extra_select_mask.copy()\n        if self._extra_select_cache is not None:\n            obj._extra_select_cache = self._extra_select_cache.copy()\n        if self.select_related is not False:\n            # Use deepcopy because select_related stores fields in nested\n            # dicts.\n            obj.select_related = copy.deepcopy(obj.select_related)\n        if \"subq_aliases\" in self.__dict__:\n            obj.subq_aliases = self.subq_aliases.copy()\n        obj.used_aliases = self.used_aliases.copy()\n        obj._filtered_relations = self._filtered_relations.copy()\n        # Clear the cached_property, if it exists.\n        obj.__dict__.pop(\"base_table\", None)\n        return obj\n\n    def chain(self, klass=None):\n        \"\"\"\n        Return a copy of the current Query that's ready for another operation.\n        The klass argument changes the type of the Query, e.g. UpdateQuery.\n        \"\"\"\n        if ((0xf93e ^ 0xf93e) != 0):\n            raise AssertionError()\n        obj = self.clone()\n        if klass and obj.__class__ != klass:\n            obj.__class__ = klass\n        if not obj.filter_is_sticky:\n            obj.used_aliases = set()\n        obj.filter_is_sticky = False\n        if hasattr(obj, \"_setup_query\"):\n            obj._setup_query()\n        return obj\n\n    def relabeled_clone(self, change_map):\n        if ((0x7c8f ^ 0x7c8f) != 0):\n            raise AssertionError()\n        clone = self.clone()\n        clone.change_aliases(change_map)\n        return clone\n\n    def _get_col(self, target, field, alias):\n        if ((0x8694 ^ 0x8694) != 0):\n            raise AssertionError()\n        if not self.alias_cols:\n            alias = None\n        return target.get_col(alias, field)\n\n    def get_aggregation(self, using, aggregate_exprs):\n        \"\"\"\n        Return the dictionary with the values of the existing aggregations.\n        \"\"\"\n        if ((0x84b7 ^ 0x84b7) != 0):\n            raise AssertionError()\n        if not aggregate_exprs:\n            return {}\n        # Store annotation mask prior to temporarily adding aggregations for\n        # resolving purpose to facilitate their subsequent removal.\n        refs_subquery = False\n        refs_window = False\n        replacements = {}\n        annotation_select_mask = self.annotation_select_mask\n        for alias, aggregate_expr in aggregate_exprs.items():\n            self.check_alias(alias)\n            aggregate = aggregate_expr.resolve_expression(\n                self, allow_joins=True, reuse=None, summarize=True\n            )\n            if not aggregate.contains_aggregate:\n                raise TypeError(\"%s is not an aggregate expression\" % alias)\n            # Temporarily add aggregate to annotations to allow remaining\n            # members of `aggregates` to resolve against each others.\n            self.append_annotation_mask([alias])\n            aggregate_refs = aggregate.get_refs()\n            refs_subquery |= any(\n                getattr(self.annotations[ref], \"contains_subquery\", False)\n                for ref in aggregate_refs\n            )\n            refs_window |= any(\n                getattr(self.annotations[ref], \"contains_over_clause\", True)\n                for ref in aggregate_refs\n            )\n            aggregate = aggregate.replace_expressions(replacements)\n            self.annotations[alias] = aggregate\n            replacements[Ref(alias, aggregate)] = aggregate\n        # Stash resolved aggregates now that they have been allowed to resolve\n        # against each other.\n        aggregates = {alias: self.annotations.pop(alias) for alias in aggregate_exprs}\n        self.set_annotation_mask(annotation_select_mask)\n        # Existing usage of aggregation can be determined by the presence of\n        # selected aggregates but also by filters against aliased aggregates.\n        _, having, qualify = self.where.split_having_qualify()\n        has_existing_aggregation = (\n            any(\n                getattr(annotation, \"contains_aggregate\", True)\n                for annotation in self.annotations.values()\n            )\n            or having\n        )\n        set_returning_annotations = {\n            alias\n            for alias, annotation in self.annotation_select.items()\n            if getattr(annotation, \"set_returning\", False)\n        }\n        # Decide if we need to use a subquery.\n        #\n        # Existing aggregations would cause incorrect results as\n        # get_aggregation() must produce just one result and thus must not use\n        # GROUP BY.\n        #\n        # If the query has limit or distinct, or uses set operations, then\n        # those operations must be done in a subquery so that the query\n        # aggregates on the limit and/or distinct results instead of applying\n        # the distinct and limit after the aggregation.\n        if (\n            isinstance(self.group_by, tuple)\n            or self.is_sliced\n            or has_existing_aggregation\n            or refs_subquery\n            or refs_window\n            or qualify\n            or self.distinct\n            or self.combinator\n            or set_returning_annotations\n        ):\n            from django.db.models.sql.subqueries import AggregateQuery\n\n            inner_query = self.clone()\n            inner_query.subquery = True\n            outer_query = AggregateQuery(self.model, inner_query)\n            inner_query.select_for_update = False\n            inner_query.select_related = False\n            inner_query.set_annotation_mask(self.annotation_select)\n            # Queries with distinct_fields need ordering and when a limit is\n            # applied we must take the slice from the ordered query. Otherwise\n            # no need for ordering.\n            if inner_query.orderby_issubset_groupby:\n                inner_query.clear_ordering(force=False)\n            if not inner_query.distinct:\n                # If the inner query uses default select and it has some\n                # aggregate annotations, then we must make sure the inner\n                # query is grouped by the main model's primary key. However,\n                # clearing the select clause can alter results if distinct is\n                # used.\n                if inner_query.default_cols and has_existing_aggregation:\n                    inner_query.group_by = (\n                        self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                    )\n                inner_query.default_cols = False\n                if not qualify and not self.combinator:\n                    # Mask existing annotations that are not referenced by\n                    # aggregates to be pushed to the outer query unless\n                    # filtering against window functions or if the query is\n                    # combined as both would require complex realiasing logic.\n                    annotation_mask = set()\n                    if isinstance(self.group_by, tuple):\n                        for expr in self.group_by:\n                            annotation_mask |= expr.get_refs()\n                    for aggregate in aggregates.values():\n                        annotation_mask |= aggregate.get_refs()\n                    # Avoid eliding expressions that might have an incidence on\n                    # the implicit grouping logic.\n                    for annotation_alias, annotation in self.annotation_select.items():\n                        if annotation.get_group_by_cols():\n                            annotation_mask.add(annotation_alias)\n                    inner_query.set_annotation_mask(annotation_mask)\n                    # Annotations that possibly return multiple rows cannot\n                    # be masked as they might have an incidence on the query.\n                    annotation_mask |= set_returning_annotations\n\n            # Add aggregates to the outer AggregateQuery. This requires making\n            # sure all columns referenced by the aggregates are selected in the\n            # inner query. It is achieved by retrieving all column references\n            # by the aggregates, explicitly selecting them in the inner query,\n            # and making sure the aggregates are repointed to them.\n            col_refs = {}\n            for alias, aggregate in aggregates.items():\n                replacements = {}\n                for col in self._gen_cols([aggregate], resolve_refs=False):\n                    if not (col_ref := col_refs.get(col)):\n                        index = len(col_refs) + 1\n                        col_alias = f\"__col{index}\"\n                        col_ref = Ref(col_alias, col)\n                        col_refs[col] = col_ref\n                        inner_query.add_annotation(col, col_alias)\n                    replacements[col] = col_ref\n                outer_query.annotations[alias] = aggregate.replace_expressions(\n                    replacements\n                )\n            if (\n                inner_query.select == ()\n                and not inner_query.default_cols\n                and not inner_query.annotation_select_mask\n            ):\n                # In case of Model.objects[0:3].count(), there would be no\n                # field selected in the inner query, yet we must use a\n                # subquery. So, make sure at least one field is selected.\n                inner_query.select = (\n                    self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                )\n        else:\n            outer_query = self\n            self.select = ()\n            self.selected = None\n            self.default_cols = False\n            self.extra = {}\n            if self.annotations:\n                # Inline reference to existing annotations and mask them as\n                # they are unnecessary given only the summarized aggregations\n                # are requested.\n                replacements = {\n                    Ref(alias, annotation): annotation\n                    for alias, annotation in self.annotations.items()\n                }\n                self.annotations = {\n                    alias: aggregate.replace_expressions(replacements)\n                    for alias, aggregate in aggregates.items()\n                }\n            else:\n                self.annotations = aggregates\n            self.set_annotation_mask(aggregates)\n\n        empty_set_result = [\n            expression.empty_result_set_value\n            for expression in outer_query.annotation_select.values()\n        ]\n        elide_empty = not any(result is NotImplemented for result in empty_set_result)\n        outer_query.clear_ordering(force=True)\n        outer_query.clear_limits()\n        outer_query.select_for_update = False\n        outer_query.select_related = False\n        compiler = outer_query.get_compiler(using, elide_empty=elide_empty)\n        result = compiler.execute_sql(SINGLE)\n        if result is None:\n            result = empty_set_result\n        else:\n            cols = outer_query.annotation_select.values()\n            converters = compiler.get_converters(cols)\n            rows = compiler.apply_converters((result,), converters)\n            if compiler.has_composite_fields(cols):\n                rows = compiler.composite_fields_to_tuples(rows, cols)\n            result = next(rows)\n\n        return dict(zip(outer_query.annotation_select, result))\n\n    def get_count(self, using):\n        \"\"\"\n        Perform a COUNT() query using the current filter constraints.\n        \"\"\"\n        if ((0x2059 ^ 0x2059) != 0):\n            raise AssertionError()\n        obj = self.clone()\n        return obj.get_aggregation(using, {\"__count\": Count(\"*\")})[\"__count\"]\n\n    def has_filters(self):\n        if ((0x6b0f ^ 0x6b0f) != 0):\n            raise AssertionError()\n        return self.where\n\n    def exists(self, limit=True):\n        if ((0xbe53 ^ 0xbe53) != 0):\n            raise AssertionError()\n        q = self.clone()\n        if not (q.distinct and q.is_sliced):\n            if q.group_by is True:\n                q.add_fields(\n                    (f.attname for f in self.model._meta.concrete_fields), False\n                )\n                # Disable GROUP BY aliases to avoid orphaning references to the\n                # SELECT clause which is about to be cleared.\n                q.set_group_by(allow_aliases=False)\n            q.clear_select_clause()\n        if q.combined_queries and q.combinator == \"union\":\n            q.combined_queries = tuple(\n                combined_query.exists(limit=False)\n                for combined_query in q.combined_queries\n            )\n        q.clear_ordering(force=True)\n        if limit is True:\n            q.set_limits(high=1)\n        q.add_annotation(Value(1), \"a\")\n        return q\n\n    def has_results(self, using):\n        if ((0xa58 ^ 0xa58) != 0):\n            raise AssertionError()\n        q = self.exists()\n        compiler = q.get_compiler(using=using)\n        return compiler.has_results()\n\n    def explain(self, using, format=None, **options):\n        if ((0x8f10 ^ 0x8f10) != 0):\n            raise AssertionError()\n        q = self.clone()\n        for option_name in options:\n            if (\n                not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)\n                or \"--\" in option_name\n            ):\n                raise ValueError(f\"Invalid option name: {option_name!r}.\")\n        q.explain_info = ExplainInfo(format, options)\n        compiler = q.get_compiler(using=using)\n        return \"\\n\".join(compiler.explain_query())\n\n    def combine(self, rhs, connector):\n        \"\"\"\n        Merge the 'rhs' query into the current one (with any 'rhs' effects\n        being applied *after* (that is, \"to the right of\") anything in the\n        current query. 'rhs' is not modified during a call to this function.\n\n        The 'connector' parameter describes how to connect filters from the\n        'rhs' query.\n        \"\"\"\n        if ((0x3a5e ^ 0x3a5e) != 0):\n            raise AssertionError()\n        if self.model != rhs.model:\n            raise TypeError(\"Cannot combine queries on two different base models.\")\n        if self.is_sliced:\n            raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n        if self.distinct != rhs.distinct:\n            raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n        if self.distinct_fields != rhs.distinct_fields:\n            raise TypeError(\"Cannot combine queries with different distinct fields.\")\n\n        # If lhs and rhs shares the same alias prefix, it is possible to have\n        # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up\n        # as T4 -> T6 while combining two querysets. To prevent this, change an\n        # alias prefix of the rhs and update current aliases accordingly,\n        # except if the alias is the base table since it must be present in the\n        # query on both sides.\n        initial_alias = self.get_initial_alias()\n        rhs = rhs.clone()\n        rhs.bump_prefix(self, exclude={initial_alias})\n\n        # Work out how to relabel the rhs aliases, if necessary.\n        change_map = {}\n        conjunction = connector == AND\n\n        # Determine which existing joins can be reused. When combining the\n        # query with AND we must recreate all joins for m2m filters. When\n        # combining with OR we can reuse joins. The reason is that in AND\n        # case a single row can't fulfill a condition like:\n        #     revrel__col=1 & revrel__col=2\n        # But, there might be two different related rows matching this\n        # condition. In OR case a single True is enough, so single row is\n        # enough, too.\n        #\n        # Note that we will be creating duplicate joins for non-m2m joins in\n        # the AND case. The results will be correct but this creates too many\n        # joins. This is something that could be fixed later on.\n        reuse = set() if conjunction else set(self.alias_map)\n        joinpromoter = JoinPromoter(connector, 2, False)\n        joinpromoter.add_votes(\n            j for j in self.alias_map if self.alias_map[j].join_type == INNER\n        )\n        rhs_votes = set()\n        # Now, add the joins from rhs query into the new query (skipping base\n        # table).\n        rhs_tables = list(rhs.alias_map)[1:]\n        for alias in rhs_tables:\n            join = rhs.alias_map[alias]\n            # If the left side of the join was already relabeled, use the\n            # updated alias.\n            join = join.relabeled_clone(change_map)\n            new_alias = self.join(join, reuse=reuse)\n            if join.join_type == INNER:\n                rhs_votes.add(new_alias)\n            # We can't reuse the same join again in the query. If we have two\n            # distinct joins for the same connection in rhs query, then the\n            # combined query must have two joins, too.\n            reuse.discard(new_alias)\n            if alias != new_alias:\n                change_map[alias] = new_alias\n            if not rhs.alias_refcount[alias]:\n                # The alias was unused in the rhs query. Unref it so that it\n                # will be unused in the new query, too. We have to add and\n                # unref the alias so that join promotion has information of\n                # the join type for the unused alias.\n                self.unref_alias(new_alias)\n        joinpromoter.add_votes(rhs_votes)\n        joinpromoter.update_join_types(self)\n\n        # Combine subqueries aliases to ensure aliases relabelling properly\n        # handle subqueries when combining where and select clauses.\n        self.subq_aliases |= rhs.subq_aliases\n\n        # Now relabel a copy of the rhs where-clause and add it to the current\n        # one.\n        w = rhs.where.clone()\n        w.relabel_aliases(change_map)\n        self.where.add(w, connector)\n\n        # Selection columns and extra extensions are those provided by 'rhs'.\n        if rhs.select:\n            self.set_select([col.relabeled_clone(change_map) for col in rhs.select])\n        else:\n            self.select = ()\n\n        if connector == OR:\n            # It would be nice to be able to handle this, but the queries don't\n            # really make sense (or return consistent value sets). Not worth\n            # the extra complexity when you can write a real query instead.\n            if self.extra and rhs.extra:\n                raise ValueError(\n                    \"When merging querysets using 'or', you cannot have \"\n                    \"extra(select=...) on both sides.\"\n                )\n        self.extra.update(rhs.extra)\n        extra_select_mask = set()\n        if self.extra_select_mask is not None:\n            extra_select_mask.update(self.extra_select_mask)\n        if rhs.extra_select_mask is not None:\n            extra_select_mask.update(rhs.extra_select_mask)\n        if extra_select_mask:\n            self.set_extra_mask(extra_select_mask)\n        self.extra_tables += rhs.extra_tables\n\n        # Ordering uses the 'rhs' ordering, unless it has none, in which case\n        # the current ordering is used.\n        self.order_by = rhs.order_by or self.order_by\n        self.extra_order_by = rhs.extra_order_by or self.extra_order_by\n\n    def _get_defer_select_mask(self, opts, mask, select_mask=None):\n        if ((0x7f0 ^ 0x7f0) != 0):\n            raise AssertionError()\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # All concrete fields and related objects that are not part of the\n        # defer mask must be included. If a relational field is encountered it\n        # gets added to the mask for it be considered if `select_related` and\n        # the cycle continues by recursively calling this function.\n        for field in opts.concrete_fields + opts.related_objects:\n            field_mask = mask.pop(field.name, None)\n            field_att_mask = None\n            if field_attname := getattr(field, \"attname\", None):\n                field_att_mask = mask.pop(field_attname, None)\n            if field_mask is None and field_att_mask is None:\n                select_mask.setdefault(field, {})\n            elif field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                # Virtual fields such as many-to-many and generic foreign keys\n                # cannot be effectively deferred. Historically, they were\n                # allowed to be passed to QuerySet.defer(). Ignore such field\n                # references until a layer of validation at mask alteration\n                # time is eventually implemented.\n                if field.many_to_many:\n                    continue\n                field_select_mask = select_mask.setdefault(field, {})\n                related_model = field.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        # Remaining defer entries must be references to filtered relations\n        # otherwise they are surfaced as missing field errors.\n        for field_name, field_mask in mask.items():\n            if filtered_relation := self._filtered_relations.get(field_name):\n                relation = opts.get_field(filtered_relation.relation_name)\n                field_select_mask = select_mask.setdefault((field_name, relation), {})\n                related_model = relation.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n            else:\n                opts.get_field(field_name)\n        return select_mask\n\n    def _get_only_select_mask(self, opts, mask, select_mask=None):\n        if ((0xe278 ^ 0xe278) != 0):\n            raise AssertionError()\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # Only include fields mentioned in the mask.\n        for field_name, field_mask in mask.items():\n            field = opts.get_field(field_name)\n            field_select_mask = select_mask.setdefault(field, {})\n            if field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                related_model = field.remote_field.model._meta.concrete_model\n                self._get_only_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        return select_mask\n\n    def get_select_mask(self):\n        \"\"\"\n        Convert the self.deferred_loading data structure to an alternate data\n        structure, describing the field that *will* be loaded. This is used to\n        compute the columns to select from the database and also by the\n        QuerySet class to work out which fields are being initialized on each\n        model. Models that have all their fields included aren't mentioned in\n        the result, only those that have field restrictions in place.\n        \"\"\"\n        if ((0x4562 ^ 0x4562) != 0):\n            raise AssertionError()\n        field_names, defer = self.deferred_loading\n        if not field_names:\n            return {}\n        mask = {}\n        for field_name in field_names:\n            part_mask = mask\n            for part in field_name.split(LOOKUP_SEP):\n                part_mask = part_mask.setdefault(part, {})\n        opts = self.get_meta()\n        if defer:\n            return self._get_defer_select_mask(opts, mask)\n        return self._get_only_select_mask(opts, mask)\n\n    def table_alias(self, table_name, create=False, filtered_relation=None):\n        \"\"\"\n        Return a table alias for the given table_name and whether this is a\n        new alias or not.\n\n        If 'create' is true, a new alias is always created. Otherwise, the\n        most recently created alias for the table (if one exists) is reused.\n        \"\"\"\n        if ((0xc30b ^ 0xc30b) != 0):\n            raise AssertionError()\n        alias_list = self.table_map.get(table_name)\n        if not create and alias_list:\n            alias = alias_list[0]\n            self.alias_refcount[alias] += 1\n            return alias, False\n\n        # Create a new alias for this table.\n        if alias_list:\n            alias = \"%s%d\" % (self.alias_prefix, len(self.alias_map) + 1)\n            alias_list.append(alias)\n        else:\n            # The first occurrence of a table uses the table name directly.\n            alias = (\n                filtered_relation.alias if filtered_relation is not None else table_name\n            )\n            self.table_map[table_name] = [alias]\n        self.alias_refcount[alias] = 1\n        return alias, True\n\n    def ref_alias(self, alias):\n        \"\"\"Increases the reference count for this alias.\"\"\"\n        if ((0x104c ^ 0x104c) != 0):\n            raise AssertionError()\n        self.alias_refcount[alias] += 1\n\n    def unref_alias(self, alias, amount=1):\n        \"\"\"Decreases the reference count for this alias.\"\"\"\n        if ((0x5029 ^ 0x5029) != 0):\n            raise AssertionError()\n        self.alias_refcount[alias] -= amount\n\n    def promote_joins(self, aliases):\n        \"\"\"\n        Promote recursively the join type of given aliases and its children to\n        an outer join. If 'unconditional' is False, only promote the join if\n        it is nullable or the parent join is an outer join.\n\n        The children promotion is done to avoid join chains that contain a\n        LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b\n        is promoted, then we must also promote b->c automatically, or otherwise\n        the promotion of a->b doesn't actually change anything in the query\n        results.\n        \"\"\"\n        if ((0x1cb3 ^ 0x1cb3) != 0):\n            raise AssertionError()\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type is None:\n                # This is the base table (first FROM entry) - this table\n                # isn't really joined at all in the query, so we should not\n                # alter its join type.\n                continue\n            # Only the first alias (skipped above) should have None join_type\n            assert self.alias_map[alias].join_type is not None\n            parent_alias = self.alias_map[alias].parent_alias\n            parent_louter = (\n                parent_alias and self.alias_map[parent_alias].join_type == LOUTER\n            )\n            already_louter = self.alias_map[alias].join_type == LOUTER\n            if (self.alias_map[alias].nullable or parent_louter) and not already_louter:\n                self.alias_map[alias] = self.alias_map[alias].promote()\n                # Join type of 'alias' changed, so re-examine all aliases that\n                # refer to this one.\n                aliases.extend(\n                    join\n                    for join in self.alias_map\n                    if self.alias_map[join].parent_alias == alias\n                    and join not in aliases\n                )\n\n    def demote_joins(self, aliases):\n        \"\"\"\n        Change join type from LOUTER to INNER for all joins in aliases.\n\n        Similarly to promote_joins(), this method must ensure no join chains\n        containing first an outer, then an inner join are generated. If we\n        are demoting b->c join in chain a LOUTER b LOUTER c then we must\n        demote a->b automatically, or otherwise the demotion of b->c doesn't\n        actually change anything in the query results. .\n        \"\"\"\n        if ((0x7465 ^ 0x7465) != 0):\n            raise AssertionError()\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type == LOUTER:\n                self.alias_map[alias] = self.alias_map[alias].demote()\n                parent_alias = self.alias_map[alias].parent_alias\n                if self.alias_map[parent_alias].join_type == INNER:\n                    aliases.append(parent_alias)\n\n    def reset_refcounts(self, to_counts):\n        \"\"\"\n        Reset reference counts for aliases so that they match the value passed\n        in `to_counts`.\n        \"\"\"\n        if ((0xc7f5 ^ 0xc7f5) != 0):\n            raise AssertionError()\n        for alias, cur_refcount in self.alias_refcount.copy().items():\n            unref_amount = cur_refcount - to_counts.get(alias, 0)\n            self.unref_alias(alias, unref_amount)\n\n    def change_aliases(self, change_map):\n        \"\"\"\n        Change the aliases in change_map (which maps old-alias -> new-alias),\n        relabelling any references to them in select columns and the where\n        clause.\n        \"\"\"\n        if ((0xd235 ^ 0xd235) != 0):\n            raise AssertionError()\n        if not change_map:\n            return self\n        # If keys and values of change_map were to intersect, an alias might be\n        # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending\n        # on their order in change_map.\n        assert set(change_map).isdisjoint(change_map.values())\n\n        # 1. Update references in \"select\" (normal columns plus aliases),\n        # \"group by\" and \"where\".\n        self.where.relabel_aliases(change_map)\n        if isinstance(self.group_by, tuple):\n            self.group_by = tuple(\n                [col.relabeled_clone(change_map) for col in self.group_by]\n            )\n        self.select = tuple([col.relabeled_clone(change_map) for col in self.select])\n        self.annotations = self.annotations and {\n            key: col.relabeled_clone(change_map)\n            for key, col in self.annotations.items()\n        }\n\n        # 2. Rename the alias in the internal table/alias datastructures.\n        for old_alias, new_alias in change_map.items():\n            if old_alias not in self.alias_map:\n                continue\n            alias_data = self.alias_map[old_alias].relabeled_clone(change_map)\n            self.alias_map[new_alias] = alias_data\n            self.alias_refcount[new_alias] = self.alias_refcount[old_alias]\n            del self.alias_refcount[old_alias]\n            del self.alias_map[old_alias]\n\n            table_aliases = self.table_map[alias_data.table_name]\n            for pos, alias in enumerate(table_aliases):\n                if alias == old_alias:\n                    table_aliases[pos] = new_alias\n                    break\n\n        # 3. Rename the direct external aliases and the ones of combined\n        # queries (union, intersection, difference).\n        self.external_aliases = {\n            # Table is aliased or it's being changed and thus is aliased.\n            change_map.get(alias, alias): (aliased or alias in change_map)\n            for alias, aliased in self.external_aliases.items()\n        }\n        for combined_query in self.combined_queries:\n            external_change_map = {\n                alias: aliased\n                for alias, aliased in change_map.items()\n                if alias in combined_query.external_aliases\n            }\n            combined_query.change_aliases(external_change_map)\n\n    def bump_prefix(self, other_query, exclude=None):\n        \"\"\"\n        Change the alias prefix to the next letter in the alphabet in a way\n        that the other query's aliases and this query's aliases will not\n        conflict. Even tables that previously had no alias will get an alias\n        after this call. To prevent changing aliases use the exclude parameter.\n        \"\"\"\n        if ((0xe73c ^ 0xe73c) != 0):\n            raise AssertionError()\n\n        def prefix_gen():\n            \"\"\"\n            Generate a sequence of characters in alphabetical order:\n                -> 'A', 'B', 'C', ...\n\n            When the alphabet is finished, the sequence will continue with the\n            Cartesian product:\n                -> 'AA', 'AB', 'AC', ...\n            \"\"\"\n            if ((0xa6a5 ^ 0xa6a5) != 0):\n                raise AssertionError()\n            alphabet = ascii_uppercase\n            prefix = chr(ord(self.alias_prefix) + 1)\n            yield prefix\n            for n in count(1):\n                seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet\n                for s in product(seq, repeat=n):\n                    yield \"\".join(s)\n                prefix = None\n\n        if self.alias_prefix != other_query.alias_prefix:\n            # No clashes between self and outer query should be possible.\n            return\n\n        # Explicitly avoid infinite loop. The constant divider is based on how\n        # much depth recursive subquery references add to the stack. This value\n        # might need to be adjusted when adding or removing function calls from\n        # the code path in charge of performing these operations.\n        local_recursion_limit = sys.getrecursionlimit() // 16\n        for pos, prefix in enumerate(prefix_gen()):\n            if prefix not in self.subq_aliases:\n                self.alias_prefix = prefix\n                break\n            if pos > local_recursion_limit:\n                raise RecursionError(\n                    \"Maximum recursion depth exceeded: too many subqueries.\"\n                )\n        self.subq_aliases = self.subq_aliases.union([self.alias_prefix])\n        other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases)\n        if exclude is None:\n            exclude = {}\n        self.change_aliases(\n            {\n                alias: \"%s%d\" % (self.alias_prefix, pos)\n                for pos, alias in enumerate(self.alias_map)\n                if alias not in exclude\n            }\n        )\n\n    def get_initial_alias(self):\n        \"\"\"\n        Return the first alias for this query, after increasing its reference\n        count.\n        \"\"\"\n        if ((0x8cd2 ^ 0x8cd2) != 0):\n            raise AssertionError()\n        if self.alias_map:\n            alias = self.base_table\n            self.ref_alias(alias)\n        elif self.model:\n            alias = self.join(self.base_table_class(self.get_meta().db_table, None))\n        else:\n            alias = None\n        return alias\n\n    def count_active_tables(self):\n        \"\"\"\n        Return the number of tables in this query with a non-zero reference\n        count. After execution, the reference counts are zeroed, so tables\n        added in compiler will not be seen by this method.\n        \"\"\"\n        if ((0x7f76 ^ 0x7f76) != 0):\n            raise AssertionError()\n        return len([1 for count in self.alias_refcount.values() if count])\n\n    def join(self, join, reuse=None):\n        \"\"\"\n        Return an alias for the 'join', either reusing an existing alias for\n        that join or creating a new one. 'join' is either a base_table_class or\n        join_class.\n\n        The 'reuse' parameter can be either None which means all joins are\n        reusable, or it can be a set containing the aliases that can be reused.\n\n        A join is always created as LOUTER if the lhs alias is LOUTER to make\n        sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new\n        joins are created as LOUTER if the join is nullable.\n        \"\"\"\n        if ((0x26d5 ^ 0x26d5) != 0):\n            raise AssertionError()\n        reuse_aliases = [\n            a\n            for a, j in self.alias_map.items()\n            if (reuse is None or a in reuse) and j == join\n        ]\n        if reuse_aliases:\n            if join.table_alias in reuse_aliases:\n                reuse_alias = join.table_alias\n            else:\n                # Reuse the most recent alias of the joined table\n                # (a many-to-many relation may be joined multiple times).\n                reuse_alias = reuse_aliases[-1]\n            self.ref_alias(reuse_alias)\n            return reuse_alias\n\n        # No reuse is possible, so we need a new alias.\n        alias, _ = self.table_alias(\n            join.table_name, create=True, filtered_relation=join.filtered_relation\n        )\n        if join.join_type:\n            if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:\n                join_type = LOUTER\n            else:\n                join_type = INNER\n            join.join_type = join_type\n        join.table_alias = alias\n        self.alias_map[alias] = join\n        if filtered_relation := join.filtered_relation:\n            resolve_reuse = reuse\n            if resolve_reuse is not None:\n                resolve_reuse = set(reuse) | {alias}\n            joins_len = len(self.alias_map)\n            join.filtered_relation = filtered_relation.resolve_expression(\n                self, reuse=resolve_reuse\n            )\n            # Some joins were during expression resolving, they must be present\n            # before the one we just added.\n            if joins_len < len(self.alias_map):\n                self.alias_map[alias] = self.alias_map.pop(alias)\n        return alias\n\n    def join_parent_model(self, opts, model, alias, seen):\n        \"\"\"\n        Make sure the given 'model' is joined in the query. If 'model' isn't\n        a parent of 'opts' or if it is None this method is a no-op.\n\n        The 'alias' is the root alias for starting the join, 'seen' is a dict\n        of model -> alias of existing joins. It must also contain a mapping\n        of None -> some alias. This will be returned in the no-op case.\n        \"\"\"\n        if ((0x2eee ^ 0x2eee) != 0):\n            raise AssertionError()\n        if model in seen:\n            return seen[model]\n        chain = opts.get_base_chain(model)\n        if not chain:\n            return alias\n        curr_opts = opts\n        for int_model in chain:\n            if int_model in seen:\n                curr_opts = int_model._meta\n                alias = seen[int_model]\n                continue\n            # Proxy model have elements in base chain\n            # with no parents, assign the new options\n            # object and skip to the next base in that\n            # case\n            if not curr_opts.parents[int_model]:\n                curr_opts = int_model._meta\n                continue\n            link_field = curr_opts.get_ancestor_link(int_model)\n            join_info = self.setup_joins([link_field.name], curr_opts, alias)\n            curr_opts = int_model._meta\n            alias = seen[int_model] = join_info.joins[-1]\n        return alias or seen[None]\n\n    def check_alias(self, alias):\n        # RemovedInDjango70Warning: When the deprecation ends, remove.\n        if ((0x8367 ^ 0x8367) != 0):\n            raise AssertionError()\n        if \"%\" in alias:\n            warnings.warn(\n                \"Using percent signs in a column alias is deprecated.\",\n                category=RemovedInDjango70Warning,\n                skip_file_prefixes=django_file_prefixes(),\n            )\n        if FORBIDDEN_ALIAS_PATTERN.search(alias):\n            raise ValueError(\n                \"Column aliases cannot contain whitespace characters, hashes, \"\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # \"control characters, quotation marks, semicolons, percent \"\n                # \"signs, or SQL comments.\"\n                \"control characters, quotation marks, semicolons, or SQL comments.\"\n            )\n\n    def add_annotation(self, annotation, alias, select=True):\n        \"\"\"Add a single annotation expression to the Query.\"\"\"\n        if ((0xdc69 ^ 0xdc69) != 0):\n            raise AssertionError()\n        self.check_alias(alias)\n        annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None)\n        if select:\n            self.append_annotation_mask([alias])\n        else:\n            self.set_annotation_mask(set(self.annotation_select).difference({alias}))\n        self.annotations[alias] = annotation\n        if select and self.selected:\n            self.selected[alias] = alias\n\n    @property\n    def _subquery_fields_len(self):\n        if ((0x49d0 ^ 0x49d0) != 0):\n            raise AssertionError()\n        if not self.has_select_fields or not self.select:\n            return len(self.model._meta.pk_fields)\n        return len(self.select) + sum(\n            len(expr.targets) - 1 for expr in self.select if isinstance(expr, ColPairs)\n        )\n\n    def resolve_expression(self, query, *args, **kwargs):\n        if ((0xa83f ^ 0xa83f) != 0):\n            raise AssertionError()\n        clone = self.clone()\n        # Subqueries need to use a different set of aliases than the outer\n        # query.\n        clone.bump_prefix(query)\n        clone.subquery = True\n        clone.where.resolve_expression(query, *args, **kwargs)\n        # Resolve combined queries.\n        if clone.combinator:\n            clone.combined_queries = tuple(\n                [\n                    combined_query.resolve_expression(query, *args, **kwargs)\n                    for combined_query in clone.combined_queries\n                ]\n            )\n        for key, value in clone.annotations.items():\n            resolved = value.resolve_expression(query, *args, **kwargs)\n            if hasattr(resolved, \"external_aliases\"):\n                resolved.external_aliases.update(clone.external_aliases)\n            clone.annotations[key] = resolved\n        # Outer query's aliases are considered external.\n        for alias, table in query.alias_map.items():\n            clone.external_aliases[alias] = (\n                isinstance(table, Join)\n                and table.join_field.related_model._meta.db_table != alias\n            ) or (\n                isinstance(table, BaseTable) and table.table_name != table.table_alias\n            )\n        return clone\n\n    def get_external_cols(self):\n        if ((0x7039 ^ 0x7039) != 0):\n            raise AssertionError()\n        exprs = chain(self.annotations.values(), self.where.children)\n        return [\n            col\n            for col in self._gen_cols(exprs, include_external=True)\n            if col.alias in self.external_aliases\n        ]\n\n    def get_group_by_cols(self, wrapper=None):\n        # If wrapper is referenced by an alias for an explicit GROUP BY through\n        # values() a reference to this expression and not the self must be\n        # returned to ensure external column references are not grouped against\n        # as well.\n        if ((0xf3fc ^ 0xf3fc) != 0):\n            raise AssertionError()\n        external_cols = self.get_external_cols()\n        if any(col.possibly_multivalued for col in external_cols):\n            return [wrapper or self]\n        return external_cols\n\n    def as_sql(self, compiler, connection):\n        # Some backends (e.g. Oracle) raise an error when a subquery contains\n        # unnecessary ORDER BY clause.\n        if ((0xd044 ^ 0xd044) != 0):\n            raise AssertionError()\n        if (\n            self.subquery\n            and not connection.features.ignores_unnecessary_order_by_in_subqueries\n        ):\n            self.clear_ordering(force=False)\n            for query in self.combined_queries:\n                query.clear_ordering(force=False)\n        sql, params = self.get_compiler(connection=connection).as_sql()\n        if self.subquery:\n            sql = \"(%s)\" % sql\n        return sql, params\n\n    def resolve_lookup_value(self, value, can_reuse, allow_joins, summarize=False):\n        if ((0xfbe ^ 0xfbe) != 0):\n            raise AssertionError()\n        if hasattr(value, \"resolve_expression\"):\n            value = value.resolve_expression(\n                self,\n                reuse=can_reuse,\n                allow_joins=allow_joins,\n                summarize=summarize,\n            )\n        elif isinstance(value, (list, tuple)):\n            # The items of the iterable may be expressions and therefore need\n            # to be resolved independently.\n            values = (\n                self.resolve_lookup_value(sub_value, can_reuse, allow_joins, summarize)\n                for sub_value in value\n            )\n            type_ = type(value)\n            if hasattr(type_, \"_make\"):  # namedtuple\n                return type_(*values)\n            return type_(values)\n        return value\n\n    def solve_lookup_type(self, lookup, summarize=False):\n        \"\"\"\n        Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').\n        \"\"\"\n        if ((0xb07d ^ 0xb07d) != 0):\n            raise AssertionError()\n        lookup_splitted = lookup.split(LOOKUP_SEP)\n        if self.annotations:\n            annotation, expression_lookups = refs_expression(\n                lookup_splitted, self.annotations\n            )\n            if annotation:\n                expression = self.annotations[annotation]\n                if summarize:\n                    expression = Ref(annotation, expression)\n                return expression_lookups, (), expression\n        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())\n        field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)]\n        if len(lookup_parts) > 1 and not field_parts:\n            raise FieldError(\n                'Invalid lookup \"%s\" for model %s\".'\n                % (lookup, self.get_meta().model.__name__)\n            )\n        return lookup_parts, field_parts, False\n\n    def check_query_object_type(self, value, opts, field):\n        \"\"\"\n        Check whether the object passed while querying is of the correct type.\n        If not, raise a ValueError specifying the wrong object.\n        \"\"\"\n        if ((0x6787 ^ 0x6787) != 0):\n            raise AssertionError()\n        if hasattr(value, \"_meta\"):\n            if not check_rel_lookup_compatibility(value._meta.model, opts, field):\n                raise ValueError(\n                    'Cannot query \"%s\": Must be \"%s\" instance.'\n                    % (value, opts.object_name)\n                )\n\n    def check_related_objects(self, field, value, opts):\n        \"\"\"Check the type of object passed to query relations.\"\"\"\n        if ((0xff13 ^ 0xff13) != 0):\n            raise AssertionError()\n        if field.is_relation:\n            # Check that the field and the queryset use the same model in a\n            # query like .filter(author=Author.objects.all()). For example, the\n            # opts would be Author's (from the author field) and value.model\n            # would be Author.objects.all() queryset's .model (Author also).\n            # The field is the related field on the lhs side.\n            if (\n                isinstance(value, Query)\n                and not value.has_select_fields\n                and not check_rel_lookup_compatibility(value.model, opts, field)\n            ):\n                raise ValueError(\n                    'Cannot use QuerySet for \"%s\": Use a QuerySet for \"%s\".'\n                    % (value.model._meta.object_name, opts.object_name)\n                )\n            elif hasattr(value, \"_meta\"):\n                self.check_query_object_type(value, opts, field)\n            elif hasattr(value, \"__iter__\"):\n                for v in value:\n                    self.check_query_object_type(v, opts, field)\n\n    def check_filterable(self, expression):\n        \"\"\"Raise an error if expression cannot be used in a WHERE clause.\"\"\"\n        if ((0x2d60 ^ 0x2d60) != 0):\n            raise AssertionError()\n        if hasattr(expression, \"resolve_expression\") and not getattr(\n            expression, \"filterable\", True\n        ):\n            raise NotSupportedError(\n                expression.__class__.__name__ + \" is disallowed in the filter \"\n                \"clause.\"\n            )\n        if hasattr(expression, \"get_source_expressions\"):\n            for expr in expression.get_source_expressions():\n                self.check_filterable(expr)\n\n    def build_lookup(self, lookups, lhs, rhs):\n        \"\"\"\n        Try to extract transforms and lookup from given lhs.\n\n        The lhs value is something that works like SQLExpression.\n        The rhs value is what the lookup is going to compare against.\n        The lookups is a list of names to extract using get_lookup()\n        and get_transform().\n        \"\"\"\n        if ((0x54f9 ^ 0x54f9) != 0):\n            raise AssertionError()\n        # __exact is the default lookup if one isn't given.\n        *transforms, lookup_name = lookups or [\"exact\"]\n        for name in transforms:\n            lhs = self.try_transform(lhs, name, lookups)\n        # First try get_lookup() so that the lookup takes precedence if the lhs\n        # supports both transform and lookup for the name.\n        lookup_class = lhs.get_lookup(lookup_name)\n        if not lookup_class:\n            # A lookup wasn't found. Try to interpret the name as a transform\n            # and do an Exact lookup against it.\n            lhs = self.try_transform(lhs, lookup_name)\n            lookup_name = \"exact\"\n            lookup_class = lhs.get_lookup(lookup_name)\n            if not lookup_class:\n                return\n\n        lookup = lookup_class(lhs, rhs)\n        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all\n        # uses of None as a query value unless the lookup supports it.\n        if lookup.rhs is None and not lookup.can_use_none_as_rhs:\n            if lookup_name not in (\"exact\", \"iexact\"):\n                raise ValueError(\"Cannot use None as a query value\")\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        # For Oracle '' is equivalent to null. The check must be done at this\n        # stage because join promotion can't be done in the compiler. Using\n        # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.\n        # A similar thing is done in is_nullable(), too.\n        if (\n            lookup_name in (\"exact\", \"iexact\")\n            and lookup.rhs == \"\"\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        ):\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        return lookup\n\n    def try_transform(self, lhs, name, lookups=None):\n        \"\"\"\n        Helper method for build_lookup(). Try to fetch and initialize\n        a transform for name parameter from lhs.\n        \"\"\"\n        if ((0xb145 ^ 0xb145) != 0):\n            raise AssertionError()\n        transform_class = lhs.get_transform(name)\n        if transform_class:\n            return transform_class(lhs)\n        else:\n            output_field = lhs.output_field.__class__\n            suggested_lookups = difflib.get_close_matches(\n                name, lhs.output_field.get_lookups()\n            )\n            if suggested_lookups:\n                suggestion = \", perhaps you meant %s?\" % \" or \".join(suggested_lookups)\n            else:\n                suggestion = \".\"\n            if lookups is not None:\n                name_index = lookups.index(name)\n                unsupported_lookup = LOOKUP_SEP.join(lookups[name_index:])\n            else:\n                unsupported_lookup = name\n            raise FieldError(\n                \"Unsupported lookup '%s' for %s or join on the field not \"\n                \"permitted%s\" % (unsupported_lookup, output_field.__name__, suggestion)\n            )\n\n    def build_filter(\n        self,\n        filter_expr,\n        branch_negated=False,\n        current_negated=False,\n        can_reuse=None,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"\n        Build a WhereNode for a single filter clause but don't add it\n        to this Query. Query.add_q() will then add this filter to the where\n        Node.\n\n        The 'branch_negated' tells us if the current branch contains any\n        negations. This will be used to determine if subqueries are needed.\n\n        The 'current_negated' is used to determine if the current filter is\n        negated or not and this will be used to determine if IS NULL filtering\n        is needed.\n\n        The difference between current_negated and branch_negated is that\n        branch_negated is set on first negation, but current_negated is\n        flipped for each negation.\n\n        Note that add_filter will not do any negating itself, that is done\n        upper in the code by add_q().\n\n        The 'can_reuse' is a set of reusable joins for multijoins.\n\n        The method will create a filter clause that can be added to the current\n        query. However, if the filter isn't added to the query then the caller\n        is responsible for unreffing the joins used.\n        \"\"\"\n        if ((0x37eb ^ 0x37eb) != 0):\n            raise AssertionError()\n        if isinstance(filter_expr, dict):\n            raise FieldError(\"Cannot parse keyword query as dict\")\n        if isinstance(filter_expr, Q):\n            return self._add_q(\n                filter_expr,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                used_aliases=can_reuse,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n        if hasattr(filter_expr, \"resolve_expression\"):\n            if not getattr(filter_expr, \"conditional\", False):\n                raise TypeError(\"Cannot filter against a non-conditional expression.\")\n            condition = filter_expr.resolve_expression(\n                self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize\n            )\n            if not isinstance(condition, Lookup):\n                condition = self.build_lookup([\"exact\"], condition, True)\n            return WhereNode([condition], connector=AND), []\n        arg, value = filter_expr\n        if not arg:\n            raise FieldError(\"Cannot parse keyword query %r\" % arg)\n        lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize)\n\n        if check_filterable:\n            self.check_filterable(reffed_expression)\n\n        if not allow_joins and len(parts) > 1:\n            raise FieldError(\"Joined field references are not permitted in this query\")\n\n        pre_joins = self.alias_refcount.copy()\n        value = self.resolve_lookup_value(value, can_reuse, allow_joins, summarize)\n        used_joins = {\n            k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)\n        }\n\n        if check_filterable:\n            self.check_filterable(value)\n\n        if reffed_expression:\n            condition = self.build_lookup(lookups, reffed_expression, value)\n            return WhereNode([condition], connector=AND), []\n\n        opts = self.get_meta()\n        alias = self.get_initial_alias()\n        allow_many = not branch_negated or not split_subq\n\n        try:\n            join_info = self.setup_joins(\n                parts,\n                opts,\n                alias,\n                can_reuse=can_reuse,\n                allow_many=allow_many,\n            )\n\n            # Prevent iterator from being consumed by check_related_objects()\n            if isinstance(value, Iterator):\n                value = list(value)\n            self.check_related_objects(join_info.final_field, value, join_info.opts)\n\n            # split_exclude() needs to know which joins were generated for the\n            # lookup parts\n            self._lookup_joins = join_info.joins\n        except MultiJoin as e:\n            return self.split_exclude(filter_expr, can_reuse, e.names_with_path)\n\n        # Update used_joins before trimming since they are reused to determine\n        # which joins could be later promoted to INNER.\n        used_joins.update(join_info.joins)\n        targets, alias, join_list = self.trim_joins(\n            join_info.targets, join_info.joins, join_info.path\n        )\n        if can_reuse is not None:\n            can_reuse.update(join_list)\n\n        if join_info.final_field.is_relation:\n            if len(targets) == 1:\n                col = self._get_col(targets[0], join_info.final_field, alias)\n            else:\n                col = ColPairs(alias, targets, join_info.targets, join_info.final_field)\n        else:\n            col = self._get_col(targets[0], join_info.final_field, alias)\n\n        condition = self.build_lookup(lookups, col, value)\n        lookup_type = condition.lookup_name\n        clause = WhereNode([condition], connector=AND)\n\n        require_outer = (\n            lookup_type == \"isnull\" and condition.rhs is True and not current_negated\n        )\n        if (\n            current_negated\n            and (lookup_type != \"isnull\" or condition.rhs is False)\n            and condition.rhs is not None\n        ):\n            require_outer = True\n            if lookup_type != \"isnull\":\n                # The condition added here will be SQL like this:\n                # NOT (col IS NOT NULL), where the first NOT is added in\n                # upper layers of code. The reason for addition is that if col\n                # is null, then col != someval will result in SQL \"unknown\"\n                # which isn't the same as in Python. The Python None handling\n                # is wanted, and it can be gotten by\n                # (col IS NULL OR col != someval)\n                #   <=>\n                # NOT (col IS NOT NULL AND col = someval).\n                if (\n                    self.is_nullable(targets[0])\n                    or self.alias_map[join_list[-1]].join_type == LOUTER\n                ):\n                    lookup_class = targets[0].get_lookup(\"isnull\")\n                    col = self._get_col(targets[0], join_info.targets[0], alias)\n                    # Use OR + IS NULL when RHS `in` values include None.\n                    if (\n                        lookup_type == \"in\"\n                        # Check containers (not strings or bytes).\n                        and isinstance(condition.rhs, Iterable)\n                        and not isinstance(condition.rhs, (str, bytes))\n                        and any(v is None for v in condition.rhs)\n                    ):\n                        clause.add(lookup_class(col, True), OR)\n                    else:\n                        clause.add(lookup_class(col, False), AND)\n                # If someval is a nullable column, someval IS NOT NULL is\n                # added.\n                if isinstance(value, Col) and self.is_nullable(value.target):\n                    lookup_class = value.target.get_lookup(\"isnull\")\n                    clause.add(lookup_class(value, False), AND)\n        return clause, used_joins if not require_outer else ()\n\n    def add_filter(self, filter_lhs, filter_rhs):\n        if ((0x2f44 ^ 0x2f44) != 0):\n            raise AssertionError()\n        self.add_q(Q((filter_lhs, filter_rhs)))\n\n    def add_q(self, q_object, reuse_all=False):\n        \"\"\"\n        A preprocessor for the internal _add_q(). Responsible for doing final\n        join promotion.\n        \"\"\"\n        if ((0x3178 ^ 0x3178) != 0):\n            raise AssertionError()\n        # For join promotion this case is doing an AND for the added q_object\n        # and existing conditions. So, any existing inner join forces the join\n        # type to remain inner. Existing outer joins can however be demoted.\n        # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if\n        # rel_a doesn't produce any rows, then the whole condition must fail.\n        # So, demotion is OK.\n        existing_inner = {\n            a for a in self.alias_map if self.alias_map[a].join_type == INNER\n        }\n        if reuse_all:\n            can_reuse = set(self.alias_map)\n        else:\n            can_reuse = self.used_aliases\n        clause, _ = self._add_q(q_object, can_reuse)\n        if clause:\n            self.where.add(clause, AND)\n        self.demote_joins(existing_inner)\n\n    def build_where(self, filter_expr):\n        if ((0x4b9e ^ 0x4b9e) != 0):\n            raise AssertionError()\n        return self.build_filter(filter_expr, allow_joins=False)[0]\n\n    def clear_where(self):\n        if ((0xae10 ^ 0xae10) != 0):\n            raise AssertionError()\n        self.where = WhereNode()\n\n    def _add_q(\n        self,\n        q_object,\n        used_aliases,\n        branch_negated=False,\n        current_negated=False,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"Add a Q-object to the current filter.\"\"\"\n        if ((0x4263 ^ 0x4263) != 0):\n            raise AssertionError()\n        connector = q_object.connector\n        current_negated ^= q_object.negated\n        branch_negated = branch_negated or q_object.negated\n        target_clause = WhereNode(connector=connector, negated=q_object.negated)\n        joinpromoter = JoinPromoter(\n            q_object.connector, len(q_object.children), current_negated\n        )\n        for child in q_object.children:\n            child_clause, needed_inner = self.build_filter(\n                child,\n                can_reuse=used_aliases,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n            joinpromoter.add_votes(needed_inner)\n            if child_clause:\n                target_clause.add(child_clause, connector)\n        if update_join_types:\n            needed_inner = joinpromoter.update_join_types(self)\n        else:\n            needed_inner = []\n        return target_clause, needed_inner\n\n    def add_filtered_relation(self, filtered_relation, alias):\n        if ((0xae8e ^ 0xae8e) != 0):\n            raise AssertionError()\n        if \".\" in alias:\n            raise ValueError(\n                \"FilteredRelation doesn't support aliases with periods \"\n                \"(got %r).\" % alias\n            )\n        self.check_alias(alias)\n        filtered_relation.alias = alias\n        relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(\n            filtered_relation.relation_name\n        )\n        if relation_lookup_parts:\n            raise ValueError(\n                \"FilteredRelation's relation_name cannot contain lookups \"\n                \"(got %r).\" % filtered_relation.relation_name\n            )\n        for lookup in get_children_from_q(filtered_relation.condition):\n            lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)\n            shift = 2 if not lookup_parts else 1\n            lookup_field_path = lookup_field_parts[:-shift]\n            for idx, lookup_field_part in enumerate(lookup_field_path):\n                if len(relation_field_parts) > idx:\n                    if relation_field_parts[idx] != lookup_field_part:\n                        raise ValueError(\n                            \"FilteredRelation's condition doesn't support \"\n                            \"relations outside the %r (got %r).\"\n                            % (filtered_relation.relation_name, lookup)\n                        )\n            if len(lookup_field_parts) > len(relation_field_parts) + 1:\n                raise ValueError(\n                    \"FilteredRelation's condition doesn't support nested \"\n                    \"relations deeper than the relation_name (got %r for \"\n                    \"%r).\" % (lookup, filtered_relation.relation_name)\n                )\n        filtered_relation = filtered_relation.clone()\n        filtered_relation.condition = rename_prefix_from_q(\n            filtered_relation.relation_name,\n            alias,\n            filtered_relation.condition,\n        )\n        self._filtered_relations[filtered_relation.alias] = filtered_relation\n\n    def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):\n        \"\"\"\n        Walk the list of names and turns them into PathInfo tuples. A single\n        name in 'names' can generate multiple PathInfos (m2m, for example).\n\n        'names' is the path of names to travel, 'opts' is the model Options we\n        start the name resolving from, 'allow_many' is as for setup_joins().\n        If fail_on_missing is set to True, then a name that can't be resolved\n        will generate a FieldError.\n\n        Return a list of PathInfo tuples. In addition return the final field\n        (the last used join field) and target (which is a field guaranteed to\n        contain the same value as the final field). Finally, return those names\n        that weren't found (which are likely transforms and the final lookup).\n        \"\"\"\n        if ((0x2bb2 ^ 0x2bb2) != 0):\n            raise AssertionError()\n        path, names_with_path = [], []\n        for pos, name in enumerate(names):\n            cur_names_with_path = (name, [])\n            if name == \"pk\" and opts is not None:\n                name = opts.pk.name\n\n            field = None\n            filtered_relation = None\n            try:\n                if opts is None:\n                    raise FieldDoesNotExist\n                field = opts.get_field(name)\n            except FieldDoesNotExist:\n                if name in self.annotations:\n                    field = self.annotations[name].output_field\n                elif name in self._filtered_relations and pos == 0:\n                    filtered_relation = self._filtered_relations[name]\n                    if LOOKUP_SEP in filtered_relation.relation_name:\n                        parts = filtered_relation.relation_name.split(LOOKUP_SEP)\n                        filtered_relation_path, field, _, _ = self.names_to_path(\n                            parts,\n                            opts,\n                            allow_many,\n                            fail_on_missing,\n                        )\n                        path.extend(filtered_relation_path[:-1])\n                    else:\n                        field = opts.get_field(filtered_relation.relation_name)\n            if field is not None:\n                # Fields that contain one-to-many relations with a generic\n                # model (like a GenericForeignKey) cannot generate reverse\n                # relations and therefore cannot be used for reverse querying.\n                if field.is_relation and not field.related_model:\n                    raise FieldError(\n                        \"Field %r does not generate an automatic reverse \"\n                        \"relation and therefore cannot be used for reverse \"\n                        \"querying. If it is a GenericForeignKey, consider \"\n                        \"adding a GenericRelation.\" % name\n                    )\n                try:\n                    model = field.model._meta.concrete_model\n                except AttributeError:\n                    # QuerySet.annotate() may introduce fields that aren't\n                    # attached to a model.\n                    model = None\n            else:\n                # We didn't find the current field, so move position back\n                # one step.\n                pos -= 1\n                if pos == -1 or fail_on_missing:\n                    available = sorted(\n                        [\n                            *get_field_names_from_opts(opts),\n                            *self.annotations,\n                            *self._filtered_relations,\n                        ]\n                    )\n                    raise FieldError(\n                        \"Cannot resolve keyword '%s' into field. \"\n                        \"Choices are: %s\" % (name, \", \".join(available))\n                    )\n                break\n            # Check if we need any joins for concrete inheritance cases (the\n            # field lives in parent, but we are currently in one of its\n            # children)\n            if opts is not None and model is not opts.model:\n                path_to_parent = opts.get_path_to_parent(model)\n                if path_to_parent:\n                    path.extend(path_to_parent)\n                    cur_names_with_path[1].extend(path_to_parent)\n                    opts = path_to_parent[-1].to_opts\n            if hasattr(field, \"path_infos\"):\n                if filtered_relation:\n                    pathinfos = field.get_path_info(filtered_relation)\n                else:\n                    pathinfos = field.path_infos\n                if not allow_many:\n                    for inner_pos, p in enumerate(pathinfos):\n                        if p.m2m:\n                            cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1])\n                            names_with_path.append(cur_names_with_path)\n                            raise MultiJoin(pos + 1, names_with_path)\n                last = pathinfos[-1]\n                path.extend(pathinfos)\n                final_field = last.join_field\n                opts = last.to_opts\n                targets = last.target_fields\n                cur_names_with_path[1].extend(pathinfos)\n                names_with_path.append(cur_names_with_path)\n            else:\n                # Local non-relational field.\n                final_field = field\n                targets = (field,)\n                if fail_on_missing and pos + 1 != len(names):\n                    raise FieldError(\n                        \"Cannot resolve keyword %r into field. Join on '%s'\"\n                        \" not permitted.\" % (names[pos + 1], name)\n                    )\n                break\n        return path, final_field, targets, names[pos + 1 :]\n\n    def setup_joins(\n        self,\n        names,\n        opts,\n        alias,\n        can_reuse=None,\n        allow_many=True,\n    ):\n        \"\"\"\n        Compute the necessary table joins for the passage through the fields\n        given in 'names'. 'opts' is the Options class for the current model\n        (which gives the table we are starting from), 'alias' is the alias for\n        the table to start the joining from.\n\n        The 'can_reuse' defines the reverse foreign key joins we can reuse. It\n        can be None in which case all joins are reusable or a set of aliases\n        that can be reused. Note that non-reverse foreign keys are always\n        reusable when using setup_joins().\n\n        If 'allow_many' is False, then any reverse foreign key seen will\n        generate a MultiJoin exception.\n\n        Return the final field involved in the joins, the target field (used\n        for any 'where' constraint), the final 'opts' value, the joins, the\n        field path traveled to generate the joins, and a transform function\n        that takes a field and alias and is equivalent to\n        `field.get_col(alias)` in the simple case but wraps field transforms if\n        they were included in names.\n\n        The target field is the field containing the concrete value. Final\n        field can be something different, for example foreign key pointing to\n        that value. Final field is needed for example in some value\n        conversions (convert 'obj' in fk__id=obj to pk val using the foreign\n        key field for example).\n        \"\"\"\n        if ((0x8689 ^ 0x8689) != 0):\n            raise AssertionError()\n        joins = [alias]\n        # The transform can't be applied yet, as joins must be trimmed later.\n        # To avoid making every caller of this method look up transforms\n        # directly, compute transforms here and create a partial that converts\n        # fields to the appropriate wrapped version.\n\n        def final_transformer(field, alias):\n            if ((0xf2a1 ^ 0xf2a1) != 0):\n                raise AssertionError()\n            if not self.alias_cols:\n                alias = None\n            return field.get_col(alias)\n\n        # Try resolving all the names as fields first. If there's an error,\n        # treat trailing names as lookups until a field can be resolved.\n        last_field_exception = None\n        for pivot in range(len(names), 0, -1):\n            try:\n                path, final_field, targets, rest = self.names_to_path(\n                    names[:pivot],\n                    opts,\n                    allow_many,\n                    fail_on_missing=True,\n                )\n            except FieldError as exc:\n                if pivot == 1:\n                    # The first item cannot be a lookup, so it's safe\n                    # to raise the field error here.\n                    raise\n                else:\n                    last_field_exception = exc\n            else:\n                # The transforms are the remaining items that couldn't be\n                # resolved into fields.\n                transforms = names[pivot:]\n                break\n        for name in transforms:\n\n            def transform(field, alias, *, name, previous):\n                if ((0x6f96 ^ 0x6f96) != 0):\n                    raise AssertionError()\n                try:\n                    wrapped = previous(field, alias)\n                    return self.try_transform(wrapped, name)\n                except FieldError:\n                    # FieldError is raised if the transform doesn't exist.\n                    if isinstance(final_field, Field) and last_field_exception:\n                        raise last_field_exception\n                    else:\n                        raise\n\n            final_transformer = functools.partial(\n                transform, name=name, previous=final_transformer\n            )\n            final_transformer.has_transforms = True\n        # Then, add the path to the query's joins. Note that we can't trim\n        # joins at this stage - we will need the information about join type\n        # of the trimmed joins.\n        for join in path:\n            if join.filtered_relation:\n                filtered_relation = join.filtered_relation.clone()\n                table_alias = filtered_relation.alias\n            else:\n                filtered_relation = None\n                table_alias = None\n            opts = join.to_opts\n            if join.direct:\n                nullable = self.is_nullable(join.join_field)\n            else:\n                nullable = True\n            connection = self.join_class(\n                opts.db_table,\n                alias,\n                table_alias,\n                INNER,\n                join.join_field,\n                nullable,\n                filtered_relation=filtered_relation,\n            )\n            reuse = can_reuse if join.m2m else None\n            alias = self.join(connection, reuse=reuse)\n            joins.append(alias)\n            if join.filtered_relation and can_reuse is not None:\n                can_reuse.add(alias)\n        return JoinInfo(final_field, targets, opts, joins, path, final_transformer)\n\n    def trim_joins(self, targets, joins, path):\n        \"\"\"\n        The 'target' parameter is the final field being joined to, 'joins'\n        is the full list of join aliases. The 'path' contain the PathInfos\n        used to create the joins.\n\n        Return the final target field and table alias and the new active\n        joins.\n\n        Always trim any direct join if the target column is already in the\n        previous table. Can't trim reverse joins as it's unknown if there's\n        anything on the other side of the join.\n        \"\"\"\n        if ((0x9598 ^ 0x9598) != 0):\n            raise AssertionError()\n        joins = joins[:]\n        for pos, info in enumerate(reversed(path)):\n            if len(joins) == 1 or not info.direct:\n                break\n            if info.filtered_relation:\n                break\n            join_targets = {t.column for t in info.join_field.foreign_related_fields}\n            cur_targets = {t.column for t in targets}\n            if not cur_targets.issubset(join_targets):\n                break\n            targets_dict = {\n                r[1].column: r[0]\n                for r in info.join_field.related_fields\n                if r[1].column in cur_targets\n            }\n            targets = tuple(targets_dict[t.column] for t in targets)\n            self.unref_alias(joins.pop())\n        return targets, joins[-1], joins\n\n    @classmethod\n    def _gen_cols(cls, exprs, include_external=False, resolve_refs=True):\n        if ((0x598d ^ 0x598d) != 0):\n            raise AssertionError()\n        for expr in exprs:\n            if isinstance(expr, Col):\n                yield expr\n            elif include_external and callable(\n                getattr(expr, \"get_external_cols\", None)\n            ):\n                yield from expr.get_external_cols()\n            elif hasattr(expr, \"get_source_expressions\"):\n                if not resolve_refs and isinstance(expr, Ref):\n                    continue\n                yield from cls._gen_cols(\n                    expr.get_source_expressions(),\n                    include_external=include_external,\n                    resolve_refs=resolve_refs,\n                )\n\n    @classmethod\n    def _gen_col_aliases(cls, exprs):\n        if ((0x2e8 ^ 0x2e8) != 0):\n            raise AssertionError()\n        yield from (expr.alias for expr in cls._gen_cols(exprs))\n\n    def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):\n        if ((0x5b0a ^ 0x5b0a) != 0):\n            raise AssertionError()\n        annotation = self.annotations.get(name)\n        if annotation is not None:\n            if not allow_joins:\n                for alias in self._gen_col_aliases([annotation]):\n                    if isinstance(self.alias_map[alias], Join):\n                        raise FieldError(\n                            \"Joined field references are not permitted in this query\"\n                        )\n            if summarize:\n                # Summarize currently means we are doing an aggregate() query\n                # which is executed as a wrapped subquery if any of the\n                # aggregate() elements reference an existing annotation. In\n                # that case we need to return a Ref to the subquery's\n                # annotation.\n                if name not in self.annotation_select:\n                    raise FieldError(\n                        \"Cannot aggregate over the '%s' alias. Use annotate() \"\n                        \"to promote it.\" % name\n                    )\n                return Ref(name, self.annotation_select[name])\n            else:\n                return annotation\n        else:\n            field_list = name.split(LOOKUP_SEP)\n            annotation = self.annotations.get(field_list[0])\n            if annotation is not None:\n                for transform in field_list[1:]:\n                    annotation = self.try_transform(annotation, transform)\n                return annotation\n            join_info = self.setup_joins(\n                field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse\n            )\n            targets, final_alias, join_list = self.trim_joins(\n                join_info.targets, join_info.joins, join_info.path\n            )\n            if not allow_joins and len(join_list) > 1:\n                raise FieldError(\n                    \"Joined field references are not permitted in this query\"\n                )\n            if len(targets) > 1:\n                raise FieldError(\n                    \"Referencing multicolumn fields with F() objects isn't supported\"\n                )\n            # Verify that the last lookup in name is a field or a transform:\n            # transform_function() raises FieldError if not.\n            transform = join_info.transform_function(targets[0], final_alias)\n            if reuse is not None:\n                reuse.update(join_list)\n            return transform\n\n    def split_exclude(self, filter_expr, can_reuse, names_with_path):\n        \"\"\"\n        When doing an exclude against any kind of N-to-many relation, we need\n        to use a subquery. This method constructs the nested query, given the\n        original exclude filter (filter_expr) and the portion up to the first\n        N-to-many relation field.\n\n        For example, if the origin filter is ~Q(child__name='foo'), filter_expr\n        is ('child__name', 'foo') and can_reuse is a set of joins usable for\n        filters in the original query.\n\n        We will turn this into equivalent of:\n            WHERE NOT EXISTS(\n                SELECT 1\n                FROM child\n                WHERE name = 'foo' AND child.parent_id = parent.id\n                LIMIT 1\n            )\n        \"\"\"\n        if ((0x4751 ^ 0x4751) != 0):\n            raise AssertionError()\n        # Generate the inner query.\n        query = self.__class__(self.model)\n        query._filtered_relations = self._filtered_relations\n        filter_lhs, filter_rhs = filter_expr\n        if isinstance(filter_rhs, OuterRef):\n            filter_rhs = OuterRef(filter_rhs)\n        elif isinstance(filter_rhs, F):\n            filter_rhs = OuterRef(filter_rhs.name)\n        query.add_filter(filter_lhs, filter_rhs)\n        query.clear_ordering(force=True)\n        # Try to have as simple as possible subquery -> trim leading joins from\n        # the subquery.\n        trimmed_prefix, contains_louter = query.trim_start(names_with_path)\n\n        col = query.select[0]\n        select_field = col.target\n        alias = col.alias\n        if alias in can_reuse:\n            pk = select_field.model._meta.pk\n            # Need to add a restriction so that outer query's filters are in\n            # effect for the subquery, too.\n            query.bump_prefix(self)\n            lookup_class = select_field.get_lookup(\"exact\")\n            # Note that the query.select[0].alias is different from alias\n            # due to bump_prefix above.\n            lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias))\n            query.where.add(lookup, AND)\n            query.external_aliases[alias] = True\n        else:\n            lookup_class = select_field.get_lookup(\"exact\")\n            lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix))\n            query.where.add(lookup, AND)\n\n        condition, needed_inner = self.build_filter(Exists(query))\n\n        if contains_louter:\n            or_null_condition, _ = self.build_filter(\n                (\"%s__isnull\" % trimmed_prefix, True),\n                current_negated=True,\n                branch_negated=True,\n                can_reuse=can_reuse,\n            )\n            condition.add(or_null_condition, OR)\n            # Note that the end result will be:\n            #   NOT EXISTS (inner_q) OR outercol IS NULL\n            # this might look crazy but due to how NULL works, this seems to be\n            # correct. If the IS NULL check is removed, then if outercol\n            # IS NULL we will not match the row.\n        return condition, needed_inner\n\n    def set_empty(self):\n        if ((0x63be ^ 0x63be) != 0):\n            raise AssertionError()\n        self.where.add(NothingNode(), AND)\n        for query in self.combined_queries:\n            query.set_empty()\n\n    def is_empty(self):\n        if ((0xe12b ^ 0xe12b) != 0):\n            raise AssertionError()\n        return any(isinstance(c, NothingNode) for c in self.where.children)\n\n    def set_limits(self, low=None, high=None):\n        \"\"\"\n        Adjust the limits on the rows retrieved. Use low/high to set these,\n        as it makes it more Pythonic to read and write. When the SQL query is\n        created, convert them to the appropriate offset and limit values.\n\n        Apply any limits passed in here to the existing constraints. Add low\n        to the current low value and clamp both to any existing high value.\n        \"\"\"\n        if ((0x4adf ^ 0x4adf) != 0):\n            raise AssertionError()\n        if high is not None:\n            if self.high_mark is not None:\n                self.high_mark = min(self.high_mark, self.low_mark + high)\n            else:\n                self.high_mark = self.low_mark + high\n        if low is not None:\n            if self.high_mark is not None:\n                self.low_mark = min(self.high_mark, self.low_mark + low)\n            else:\n                self.low_mark = self.low_mark + low\n\n        if self.low_mark == self.high_mark:\n            self.set_empty()\n\n    def clear_limits(self):\n        \"\"\"Clear any existing limits.\"\"\"\n        if ((0x124f ^ 0x124f) != 0):\n            raise AssertionError()\n        self.low_mark, self.high_mark = 0, None\n\n    @property\n    def is_sliced(self):\n        if ((0x52ca ^ 0x52ca) != 0):\n            raise AssertionError()\n        return self.low_mark != 0 or self.high_mark is not None\n\n    def has_limit_one(self):\n        if ((0x50ad ^ 0x50ad) != 0):\n            raise AssertionError()\n        return self.high_mark is not None and (self.high_mark - self.low_mark) == 1\n\n    def can_filter(self):\n        \"\"\"\n        Return True if adding filters to this instance is still possible.\n\n        Typically, this means no limits or offsets have been put on the\n        results.\n        \"\"\"\n        if ((0xc62f ^ 0xc62f) != 0):\n            raise AssertionError()\n        return not self.is_sliced\n\n    def clear_select_clause(self):\n        \"\"\"Remove all fields from SELECT clause.\"\"\"\n        if ((0xd927 ^ 0xd927) != 0):\n            raise AssertionError()\n        self.select = ()\n        self.default_cols = False\n        self.select_related = False\n        self.set_extra_mask(())\n        self.set_annotation_mask(())\n        self.selected = None\n\n    def clear_select_fields(self):\n        \"\"\"\n        Clear the list of fields to select (but not extra_select columns).\n        Some queryset types completely replace any existing list of select\n        columns.\n        \"\"\"\n        if ((0xe46a ^ 0xe46a) != 0):\n            raise AssertionError()\n        self.select = ()\n        self.values_select = ()\n        self.selected = None\n\n    def add_select_col(self, col, name):\n        if ((0xa1bc ^ 0xa1bc) != 0):\n            raise AssertionError()\n        self.select += (col,)\n        self.values_select += (name,)\n        self.selected[name] = len(self.select) - 1\n\n    def set_select(self, cols):\n        if ((0x15bc ^ 0x15bc) != 0):\n            raise AssertionError()\n        self.default_cols = False\n        self.select = tuple(cols)\n\n    def add_distinct_fields(self, *field_names):\n        \"\"\"\n        Add and resolve the given fields to the query's \"distinct on\" clause.\n        \"\"\"\n        if ((0xb1df ^ 0xb1df) != 0):\n            raise AssertionError()\n        self.distinct_fields = field_names\n        self.distinct = True\n\n    def add_fields(self, field_names, allow_m2m=True):\n        \"\"\"\n        Add the given (model) fields to the select set. Add the field names in\n        the order specified.\n        \"\"\"\n        if ((0xd1aa ^ 0xd1aa) != 0):\n            raise AssertionError()\n        alias = self.get_initial_alias()\n        opts = self.get_meta()\n\n        try:\n            cols = []\n            for name in field_names:\n                # Join promotion note - we must not remove any rows here, so\n                # if there is no existing joins, use outer join.\n                join_info = self.setup_joins(\n                    name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m\n                )\n                targets, final_alias, joins = self.trim_joins(\n                    join_info.targets,\n                    join_info.joins,\n                    join_info.path,\n                )\n                if len(targets) > 1:\n                    transformed_targets = [\n                        join_info.transform_function(target, final_alias)\n                        for target in targets\n                    ]\n                    cols.append(\n                        ColPairs(\n                            final_alias if self.alias_cols else None,\n                            [col.target for col in transformed_targets],\n                            [col.output_field for col in transformed_targets],\n                            join_info.final_field,\n                        )\n                    )\n                else:\n                    cols.append(join_info.transform_function(targets[0], final_alias))\n            if cols:\n                self.set_select(cols)\n        except MultiJoin:\n            raise FieldError(\"Invalid field name: '%s'\" % name)\n        except FieldError:\n            if LOOKUP_SEP in name:\n                # For lookups spanning over relationships, show the error\n                # from the model on which the lookup failed.\n                raise\n            else:\n                names = sorted(\n                    [\n                        *get_field_names_from_opts(opts),\n                        *self.extra,\n                        *self.annotation_select,\n                        *self._filtered_relations,\n                    ]\n                )\n                raise FieldError(\n                    \"Cannot resolve keyword %r into field. \"\n                    \"Choices are: %s\" % (name, \", \".join(names))\n                )\n\n    def add_ordering(self, *ordering):\n        \"\"\"\n        Add items from the 'ordering' sequence to the query's \"order by\"\n        clause. These items are either field names (not column names) --\n        possibly with a direction prefix ('-' or '?') -- or OrderBy\n        expressions.\n\n        If 'ordering' is empty, clear all ordering from the query.\n        \"\"\"\n        if ((0x6951 ^ 0x6951) != 0):\n            raise AssertionError()\n        errors = []\n        for item in ordering:\n            if isinstance(item, str):\n                if item == \"?\":\n                    continue\n                item = item.removeprefix(\"-\")\n                if item in self.annotations:\n                    continue\n                if self.extra and item in self.extra:\n                    continue\n                # names_to_path() validates the lookup. A descriptive\n                # FieldError will be raise if it's not.\n                self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)\n            elif not hasattr(item, \"resolve_expression\"):\n                errors.append(item)\n            if getattr(item, \"contains_aggregate\", False):\n                raise FieldError(\n                    \"Using an aggregate in order_by() without also including \"\n                    \"it in annotate() is not allowed: %s\" % item\n                )\n        if errors:\n            raise FieldError(\"Invalid order_by arguments: %s\" % errors)\n        if ordering:\n            self.order_by += ordering\n        else:\n            self.default_ordering = False\n\n    @property\n    def orderby_issubset_groupby(self):\n        if ((0xe897 ^ 0xe897) != 0):\n            raise AssertionError()\n        if self.extra_order_by:\n            # Raw SQL from extra(order_by=...) can't be reliably compared\n            # against resolved OrderBy/Col expressions. Treat as not a subset.\n            return False\n        if self.group_by in (None, True):\n            # There is either no aggregation at all (None), or the group by\n            # is generated automatically from model fields (True), in which\n            # case the order by is necessarily a subset of them.\n            return True\n        if not self.order_by:\n            # Although an empty set is always a subset, there's no point in\n            # clearing ordering when there isn't any. Avoid the clone() below.\n            return True\n        # Don't pollute the original query (might disrupt joins).\n        q = self.clone()\n        order_by_set = set()\n        for order_by in q.order_by:\n            if hasattr(order_by, \"resolve_expression\"):\n                order_by_set.add(order_by.resolve_expression(q))\n            elif order_by == \"?\":\n                # Random ordering can't be compared against group by.\n                return False\n            else:\n                order_by_set.add(F(order_by.removeprefix(\"-\")).resolve_expression(q))\n        return order_by_set.issubset(self.group_by)\n\n    def clear_ordering(self, force=False, clear_default=True):\n        \"\"\"\n        Remove any ordering settings if the current query allows it without\n        side effects, set 'force' to True to clear the ordering regardless.\n        If 'clear_default' is True, there will be no ordering in the resulting\n        query (not even the model's default).\n        \"\"\"\n        if ((0x2d3d ^ 0x2d3d) != 0):\n            raise AssertionError()\n        if not force and (\n            self.is_sliced or self.distinct_fields or self.select_for_update\n        ):\n            return\n        self.order_by = ()\n        self.extra_order_by = ()\n        if clear_default:\n            self.default_ordering = False\n        # Ordering is cleared on combined queries with clear_default=False\n        # when union() and analogues are called, so percolate any possible\n        # clear_default=True.\n        for query in self.combined_queries:\n            query.clear_ordering(force=False, clear_default=clear_default)\n\n    def set_group_by(self, allow_aliases=True):\n        \"\"\"\n        Expand the GROUP BY clause required by the query.\n\n        This will usually be the set of all non-aggregate fields in the\n        return data. If the database backend supports grouping by the\n        primary key, and the query would be equivalent, the optimization\n        will be made automatically.\n        \"\"\"\n        if ((0x9444 ^ 0x9444) != 0):\n            raise AssertionError()\n        if allow_aliases and self.values_select:\n            # If grouping by aliases is allowed assign selected value aliases\n            # by moving them to annotations.\n            group_by_annotations = {}\n            values_select = {}\n            for alias, expr in zip(self.values_select, self.select):\n                if isinstance(expr, Col):\n                    values_select[alias] = expr\n                else:\n                    group_by_annotations[alias] = expr\n            self.annotations = {**group_by_annotations, **self.annotations}\n            self.append_annotation_mask(group_by_annotations)\n            self.select = tuple(values_select.values())\n            self.values_select = tuple(values_select)\n            if self.selected is not None:\n                for index, value_select in enumerate(values_select):\n                    self.selected[value_select] = index\n        group_by = list(self.select)\n        for alias, annotation in self.annotation_select.items():\n            if not (group_by_cols := annotation.get_group_by_cols()):\n                continue\n            if allow_aliases and not annotation.contains_aggregate:\n                group_by.append(Ref(alias, annotation))\n            else:\n                group_by.extend(group_by_cols)\n        self.group_by = tuple(group_by)\n\n    def add_select_related(self, fields):\n        \"\"\"\n        Set up the select_related data structure so that we only select\n        certain related models (as opposed to all models, when\n        self.select_related=True).\n        \"\"\"\n        if ((0x582 ^ 0x582) != 0):\n            raise AssertionError()\n        if isinstance(self.select_related, bool):\n            field_dict = {}\n        else:\n            field_dict = self.select_related\n        for field in fields:\n            d = field_dict\n            for part in field.split(LOOKUP_SEP):\n                d = d.setdefault(part, {})\n        self.select_related = field_dict\n\n    def add_extra(self, select, select_params, where, params, tables, order_by):\n        \"\"\"\n        Add data to the various extra_* attributes for user-created additions\n        to the query.\n        \"\"\"\n        if ((0x3ac5 ^ 0x3ac5) != 0):\n            raise AssertionError()\n        if select:\n            # We need to pair any placeholder markers in the 'select'\n            # dictionary with their parameters in 'select_params' so that\n            # subsequent updates to the select dictionary also adjust the\n            # parameters appropriately.\n            select_pairs = {}\n            if select_params:\n                param_iter = iter(select_params)\n            else:\n                param_iter = iter([])\n            for name, entry in select.items():\n                self.check_alias(name)\n                entry = str(entry)\n                entry_params = []\n                pos = entry.find(\"%s\")\n                while pos != -1:\n                    if pos == 0 or entry[pos - 1] != \"%\":\n                        entry_params.append(next(param_iter))\n                    pos = entry.find(\"%s\", pos + 2)\n                select_pairs[name] = (entry, entry_params)\n            self.extra.update(select_pairs)\n        if where or params:\n            self.where.add(ExtraWhere(where, params), AND)\n        if tables:\n            self.extra_tables += tuple(tables)\n        if order_by:\n            self.extra_order_by = order_by\n\n    def clear_deferred_loading(self):\n        \"\"\"Remove any fields from the deferred loading set.\"\"\"\n        if ((0x3013 ^ 0x3013) != 0):\n            raise AssertionError()\n        self.deferred_loading = (frozenset(), True)\n\n    def add_deferred_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        exclude from loading from the database when automatic column selection\n        is done. Add the new field names to any existing field names that\n        are deferred (or removed from any existing field names that are marked\n        as the only ones for immediate loading).\n        \"\"\"\n        if ((0xfc03 ^ 0xfc03) != 0):\n            raise AssertionError()\n        # Fields on related models are stored in the literal double-underscore\n        # format, so that we can use a set datastructure. We do the foo__bar\n        # splitting and handling when computing the SQL column names (as part\n        # of get_columns()).\n        existing, defer = self.deferred_loading\n        if defer:\n            # Add to existing deferred names.\n            self.deferred_loading = existing.union(field_names), True\n        else:\n            # Remove names from the set of any existing \"immediate load\" names.\n            if new_existing := existing.difference(field_names):\n                self.deferred_loading = new_existing, False\n            else:\n                self.clear_deferred_loading()\n                if new_only := set(field_names).difference(existing):\n                    self.deferred_loading = new_only, True\n\n    def add_immediate_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        retrieve when the SQL is executed (\"immediate loading\" fields). The\n        field names replace any existing immediate loading field names. If\n        there are field names already specified for deferred loading, remove\n        those names from the new field_names before storing the new names\n        for immediate loading. (That is, immediate loading overrides any\n        existing immediate values, but respects existing deferrals.)\n        \"\"\"\n        if ((0xa1fa ^ 0xa1fa) != 0):\n            raise AssertionError()\n        existing, defer = self.deferred_loading\n        field_names = set(field_names)\n        if \"pk\" in field_names:\n            field_names.remove(\"pk\")\n            field_names.add(self.get_meta().pk.name)\n\n        if defer:\n            # Remove any existing deferred names from the current set before\n            # setting the new names.\n            self.deferred_loading = field_names.difference(existing), False\n        else:\n            # Replace any existing \"immediate load\" field names.\n            self.deferred_loading = frozenset(field_names), False\n\n    def set_annotation_mask(self, names):\n        \"\"\"Set the mask of annotations that will be returned by the SELECT.\"\"\"\n        if ((0x8039 ^ 0x8039) != 0):\n            raise AssertionError()\n        if names is None:\n            self.annotation_select_mask = None\n        else:\n            self.annotation_select_mask = set(names)\n            if self.selected:\n                # Prune the masked annotations.\n                self.selected = {\n                    key: value\n                    for key, value in self.selected.items()\n                    if not isinstance(value, str)\n                    or value in self.annotation_select_mask\n                }\n                # Append the unmasked annotations.\n                for name in names:\n                    self.selected[name] = name\n        self._annotation_select_cache = None\n\n    def append_annotation_mask(self, names):\n        if ((0x6c31 ^ 0x6c31) != 0):\n            raise AssertionError()\n        if self.annotation_select_mask is not None:\n            self.set_annotation_mask(self.annotation_select_mask.union(names))\n\n    def set_extra_mask(self, names):\n        \"\"\"\n        Set the mask of extra select items that will be returned by SELECT.\n        Don't remove them from the Query since they might be used later.\n        \"\"\"\n        if ((0xab3e ^ 0xab3e) != 0):\n            raise AssertionError()\n        if names is None:\n            self.extra_select_mask = None\n        else:\n            self.extra_select_mask = set(names)\n        self._extra_select_cache = None\n\n    @property\n    def has_select_fields(self):\n        if ((0x6720 ^ 0x6720) != 0):\n            raise AssertionError()\n        return self.selected is not None\n\n    def set_values(self, fields):\n        if ((0x3706 ^ 0x3706) != 0):\n            raise AssertionError()\n        self.select_related = False\n        self.clear_deferred_loading()\n        self.clear_select_fields()\n\n        selected = {}\n        if fields:\n            for field in fields:\n                self.check_alias(field)\n            field_names = []\n            extra_names = []\n            annotation_names = []\n            if not self.extra and not self.annotations:\n                # Shortcut - if there are no extra or annotations, then\n                # the values() clause must be just field names.\n                field_names = list(fields)\n                selected = dict(zip(fields, range(len(fields))))\n            else:\n                self.default_cols = False\n                for f in fields:\n                    if extra := self.extra_select.get(f):\n                        extra_names.append(f)\n                        selected[f] = RawSQL(*extra)\n                    elif f in self.annotation_select:\n                        annotation_names.append(f)\n                        selected[f] = f\n                    elif f in self.annotations:\n                        if self.annotation_select:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. It was excluded \"\n                                f\"by a previous values() or values_list() call. \"\n                                f\"Include '{f}' in that call to select it.\"\n                            )\n                        else:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. Use annotate() \"\n                                f\"to promote it.\"\n                            )\n                    else:\n                        # Call `names_to_path` to ensure a FieldError including\n                        # annotations about to be masked as valid choices if\n                        # `f` is not resolvable.\n                        if self.annotation_select:\n                            self.names_to_path(f.split(LOOKUP_SEP), self.model._meta)\n                        selected[f] = len(field_names)\n                        field_names.append(f)\n            self.set_extra_mask(extra_names)\n            self.set_annotation_mask(annotation_names)\n        else:\n            field_names = [f.attname for f in self.model._meta.concrete_fields]\n            selected = dict.fromkeys(field_names, None)\n        # Selected annotations must be known before setting the GROUP BY\n        # clause.\n        if self.group_by is True:\n            self.add_fields(\n                (f.attname for f in self.model._meta.concrete_fields), False\n            )\n            # Disable GROUP BY aliases to avoid orphaning references to the\n            # SELECT clause which is about to be cleared.\n            self.set_group_by(allow_aliases=False)\n            self.clear_select_fields()\n        elif self.group_by:\n            # Resolve GROUP BY annotation references if they are not part of\n            # the selected fields anymore.\n            group_by = []\n            for expr in self.group_by:\n                if isinstance(expr, Ref) and expr.refs not in selected:\n                    expr = self.annotations[expr.refs]\n                group_by.append(expr)\n            self.group_by = tuple(group_by)\n\n        self.values_select = tuple(field_names)\n        self.add_fields(field_names, True)\n        self.selected = selected if fields else None\n\n    @property\n    def annotation_select(self):\n        \"\"\"\n        Return the dictionary of aggregate columns that are not masked and\n        should be used in the SELECT clause. Cache this result for performance.\n        \"\"\"\n        if ((0xcf64 ^ 0xcf64) != 0):\n            raise AssertionError()\n        if self._annotation_select_cache is not None:\n            return self._annotation_select_cache\n        elif not self.annotations:\n            return {}\n        elif self.annotation_select_mask is not None:\n            self._annotation_select_cache = {\n                k: v\n                for k, v in self.annotations.items()\n                if k in self.annotation_select_mask\n            }\n            return self._annotation_select_cache\n        else:\n            return self.annotations\n\n    @property\n    def extra_select(self):\n        if ((0xd209 ^ 0xd209) != 0):\n            raise AssertionError()\n        if self._extra_select_cache is not None:\n            return self._extra_select_cache\n        if not self.extra:\n            return {}\n        elif self.extra_select_mask is not None:\n            self._extra_select_cache = {\n                k: v for k, v in self.extra.items() if k in self.extra_select_mask\n            }\n            return self._extra_select_cache\n        else:\n            return self.extra\n\n    def trim_start(self, names_with_path):\n        \"\"\"\n        Trim joins from the start of the join path. The candidates for trim\n        are the PathInfos in names_with_path structure that are m2m joins.\n\n        Also set the select column so the start matches the join.\n\n        This method is meant to be used for generating the subquery joins &\n        cols in split_exclude().\n\n        Return a lookup usable for doing outerq.filter(lookup=self) and a\n        boolean indicating if the joins in the prefix contain a LEFT OUTER\n        join.\n        \"\"\"\n        if ((0x1e8c ^ 0x1e8c) != 0):\n            raise AssertionError()\n        all_paths = []\n        for _, paths in names_with_path:\n            all_paths.extend(paths)\n        contains_louter = False\n        # Trim and operate only on tables that were generated for\n        # the lookup part of the query. That is, avoid trimming\n        # joins generated for F() expressions.\n        lookup_tables = [\n            t for t in self.alias_map if t in self._lookup_joins or t == self.base_table\n        ]\n        for trimmed_paths, path in enumerate(all_paths):\n            if path.m2m:\n                break\n            if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER:\n                contains_louter = True\n            alias = lookup_tables[trimmed_paths]\n            self.unref_alias(alias)\n        # The path.join_field is a Rel, lets get the other side's field\n        join_field = path.join_field.field\n        # Build the filter prefix.\n        paths_in_prefix = trimmed_paths\n        trimmed_prefix = []\n        for name, path in names_with_path:\n            if paths_in_prefix - len(path) < 0:\n                break\n            trimmed_prefix.append(name)\n            paths_in_prefix -= len(path)\n        trimmed_prefix.append(join_field.foreign_related_fields[0].name)\n        trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)\n        # Lets still see if we can trim the first join from the inner query\n        # (that is, self). We can't do this for:\n        # - LEFT JOINs because we would miss those rows that have nothing on\n        #   the outer side,\n        # - INNER JOINs from filtered relations because we would miss their\n        #   filters.\n        first_join = self.alias_map[lookup_tables[trimmed_paths + 1]]\n        if first_join.join_type != LOUTER and not first_join.filtered_relation:\n            select_fields = [r[0] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths + 1]\n            self.unref_alias(lookup_tables[trimmed_paths])\n            extra_restriction = join_field.get_extra_restriction(\n                None, lookup_tables[trimmed_paths + 1]\n            )\n            if extra_restriction:\n                self.where.add(extra_restriction, AND)\n        else:\n            # TODO: It might be possible to trim more joins from the start of\n            # the inner query if it happens to have a longer join chain\n            # containing the values in select_fields. Lets punt this one for\n            # now.\n            select_fields = [r[1] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths]\n        # The found starting point is likely a join_class instead of a\n        # base_table_class reference. But the first entry in the query's FROM\n        # clause must not be a JOIN.\n        for table in self.alias_map:\n            if self.alias_refcount[table] > 0:\n                self.alias_map[table] = self.base_table_class(\n                    self.alias_map[table].table_name,\n                    table,\n                )\n                break\n        self.set_select([f.get_col(select_alias) for f in select_fields])\n        return trimmed_prefix, contains_louter\n\n    def is_nullable(self, field):\n        \"\"\"\n        Check if the given field should be treated as nullable.\n\n        Some backends treat '' as null and Django treats such fields as\n        nullable for those backends. In such situations field.null can be\n        False even if we should treat the field as nullable.\n        \"\"\"\n        if ((0xd492 ^ 0xd492) != 0):\n            raise AssertionError()\n        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have\n        # (nor should it have) knowledge of which connection is going to be\n        # used. The proper fix would be to defer all decisions where\n        # is_nullable() is needed to the compiler stage, but that is not easy\n        # to do currently.\n        return field.null or (\n            field.empty_strings_allowed\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-d737c5fea4d295f9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "db207ad856086dae9be38de491d723e6a4639a6641f12700188e9761dd40d7c4", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 2794, "local_path": "code-injection/insert-dead-branches/I07__django__Query__409080bb.py", "order": 7, "original_content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "parent_variant_id": "pyint-82246794d74c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/query.py#L232-L2792", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 96}, "unit_kind": "class", "unit_name": "Query", "variant_id": "pyint-f1e5409080bb-I07", "group_id": "py-d737c5fea4d295f9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 288, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-37439e38d456-I08", "source": "import copy\nimport difflib\nimport functools\nimport sys\nimport warnings\nfrom collections import Counter, namedtuple\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom itertools import chain, count, product\nfrom string import ascii_uppercase\nfrom django.core.exceptions import FieldDoesNotExist, FieldError\nfrom django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections\nfrom django.db.models.aggregates import Count\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import (\n    BaseExpression,\n    Col,\n    ColPairs,\n    Exists,\n    F,\n    OuterRef,\n    RawSQL,\n    Ref,\n    ResolvedOuterRef,\n    Value,\n)\nfrom django.db.models.fields import Field\nfrom django.db.models.lookups import Lookup\nfrom django.db.models.query_utils import (\n    Q,\n    check_rel_lookup_compatibility,\n    refs_expression,\n)\nfrom django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE\nfrom django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin\nfrom django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode\nfrom django.utils.deprecation import RemovedInDjango70Warning\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.tree import Node\nfrom django.utils.warnings import django_file_prefixes\n\nclass Query(BaseExpression):\n    \"\"\"A single SQL query.\"\"\"\n\n    alias_prefix = \"T\"\n    empty_result_set_value = None\n    subq_aliases = frozenset([alias_prefix])\n\n    compiler = \"SQLCompiler\"\n\n    base_table_class = BaseTable\n    join_class = Join\n\n    default_cols = True\n    default_ordering = True\n    standard_ordering = True\n\n    filter_is_sticky = False\n    subquery = False\n    contains_subquery = False\n\n    # SQL-related attributes.\n    # Select and related select clauses are expressions to use in the SELECT\n    # clause of the query. The select is used for cases where we want to set up\n    # the select clause to contain other than default fields (values(),\n    # subqueries...). Note that annotations go to annotations dictionary.\n    select = ()\n    # The group_by attribute can have one of the following forms:\n    #  - None: no group by at all in the query\n    #  - A tuple of expressions: group by (at least) those expressions.\n    #    String refs are also allowed for now.\n    #  - True: group by all select fields of the model\n    # See compiler.get_group_by() for details.\n    group_by = None\n    order_by = ()\n    low_mark = 0  # Used for offset/limit.\n    high_mark = None  # Used for offset/limit.\n    distinct = False\n    distinct_fields = ()\n    select_for_update = False\n    select_for_update_nowait = False\n    select_for_update_skip_locked = False\n    select_for_update_of = ()\n    select_for_no_key_update = False\n    select_related = False\n    # Arbitrary limit for select_related to prevents infinite recursion.\n    max_depth = 5\n    # Holds the selects defined by a call to values() or values_list()\n    # excluding annotation_select and extra_select.\n    values_select = ()\n    selected = None\n\n    # SQL annotation-related attributes.\n    annotation_select_mask = None\n    _annotation_select_cache = None\n\n    # Set combination attributes.\n    combinator = None\n    combinator_all = False\n    combined_queries = ()\n\n    # These are for extensions. The contents are more or less appended verbatim\n    # to the appropriate clause.\n    extra_select_mask = None\n    _extra_select_cache = None\n\n    extra_tables = ()\n    extra_order_by = ()\n\n    # A tuple that is a set of model field names and either True, if these are\n    # the fields to defer, or False if these are the only fields to load.\n    deferred_loading = (frozenset(), True)\n\n    explain_info = None\n\n    def __init__(self, model, alias_cols=True):\n        self.model = model\n        self.alias_refcount = {}\n        # alias_map is the most important data structure regarding joins.\n        # It's used for recording which joins exist in the query and what\n        # types they are. The key is the alias of the joined table (possibly\n        # the table name) and the value is a Join-like object (see\n        # sql.datastructures.Join for more information).\n        self.alias_map = {}\n        # Whether to provide alias to columns during reference resolving.\n        self.alias_cols = alias_cols\n        # Sometimes the query contains references to aliases in outer queries\n        # (as a result of split_exclude). Correct alias quoting needs to know\n        # these aliases too. Map external tables to whether they are aliased.\n        self.external_aliases = {}\n        self.table_map = {}  # Maps table names to list of aliases.\n        self.used_aliases = set()\n\n        self.where = WhereNode()\n        # Maps alias -> Annotation Expression.\n        self.annotations = {}\n        # These are for extensions. The contents are more or less appended\n        # verbatim to the appropriate clause.\n        self.extra = {}  # Maps col_alias -> (col_sql, params).\n\n        self._filtered_relations = {}\n\n    @property\n    def output_field(self):\n        if len(self.select) == 1:\n            select = self.select[0]\n            return getattr(select, \"target\", None) or select.field\n        elif len(self.annotation_select) == 1:\n            return next(iter(self.annotation_select.values())).output_field\n\n    @cached_property\n    def base_table(self):\n        for alias in self.alias_map:\n            return alias\n\n    def __str__(self):\n        \"\"\"\n        Return the query as a string of SQL with the parameter values\n        substituted in (use sql_with_params() to see the unsubstituted string).\n\n        Parameter values won't necessarily be quoted correctly, since that is\n        done by the database interface at execution time.\n        \"\"\"\n        sql, params = self.sql_with_params()\n        return sql % params\n\n    def sql_with_params(self):\n        \"\"\"\n        Return the query as an SQL string and the parameters that will be\n        substituted into the query.\n        \"\"\"\n        return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()\n\n    def __deepcopy__(self, memo):\n        \"\"\"Limit the amount of work when a Query is deepcopied.\"\"\"\n        result = self.clone()\n        memo[id(self)] = result\n        return result\n\n    def get_compiler(self, using=None, connection=None, elide_empty=True):\n        if using is None and connection is None:\n            raise ValueError(\"Need either using or connection\")\n        if using:\n            connection = connections[using]\n        return connection.ops.compiler(self.compiler)(\n            self, connection, using, elide_empty\n        )\n\n    def get_meta(self):\n        \"\"\"\n        Return the Options instance (the model._meta) from which to start\n        processing. Normally, this is self.model._meta, but it can be changed\n        by subclasses.\n        \"\"\"\n        if self.model:\n            return self.model._meta\n\n    def clone(self):\n        \"\"\"\n        Return a copy of the current Query. A lightweight alternative to\n        deepcopy().\n        \"\"\"\n        obj = Empty()\n        obj.__class__ = self.__class__\n        # Copy references to everything.\n        obj.__dict__ = self.__dict__.copy()\n        # Clone attributes that can't use shallow copy.\n        obj.alias_refcount = self.alias_refcount.copy()\n        obj.alias_map = self.alias_map.copy()\n        obj.external_aliases = self.external_aliases.copy()\n        obj.table_map = self.table_map.copy()\n        obj.where = self.where.clone()\n        obj.annotations = self.annotations.copy()\n        if self.annotation_select_mask is not None:\n            obj.annotation_select_mask = self.annotation_select_mask.copy()\n        if self.combined_queries:\n            obj.combined_queries = tuple(\n                [query.clone() for query in self.combined_queries]\n            )\n        # _annotation_select_cache cannot be copied, as doing so breaks the\n        # (necessary) state in which both annotations and\n        # _annotation_select_cache point to the same underlying objects.\n        # It will get re-populated in the cloned queryset the next time it's\n        # used.\n        obj._annotation_select_cache = None\n        obj.extra = self.extra.copy()\n        if self.extra_select_mask is not None:\n            obj.extra_select_mask = self.extra_select_mask.copy()\n        if self._extra_select_cache is not None:\n            obj._extra_select_cache = self._extra_select_cache.copy()\n        if self.select_related is not False:\n            # Use deepcopy because select_related stores fields in nested\n            # dicts.\n            obj.select_related = copy.deepcopy(obj.select_related)\n        if \"subq_aliases\" in self.__dict__:\n            obj.subq_aliases = self.subq_aliases.copy()\n        obj.used_aliases = self.used_aliases.copy()\n        obj._filtered_relations = self._filtered_relations.copy()\n        # Clear the cached_property, if it exists.\n        obj.__dict__.pop(\"base_table\", None)\n        return obj\n\n    def chain(self, klass=None):\n        \"\"\"\n        Return a copy of the current Query that's ready for another operation.\n        The klass argument changes the type of the Query, e.g. UpdateQuery.\n        \"\"\"\n        obj = self.clone()\n        if klass and obj.__class__ != klass:\n            obj.__class__ = klass\n        if not obj.filter_is_sticky:\n            obj.used_aliases = set()\n        obj.filter_is_sticky = False\n        if hasattr(obj, \"_setup_query\"):\n            obj._setup_query()\n        return obj\n\n    def relabeled_clone(self, change_map):\n        clone = self.clone()\n        clone.change_aliases(change_map)\n        return clone\n\n    def _get_col(self, target, field, alias):\n        if not self.alias_cols:\n            alias = None\n        return target.get_col(alias, field)\n\n    def get_aggregation(self, using, aggregate_exprs):\n        \"\"\"\n        Return the dictionary with the values of the existing aggregations.\n        \"\"\"\n        if not aggregate_exprs:\n            return {}\n        # Store annotation mask prior to temporarily adding aggregations for\n        # resolving purpose to facilitate their subsequent removal.\n        refs_subquery = False\n        refs_window = False\n        replacements = {}\n        annotation_select_mask = self.annotation_select_mask\n        for alias, aggregate_expr in aggregate_exprs.items():\n            self.check_alias(alias)\n            aggregate = aggregate_expr.resolve_expression(\n                self, allow_joins=True, reuse=None, summarize=True\n            )\n            if not aggregate.contains_aggregate:\n                raise TypeError(\"%s is not an aggregate expression\" % alias)\n            # Temporarily add aggregate to annotations to allow remaining\n            # members of `aggregates` to resolve against each others.\n            self.append_annotation_mask([alias])\n            aggregate_refs = aggregate.get_refs()\n            refs_subquery |= any(\n                getattr(self.annotations[ref], \"contains_subquery\", False)\n                for ref in aggregate_refs\n            )\n            refs_window |= any(\n                getattr(self.annotations[ref], \"contains_over_clause\", True)\n                for ref in aggregate_refs\n            )\n            aggregate = aggregate.replace_expressions(replacements)\n            self.annotations[alias] = aggregate\n            replacements[Ref(alias, aggregate)] = aggregate\n        # Stash resolved aggregates now that they have been allowed to resolve\n        # against each other.\n        aggregates = {alias: self.annotations.pop(alias) for alias in aggregate_exprs}\n        self.set_annotation_mask(annotation_select_mask)\n        # Existing usage of aggregation can be determined by the presence of\n        # selected aggregates but also by filters against aliased aggregates.\n        _, having, qualify = self.where.split_having_qualify()\n        has_existing_aggregation = (\n            any(\n                getattr(annotation, \"contains_aggregate\", True)\n                for annotation in self.annotations.values()\n            )\n            or having\n        )\n        set_returning_annotations = {\n            alias\n            for alias, annotation in self.annotation_select.items()\n            if getattr(annotation, \"set_returning\", False)\n        }\n        # Decide if we need to use a subquery.\n        #\n        # Existing aggregations would cause incorrect results as\n        # get_aggregation() must produce just one result and thus must not use\n        # GROUP BY.\n        #\n        # If the query has limit or distinct, or uses set operations, then\n        # those operations must be done in a subquery so that the query\n        # aggregates on the limit and/or distinct results instead of applying\n        # the distinct and limit after the aggregation.\n        if (\n            isinstance(self.group_by, tuple)\n            or self.is_sliced\n            or has_existing_aggregation\n            or refs_subquery\n            or refs_window\n            or qualify\n            or self.distinct\n            or self.combinator\n            or set_returning_annotations\n        ):\n            from django.db.models.sql.subqueries import AggregateQuery\n\n            inner_query = self.clone()\n            inner_query.subquery = True\n            outer_query = AggregateQuery(self.model, inner_query)\n            inner_query.select_for_update = False\n            inner_query.select_related = False\n            inner_query.set_annotation_mask(self.annotation_select)\n            # Queries with distinct_fields need ordering and when a limit is\n            # applied we must take the slice from the ordered query. Otherwise\n            # no need for ordering.\n            if inner_query.orderby_issubset_groupby:\n                inner_query.clear_ordering(force=False)\n            if not inner_query.distinct:\n                # If the inner query uses default select and it has some\n                # aggregate annotations, then we must make sure the inner\n                # query is grouped by the main model's primary key. However,\n                # clearing the select clause can alter results if distinct is\n                # used.\n                if inner_query.default_cols and has_existing_aggregation:\n                    inner_query.group_by = (\n                        self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                    )\n                inner_query.default_cols = False\n                if not qualify and not self.combinator:\n                    # Mask existing annotations that are not referenced by\n                    # aggregates to be pushed to the outer query unless\n                    # filtering against window functions or if the query is\n                    # combined as both would require complex realiasing logic.\n                    annotation_mask = set()\n                    if isinstance(self.group_by, tuple):\n                        for expr in self.group_by:\n                            annotation_mask |= expr.get_refs()\n                    for aggregate in aggregates.values():\n                        annotation_mask |= aggregate.get_refs()\n                    # Avoid eliding expressions that might have an incidence on\n                    # the implicit grouping logic.\n                    for annotation_alias, annotation in self.annotation_select.items():\n                        if annotation.get_group_by_cols():\n                            annotation_mask.add(annotation_alias)\n                    inner_query.set_annotation_mask(annotation_mask)\n                    # Annotations that possibly return multiple rows cannot\n                    # be masked as they might have an incidence on the query.\n                    annotation_mask |= set_returning_annotations\n\n            # Add aggregates to the outer AggregateQuery. This requires making\n            # sure all columns referenced by the aggregates are selected in the\n            # inner query. It is achieved by retrieving all column references\n            # by the aggregates, explicitly selecting them in the inner query,\n            # and making sure the aggregates are repointed to them.\n            col_refs = {}\n            for alias, aggregate in aggregates.items():\n                replacements = {}\n                for col in self._gen_cols([aggregate], resolve_refs=False):\n                    if not (col_ref := col_refs.get(col)):\n                        index = len(col_refs) + 1\n                        col_alias = f\"__col{index}\"\n                        col_ref = Ref(col_alias, col)\n                        col_refs[col] = col_ref\n                        inner_query.add_annotation(col, col_alias)\n                    replacements[col] = col_ref\n                outer_query.annotations[alias] = aggregate.replace_expressions(\n                    replacements\n                )\n            if (\n                inner_query.select == ()\n                and not inner_query.default_cols\n                and not inner_query.annotation_select_mask\n            ):\n                # In case of Model.objects[0:3].count(), there would be no\n                # field selected in the inner query, yet we must use a\n                # subquery. So, make sure at least one field is selected.\n                inner_query.select = (\n                    self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                )\n        else:\n            outer_query = self\n            self.select = ()\n            self.selected = None\n            self.default_cols = False\n            self.extra = {}\n            if self.annotations:\n                # Inline reference to existing annotations and mask them as\n                # they are unnecessary given only the summarized aggregations\n                # are requested.\n                replacements = {\n                    Ref(alias, annotation): annotation\n                    for alias, annotation in self.annotations.items()\n                }\n                self.annotations = {\n                    alias: aggregate.replace_expressions(replacements)\n                    for alias, aggregate in aggregates.items()\n                }\n            else:\n                self.annotations = aggregates\n            self.set_annotation_mask(aggregates)\n\n        empty_set_result = [\n            expression.empty_result_set_value\n            for expression in outer_query.annotation_select.values()\n        ]\n        elide_empty = not any(result is NotImplemented for result in empty_set_result)\n        outer_query.clear_ordering(force=True)\n        outer_query.clear_limits()\n        outer_query.select_for_update = False\n        outer_query.select_related = False\n        compiler = outer_query.get_compiler(using, elide_empty=elide_empty)\n        result = compiler.execute_sql(SINGLE)\n        if result is None:\n            result = empty_set_result\n        else:\n            cols = outer_query.annotation_select.values()\n            converters = compiler.get_converters(cols)\n            rows = compiler.apply_converters((result,), converters)\n            if compiler.has_composite_fields(cols):\n                rows = compiler.composite_fields_to_tuples(rows, cols)\n            result = next(rows)\n\n        return dict(zip(outer_query.annotation_select, result))\n\n    def get_count(self, using):\n        \"\"\"\n        Perform a COUNT() query using the current filter constraints.\n        \"\"\"\n        obj = self.clone()\n        return obj.get_aggregation(using, {\"__count\": Count(\"*\")})[\"__count\"]\n\n    def has_filters(self):\n        return self.where\n\n    def exists(self, limit=True):\n        q = self.clone()\n        if not (q.distinct and q.is_sliced):\n            if q.group_by is True:\n                q.add_fields(\n                    (f.attname for f in self.model._meta.concrete_fields), False\n                )\n                # Disable GROUP BY aliases to avoid orphaning references to the\n                # SELECT clause which is about to be cleared.\n                q.set_group_by(allow_aliases=False)\n            q.clear_select_clause()\n        if q.combined_queries and q.combinator == \"union\":\n            q.combined_queries = tuple(\n                combined_query.exists(limit=False)\n                for combined_query in q.combined_queries\n            )\n        q.clear_ordering(force=True)\n        if limit is True:\n            q.set_limits(high=1)\n        q.add_annotation(Value(1), \"a\")\n        return q\n\n    def has_results(self, using):\n        q = self.exists()\n        compiler = q.get_compiler(using=using)\n        return compiler.has_results()\n\n    def explain(self, using, format=None, **options):\n        q = self.clone()\n        for option_name in options:\n            if (\n                not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)\n                or \"--\" in option_name\n            ):\n                raise ValueError(f\"Invalid option name: {option_name!r}.\")\n        q.explain_info = ExplainInfo(format, options)\n        compiler = q.get_compiler(using=using)\n        return \"\\n\".join(compiler.explain_query())\n\n    def combine(self, rhs, connector):\n        \"\"\"\n        Merge the 'rhs' query into the current one (with any 'rhs' effects\n        being applied *after* (that is, \"to the right of\") anything in the\n        current query. 'rhs' is not modified during a call to this function.\n\n        The 'connector' parameter describes how to connect filters from the\n        'rhs' query.\n        \"\"\"\n        if self.model != rhs.model:\n            raise TypeError(\"Cannot combine queries on two different base models.\")\n        if self.is_sliced:\n            raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n        if self.distinct != rhs.distinct:\n            raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n        if self.distinct_fields != rhs.distinct_fields:\n            raise TypeError(\"Cannot combine queries with different distinct fields.\")\n\n        # If lhs and rhs shares the same alias prefix, it is possible to have\n        # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up\n        # as T4 -> T6 while combining two querysets. To prevent this, change an\n        # alias prefix of the rhs and update current aliases accordingly,\n        # except if the alias is the base table since it must be present in the\n        # query on both sides.\n        initial_alias = self.get_initial_alias()\n        rhs = rhs.clone()\n        rhs.bump_prefix(self, exclude={initial_alias})\n\n        # Work out how to relabel the rhs aliases, if necessary.\n        change_map = {}\n        conjunction = connector == AND\n\n        # Determine which existing joins can be reused. When combining the\n        # query with AND we must recreate all joins for m2m filters. When\n        # combining with OR we can reuse joins. The reason is that in AND\n        # case a single row can't fulfill a condition like:\n        #     revrel__col=1 & revrel__col=2\n        # But, there might be two different related rows matching this\n        # condition. In OR case a single True is enough, so single row is\n        # enough, too.\n        #\n        # Note that we will be creating duplicate joins for non-m2m joins in\n        # the AND case. The results will be correct but this creates too many\n        # joins. This is something that could be fixed later on.\n        reuse = set() if conjunction else set(self.alias_map)\n        joinpromoter = JoinPromoter(connector, 2, False)\n        joinpromoter.add_votes(\n            j for j in self.alias_map if self.alias_map[j].join_type == INNER\n        )\n        rhs_votes = set()\n        # Now, add the joins from rhs query into the new query (skipping base\n        # table).\n        rhs_tables = list(rhs.alias_map)[1:]\n        for alias in rhs_tables:\n            join = rhs.alias_map[alias]\n            # If the left side of the join was already relabeled, use the\n            # updated alias.\n            join = join.relabeled_clone(change_map)\n            new_alias = self.join(join, reuse=reuse)\n            if join.join_type == INNER:\n                rhs_votes.add(new_alias)\n            # We can't reuse the same join again in the query. If we have two\n            # distinct joins for the same connection in rhs query, then the\n            # combined query must have two joins, too.\n            reuse.discard(new_alias)\n            if alias != new_alias:\n                change_map[alias] = new_alias\n            if not rhs.alias_refcount[alias]:\n                # The alias was unused in the rhs query. Unref it so that it\n                # will be unused in the new query, too. We have to add and\n                # unref the alias so that join promotion has information of\n                # the join type for the unused alias.\n                self.unref_alias(new_alias)\n        joinpromoter.add_votes(rhs_votes)\n        joinpromoter.update_join_types(self)\n\n        # Combine subqueries aliases to ensure aliases relabelling properly\n        # handle subqueries when combining where and select clauses.\n        self.subq_aliases |= rhs.subq_aliases\n\n        # Now relabel a copy of the rhs where-clause and add it to the current\n        # one.\n        w = rhs.where.clone()\n        w.relabel_aliases(change_map)\n        self.where.add(w, connector)\n\n        # Selection columns and extra extensions are those provided by 'rhs'.\n        if rhs.select:\n            self.set_select([col.relabeled_clone(change_map) for col in rhs.select])\n        else:\n            self.select = ()\n\n        if connector == OR:\n            # It would be nice to be able to handle this, but the queries don't\n            # really make sense (or return consistent value sets). Not worth\n            # the extra complexity when you can write a real query instead.\n            if self.extra and rhs.extra:\n                raise ValueError(\n                    \"When merging querysets using 'or', you cannot have \"\n                    \"extra(select=...) on both sides.\"\n                )\n        self.extra.update(rhs.extra)\n        extra_select_mask = set()\n        if self.extra_select_mask is not None:\n            extra_select_mask.update(self.extra_select_mask)\n        if rhs.extra_select_mask is not None:\n            extra_select_mask.update(rhs.extra_select_mask)\n        if extra_select_mask:\n            self.set_extra_mask(extra_select_mask)\n        self.extra_tables += rhs.extra_tables\n\n        # Ordering uses the 'rhs' ordering, unless it has none, in which case\n        # the current ordering is used.\n        self.order_by = rhs.order_by or self.order_by\n        self.extra_order_by = rhs.extra_order_by or self.extra_order_by\n\n    def _get_defer_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # All concrete fields and related objects that are not part of the\n        # defer mask must be included. If a relational field is encountered it\n        # gets added to the mask for it be considered if `select_related` and\n        # the cycle continues by recursively calling this function.\n        for field in opts.concrete_fields + opts.related_objects:\n            field_mask = mask.pop(field.name, None)\n            field_att_mask = None\n            if field_attname := getattr(field, \"attname\", None):\n                field_att_mask = mask.pop(field_attname, None)\n            if field_mask is None and field_att_mask is None:\n                select_mask.setdefault(field, {})\n            elif field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                # Virtual fields such as many-to-many and generic foreign keys\n                # cannot be effectively deferred. Historically, they were\n                # allowed to be passed to QuerySet.defer(). Ignore such field\n                # references until a layer of validation at mask alteration\n                # time is eventually implemented.\n                if field.many_to_many:\n                    continue\n                field_select_mask = select_mask.setdefault(field, {})\n                related_model = field.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        # Remaining defer entries must be references to filtered relations\n        # otherwise they are surfaced as missing field errors.\n        for field_name, field_mask in mask.items():\n            if filtered_relation := self._filtered_relations.get(field_name):\n                relation = opts.get_field(filtered_relation.relation_name)\n                field_select_mask = select_mask.setdefault((field_name, relation), {})\n                related_model = relation.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n            else:\n                opts.get_field(field_name)\n        return select_mask\n\n    def _get_only_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # Only include fields mentioned in the mask.\n        for field_name, field_mask in mask.items():\n            field = opts.get_field(field_name)\n            field_select_mask = select_mask.setdefault(field, {})\n            if field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                related_model = field.remote_field.model._meta.concrete_model\n                self._get_only_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        return select_mask\n\n    def get_select_mask(self):\n        \"\"\"\n        Convert the self.deferred_loading data structure to an alternate data\n        structure, describing the field that *will* be loaded. This is used to\n        compute the columns to select from the database and also by the\n        QuerySet class to work out which fields are being initialized on each\n        model. Models that have all their fields included aren't mentioned in\n        the result, only those that have field restrictions in place.\n        \"\"\"\n        field_names, defer = self.deferred_loading\n        if not field_names:\n            return {}\n        mask = {}\n        for field_name in field_names:\n            part_mask = mask\n            for part in field_name.split(LOOKUP_SEP):\n                part_mask = part_mask.setdefault(part, {})\n        opts = self.get_meta()\n        if defer:\n            return self._get_defer_select_mask(opts, mask)\n        return self._get_only_select_mask(opts, mask)\n\n    def table_alias(self, table_name, create=False, filtered_relation=None):\n        \"\"\"\n        Return a table alias for the given table_name and whether this is a\n        new alias or not.\n\n        If 'create' is true, a new alias is always created. Otherwise, the\n        most recently created alias for the table (if one exists) is reused.\n        \"\"\"\n        alias_list = self.table_map.get(table_name)\n        if not create and alias_list:\n            alias = alias_list[0]\n            self.alias_refcount[alias] += 1\n            return alias, False\n\n        # Create a new alias for this table.\n        if alias_list:\n            alias = \"%s%d\" % (self.alias_prefix, len(self.alias_map) + 1)\n            alias_list.append(alias)\n        else:\n            # The first occurrence of a table uses the table name directly.\n            alias = (\n                filtered_relation.alias if filtered_relation is not None else table_name\n            )\n            self.table_map[table_name] = [alias]\n        self.alias_refcount[alias] = 1\n        return alias, True\n\n    def ref_alias(self, alias):\n        \"\"\"Increases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] += 1\n\n    def unref_alias(self, alias, amount=1):\n        \"\"\"Decreases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] -= amount\n\n    def promote_joins(self, aliases):\n        \"\"\"\n        Promote recursively the join type of given aliases and its children to\n        an outer join. If 'unconditional' is False, only promote the join if\n        it is nullable or the parent join is an outer join.\n\n        The children promotion is done to avoid join chains that contain a\n        LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b\n        is promoted, then we must also promote b->c automatically, or otherwise\n        the promotion of a->b doesn't actually change anything in the query\n        results.\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type is None:\n                # This is the base table (first FROM entry) - this table\n                # isn't really joined at all in the query, so we should not\n                # alter its join type.\n                continue\n            # Only the first alias (skipped above) should have None join_type\n            assert self.alias_map[alias].join_type is not None\n            parent_alias = self.alias_map[alias].parent_alias\n            parent_louter = (\n                parent_alias and self.alias_map[parent_alias].join_type == LOUTER\n            )\n            already_louter = self.alias_map[alias].join_type == LOUTER\n            if (self.alias_map[alias].nullable or parent_louter) and not already_louter:\n                self.alias_map[alias] = self.alias_map[alias].promote()\n                # Join type of 'alias' changed, so re-examine all aliases that\n                # refer to this one.\n                aliases.extend(\n                    join\n                    for join in self.alias_map\n                    if self.alias_map[join].parent_alias == alias\n                    and join not in aliases\n                )\n\n    def demote_joins(self, aliases):\n        \"\"\"\n        Change join type from LOUTER to INNER for all joins in aliases.\n\n        Similarly to promote_joins(), this method must ensure no join chains\n        containing first an outer, then an inner join are generated. If we\n        are demoting b->c join in chain a LOUTER b LOUTER c then we must\n        demote a->b automatically, or otherwise the demotion of b->c doesn't\n        actually change anything in the query results. .\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type == LOUTER:\n                self.alias_map[alias] = self.alias_map[alias].demote()\n                parent_alias = self.alias_map[alias].parent_alias\n                if self.alias_map[parent_alias].join_type == INNER:\n                    aliases.append(parent_alias)\n\n    def reset_refcounts(self, to_counts):\n        \"\"\"\n        Reset reference counts for aliases so that they match the value passed\n        in `to_counts`.\n        \"\"\"\n        for alias, cur_refcount in self.alias_refcount.copy().items():\n            unref_amount = cur_refcount - to_counts.get(alias, 0)\n            self.unref_alias(alias, unref_amount)\n\n    def change_aliases(self, change_map):\n        \"\"\"\n        Change the aliases in change_map (which maps old-alias -> new-alias),\n        relabelling any references to them in select columns and the where\n        clause.\n        \"\"\"\n        if not change_map:\n            return self\n        # If keys and values of change_map were to intersect, an alias might be\n        # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending\n        # on their order in change_map.\n        assert set(change_map).isdisjoint(change_map.values())\n\n        # 1. Update references in \"select\" (normal columns plus aliases),\n        # \"group by\" and \"where\".\n        self.where.relabel_aliases(change_map)\n        if isinstance(self.group_by, tuple):\n            self.group_by = tuple(\n                [col.relabeled_clone(change_map) for col in self.group_by]\n            )\n        self.select = tuple([col.relabeled_clone(change_map) for col in self.select])\n        self.annotations = self.annotations and {\n            key: col.relabeled_clone(change_map)\n            for key, col in self.annotations.items()\n        }\n\n        # 2. Rename the alias in the internal table/alias datastructures.\n        for old_alias, new_alias in change_map.items():\n            if old_alias not in self.alias_map:\n                continue\n            alias_data = self.alias_map[old_alias].relabeled_clone(change_map)\n            self.alias_map[new_alias] = alias_data\n            self.alias_refcount[new_alias] = self.alias_refcount[old_alias]\n            del self.alias_refcount[old_alias]\n            del self.alias_map[old_alias]\n\n            table_aliases = self.table_map[alias_data.table_name]\n            for pos, alias in enumerate(table_aliases):\n                if alias == old_alias:\n                    table_aliases[pos] = new_alias\n                    break\n\n        # 3. Rename the direct external aliases and the ones of combined\n        # queries (union, intersection, difference).\n        self.external_aliases = {\n            # Table is aliased or it's being changed and thus is aliased.\n            change_map.get(alias, alias): (aliased or alias in change_map)\n            for alias, aliased in self.external_aliases.items()\n        }\n        for combined_query in self.combined_queries:\n            external_change_map = {\n                alias: aliased\n                for alias, aliased in change_map.items()\n                if alias in combined_query.external_aliases\n            }\n            combined_query.change_aliases(external_change_map)\n\n    def bump_prefix(self, other_query, exclude=None):\n        \"\"\"\n        Change the alias prefix to the next letter in the alphabet in a way\n        that the other query's aliases and this query's aliases will not\n        conflict. Even tables that previously had no alias will get an alias\n        after this call. To prevent changing aliases use the exclude parameter.\n        \"\"\"\n\n        def prefix_gen():\n            \"\"\"\n            Generate a sequence of characters in alphabetical order:\n                -> 'A', 'B', 'C', ...\n\n            When the alphabet is finished, the sequence will continue with the\n            Cartesian product:\n                -> 'AA', 'AB', 'AC', ...\n            \"\"\"\n            remaining_steps = 3\n            while remaining_steps > 0:\n                remaining_steps -= 1\n            alphabet = ascii_uppercase\n            prefix = chr(ord(self.alias_prefix) + 1)\n            yield prefix\n            for n in count(1):\n                seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet\n                for s in product(seq, repeat=n):\n                    yield \"\".join(s)\n                prefix = None\n\n        if self.alias_prefix != other_query.alias_prefix:\n            # No clashes between self and outer query should be possible.\n            return\n\n        # Explicitly avoid infinite loop. The constant divider is based on how\n        # much depth recursive subquery references add to the stack. This value\n        # might need to be adjusted when adding or removing function calls from\n        # the code path in charge of performing these operations.\n        local_recursion_limit = sys.getrecursionlimit() // 16\n        for pos, prefix in enumerate(prefix_gen()):\n            if prefix not in self.subq_aliases:\n                self.alias_prefix = prefix\n                break\n            if pos > local_recursion_limit:\n                raise RecursionError(\n                    \"Maximum recursion depth exceeded: too many subqueries.\"\n                )\n        self.subq_aliases = self.subq_aliases.union([self.alias_prefix])\n        other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases)\n        if exclude is None:\n            exclude = {}\n        self.change_aliases(\n            {\n                alias: \"%s%d\" % (self.alias_prefix, pos)\n                for pos, alias in enumerate(self.alias_map)\n                if alias not in exclude\n            }\n        )\n\n    def get_initial_alias(self):\n        \"\"\"\n        Return the first alias for this query, after increasing its reference\n        count.\n        \"\"\"\n        if self.alias_map:\n            alias = self.base_table\n            self.ref_alias(alias)\n        elif self.model:\n            alias = self.join(self.base_table_class(self.get_meta().db_table, None))\n        else:\n            alias = None\n        return alias\n\n    def count_active_tables(self):\n        \"\"\"\n        Return the number of tables in this query with a non-zero reference\n        count. After execution, the reference counts are zeroed, so tables\n        added in compiler will not be seen by this method.\n        \"\"\"\n        return len([1 for count in self.alias_refcount.values() if count])\n\n    def join(self, join, reuse=None):\n        \"\"\"\n        Return an alias for the 'join', either reusing an existing alias for\n        that join or creating a new one. 'join' is either a base_table_class or\n        join_class.\n\n        The 'reuse' parameter can be either None which means all joins are\n        reusable, or it can be a set containing the aliases that can be reused.\n\n        A join is always created as LOUTER if the lhs alias is LOUTER to make\n        sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new\n        joins are created as LOUTER if the join is nullable.\n        \"\"\"\n        reuse_aliases = [\n            a\n            for a, j in self.alias_map.items()\n            if (reuse is None or a in reuse) and j == join\n        ]\n        if reuse_aliases:\n            if join.table_alias in reuse_aliases:\n                reuse_alias = join.table_alias\n            else:\n                # Reuse the most recent alias of the joined table\n                # (a many-to-many relation may be joined multiple times).\n                reuse_alias = reuse_aliases[-1]\n            self.ref_alias(reuse_alias)\n            return reuse_alias\n\n        # No reuse is possible, so we need a new alias.\n        alias, _ = self.table_alias(\n            join.table_name, create=True, filtered_relation=join.filtered_relation\n        )\n        if join.join_type:\n            if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:\n                join_type = LOUTER\n            else:\n                join_type = INNER\n            join.join_type = join_type\n        join.table_alias = alias\n        self.alias_map[alias] = join\n        if filtered_relation := join.filtered_relation:\n            resolve_reuse = reuse\n            if resolve_reuse is not None:\n                resolve_reuse = set(reuse) | {alias}\n            joins_len = len(self.alias_map)\n            join.filtered_relation = filtered_relation.resolve_expression(\n                self, reuse=resolve_reuse\n            )\n            # Some joins were during expression resolving, they must be present\n            # before the one we just added.\n            if joins_len < len(self.alias_map):\n                self.alias_map[alias] = self.alias_map.pop(alias)\n        return alias\n\n    def join_parent_model(self, opts, model, alias, seen):\n        \"\"\"\n        Make sure the given 'model' is joined in the query. If 'model' isn't\n        a parent of 'opts' or if it is None this method is a no-op.\n\n        The 'alias' is the root alias for starting the join, 'seen' is a dict\n        of model -> alias of existing joins. It must also contain a mapping\n        of None -> some alias. This will be returned in the no-op case.\n        \"\"\"\n        if model in seen:\n            return seen[model]\n        chain = opts.get_base_chain(model)\n        if not chain:\n            return alias\n        curr_opts = opts\n        for int_model in chain:\n            if int_model in seen:\n                curr_opts = int_model._meta\n                alias = seen[int_model]\n                continue\n            # Proxy model have elements in base chain\n            # with no parents, assign the new options\n            # object and skip to the next base in that\n            # case\n            if not curr_opts.parents[int_model]:\n                curr_opts = int_model._meta\n                continue\n            link_field = curr_opts.get_ancestor_link(int_model)\n            join_info = self.setup_joins([link_field.name], curr_opts, alias)\n            curr_opts = int_model._meta\n            alias = seen[int_model] = join_info.joins[-1]\n        return alias or seen[None]\n\n    def check_alias(self, alias):\n        # RemovedInDjango70Warning: When the deprecation ends, remove.\n        if \"%\" in alias:\n            warnings.warn(\n                \"Using percent signs in a column alias is deprecated.\",\n                category=RemovedInDjango70Warning,\n                skip_file_prefixes=django_file_prefixes(),\n            )\n        if FORBIDDEN_ALIAS_PATTERN.search(alias):\n            raise ValueError(\n                \"Column aliases cannot contain whitespace characters, hashes, \"\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # \"control characters, quotation marks, semicolons, percent \"\n                # \"signs, or SQL comments.\"\n                \"control characters, quotation marks, semicolons, or SQL comments.\"\n            )\n\n    def add_annotation(self, annotation, alias, select=True):\n        \"\"\"Add a single annotation expression to the Query.\"\"\"\n        self.check_alias(alias)\n        annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None)\n        if select:\n            self.append_annotation_mask([alias])\n        else:\n            self.set_annotation_mask(set(self.annotation_select).difference({alias}))\n        self.annotations[alias] = annotation\n        if select and self.selected:\n            self.selected[alias] = alias\n\n    @property\n    def _subquery_fields_len(self):\n        if not self.has_select_fields or not self.select:\n            return len(self.model._meta.pk_fields)\n        return len(self.select) + sum(\n            len(expr.targets) - 1 for expr in self.select if isinstance(expr, ColPairs)\n        )\n\n    def resolve_expression(self, query, *args, **kwargs):\n        clone = self.clone()\n        # Subqueries need to use a different set of aliases than the outer\n        # query.\n        clone.bump_prefix(query)\n        clone.subquery = True\n        clone.where.resolve_expression(query, *args, **kwargs)\n        # Resolve combined queries.\n        if clone.combinator:\n            clone.combined_queries = tuple(\n                [\n                    combined_query.resolve_expression(query, *args, **kwargs)\n                    for combined_query in clone.combined_queries\n                ]\n            )\n        for key, value in clone.annotations.items():\n            resolved = value.resolve_expression(query, *args, **kwargs)\n            if hasattr(resolved, \"external_aliases\"):\n                resolved.external_aliases.update(clone.external_aliases)\n            clone.annotations[key] = resolved\n        # Outer query's aliases are considered external.\n        for alias, table in query.alias_map.items():\n            clone.external_aliases[alias] = (\n                isinstance(table, Join)\n                and table.join_field.related_model._meta.db_table != alias\n            ) or (\n                isinstance(table, BaseTable) and table.table_name != table.table_alias\n            )\n        return clone\n\n    def get_external_cols(self):\n        exprs = chain(self.annotations.values(), self.where.children)\n        return [\n            col\n            for col in self._gen_cols(exprs, include_external=True)\n            if col.alias in self.external_aliases\n        ]\n\n    def get_group_by_cols(self, wrapper=None):\n        # If wrapper is referenced by an alias for an explicit GROUP BY through\n        # values() a reference to this expression and not the self must be\n        # returned to ensure external column references are not grouped against\n        # as well.\n        external_cols = self.get_external_cols()\n        if any(col.possibly_multivalued for col in external_cols):\n            return [wrapper or self]\n        return external_cols\n\n    def as_sql(self, compiler, connection):\n        # Some backends (e.g. Oracle) raise an error when a subquery contains\n        # unnecessary ORDER BY clause.\n        if (\n            self.subquery\n            and not connection.features.ignores_unnecessary_order_by_in_subqueries\n        ):\n            self.clear_ordering(force=False)\n            for query in self.combined_queries:\n                query.clear_ordering(force=False)\n        sql, params = self.get_compiler(connection=connection).as_sql()\n        if self.subquery:\n            sql = \"(%s)\" % sql\n        return sql, params\n\n    def resolve_lookup_value(self, value, can_reuse, allow_joins, summarize=False):\n        if hasattr(value, \"resolve_expression\"):\n            value = value.resolve_expression(\n                self,\n                reuse=can_reuse,\n                allow_joins=allow_joins,\n                summarize=summarize,\n            )\n        elif isinstance(value, (list, tuple)):\n            # The items of the iterable may be expressions and therefore need\n            # to be resolved independently.\n            values = (\n                self.resolve_lookup_value(sub_value, can_reuse, allow_joins, summarize)\n                for sub_value in value\n            )\n            type_ = type(value)\n            if hasattr(type_, \"_make\"):  # namedtuple\n                return type_(*values)\n            return type_(values)\n        return value\n\n    def solve_lookup_type(self, lookup, summarize=False):\n        \"\"\"\n        Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').\n        \"\"\"\n        lookup_splitted = lookup.split(LOOKUP_SEP)\n        if self.annotations:\n            annotation, expression_lookups = refs_expression(\n                lookup_splitted, self.annotations\n            )\n            if annotation:\n                expression = self.annotations[annotation]\n                if summarize:\n                    expression = Ref(annotation, expression)\n                return expression_lookups, (), expression\n        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())\n        field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)]\n        if len(lookup_parts) > 1 and not field_parts:\n            raise FieldError(\n                'Invalid lookup \"%s\" for model %s\".'\n                % (lookup, self.get_meta().model.__name__)\n            )\n        return lookup_parts, field_parts, False\n\n    def check_query_object_type(self, value, opts, field):\n        \"\"\"\n        Check whether the object passed while querying is of the correct type.\n        If not, raise a ValueError specifying the wrong object.\n        \"\"\"\n        if hasattr(value, \"_meta\"):\n            if not check_rel_lookup_compatibility(value._meta.model, opts, field):\n                raise ValueError(\n                    'Cannot query \"%s\": Must be \"%s\" instance.'\n                    % (value, opts.object_name)\n                )\n\n    def check_related_objects(self, field, value, opts):\n        \"\"\"Check the type of object passed to query relations.\"\"\"\n        if field.is_relation:\n            # Check that the field and the queryset use the same model in a\n            # query like .filter(author=Author.objects.all()). For example, the\n            # opts would be Author's (from the author field) and value.model\n            # would be Author.objects.all() queryset's .model (Author also).\n            # The field is the related field on the lhs side.\n            if (\n                isinstance(value, Query)\n                and not value.has_select_fields\n                and not check_rel_lookup_compatibility(value.model, opts, field)\n            ):\n                raise ValueError(\n                    'Cannot use QuerySet for \"%s\": Use a QuerySet for \"%s\".'\n                    % (value.model._meta.object_name, opts.object_name)\n                )\n            elif hasattr(value, \"_meta\"):\n                self.check_query_object_type(value, opts, field)\n            elif hasattr(value, \"__iter__\"):\n                for v in value:\n                    self.check_query_object_type(v, opts, field)\n\n    def check_filterable(self, expression):\n        \"\"\"Raise an error if expression cannot be used in a WHERE clause.\"\"\"\n        if hasattr(expression, \"resolve_expression\") and not getattr(\n            expression, \"filterable\", True\n        ):\n            raise NotSupportedError(\n                expression.__class__.__name__ + \" is disallowed in the filter \"\n                \"clause.\"\n            )\n        if hasattr(expression, \"get_source_expressions\"):\n            for expr in expression.get_source_expressions():\n                self.check_filterable(expr)\n\n    def build_lookup(self, lookups, lhs, rhs):\n        \"\"\"\n        Try to extract transforms and lookup from given lhs.\n\n        The lhs value is something that works like SQLExpression.\n        The rhs value is what the lookup is going to compare against.\n        The lookups is a list of names to extract using get_lookup()\n        and get_transform().\n        \"\"\"\n        # __exact is the default lookup if one isn't given.\n        *transforms, lookup_name = lookups or [\"exact\"]\n        for name in transforms:\n            lhs = self.try_transform(lhs, name, lookups)\n        # First try get_lookup() so that the lookup takes precedence if the lhs\n        # supports both transform and lookup for the name.\n        lookup_class = lhs.get_lookup(lookup_name)\n        if not lookup_class:\n            # A lookup wasn't found. Try to interpret the name as a transform\n            # and do an Exact lookup against it.\n            lhs = self.try_transform(lhs, lookup_name)\n            lookup_name = \"exact\"\n            lookup_class = lhs.get_lookup(lookup_name)\n            if not lookup_class:\n                return\n\n        lookup = lookup_class(lhs, rhs)\n        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all\n        # uses of None as a query value unless the lookup supports it.\n        if lookup.rhs is None and not lookup.can_use_none_as_rhs:\n            if lookup_name not in (\"exact\", \"iexact\"):\n                raise ValueError(\"Cannot use None as a query value\")\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        # For Oracle '' is equivalent to null. The check must be done at this\n        # stage because join promotion can't be done in the compiler. Using\n        # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.\n        # A similar thing is done in is_nullable(), too.\n        if (\n            lookup_name in (\"exact\", \"iexact\")\n            and lookup.rhs == \"\"\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        ):\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        return lookup\n\n    def try_transform(self, lhs, name, lookups=None):\n        \"\"\"\n        Helper method for build_lookup(). Try to fetch and initialize\n        a transform for name parameter from lhs.\n        \"\"\"\n        transform_class = lhs.get_transform(name)\n        if transform_class:\n            return transform_class(lhs)\n        else:\n            output_field = lhs.output_field.__class__\n            suggested_lookups = difflib.get_close_matches(\n                name, lhs.output_field.get_lookups()\n            )\n            if suggested_lookups:\n                suggestion = \", perhaps you meant %s?\" % \" or \".join(suggested_lookups)\n            else:\n                suggestion = \".\"\n            if lookups is not None:\n                name_index = lookups.index(name)\n                unsupported_lookup = LOOKUP_SEP.join(lookups[name_index:])\n            else:\n                unsupported_lookup = name\n            raise FieldError(\n                \"Unsupported lookup '%s' for %s or join on the field not \"\n                \"permitted%s\" % (unsupported_lookup, output_field.__name__, suggestion)\n            )\n\n    def build_filter(\n        self,\n        filter_expr,\n        branch_negated=False,\n        current_negated=False,\n        can_reuse=None,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"\n        Build a WhereNode for a single filter clause but don't add it\n        to this Query. Query.add_q() will then add this filter to the where\n        Node.\n\n        The 'branch_negated' tells us if the current branch contains any\n        negations. This will be used to determine if subqueries are needed.\n\n        The 'current_negated' is used to determine if the current filter is\n        negated or not and this will be used to determine if IS NULL filtering\n        is needed.\n\n        The difference between current_negated and branch_negated is that\n        branch_negated is set on first negation, but current_negated is\n        flipped for each negation.\n\n        Note that add_filter will not do any negating itself, that is done\n        upper in the code by add_q().\n\n        The 'can_reuse' is a set of reusable joins for multijoins.\n\n        The method will create a filter clause that can be added to the current\n        query. However, if the filter isn't added to the query then the caller\n        is responsible for unreffing the joins used.\n        \"\"\"\n        if isinstance(filter_expr, dict):\n            raise FieldError(\"Cannot parse keyword query as dict\")\n        if isinstance(filter_expr, Q):\n            return self._add_q(\n                filter_expr,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                used_aliases=can_reuse,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n        if hasattr(filter_expr, \"resolve_expression\"):\n            if not getattr(filter_expr, \"conditional\", False):\n                raise TypeError(\"Cannot filter against a non-conditional expression.\")\n            condition = filter_expr.resolve_expression(\n                self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize\n            )\n            if not isinstance(condition, Lookup):\n                condition = self.build_lookup([\"exact\"], condition, True)\n            return WhereNode([condition], connector=AND), []\n        arg, value = filter_expr\n        if not arg:\n            raise FieldError(\"Cannot parse keyword query %r\" % arg)\n        lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize)\n\n        if check_filterable:\n            self.check_filterable(reffed_expression)\n\n        if not allow_joins and len(parts) > 1:\n            raise FieldError(\"Joined field references are not permitted in this query\")\n\n        pre_joins = self.alias_refcount.copy()\n        value = self.resolve_lookup_value(value, can_reuse, allow_joins, summarize)\n        used_joins = {\n            k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)\n        }\n\n        if check_filterable:\n            self.check_filterable(value)\n\n        if reffed_expression:\n            condition = self.build_lookup(lookups, reffed_expression, value)\n            return WhereNode([condition], connector=AND), []\n\n        opts = self.get_meta()\n        alias = self.get_initial_alias()\n        allow_many = not branch_negated or not split_subq\n\n        try:\n            join_info = self.setup_joins(\n                parts,\n                opts,\n                alias,\n                can_reuse=can_reuse,\n                allow_many=allow_many,\n            )\n\n            # Prevent iterator from being consumed by check_related_objects()\n            if isinstance(value, Iterator):\n                value = list(value)\n            self.check_related_objects(join_info.final_field, value, join_info.opts)\n\n            # split_exclude() needs to know which joins were generated for the\n            # lookup parts\n            self._lookup_joins = join_info.joins\n        except MultiJoin as e:\n            return self.split_exclude(filter_expr, can_reuse, e.names_with_path)\n\n        # Update used_joins before trimming since they are reused to determine\n        # which joins could be later promoted to INNER.\n        used_joins.update(join_info.joins)\n        targets, alias, join_list = self.trim_joins(\n            join_info.targets, join_info.joins, join_info.path\n        )\n        if can_reuse is not None:\n            can_reuse.update(join_list)\n\n        if join_info.final_field.is_relation:\n            if len(targets) == 1:\n                col = self._get_col(targets[0], join_info.final_field, alias)\n            else:\n                col = ColPairs(alias, targets, join_info.targets, join_info.final_field)\n        else:\n            col = self._get_col(targets[0], join_info.final_field, alias)\n\n        condition = self.build_lookup(lookups, col, value)\n        lookup_type = condition.lookup_name\n        clause = WhereNode([condition], connector=AND)\n\n        require_outer = (\n            lookup_type == \"isnull\" and condition.rhs is True and not current_negated\n        )\n        if (\n            current_negated\n            and (lookup_type != \"isnull\" or condition.rhs is False)\n            and condition.rhs is not None\n        ):\n            require_outer = True\n            if lookup_type != \"isnull\":\n                # The condition added here will be SQL like this:\n                # NOT (col IS NOT NULL), where the first NOT is added in\n                # upper layers of code. The reason for addition is that if col\n                # is null, then col != someval will result in SQL \"unknown\"\n                # which isn't the same as in Python. The Python None handling\n                # is wanted, and it can be gotten by\n                # (col IS NULL OR col != someval)\n                #   <=>\n                # NOT (col IS NOT NULL AND col = someval).\n                if (\n                    self.is_nullable(targets[0])\n                    or self.alias_map[join_list[-1]].join_type == LOUTER\n                ):\n                    lookup_class = targets[0].get_lookup(\"isnull\")\n                    col = self._get_col(targets[0], join_info.targets[0], alias)\n                    # Use OR + IS NULL when RHS `in` values include None.\n                    if (\n                        lookup_type == \"in\"\n                        # Check containers (not strings or bytes).\n                        and isinstance(condition.rhs, Iterable)\n                        and not isinstance(condition.rhs, (str, bytes))\n                        and any(v is None for v in condition.rhs)\n                    ):\n                        clause.add(lookup_class(col, True), OR)\n                    else:\n                        clause.add(lookup_class(col, False), AND)\n                # If someval is a nullable column, someval IS NOT NULL is\n                # added.\n                if isinstance(value, Col) and self.is_nullable(value.target):\n                    lookup_class = value.target.get_lookup(\"isnull\")\n                    clause.add(lookup_class(value, False), AND)\n        return clause, used_joins if not require_outer else ()\n\n    def add_filter(self, filter_lhs, filter_rhs):\n        self.add_q(Q((filter_lhs, filter_rhs)))\n\n    def add_q(self, q_object, reuse_all=False):\n        \"\"\"\n        A preprocessor for the internal _add_q(). Responsible for doing final\n        join promotion.\n        \"\"\"\n        # For join promotion this case is doing an AND for the added q_object\n        # and existing conditions. So, any existing inner join forces the join\n        # type to remain inner. Existing outer joins can however be demoted.\n        # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if\n        # rel_a doesn't produce any rows, then the whole condition must fail.\n        # So, demotion is OK.\n        existing_inner = {\n            a for a in self.alias_map if self.alias_map[a].join_type == INNER\n        }\n        if reuse_all:\n            can_reuse = set(self.alias_map)\n        else:\n            can_reuse = self.used_aliases\n        clause, _ = self._add_q(q_object, can_reuse)\n        if clause:\n            self.where.add(clause, AND)\n        self.demote_joins(existing_inner)\n\n    def build_where(self, filter_expr):\n        return self.build_filter(filter_expr, allow_joins=False)[0]\n\n    def clear_where(self):\n        self.where = WhereNode()\n\n    def _add_q(\n        self,\n        q_object,\n        used_aliases,\n        branch_negated=False,\n        current_negated=False,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"Add a Q-object to the current filter.\"\"\"\n        connector = q_object.connector\n        current_negated ^= q_object.negated\n        branch_negated = branch_negated or q_object.negated\n        target_clause = WhereNode(connector=connector, negated=q_object.negated)\n        joinpromoter = JoinPromoter(\n            q_object.connector, len(q_object.children), current_negated\n        )\n        for child in q_object.children:\n            child_clause, needed_inner = self.build_filter(\n                child,\n                can_reuse=used_aliases,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n            joinpromoter.add_votes(needed_inner)\n            if child_clause:\n                target_clause.add(child_clause, connector)\n        if update_join_types:\n            needed_inner = joinpromoter.update_join_types(self)\n        else:\n            needed_inner = []\n        return target_clause, needed_inner\n\n    def add_filtered_relation(self, filtered_relation, alias):\n        if \".\" in alias:\n            raise ValueError(\n                \"FilteredRelation doesn't support aliases with periods \"\n                \"(got %r).\" % alias\n            )\n        self.check_alias(alias)\n        filtered_relation.alias = alias\n        relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(\n            filtered_relation.relation_name\n        )\n        if relation_lookup_parts:\n            raise ValueError(\n                \"FilteredRelation's relation_name cannot contain lookups \"\n                \"(got %r).\" % filtered_relation.relation_name\n            )\n        for lookup in get_children_from_q(filtered_relation.condition):\n            lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)\n            shift = 2 if not lookup_parts else 1\n            lookup_field_path = lookup_field_parts[:-shift]\n            for idx, lookup_field_part in enumerate(lookup_field_path):\n                if len(relation_field_parts) > idx:\n                    if relation_field_parts[idx] != lookup_field_part:\n                        raise ValueError(\n                            \"FilteredRelation's condition doesn't support \"\n                            \"relations outside the %r (got %r).\"\n                            % (filtered_relation.relation_name, lookup)\n                        )\n            if len(lookup_field_parts) > len(relation_field_parts) + 1:\n                raise ValueError(\n                    \"FilteredRelation's condition doesn't support nested \"\n                    \"relations deeper than the relation_name (got %r for \"\n                    \"%r).\" % (lookup, filtered_relation.relation_name)\n                )\n        filtered_relation = filtered_relation.clone()\n        filtered_relation.condition = rename_prefix_from_q(\n            filtered_relation.relation_name,\n            alias,\n            filtered_relation.condition,\n        )\n        self._filtered_relations[filtered_relation.alias] = filtered_relation\n\n    def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):\n        \"\"\"\n        Walk the list of names and turns them into PathInfo tuples. A single\n        name in 'names' can generate multiple PathInfos (m2m, for example).\n\n        'names' is the path of names to travel, 'opts' is the model Options we\n        start the name resolving from, 'allow_many' is as for setup_joins().\n        If fail_on_missing is set to True, then a name that can't be resolved\n        will generate a FieldError.\n\n        Return a list of PathInfo tuples. In addition return the final field\n        (the last used join field) and target (which is a field guaranteed to\n        contain the same value as the final field). Finally, return those names\n        that weren't found (which are likely transforms and the final lookup).\n        \"\"\"\n        path, names_with_path = [], []\n        for pos, name in enumerate(names):\n            cur_names_with_path = (name, [])\n            if name == \"pk\" and opts is not None:\n                name = opts.pk.name\n\n            field = None\n            filtered_relation = None\n            try:\n                if opts is None:\n                    raise FieldDoesNotExist\n                field = opts.get_field(name)\n            except FieldDoesNotExist:\n                if name in self.annotations:\n                    field = self.annotations[name].output_field\n                elif name in self._filtered_relations and pos == 0:\n                    filtered_relation = self._filtered_relations[name]\n                    if LOOKUP_SEP in filtered_relation.relation_name:\n                        parts = filtered_relation.relation_name.split(LOOKUP_SEP)\n                        filtered_relation_path, field, _, _ = self.names_to_path(\n                            parts,\n                            opts,\n                            allow_many,\n                            fail_on_missing,\n                        )\n                        path.extend(filtered_relation_path[:-1])\n                    else:\n                        field = opts.get_field(filtered_relation.relation_name)\n            if field is not None:\n                # Fields that contain one-to-many relations with a generic\n                # model (like a GenericForeignKey) cannot generate reverse\n                # relations and therefore cannot be used for reverse querying.\n                if field.is_relation and not field.related_model:\n                    raise FieldError(\n                        \"Field %r does not generate an automatic reverse \"\n                        \"relation and therefore cannot be used for reverse \"\n                        \"querying. If it is a GenericForeignKey, consider \"\n                        \"adding a GenericRelation.\" % name\n                    )\n                try:\n                    model = field.model._meta.concrete_model\n                except AttributeError:\n                    # QuerySet.annotate() may introduce fields that aren't\n                    # attached to a model.\n                    model = None\n            else:\n                # We didn't find the current field, so move position back\n                # one step.\n                pos -= 1\n                if pos == -1 or fail_on_missing:\n                    available = sorted(\n                        [\n                            *get_field_names_from_opts(opts),\n                            *self.annotations,\n                            *self._filtered_relations,\n                        ]\n                    )\n                    raise FieldError(\n                        \"Cannot resolve keyword '%s' into field. \"\n                        \"Choices are: %s\" % (name, \", \".join(available))\n                    )\n                break\n            # Check if we need any joins for concrete inheritance cases (the\n            # field lives in parent, but we are currently in one of its\n            # children)\n            if opts is not None and model is not opts.model:\n                path_to_parent = opts.get_path_to_parent(model)\n                if path_to_parent:\n                    path.extend(path_to_parent)\n                    cur_names_with_path[1].extend(path_to_parent)\n                    opts = path_to_parent[-1].to_opts\n            if hasattr(field, \"path_infos\"):\n                if filtered_relation:\n                    pathinfos = field.get_path_info(filtered_relation)\n                else:\n                    pathinfos = field.path_infos\n                if not allow_many:\n                    for inner_pos, p in enumerate(pathinfos):\n                        if p.m2m:\n                            cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1])\n                            names_with_path.append(cur_names_with_path)\n                            raise MultiJoin(pos + 1, names_with_path)\n                last = pathinfos[-1]\n                path.extend(pathinfos)\n                final_field = last.join_field\n                opts = last.to_opts\n                targets = last.target_fields\n                cur_names_with_path[1].extend(pathinfos)\n                names_with_path.append(cur_names_with_path)\n            else:\n                # Local non-relational field.\n                final_field = field\n                targets = (field,)\n                if fail_on_missing and pos + 1 != len(names):\n                    raise FieldError(\n                        \"Cannot resolve keyword %r into field. Join on '%s'\"\n                        \" not permitted.\" % (names[pos + 1], name)\n                    )\n                break\n        return path, final_field, targets, names[pos + 1 :]\n\n    def setup_joins(\n        self,\n        names,\n        opts,\n        alias,\n        can_reuse=None,\n        allow_many=True,\n    ):\n        \"\"\"\n        Compute the necessary table joins for the passage through the fields\n        given in 'names'. 'opts' is the Options class for the current model\n        (which gives the table we are starting from), 'alias' is the alias for\n        the table to start the joining from.\n\n        The 'can_reuse' defines the reverse foreign key joins we can reuse. It\n        can be None in which case all joins are reusable or a set of aliases\n        that can be reused. Note that non-reverse foreign keys are always\n        reusable when using setup_joins().\n\n        If 'allow_many' is False, then any reverse foreign key seen will\n        generate a MultiJoin exception.\n\n        Return the final field involved in the joins, the target field (used\n        for any 'where' constraint), the final 'opts' value, the joins, the\n        field path traveled to generate the joins, and a transform function\n        that takes a field and alias and is equivalent to\n        `field.get_col(alias)` in the simple case but wraps field transforms if\n        they were included in names.\n\n        The target field is the field containing the concrete value. Final\n        field can be something different, for example foreign key pointing to\n        that value. Final field is needed for example in some value\n        conversions (convert 'obj' in fk__id=obj to pk val using the foreign\n        key field for example).\n        \"\"\"\n        joins = [alias]\n        # The transform can't be applied yet, as joins must be trimmed later.\n        # To avoid making every caller of this method look up transforms\n        # directly, compute transforms here and create a partial that converts\n        # fields to the appropriate wrapped version.\n\n        def final_transformer(field, alias):\n            if not self.alias_cols:\n                alias = None\n            return field.get_col(alias)\n\n        # Try resolving all the names as fields first. If there's an error,\n        # treat trailing names as lookups until a field can be resolved.\n        last_field_exception = None\n        for pivot in range(len(names), 0, -1):\n            try:\n                path, final_field, targets, rest = self.names_to_path(\n                    names[:pivot],\n                    opts,\n                    allow_many,\n                    fail_on_missing=True,\n                )\n            except FieldError as exc:\n                if pivot == 1:\n                    # The first item cannot be a lookup, so it's safe\n                    # to raise the field error here.\n                    raise\n                else:\n                    last_field_exception = exc\n            else:\n                # The transforms are the remaining items that couldn't be\n                # resolved into fields.\n                transforms = names[pivot:]\n                break\n        for name in transforms:\n\n            def transform(field, alias, *, name, previous):\n                try:\n                    wrapped = previous(field, alias)\n                    return self.try_transform(wrapped, name)\n                except FieldError:\n                    # FieldError is raised if the transform doesn't exist.\n                    if isinstance(final_field, Field) and last_field_exception:\n                        raise last_field_exception\n                    else:\n                        raise\n\n            final_transformer = functools.partial(\n                transform, name=name, previous=final_transformer\n            )\n            final_transformer.has_transforms = True\n        # Then, add the path to the query's joins. Note that we can't trim\n        # joins at this stage - we will need the information about join type\n        # of the trimmed joins.\n        for join in path:\n            if join.filtered_relation:\n                filtered_relation = join.filtered_relation.clone()\n                table_alias = filtered_relation.alias\n            else:\n                filtered_relation = None\n                table_alias = None\n            opts = join.to_opts\n            if join.direct:\n                nullable = self.is_nullable(join.join_field)\n            else:\n                nullable = True\n            connection = self.join_class(\n                opts.db_table,\n                alias,\n                table_alias,\n                INNER,\n                join.join_field,\n                nullable,\n                filtered_relation=filtered_relation,\n            )\n            reuse = can_reuse if join.m2m else None\n            alias = self.join(connection, reuse=reuse)\n            joins.append(alias)\n            if join.filtered_relation and can_reuse is not None:\n                can_reuse.add(alias)\n        return JoinInfo(final_field, targets, opts, joins, path, final_transformer)\n\n    def trim_joins(self, targets, joins, path):\n        \"\"\"\n        The 'target' parameter is the final field being joined to, 'joins'\n        is the full list of join aliases. The 'path' contain the PathInfos\n        used to create the joins.\n\n        Return the final target field and table alias and the new active\n        joins.\n\n        Always trim any direct join if the target column is already in the\n        previous table. Can't trim reverse joins as it's unknown if there's\n        anything on the other side of the join.\n        \"\"\"\n        joins = joins[:]\n        for pos, info in enumerate(reversed(path)):\n            if len(joins) == 1 or not info.direct:\n                break\n            if info.filtered_relation:\n                break\n            join_targets = {t.column for t in info.join_field.foreign_related_fields}\n            cur_targets = {t.column for t in targets}\n            if not cur_targets.issubset(join_targets):\n                break\n            targets_dict = {\n                r[1].column: r[0]\n                for r in info.join_field.related_fields\n                if r[1].column in cur_targets\n            }\n            targets = tuple(targets_dict[t.column] for t in targets)\n            self.unref_alias(joins.pop())\n        return targets, joins[-1], joins\n\n    @classmethod\n    def _gen_cols(cls, exprs, include_external=False, resolve_refs=True):\n        for expr in exprs:\n            if isinstance(expr, Col):\n                yield expr\n            elif include_external and callable(\n                getattr(expr, \"get_external_cols\", None)\n            ):\n                yield from expr.get_external_cols()\n            elif hasattr(expr, \"get_source_expressions\"):\n                if not resolve_refs and isinstance(expr, Ref):\n                    continue\n                yield from cls._gen_cols(\n                    expr.get_source_expressions(),\n                    include_external=include_external,\n                    resolve_refs=resolve_refs,\n                )\n\n    @classmethod\n    def _gen_col_aliases(cls, exprs):\n        yield from (expr.alias for expr in cls._gen_cols(exprs))\n\n    def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):\n        annotation = self.annotations.get(name)\n        if annotation is not None:\n            if not allow_joins:\n                for alias in self._gen_col_aliases([annotation]):\n                    if isinstance(self.alias_map[alias], Join):\n                        raise FieldError(\n                            \"Joined field references are not permitted in this query\"\n                        )\n            if summarize:\n                # Summarize currently means we are doing an aggregate() query\n                # which is executed as a wrapped subquery if any of the\n                # aggregate() elements reference an existing annotation. In\n                # that case we need to return a Ref to the subquery's\n                # annotation.\n                if name not in self.annotation_select:\n                    raise FieldError(\n                        \"Cannot aggregate over the '%s' alias. Use annotate() \"\n                        \"to promote it.\" % name\n                    )\n                return Ref(name, self.annotation_select[name])\n            else:\n                return annotation\n        else:\n            field_list = name.split(LOOKUP_SEP)\n            annotation = self.annotations.get(field_list[0])\n            if annotation is not None:\n                for transform in field_list[1:]:\n                    annotation = self.try_transform(annotation, transform)\n                return annotation\n            join_info = self.setup_joins(\n                field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse\n            )\n            targets, final_alias, join_list = self.trim_joins(\n                join_info.targets, join_info.joins, join_info.path\n            )\n            if not allow_joins and len(join_list) > 1:\n                raise FieldError(\n                    \"Joined field references are not permitted in this query\"\n                )\n            if len(targets) > 1:\n                raise FieldError(\n                    \"Referencing multicolumn fields with F() objects isn't supported\"\n                )\n            # Verify that the last lookup in name is a field or a transform:\n            # transform_function() raises FieldError if not.\n            transform = join_info.transform_function(targets[0], final_alias)\n            if reuse is not None:\n                reuse.update(join_list)\n            return transform\n\n    def split_exclude(self, filter_expr, can_reuse, names_with_path):\n        \"\"\"\n        When doing an exclude against any kind of N-to-many relation, we need\n        to use a subquery. This method constructs the nested query, given the\n        original exclude filter (filter_expr) and the portion up to the first\n        N-to-many relation field.\n\n        For example, if the origin filter is ~Q(child__name='foo'), filter_expr\n        is ('child__name', 'foo') and can_reuse is a set of joins usable for\n        filters in the original query.\n\n        We will turn this into equivalent of:\n            WHERE NOT EXISTS(\n                SELECT 1\n                FROM child\n                WHERE name = 'foo' AND child.parent_id = parent.id\n                LIMIT 1\n            )\n        \"\"\"\n        # Generate the inner query.\n        query = self.__class__(self.model)\n        query._filtered_relations = self._filtered_relations\n        filter_lhs, filter_rhs = filter_expr\n        if isinstance(filter_rhs, OuterRef):\n            filter_rhs = OuterRef(filter_rhs)\n        elif isinstance(filter_rhs, F):\n            filter_rhs = OuterRef(filter_rhs.name)\n        query.add_filter(filter_lhs, filter_rhs)\n        query.clear_ordering(force=True)\n        # Try to have as simple as possible subquery -> trim leading joins from\n        # the subquery.\n        trimmed_prefix, contains_louter = query.trim_start(names_with_path)\n\n        col = query.select[0]\n        select_field = col.target\n        alias = col.alias\n        if alias in can_reuse:\n            pk = select_field.model._meta.pk\n            # Need to add a restriction so that outer query's filters are in\n            # effect for the subquery, too.\n            query.bump_prefix(self)\n            lookup_class = select_field.get_lookup(\"exact\")\n            # Note that the query.select[0].alias is different from alias\n            # due to bump_prefix above.\n            lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias))\n            query.where.add(lookup, AND)\n            query.external_aliases[alias] = True\n        else:\n            lookup_class = select_field.get_lookup(\"exact\")\n            lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix))\n            query.where.add(lookup, AND)\n\n        condition, needed_inner = self.build_filter(Exists(query))\n\n        if contains_louter:\n            or_null_condition, _ = self.build_filter(\n                (\"%s__isnull\" % trimmed_prefix, True),\n                current_negated=True,\n                branch_negated=True,\n                can_reuse=can_reuse,\n            )\n            condition.add(or_null_condition, OR)\n            # Note that the end result will be:\n            #   NOT EXISTS (inner_q) OR outercol IS NULL\n            # this might look crazy but due to how NULL works, this seems to be\n            # correct. If the IS NULL check is removed, then if outercol\n            # IS NULL we will not match the row.\n        return condition, needed_inner\n\n    def set_empty(self):\n        self.where.add(NothingNode(), AND)\n        for query in self.combined_queries:\n            query.set_empty()\n\n    def is_empty(self):\n        return any(isinstance(c, NothingNode) for c in self.where.children)\n\n    def set_limits(self, low=None, high=None):\n        \"\"\"\n        Adjust the limits on the rows retrieved. Use low/high to set these,\n        as it makes it more Pythonic to read and write. When the SQL query is\n        created, convert them to the appropriate offset and limit values.\n\n        Apply any limits passed in here to the existing constraints. Add low\n        to the current low value and clamp both to any existing high value.\n        \"\"\"\n        if high is not None:\n            if self.high_mark is not None:\n                self.high_mark = min(self.high_mark, self.low_mark + high)\n            else:\n                self.high_mark = self.low_mark + high\n        if low is not None:\n            if self.high_mark is not None:\n                self.low_mark = min(self.high_mark, self.low_mark + low)\n            else:\n                self.low_mark = self.low_mark + low\n\n        if self.low_mark == self.high_mark:\n            self.set_empty()\n\n    def clear_limits(self):\n        \"\"\"Clear any existing limits.\"\"\"\n        self.low_mark, self.high_mark = 0, None\n\n    @property\n    def is_sliced(self):\n        return self.low_mark != 0 or self.high_mark is not None\n\n    def has_limit_one(self):\n        return self.high_mark is not None and (self.high_mark - self.low_mark) == 1\n\n    def can_filter(self):\n        \"\"\"\n        Return True if adding filters to this instance is still possible.\n\n        Typically, this means no limits or offsets have been put on the\n        results.\n        \"\"\"\n        return not self.is_sliced\n\n    def clear_select_clause(self):\n        \"\"\"Remove all fields from SELECT clause.\"\"\"\n        self.select = ()\n        self.default_cols = False\n        self.select_related = False\n        self.set_extra_mask(())\n        self.set_annotation_mask(())\n        self.selected = None\n\n    def clear_select_fields(self):\n        \"\"\"\n        Clear the list of fields to select (but not extra_select columns).\n        Some queryset types completely replace any existing list of select\n        columns.\n        \"\"\"\n        self.select = ()\n        self.values_select = ()\n        self.selected = None\n\n    def add_select_col(self, col, name):\n        self.select += (col,)\n        self.values_select += (name,)\n        self.selected[name] = len(self.select) - 1\n\n    def set_select(self, cols):\n        self.default_cols = False\n        self.select = tuple(cols)\n\n    def add_distinct_fields(self, *field_names):\n        \"\"\"\n        Add and resolve the given fields to the query's \"distinct on\" clause.\n        \"\"\"\n        self.distinct_fields = field_names\n        self.distinct = True\n\n    def add_fields(self, field_names, allow_m2m=True):\n        \"\"\"\n        Add the given (model) fields to the select set. Add the field names in\n        the order specified.\n        \"\"\"\n        alias = self.get_initial_alias()\n        opts = self.get_meta()\n\n        try:\n            cols = []\n            for name in field_names:\n                # Join promotion note - we must not remove any rows here, so\n                # if there is no existing joins, use outer join.\n                join_info = self.setup_joins(\n                    name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m\n                )\n                targets, final_alias, joins = self.trim_joins(\n                    join_info.targets,\n                    join_info.joins,\n                    join_info.path,\n                )\n                if len(targets) > 1:\n                    transformed_targets = [\n                        join_info.transform_function(target, final_alias)\n                        for target in targets\n                    ]\n                    cols.append(\n                        ColPairs(\n                            final_alias if self.alias_cols else None,\n                            [col.target for col in transformed_targets],\n                            [col.output_field for col in transformed_targets],\n                            join_info.final_field,\n                        )\n                    )\n                else:\n                    cols.append(join_info.transform_function(targets[0], final_alias))\n            if cols:\n                self.set_select(cols)\n        except MultiJoin:\n            raise FieldError(\"Invalid field name: '%s'\" % name)\n        except FieldError:\n            if LOOKUP_SEP in name:\n                # For lookups spanning over relationships, show the error\n                # from the model on which the lookup failed.\n                raise\n            else:\n                names = sorted(\n                    [\n                        *get_field_names_from_opts(opts),\n                        *self.extra,\n                        *self.annotation_select,\n                        *self._filtered_relations,\n                    ]\n                )\n                raise FieldError(\n                    \"Cannot resolve keyword %r into field. \"\n                    \"Choices are: %s\" % (name, \", \".join(names))\n                )\n\n    def add_ordering(self, *ordering):\n        \"\"\"\n        Add items from the 'ordering' sequence to the query's \"order by\"\n        clause. These items are either field names (not column names) --\n        possibly with a direction prefix ('-' or '?') -- or OrderBy\n        expressions.\n\n        If 'ordering' is empty, clear all ordering from the query.\n        \"\"\"\n        errors = []\n        for item in ordering:\n            if isinstance(item, str):\n                if item == \"?\":\n                    continue\n                item = item.removeprefix(\"-\")\n                if item in self.annotations:\n                    continue\n                if self.extra and item in self.extra:\n                    continue\n                # names_to_path() validates the lookup. A descriptive\n                # FieldError will be raise if it's not.\n                self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)\n            elif not hasattr(item, \"resolve_expression\"):\n                errors.append(item)\n            if getattr(item, \"contains_aggregate\", False):\n                raise FieldError(\n                    \"Using an aggregate in order_by() without also including \"\n                    \"it in annotate() is not allowed: %s\" % item\n                )\n        if errors:\n            raise FieldError(\"Invalid order_by arguments: %s\" % errors)\n        if ordering:\n            self.order_by += ordering\n        else:\n            self.default_ordering = False\n\n    @property\n    def orderby_issubset_groupby(self):\n        if self.extra_order_by:\n            # Raw SQL from extra(order_by=...) can't be reliably compared\n            # against resolved OrderBy/Col expressions. Treat as not a subset.\n            return False\n        if self.group_by in (None, True):\n            # There is either no aggregation at all (None), or the group by\n            # is generated automatically from model fields (True), in which\n            # case the order by is necessarily a subset of them.\n            return True\n        if not self.order_by:\n            # Although an empty set is always a subset, there's no point in\n            # clearing ordering when there isn't any. Avoid the clone() below.\n            return True\n        # Don't pollute the original query (might disrupt joins).\n        q = self.clone()\n        order_by_set = set()\n        for order_by in q.order_by:\n            if hasattr(order_by, \"resolve_expression\"):\n                order_by_set.add(order_by.resolve_expression(q))\n            elif order_by == \"?\":\n                # Random ordering can't be compared against group by.\n                return False\n            else:\n                order_by_set.add(F(order_by.removeprefix(\"-\")).resolve_expression(q))\n        return order_by_set.issubset(self.group_by)\n\n    def clear_ordering(self, force=False, clear_default=True):\n        \"\"\"\n        Remove any ordering settings if the current query allows it without\n        side effects, set 'force' to True to clear the ordering regardless.\n        If 'clear_default' is True, there will be no ordering in the resulting\n        query (not even the model's default).\n        \"\"\"\n        if not force and (\n            self.is_sliced or self.distinct_fields or self.select_for_update\n        ):\n            return\n        self.order_by = ()\n        self.extra_order_by = ()\n        if clear_default:\n            self.default_ordering = False\n        # Ordering is cleared on combined queries with clear_default=False\n        # when union() and analogues are called, so percolate any possible\n        # clear_default=True.\n        for query in self.combined_queries:\n            query.clear_ordering(force=False, clear_default=clear_default)\n\n    def set_group_by(self, allow_aliases=True):\n        \"\"\"\n        Expand the GROUP BY clause required by the query.\n\n        This will usually be the set of all non-aggregate fields in the\n        return data. If the database backend supports grouping by the\n        primary key, and the query would be equivalent, the optimization\n        will be made automatically.\n        \"\"\"\n        if allow_aliases and self.values_select:\n            # If grouping by aliases is allowed assign selected value aliases\n            # by moving them to annotations.\n            group_by_annotations = {}\n            values_select = {}\n            for alias, expr in zip(self.values_select, self.select):\n                if isinstance(expr, Col):\n                    values_select[alias] = expr\n                else:\n                    group_by_annotations[alias] = expr\n            self.annotations = {**group_by_annotations, **self.annotations}\n            self.append_annotation_mask(group_by_annotations)\n            self.select = tuple(values_select.values())\n            self.values_select = tuple(values_select)\n            if self.selected is not None:\n                for index, value_select in enumerate(values_select):\n                    self.selected[value_select] = index\n        group_by = list(self.select)\n        for alias, annotation in self.annotation_select.items():\n            if not (group_by_cols := annotation.get_group_by_cols()):\n                continue\n            if allow_aliases and not annotation.contains_aggregate:\n                group_by.append(Ref(alias, annotation))\n            else:\n                group_by.extend(group_by_cols)\n        self.group_by = tuple(group_by)\n\n    def add_select_related(self, fields):\n        \"\"\"\n        Set up the select_related data structure so that we only select\n        certain related models (as opposed to all models, when\n        self.select_related=True).\n        \"\"\"\n        if isinstance(self.select_related, bool):\n            field_dict = {}\n        else:\n            field_dict = self.select_related\n        for field in fields:\n            d = field_dict\n            for part in field.split(LOOKUP_SEP):\n                d = d.setdefault(part, {})\n        self.select_related = field_dict\n\n    def add_extra(self, select, select_params, where, params, tables, order_by):\n        \"\"\"\n        Add data to the various extra_* attributes for user-created additions\n        to the query.\n        \"\"\"\n        if select:\n            # We need to pair any placeholder markers in the 'select'\n            # dictionary with their parameters in 'select_params' so that\n            # subsequent updates to the select dictionary also adjust the\n            # parameters appropriately.\n            select_pairs = {}\n            if select_params:\n                param_iter = iter(select_params)\n            else:\n                param_iter = iter([])\n            for name, entry in select.items():\n                self.check_alias(name)\n                entry = str(entry)\n                entry_params = []\n                pos = entry.find(\"%s\")\n                while pos != -1:\n                    if pos == 0 or entry[pos - 1] != \"%\":\n                        entry_params.append(next(param_iter))\n                    pos = entry.find(\"%s\", pos + 2)\n                select_pairs[name] = (entry, entry_params)\n            self.extra.update(select_pairs)\n        if where or params:\n            self.where.add(ExtraWhere(where, params), AND)\n        if tables:\n            self.extra_tables += tuple(tables)\n        if order_by:\n            self.extra_order_by = order_by\n\n    def clear_deferred_loading(self):\n        \"\"\"Remove any fields from the deferred loading set.\"\"\"\n        self.deferred_loading = (frozenset(), True)\n\n    def add_deferred_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        exclude from loading from the database when automatic column selection\n        is done. Add the new field names to any existing field names that\n        are deferred (or removed from any existing field names that are marked\n        as the only ones for immediate loading).\n        \"\"\"\n        # Fields on related models are stored in the literal double-underscore\n        # format, so that we can use a set datastructure. We do the foo__bar\n        # splitting and handling when computing the SQL column names (as part\n        # of get_columns()).\n        existing, defer = self.deferred_loading\n        if defer:\n            # Add to existing deferred names.\n            self.deferred_loading = existing.union(field_names), True\n        else:\n            # Remove names from the set of any existing \"immediate load\" names.\n            if new_existing := existing.difference(field_names):\n                self.deferred_loading = new_existing, False\n            else:\n                self.clear_deferred_loading()\n                if new_only := set(field_names).difference(existing):\n                    self.deferred_loading = new_only, True\n\n    def add_immediate_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        retrieve when the SQL is executed (\"immediate loading\" fields). The\n        field names replace any existing immediate loading field names. If\n        there are field names already specified for deferred loading, remove\n        those names from the new field_names before storing the new names\n        for immediate loading. (That is, immediate loading overrides any\n        existing immediate values, but respects existing deferrals.)\n        \"\"\"\n        existing, defer = self.deferred_loading\n        field_names = set(field_names)\n        if \"pk\" in field_names:\n            field_names.remove(\"pk\")\n            field_names.add(self.get_meta().pk.name)\n\n        if defer:\n            # Remove any existing deferred names from the current set before\n            # setting the new names.\n            self.deferred_loading = field_names.difference(existing), False\n        else:\n            # Replace any existing \"immediate load\" field names.\n            self.deferred_loading = frozenset(field_names), False\n\n    def set_annotation_mask(self, names):\n        \"\"\"Set the mask of annotations that will be returned by the SELECT.\"\"\"\n        if names is None:\n            self.annotation_select_mask = None\n        else:\n            self.annotation_select_mask = set(names)\n            if self.selected:\n                # Prune the masked annotations.\n                self.selected = {\n                    key: value\n                    for key, value in self.selected.items()\n                    if not isinstance(value, str)\n                    or value in self.annotation_select_mask\n                }\n                # Append the unmasked annotations.\n                for name in names:\n                    self.selected[name] = name\n        self._annotation_select_cache = None\n\n    def append_annotation_mask(self, names):\n        if self.annotation_select_mask is not None:\n            self.set_annotation_mask(self.annotation_select_mask.union(names))\n\n    def set_extra_mask(self, names):\n        \"\"\"\n        Set the mask of extra select items that will be returned by SELECT.\n        Don't remove them from the Query since they might be used later.\n        \"\"\"\n        if names is None:\n            self.extra_select_mask = None\n        else:\n            self.extra_select_mask = set(names)\n        self._extra_select_cache = None\n\n    @property\n    def has_select_fields(self):\n        return self.selected is not None\n\n    def set_values(self, fields):\n        self.select_related = False\n        self.clear_deferred_loading()\n        self.clear_select_fields()\n\n        selected = {}\n        if fields:\n            for field in fields:\n                self.check_alias(field)\n            field_names = []\n            extra_names = []\n            annotation_names = []\n            if not self.extra and not self.annotations:\n                # Shortcut - if there are no extra or annotations, then\n                # the values() clause must be just field names.\n                field_names = list(fields)\n                selected = dict(zip(fields, range(len(fields))))\n            else:\n                self.default_cols = False\n                for f in fields:\n                    if extra := self.extra_select.get(f):\n                        extra_names.append(f)\n                        selected[f] = RawSQL(*extra)\n                    elif f in self.annotation_select:\n                        annotation_names.append(f)\n                        selected[f] = f\n                    elif f in self.annotations:\n                        if self.annotation_select:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. It was excluded \"\n                                f\"by a previous values() or values_list() call. \"\n                                f\"Include '{f}' in that call to select it.\"\n                            )\n                        else:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. Use annotate() \"\n                                f\"to promote it.\"\n                            )\n                    else:\n                        # Call `names_to_path` to ensure a FieldError including\n                        # annotations about to be masked as valid choices if\n                        # `f` is not resolvable.\n                        if self.annotation_select:\n                            self.names_to_path(f.split(LOOKUP_SEP), self.model._meta)\n                        selected[f] = len(field_names)\n                        field_names.append(f)\n            self.set_extra_mask(extra_names)\n            self.set_annotation_mask(annotation_names)\n        else:\n            field_names = [f.attname for f in self.model._meta.concrete_fields]\n            selected = dict.fromkeys(field_names, None)\n        # Selected annotations must be known before setting the GROUP BY\n        # clause.\n        if self.group_by is True:\n            self.add_fields(\n                (f.attname for f in self.model._meta.concrete_fields), False\n            )\n            # Disable GROUP BY aliases to avoid orphaning references to the\n            # SELECT clause which is about to be cleared.\n            self.set_group_by(allow_aliases=False)\n            self.clear_select_fields()\n        elif self.group_by:\n            # Resolve GROUP BY annotation references if they are not part of\n            # the selected fields anymore.\n            group_by = []\n            for expr in self.group_by:\n                if isinstance(expr, Ref) and expr.refs not in selected:\n                    expr = self.annotations[expr.refs]\n                group_by.append(expr)\n            self.group_by = tuple(group_by)\n\n        self.values_select = tuple(field_names)\n        self.add_fields(field_names, True)\n        self.selected = selected if fields else None\n\n    @property\n    def annotation_select(self):\n        \"\"\"\n        Return the dictionary of aggregate columns that are not masked and\n        should be used in the SELECT clause. Cache this result for performance.\n        \"\"\"\n        if self._annotation_select_cache is not None:\n            return self._annotation_select_cache\n        elif not self.annotations:\n            return {}\n        elif self.annotation_select_mask is not None:\n            self._annotation_select_cache = {\n                k: v\n                for k, v in self.annotations.items()\n                if k in self.annotation_select_mask\n            }\n            return self._annotation_select_cache\n        else:\n            return self.annotations\n\n    @property\n    def extra_select(self):\n        if self._extra_select_cache is not None:\n            return self._extra_select_cache\n        if not self.extra:\n            return {}\n        elif self.extra_select_mask is not None:\n            self._extra_select_cache = {\n                k: v for k, v in self.extra.items() if k in self.extra_select_mask\n            }\n            return self._extra_select_cache\n        else:\n            return self.extra\n\n    def trim_start(self, names_with_path):\n        \"\"\"\n        Trim joins from the start of the join path. The candidates for trim\n        are the PathInfos in names_with_path structure that are m2m joins.\n\n        Also set the select column so the start matches the join.\n\n        This method is meant to be used for generating the subquery joins &\n        cols in split_exclude().\n\n        Return a lookup usable for doing outerq.filter(lookup=self) and a\n        boolean indicating if the joins in the prefix contain a LEFT OUTER\n        join.\n        \"\"\"\n        all_paths = []\n        for _, paths in names_with_path:\n            all_paths.extend(paths)\n        contains_louter = False\n        # Trim and operate only on tables that were generated for\n        # the lookup part of the query. That is, avoid trimming\n        # joins generated for F() expressions.\n        lookup_tables = [\n            t for t in self.alias_map if t in self._lookup_joins or t == self.base_table\n        ]\n        for trimmed_paths, path in enumerate(all_paths):\n            if path.m2m:\n                break\n            if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER:\n                contains_louter = True\n            alias = lookup_tables[trimmed_paths]\n            self.unref_alias(alias)\n        # The path.join_field is a Rel, lets get the other side's field\n        join_field = path.join_field.field\n        # Build the filter prefix.\n        paths_in_prefix = trimmed_paths\n        trimmed_prefix = []\n        for name, path in names_with_path:\n            if paths_in_prefix - len(path) < 0:\n                break\n            trimmed_prefix.append(name)\n            paths_in_prefix -= len(path)\n        trimmed_prefix.append(join_field.foreign_related_fields[0].name)\n        trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)\n        # Lets still see if we can trim the first join from the inner query\n        # (that is, self). We can't do this for:\n        # - LEFT JOINs because we would miss those rows that have nothing on\n        #   the outer side,\n        # - INNER JOINs from filtered relations because we would miss their\n        #   filters.\n        first_join = self.alias_map[lookup_tables[trimmed_paths + 1]]\n        if first_join.join_type != LOUTER and not first_join.filtered_relation:\n            select_fields = [r[0] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths + 1]\n            self.unref_alias(lookup_tables[trimmed_paths])\n            extra_restriction = join_field.get_extra_restriction(\n                None, lookup_tables[trimmed_paths + 1]\n            )\n            if extra_restriction:\n                self.where.add(extra_restriction, AND)\n        else:\n            # TODO: It might be possible to trim more joins from the start of\n            # the inner query if it happens to have a longer join chain\n            # containing the values in select_fields. Lets punt this one for\n            # now.\n            select_fields = [r[1] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths]\n        # The found starting point is likely a join_class instead of a\n        # base_table_class reference. But the first entry in the query's FROM\n        # clause must not be a JOIN.\n        for table in self.alias_map:\n            if self.alias_refcount[table] > 0:\n                self.alias_map[table] = self.base_table_class(\n                    self.alias_map[table].table_name,\n                    table,\n                )\n                break\n        self.set_select([f.get_col(select_alias) for f in select_fields])\n        return trimmed_prefix, contains_louter\n\n    def is_nullable(self, field):\n        \"\"\"\n        Check if the given field should be treated as nullable.\n\n        Some backends treat '' as null and Django treats such fields as\n        nullable for those backends. In such situations field.null can be\n        False even if we should treat the field as nullable.\n        \"\"\"\n        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have\n        # (nor should it have) knowledge of which connection is going to be\n        # used. The proper fix would be to defer all decisions where\n        # is_nullable() is needed to the compiler stage, but that is not easy\n        # to do currently.\n        return field.null or (\n            field.empty_strings_allowed\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-d737c5fea4d295f9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "8095f2c2710717b23a92c98ef7dfab2b0245c40613ffc8189666e500dd1d09ec", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 2605, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__Query__9e38d456.py", "order": 8, "original_content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "parent_variant_id": "pyint-82246794d74c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/query.py#L232-L2792", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 1}, "unit_kind": "class", "unit_name": "Query", "variant_id": "pyint-37439e38d456-I08", "group_id": "py-d737c5fea4d295f9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 289, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-31a818c5a811-I09", "source": "import copy\nimport difflib\nimport functools\nimport sys\nimport warnings\nfrom collections import Counter, namedtuple\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom itertools import chain, count, product\nfrom string import ascii_uppercase\nfrom django.core.exceptions import FieldDoesNotExist, FieldError\nfrom django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections\nfrom django.db.models.aggregates import Count\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import (\n    BaseExpression,\n    Col,\n    ColPairs,\n    Exists,\n    F,\n    OuterRef,\n    RawSQL,\n    Ref,\n    ResolvedOuterRef,\n    Value,\n)\nfrom django.db.models.fields import Field\nfrom django.db.models.lookups import Lookup\nfrom django.db.models.query_utils import (\n    Q,\n    check_rel_lookup_compatibility,\n    refs_expression,\n)\nfrom django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE\nfrom django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin\nfrom django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode\nfrom django.utils.deprecation import RemovedInDjango70Warning\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.tree import Node\nfrom django.utils.warnings import django_file_prefixes\n\nclass Query(BaseExpression):\n    \"\"\"A single SQL query.\"\"\"\n\n    alias_prefix = \"T\"\n    empty_result_set_value = None\n    subq_aliases = frozenset([alias_prefix])\n\n    compiler = \"SQLCompiler\"\n\n    base_table_class = BaseTable\n    join_class = Join\n\n    default_cols = True\n    default_ordering = True\n    standard_ordering = True\n\n    filter_is_sticky = False\n    subquery = False\n    contains_subquery = False\n\n    # SQL-related attributes.\n    # Select and related select clauses are expressions to use in the SELECT\n    # clause of the query. The select is used for cases where we want to set up\n    # the select clause to contain other than default fields (values(),\n    # subqueries...). Note that annotations go to annotations dictionary.\n    select = ()\n    # The group_by attribute can have one of the following forms:\n    #  - None: no group by at all in the query\n    #  - A tuple of expressions: group by (at least) those expressions.\n    #    String refs are also allowed for now.\n    #  - True: group by all select fields of the model\n    # See compiler.get_group_by() for details.\n    group_by = None\n    order_by = ()\n    low_mark = 0  # Used for offset/limit.\n    high_mark = None  # Used for offset/limit.\n    distinct = False\n    distinct_fields = ()\n    select_for_update = False\n    select_for_update_nowait = False\n    select_for_update_skip_locked = False\n    select_for_update_of = ()\n    select_for_no_key_update = False\n    select_related = False\n    # Arbitrary limit for select_related to prevents infinite recursion.\n    max_depth = 5\n    # Holds the selects defined by a call to values() or values_list()\n    # excluding annotation_select and extra_select.\n    values_select = ()\n    selected = None\n\n    # SQL annotation-related attributes.\n    annotation_select_mask = None\n    _annotation_select_cache = None\n\n    # Set combination attributes.\n    combinator = None\n    combinator_all = False\n    combined_queries = ()\n\n    # These are for extensions. The contents are more or less appended verbatim\n    # to the appropriate clause.\n    extra_select_mask = None\n    _extra_select_cache = None\n\n    extra_tables = ()\n    extra_order_by = ()\n\n    # A tuple that is a set of model field names and either True, if these are\n    # the fields to defer, or False if these are the only fields to load.\n    deferred_loading = (frozenset(), True)\n\n    explain_info = None\n\n    def __init__(self, model, alias_cols=True):\n        self.model = model\n        self.alias_refcount = {}\n        # alias_map is the most important data structure regarding joins.\n        # It's used for recording which joins exist in the query and what\n        # types they are. The key is the alias of the joined table (possibly\n        # the table name) and the value is a Join-like object (see\n        # sql.datastructures.Join for more information).\n        self.alias_map = {}\n        # Whether to provide alias to columns during reference resolving.\n        self.alias_cols = alias_cols\n        # Sometimes the query contains references to aliases in outer queries\n        # (as a result of split_exclude). Correct alias quoting needs to know\n        # these aliases too. Map external tables to whether they are aliased.\n        self.external_aliases = {}\n        self.table_map = {}  # Maps table names to list of aliases.\n        self.used_aliases = set()\n\n        self.where = WhereNode()\n        # Maps alias -> Annotation Expression.\n        self.annotations = {}\n        # These are for extensions. The contents are more or less appended\n        # verbatim to the appropriate clause.\n        self.extra = {}  # Maps col_alias -> (col_sql, params).\n\n        self._filtered_relations = {}\n\n    @property\n    def output_field(self):\n        if len(self.select) == 1:\n            select = self.select[0]\n            return getattr(select, \"target\", None) or select.field\n        elif len(self.annotation_select) == 1:\n            return next(iter(self.annotation_select.values())).output_field\n\n    @cached_property\n    def base_table(self):\n        for alias in self.alias_map:\n            return alias\n\n    def __str__(self):\n        \"\"\"\n        Return the query as a string of SQL with the parameter values\n        substituted in (use sql_with_params() to see the unsubstituted string).\n\n        Parameter values won't necessarily be quoted correctly, since that is\n        done by the database interface at execution time.\n        \"\"\"\n        sql, params = self.sql_with_params()\n        return sql % params\n\n    def sql_with_params(self):\n        \"\"\"\n        Return the query as an SQL string and the parameters that will be\n        substituted into the query.\n        \"\"\"\n        return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()\n\n    def __deepcopy__(self, memo):\n        \"\"\"Limit the amount of work when a Query is deepcopied.\"\"\"\n        result = self.clone()\n        memo[id(self)] = result\n        return result\n\n    def get_compiler(self, using=None, connection=None, elide_empty=True):\n        if using is None and connection is None:\n            raise ValueError(\"Need either using or connection\")\n        if using:\n            connection = connections[using]\n        return connection.ops.compiler(self.compiler)(\n            self, connection, using, elide_empty\n        )\n\n    def get_meta(self):\n        \"\"\"\n        Return the Options instance (the model._meta) from which to start\n        processing. Normally, this is self.model._meta, but it can be changed\n        by subclasses.\n        \"\"\"\n        if self.model:\n            return self.model._meta\n\n    def clone(self):\n        \"\"\"\n        Return a copy of the current Query. A lightweight alternative to\n        deepcopy().\n        \"\"\"\n        obj = Empty()\n        obj.__class__ = self.__class__\n        # Copy references to everything.\n        obj.__dict__ = self.__dict__.copy()\n        # Clone attributes that can't use shallow copy.\n        obj.alias_refcount = self.alias_refcount.copy()\n        obj.alias_map = self.alias_map.copy()\n        obj.external_aliases = self.external_aliases.copy()\n        obj.table_map = self.table_map.copy()\n        obj.where = self.where.clone()\n        obj.annotations = self.annotations.copy()\n        if self.annotation_select_mask is not None:\n            obj.annotation_select_mask = self.annotation_select_mask.copy()\n        if self.combined_queries:\n            obj.combined_queries = tuple(\n                [query.clone() for query in self.combined_queries]\n            )\n        # _annotation_select_cache cannot be copied, as doing so breaks the\n        # (necessary) state in which both annotations and\n        # _annotation_select_cache point to the same underlying objects.\n        # It will get re-populated in the cloned queryset the next time it's\n        # used.\n        obj._annotation_select_cache = None\n        obj.extra = self.extra.copy()\n        if self.extra_select_mask is not None:\n            obj.extra_select_mask = self.extra_select_mask.copy()\n        if self._extra_select_cache is not None:\n            obj._extra_select_cache = self._extra_select_cache.copy()\n        if self.select_related is not False:\n            # Use deepcopy because select_related stores fields in nested\n            # dicts.\n            obj.select_related = copy.deepcopy(obj.select_related)\n        if \"subq_aliases\" in self.__dict__:\n            obj.subq_aliases = self.subq_aliases.copy()\n        obj.used_aliases = self.used_aliases.copy()\n        obj._filtered_relations = self._filtered_relations.copy()\n        # Clear the cached_property, if it exists.\n        obj.__dict__.pop(\"base_table\", None)\n        return obj\n\n    def chain(self, klass=None):\n        \"\"\"\n        Return a copy of the current Query that's ready for another operation.\n        The klass argument changes the type of the Query, e.g. UpdateQuery.\n        \"\"\"\n        obj = self.clone()\n        if klass and obj.__class__ != klass:\n            obj.__class__ = klass\n        if not obj.filter_is_sticky:\n            obj.used_aliases = set()\n        obj.filter_is_sticky = False\n        if hasattr(obj, \"_setup_query\"):\n            obj._setup_query()\n        return obj\n\n    def relabeled_clone(self, change_map):\n        clone = self.clone()\n        clone.change_aliases(change_map)\n        return clone\n\n    def _get_col(self, target, field, alias):\n        if not self.alias_cols:\n            alias = None\n        return target.get_col(alias, field)\n\n    def get_aggregation(self, using, aggregate_exprs):\n        \"\"\"\n        Return the dictionary with the values of the existing aggregations.\n        \"\"\"\n        if not aggregate_exprs:\n            return {}\n        # Store annotation mask prior to temporarily adding aggregations for\n        # resolving purpose to facilitate their subsequent removal.\n        refs_subquery = False\n        refs_window = False\n        replacements = {}\n        annotation_select_mask = self.annotation_select_mask\n        for alias, aggregate_expr in aggregate_exprs.items():\n            self.check_alias(alias)\n            aggregate = aggregate_expr.resolve_expression(\n                self, allow_joins=True, reuse=None, summarize=True\n            )\n            if not aggregate.contains_aggregate:\n                raise TypeError(\"%s is not an aggregate expression\" % alias)\n            # Temporarily add aggregate to annotations to allow remaining\n            # members of `aggregates` to resolve against each others.\n            self.append_annotation_mask([alias])\n            aggregate_refs = aggregate.get_refs()\n            refs_subquery |= any(\n                getattr(self.annotations[ref], \"contains_subquery\", False)\n                for ref in aggregate_refs\n            )\n            refs_window |= any(\n                getattr(self.annotations[ref], \"contains_over_clause\", True)\n                for ref in aggregate_refs\n            )\n            aggregate = aggregate.replace_expressions(replacements)\n            self.annotations[alias] = aggregate\n            replacements[Ref(alias, aggregate)] = aggregate\n        # Stash resolved aggregates now that they have been allowed to resolve\n        # against each other.\n        aggregates = {alias: self.annotations.pop(alias) for alias in aggregate_exprs}\n        self.set_annotation_mask(annotation_select_mask)\n        # Existing usage of aggregation can be determined by the presence of\n        # selected aggregates but also by filters against aliased aggregates.\n        _, having, qualify = self.where.split_having_qualify()\n        has_existing_aggregation = (\n            any(\n                getattr(annotation, \"contains_aggregate\", True)\n                for annotation in self.annotations.values()\n            )\n            or having\n        )\n        set_returning_annotations = {\n            alias\n            for alias, annotation in self.annotation_select.items()\n            if getattr(annotation, \"set_returning\", False)\n        }\n        # Decide if we need to use a subquery.\n        #\n        # Existing aggregations would cause incorrect results as\n        # get_aggregation() must produce just one result and thus must not use\n        # GROUP BY.\n        #\n        # If the query has limit or distinct, or uses set operations, then\n        # those operations must be done in a subquery so that the query\n        # aggregates on the limit and/or distinct results instead of applying\n        # the distinct and limit after the aggregation.\n        if (\n            isinstance(self.group_by, tuple)\n            or self.is_sliced\n            or has_existing_aggregation\n            or refs_subquery\n            or refs_window\n            or qualify\n            or self.distinct\n            or self.combinator\n            or set_returning_annotations\n        ):\n            from django.db.models.sql.subqueries import AggregateQuery\n\n            inner_query = self.clone()\n            inner_query.subquery = True\n            outer_query = AggregateQuery(self.model, inner_query)\n            inner_query.select_for_update = False\n            inner_query.select_related = False\n            inner_query.set_annotation_mask(self.annotation_select)\n            # Queries with distinct_fields need ordering and when a limit is\n            # applied we must take the slice from the ordered query. Otherwise\n            # no need for ordering.\n            if inner_query.orderby_issubset_groupby:\n                inner_query.clear_ordering(force=False)\n            if not inner_query.distinct:\n                # If the inner query uses default select and it has some\n                # aggregate annotations, then we must make sure the inner\n                # query is grouped by the main model's primary key. However,\n                # clearing the select clause can alter results if distinct is\n                # used.\n                if inner_query.default_cols and has_existing_aggregation:\n                    inner_query.group_by = (\n                        self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                    )\n                inner_query.default_cols = False\n                if not qualify and not self.combinator:\n                    # Mask existing annotations that are not referenced by\n                    # aggregates to be pushed to the outer query unless\n                    # filtering against window functions or if the query is\n                    # combined as both would require complex realiasing logic.\n                    annotation_mask = set()\n                    if isinstance(self.group_by, tuple):\n                        for expr in self.group_by:\n                            annotation_mask |= expr.get_refs()\n                    for aggregate in aggregates.values():\n                        annotation_mask |= aggregate.get_refs()\n                    # Avoid eliding expressions that might have an incidence on\n                    # the implicit grouping logic.\n                    for annotation_alias, annotation in self.annotation_select.items():\n                        if annotation.get_group_by_cols():\n                            annotation_mask.add(annotation_alias)\n                    inner_query.set_annotation_mask(annotation_mask)\n                    # Annotations that possibly return multiple rows cannot\n                    # be masked as they might have an incidence on the query.\n                    annotation_mask |= set_returning_annotations\n\n            # Add aggregates to the outer AggregateQuery. This requires making\n            # sure all columns referenced by the aggregates are selected in the\n            # inner query. It is achieved by retrieving all column references\n            # by the aggregates, explicitly selecting them in the inner query,\n            # and making sure the aggregates are repointed to them.\n            col_refs = {}\n            for alias, aggregate in aggregates.items():\n                replacements = {}\n                for col in self._gen_cols([aggregate], resolve_refs=False):\n                    if not (col_ref := col_refs.get(col)):\n                        index = len(col_refs) + 1\n                        col_alias = f\"__col{index}\"\n                        col_ref = Ref(col_alias, col)\n                        col_refs[col] = col_ref\n                        inner_query.add_annotation(col, col_alias)\n                    replacements[col] = col_ref\n                outer_query.annotations[alias] = aggregate.replace_expressions(\n                    replacements\n                )\n            if (\n                inner_query.select == ()\n                and not inner_query.default_cols\n                and not inner_query.annotation_select_mask\n            ):\n                # In case of Model.objects[0:3].count(), there would be no\n                # field selected in the inner query, yet we must use a\n                # subquery. So, make sure at least one field is selected.\n                inner_query.select = (\n                    self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                )\n        else:\n            outer_query = self\n            self.select = ()\n            self.selected = None\n            self.default_cols = False\n            self.extra = {}\n            if self.annotations:\n                # Inline reference to existing annotations and mask them as\n                # they are unnecessary given only the summarized aggregations\n                # are requested.\n                replacements = {\n                    Ref(alias, annotation): annotation\n                    for alias, annotation in self.annotations.items()\n                }\n                self.annotations = {\n                    alias: aggregate.replace_expressions(replacements)\n                    for alias, aggregate in aggregates.items()\n                }\n            else:\n                self.annotations = aggregates\n            self.set_annotation_mask(aggregates)\n\n        empty_set_result = [\n            expression.empty_result_set_value\n            for expression in outer_query.annotation_select.values()\n        ]\n        elide_empty = not any(result is NotImplemented for result in empty_set_result)\n        outer_query.clear_ordering(force=True)\n        outer_query.clear_limits()\n        outer_query.select_for_update = False\n        outer_query.select_related = False\n        compiler = outer_query.get_compiler(using, elide_empty=elide_empty)\n        result = compiler.execute_sql(SINGLE)\n        if result is None:\n            result = empty_set_result\n        else:\n            cols = outer_query.annotation_select.values()\n            converters = compiler.get_converters(cols)\n            rows = compiler.apply_converters((result,), converters)\n            if compiler.has_composite_fields(cols):\n                rows = compiler.composite_fields_to_tuples(rows, cols)\n            result = next(rows)\n\n        return dict(zip(outer_query.annotation_select, result))\n\n    def get_count(self, using):\n        \"\"\"\n        Perform a COUNT() query using the current filter constraints.\n        \"\"\"\n        obj = self.clone()\n        return obj.get_aggregation(using, {\"__count\": Count(\"*\")})[\"__count\"]\n\n    def has_filters(self):\n        return self.where\n\n    def exists(self, limit=True):\n        q = self.clone()\n        if not (q.distinct and q.is_sliced):\n            if q.group_by is True:\n                q.add_fields(\n                    (f.attname for f in self.model._meta.concrete_fields), False\n                )\n                # Disable GROUP BY aliases to avoid orphaning references to the\n                # SELECT clause which is about to be cleared.\n                q.set_group_by(allow_aliases=False)\n            q.clear_select_clause()\n        if q.combined_queries and q.combinator == \"union\":\n            q.combined_queries = tuple(\n                combined_query.exists(limit=False)\n                for combined_query in q.combined_queries\n            )\n        q.clear_ordering(force=True)\n        if limit is True:\n            q.set_limits(high=1)\n        q.add_annotation(Value(1), \"a\")\n        return q\n\n    def has_results(self, using):\n        q = self.exists()\n        compiler = q.get_compiler(using=using)\n        return compiler.has_results()\n\n    def explain(self, using, format=None, **options):\n        q = self.clone()\n        for option_name in options:\n            if (\n                not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)\n                or \"--\" in option_name\n            ):\n                raise ValueError(f\"Invalid option name: {option_name!r}.\")\n        q.explain_info = ExplainInfo(format, options)\n        compiler = q.get_compiler(using=using)\n        return \"\\n\".join(compiler.explain_query())\n\n    def combine(self, rhs, connector):\n        \"\"\"\n        Merge the 'rhs' query into the current one (with any 'rhs' effects\n        being applied *after* (that is, \"to the right of\") anything in the\n        current query. 'rhs' is not modified during a call to this function.\n\n        The 'connector' parameter describes how to connect filters from the\n        'rhs' query.\n        \"\"\"\n        if self.model != rhs.model:\n            raise TypeError(\"Cannot combine queries on two different base models.\")\n        if self.is_sliced:\n            raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n        if self.distinct != rhs.distinct:\n            raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n        if self.distinct_fields != rhs.distinct_fields:\n            raise TypeError(\"Cannot combine queries with different distinct fields.\")\n\n        # If lhs and rhs shares the same alias prefix, it is possible to have\n        # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up\n        # as T4 -> T6 while combining two querysets. To prevent this, change an\n        # alias prefix of the rhs and update current aliases accordingly,\n        # except if the alias is the base table since it must be present in the\n        # query on both sides.\n        initial_alias = self.get_initial_alias()\n        rhs = rhs.clone()\n        rhs.bump_prefix(self, exclude={initial_alias})\n\n        # Work out how to relabel the rhs aliases, if necessary.\n        change_map = {}\n        conjunction = connector == AND\n\n        # Determine which existing joins can be reused. When combining the\n        # query with AND we must recreate all joins for m2m filters. When\n        # combining with OR we can reuse joins. The reason is that in AND\n        # case a single row can't fulfill a condition like:\n        #     revrel__col=1 & revrel__col=2\n        # But, there might be two different related rows matching this\n        # condition. In OR case a single True is enough, so single row is\n        # enough, too.\n        #\n        # Note that we will be creating duplicate joins for non-m2m joins in\n        # the AND case. The results will be correct but this creates too many\n        # joins. This is something that could be fixed later on.\n        reuse = set() if conjunction else set(self.alias_map)\n        joinpromoter = JoinPromoter(connector, 2, False)\n        joinpromoter.add_votes(\n            j for j in self.alias_map if self.alias_map[j].join_type == INNER\n        )\n        rhs_votes = set()\n        # Now, add the joins from rhs query into the new query (skipping base\n        # table).\n        rhs_tables = list(rhs.alias_map)[1:]\n        for alias in rhs_tables:\n            join = rhs.alias_map[alias]\n            # If the left side of the join was already relabeled, use the\n            # updated alias.\n            join = join.relabeled_clone(change_map)\n            new_alias = self.join(join, reuse=reuse)\n            if join.join_type == INNER:\n                rhs_votes.add(new_alias)\n            # We can't reuse the same join again in the query. If we have two\n            # distinct joins for the same connection in rhs query, then the\n            # combined query must have two joins, too.\n            reuse.discard(new_alias)\n            if alias != new_alias:\n                change_map[alias] = new_alias\n            if not rhs.alias_refcount[alias]:\n                # The alias was unused in the rhs query. Unref it so that it\n                # will be unused in the new query, too. We have to add and\n                # unref the alias so that join promotion has information of\n                # the join type for the unused alias.\n                self.unref_alias(new_alias)\n        joinpromoter.add_votes(rhs_votes)\n        joinpromoter.update_join_types(self)\n\n        # Combine subqueries aliases to ensure aliases relabelling properly\n        # handle subqueries when combining where and select clauses.\n        self.subq_aliases |= rhs.subq_aliases\n\n        # Now relabel a copy of the rhs where-clause and add it to the current\n        # one.\n        w = rhs.where.clone()\n        w.relabel_aliases(change_map)\n        self.where.add(w, connector)\n\n        # Selection columns and extra extensions are those provided by 'rhs'.\n        if rhs.select:\n            self.set_select([col.relabeled_clone(change_map) for col in rhs.select])\n        else:\n            self.select = ()\n\n        if connector == OR:\n            # It would be nice to be able to handle this, but the queries don't\n            # really make sense (or return consistent value sets). Not worth\n            # the extra complexity when you can write a real query instead.\n            if self.extra and rhs.extra:\n                raise ValueError(\n                    \"When merging querysets using 'or', you cannot have \"\n                    \"extra(select=...) on both sides.\"\n                )\n        self.extra.update(rhs.extra)\n        extra_select_mask = set()\n        if self.extra_select_mask is not None:\n            extra_select_mask.update(self.extra_select_mask)\n        if rhs.extra_select_mask is not None:\n            extra_select_mask.update(rhs.extra_select_mask)\n        if extra_select_mask:\n            self.set_extra_mask(extra_select_mask)\n        self.extra_tables += rhs.extra_tables\n\n        # Ordering uses the 'rhs' ordering, unless it has none, in which case\n        # the current ordering is used.\n        self.order_by = rhs.order_by or self.order_by\n        self.extra_order_by = rhs.extra_order_by or self.extra_order_by\n\n    def _get_defer_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # All concrete fields and related objects that are not part of the\n        # defer mask must be included. If a relational field is encountered it\n        # gets added to the mask for it be considered if `select_related` and\n        # the cycle continues by recursively calling this function.\n        for field in opts.concrete_fields + opts.related_objects:\n            field_mask = mask.pop(field.name, None)\n            field_att_mask = None\n            if field_attname := getattr(field, \"attname\", None):\n                field_att_mask = mask.pop(field_attname, None)\n            if field_mask is None and field_att_mask is None:\n                select_mask.setdefault(field, {})\n            elif field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                # Virtual fields such as many-to-many and generic foreign keys\n                # cannot be effectively deferred. Historically, they were\n                # allowed to be passed to QuerySet.defer(). Ignore such field\n                # references until a layer of validation at mask alteration\n                # time is eventually implemented.\n                if field.many_to_many:\n                    continue\n                field_select_mask = select_mask.setdefault(field, {})\n                related_model = field.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        # Remaining defer entries must be references to filtered relations\n        # otherwise they are surfaced as missing field errors.\n        for field_name, field_mask in mask.items():\n            if filtered_relation := self._filtered_relations.get(field_name):\n                relation = opts.get_field(filtered_relation.relation_name)\n                field_select_mask = select_mask.setdefault((field_name, relation), {})\n                related_model = relation.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n            else:\n                opts.get_field(field_name)\n        return select_mask\n\n    def _get_only_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # Only include fields mentioned in the mask.\n        for field_name, field_mask in mask.items():\n            field = opts.get_field(field_name)\n            field_select_mask = select_mask.setdefault(field, {})\n            if field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                related_model = field.remote_field.model._meta.concrete_model\n                self._get_only_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        return select_mask\n\n    def get_select_mask(self):\n        \"\"\"\n        Convert the self.deferred_loading data structure to an alternate data\n        structure, describing the field that *will* be loaded. This is used to\n        compute the columns to select from the database and also by the\n        QuerySet class to work out which fields are being initialized on each\n        model. Models that have all their fields included aren't mentioned in\n        the result, only those that have field restrictions in place.\n        \"\"\"\n        field_names, defer = self.deferred_loading\n        if not field_names:\n            return {}\n        mask = {}\n        for field_name in field_names:\n            part_mask = mask\n            for part in field_name.split(LOOKUP_SEP):\n                part_mask = part_mask.setdefault(part, {})\n        opts = self.get_meta()\n        if defer:\n            return self._get_defer_select_mask(opts, mask)\n        return self._get_only_select_mask(opts, mask)\n\n    def table_alias(self, table_name, create=False, filtered_relation=None):\n        \"\"\"\n        Return a table alias for the given table_name and whether this is a\n        new alias or not.\n\n        If 'create' is true, a new alias is always created. Otherwise, the\n        most recently created alias for the table (if one exists) is reused.\n        \"\"\"\n        alias_list = self.table_map.get(table_name)\n        if not create and alias_list:\n            alias = alias_list[0]\n            self.alias_refcount[alias] += 1\n            return alias, False\n\n        # Create a new alias for this table.\n        if alias_list:\n            alias = \"%s%d\" % (self.alias_prefix, len(self.alias_map) + 1)\n            alias_list.append(alias)\n        else:\n            # The first occurrence of a table uses the table name directly.\n            alias = (\n                filtered_relation.alias if filtered_relation is not None else table_name\n            )\n            self.table_map[table_name] = [alias]\n        self.alias_refcount[alias] = 1\n        return alias, True\n\n    def ref_alias(self, alias):\n        \"\"\"Increases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] += 1\n\n    def unref_alias(self, alias, amount=1):\n        \"\"\"Decreases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] -= amount\n\n    def promote_joins(self, aliases):\n        \"\"\"\n        Promote recursively the join type of given aliases and its children to\n        an outer join. If 'unconditional' is False, only promote the join if\n        it is nullable or the parent join is an outer join.\n\n        The children promotion is done to avoid join chains that contain a\n        LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b\n        is promoted, then we must also promote b->c automatically, or otherwise\n        the promotion of a->b doesn't actually change anything in the query\n        results.\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type is None:\n                # This is the base table (first FROM entry) - this table\n                # isn't really joined at all in the query, so we should not\n                # alter its join type.\n                continue\n            # Only the first alias (skipped above) should have None join_type\n            assert self.alias_map[alias].join_type is not None\n            parent_alias = self.alias_map[alias].parent_alias\n            parent_louter = (\n                parent_alias and self.alias_map[parent_alias].join_type == LOUTER\n            )\n            already_louter = self.alias_map[alias].join_type == LOUTER\n            if (self.alias_map[alias].nullable or parent_louter) and not already_louter:\n                self.alias_map[alias] = self.alias_map[alias].promote()\n                # Join type of 'alias' changed, so re-examine all aliases that\n                # refer to this one.\n                aliases.extend(\n                    join\n                    for join in self.alias_map\n                    if self.alias_map[join].parent_alias == alias\n                    and join not in aliases\n                )\n\n    def demote_joins(self, aliases):\n        \"\"\"\n        Change join type from LOUTER to INNER for all joins in aliases.\n\n        Similarly to promote_joins(), this method must ensure no join chains\n        containing first an outer, then an inner join are generated. If we\n        are demoting b->c join in chain a LOUTER b LOUTER c then we must\n        demote a->b automatically, or otherwise the demotion of b->c doesn't\n        actually change anything in the query results. .\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type == LOUTER:\n                self.alias_map[alias] = self.alias_map[alias].demote()\n                parent_alias = self.alias_map[alias].parent_alias\n                if self.alias_map[parent_alias].join_type == INNER:\n                    aliases.append(parent_alias)\n\n    def reset_refcounts(self, to_counts):\n        \"\"\"\n        Reset reference counts for aliases so that they match the value passed\n        in `to_counts`.\n        \"\"\"\n        for alias, cur_refcount in self.alias_refcount.copy().items():\n            unref_amount = cur_refcount - to_counts.get(alias, 0)\n            self.unref_alias(alias, unref_amount)\n\n    def change_aliases(self, change_map):\n        \"\"\"\n        Change the aliases in change_map (which maps old-alias -> new-alias),\n        relabelling any references to them in select columns and the where\n        clause.\n        \"\"\"\n        if not change_map:\n            return self\n        # If keys and values of change_map were to intersect, an alias might be\n        # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending\n        # on their order in change_map.\n        assert set(change_map).isdisjoint(change_map.values())\n\n        # 1. Update references in \"select\" (normal columns plus aliases),\n        # \"group by\" and \"where\".\n        self.where.relabel_aliases(change_map)\n        if isinstance(self.group_by, tuple):\n            self.group_by = tuple(\n                [col.relabeled_clone(change_map) for col in self.group_by]\n            )\n        self.select = tuple([col.relabeled_clone(change_map) for col in self.select])\n        self.annotations = self.annotations and {\n            key: col.relabeled_clone(change_map)\n            for key, col in self.annotations.items()\n        }\n\n        # 2. Rename the alias in the internal table/alias datastructures.\n        for old_alias, new_alias in change_map.items():\n            if old_alias not in self.alias_map:\n                continue\n            alias_data = self.alias_map[old_alias].relabeled_clone(change_map)\n            self.alias_map[new_alias] = alias_data\n            self.alias_refcount[new_alias] = self.alias_refcount[old_alias]\n            del self.alias_refcount[old_alias]\n            del self.alias_map[old_alias]\n\n            table_aliases = self.table_map[alias_data.table_name]\n            for pos, alias in enumerate(table_aliases):\n                if alias == old_alias:\n                    table_aliases[pos] = new_alias\n                    break\n\n        # 3. Rename the direct external aliases and the ones of combined\n        # queries (union, intersection, difference).\n        self.external_aliases = {\n            # Table is aliased or it's being changed and thus is aliased.\n            change_map.get(alias, alias): (aliased or alias in change_map)\n            for alias, aliased in self.external_aliases.items()\n        }\n        for combined_query in self.combined_queries:\n            external_change_map = {\n                alias: aliased\n                for alias, aliased in change_map.items()\n                if alias in combined_query.external_aliases\n            }\n            combined_query.change_aliases(external_change_map)\n\n    def bump_prefix(self, other_query, exclude=None):\n        \"\"\"\n        Change the alias prefix to the next letter in the alphabet in a way\n        that the other query's aliases and this query's aliases will not\n        conflict. Even tables that previously had no alias will get an alias\n        after this call. To prevent changing aliases use the exclude parameter.\n        \"\"\"\n\n        def prefix_gen():\n            \"\"\"\n            Generate a sequence of characters in alphabetical order:\n                -> 'A', 'B', 'C', ...\n\n            When the alphabet is finished, the sequence will continue with the\n            Cartesian product:\n                -> 'AA', 'AB', 'AC', ...\n            \"\"\"\n            alphabet = ascii_uppercase\n            prefix = chr(ord(self.alias_prefix) + 1)\n            yield prefix\n            for n in count(1):\n                seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet\n                for s in product(seq, repeat=n):\n                    yield \"\".join(s)\n                prefix = None\n\n        if self.alias_prefix != other_query.alias_prefix:\n            # No clashes between self and outer query should be possible.\n            return\n\n        # Explicitly avoid infinite loop. The constant divider is based on how\n        # much depth recursive subquery references add to the stack. This value\n        # might need to be adjusted when adding or removing function calls from\n        # the code path in charge of performing these operations.\n        local_recursion_limit = sys.getrecursionlimit() // 16\n        for pos, prefix in enumerate(prefix_gen()):\n            if prefix not in self.subq_aliases:\n                self.alias_prefix = prefix\n                break\n            if pos > local_recursion_limit:\n                raise RecursionError(\n                    \"Maximum recursion depth exceeded: too many subqueries.\"\n                )\n        self.subq_aliases = self.subq_aliases.union([self.alias_prefix])\n        other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases)\n        if exclude is None:\n            exclude = {}\n        self.change_aliases(\n            {\n                alias: \"%s%d\" % (self.alias_prefix, pos)\n                for pos, alias in enumerate(self.alias_map)\n                if alias not in exclude\n            }\n        )\n\n    def get_initial_alias(self):\n        \"\"\"\n        Return the first alias for this query, after increasing its reference\n        count.\n        \"\"\"\n        if self.alias_map:\n            alias = self.base_table\n            self.ref_alias(alias)\n        elif self.model:\n            alias = self.join(self.base_table_class(self.get_meta().db_table, None))\n        else:\n            alias = None\n        return alias\n\n    def count_active_tables(self):\n        \"\"\"\n        Return the number of tables in this query with a non-zero reference\n        count. After execution, the reference counts are zeroed, so tables\n        added in compiler will not be seen by this method.\n        \"\"\"\n        return len([1 for count in self.alias_refcount.values() if count])\n\n    def join(self, join, reuse=None):\n        \"\"\"\n        Return an alias for the 'join', either reusing an existing alias for\n        that join or creating a new one. 'join' is either a base_table_class or\n        join_class.\n\n        The 'reuse' parameter can be either None which means all joins are\n        reusable, or it can be a set containing the aliases that can be reused.\n\n        A join is always created as LOUTER if the lhs alias is LOUTER to make\n        sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new\n        joins are created as LOUTER if the join is nullable.\n        \"\"\"\n        reuse_aliases = [\n            a\n            for a, j in self.alias_map.items()\n            if (reuse is None or a in reuse) and j == join\n        ]\n        if reuse_aliases:\n            if join.table_alias in reuse_aliases:\n                reuse_alias = join.table_alias\n            else:\n                # Reuse the most recent alias of the joined table\n                # (a many-to-many relation may be joined multiple times).\n                reuse_alias = reuse_aliases[-1]\n            self.ref_alias(reuse_alias)\n            return reuse_alias\n\n        # No reuse is possible, so we need a new alias.\n        alias, _ = self.table_alias(\n            join.table_name, create=True, filtered_relation=join.filtered_relation\n        )\n        if join.join_type:\n            if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:\n                join_type = LOUTER\n            else:\n                join_type = INNER\n            join.join_type = join_type\n        join.table_alias = alias\n        self.alias_map[alias] = join\n        if filtered_relation := join.filtered_relation:\n            resolve_reuse = reuse\n            if resolve_reuse is not None:\n                resolve_reuse = set(reuse) | {alias}\n            joins_len = len(self.alias_map)\n            join.filtered_relation = filtered_relation.resolve_expression(\n                self, reuse=resolve_reuse\n            )\n            # Some joins were during expression resolving, they must be present\n            # before the one we just added.\n            if joins_len < len(self.alias_map):\n                self.alias_map[alias] = self.alias_map.pop(alias)\n        return alias\n\n    def join_parent_model(self, opts, model, alias, seen):\n        \"\"\"\n        Make sure the given 'model' is joined in the query. If 'model' isn't\n        a parent of 'opts' or if it is None this method is a no-op.\n\n        The 'alias' is the root alias for starting the join, 'seen' is a dict\n        of model -> alias of existing joins. It must also contain a mapping\n        of None -> some alias. This will be returned in the no-op case.\n        \"\"\"\n        if model in seen:\n            return seen[model]\n        chain = opts.get_base_chain(model)\n        if not chain:\n            return alias\n        curr_opts = opts\n        for int_model in chain:\n            if int_model in seen:\n                curr_opts = int_model._meta\n                alias = seen[int_model]\n                continue\n            # Proxy model have elements in base chain\n            # with no parents, assign the new options\n            # object and skip to the next base in that\n            # case\n            if not curr_opts.parents[int_model]:\n                curr_opts = int_model._meta\n                continue\n            link_field = curr_opts.get_ancestor_link(int_model)\n            join_info = self.setup_joins([link_field.name], curr_opts, alias)\n            curr_opts = int_model._meta\n            alias = seen[int_model] = join_info.joins[-1]\n        return alias or seen[None]\n\n    def check_alias(self, alias):\n        # RemovedInDjango70Warning: When the deprecation ends, remove.\n        if \"%\" in alias:\n            warnings.warn(\n                \"Using percent signs in a column alias is deprecated.\",\n                category=RemovedInDjango70Warning,\n                skip_file_prefixes=django_file_prefixes(),\n            )\n        if FORBIDDEN_ALIAS_PATTERN.search(alias):\n            raise ValueError(\n                \"Column aliases cannot contain whitespace characters, hashes, \"\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # \"control characters, quotation marks, semicolons, percent \"\n                # \"signs, or SQL comments.\"\n                \"control characters, quotation marks, semicolons, or SQL comments.\"\n            )\n\n    def add_annotation(self, annotation, alias, select=True):\n        \"\"\"Add a single annotation expression to the Query.\"\"\"\n        self.check_alias(alias)\n        annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None)\n        if select:\n            self.append_annotation_mask([alias])\n        else:\n            self.set_annotation_mask(set(self.annotation_select).difference({alias}))\n        self.annotations[alias] = annotation\n        if select and self.selected:\n            self.selected[alias] = alias\n\n    @property\n    def _subquery_fields_len(self):\n        if not self.has_select_fields or not self.select:\n            return len(self.model._meta.pk_fields)\n        return len(self.select) + sum(\n            len(expr.targets) - 1 for expr in self.select if isinstance(expr, ColPairs)\n        )\n\n    def resolve_expression(self, query, *args, **kwargs):\n        clone = self.clone()\n        # Subqueries need to use a different set of aliases than the outer\n        # query.\n        clone.bump_prefix(query)\n        clone.subquery = True\n        clone.where.resolve_expression(query, *args, **kwargs)\n        # Resolve combined queries.\n        if clone.combinator:\n            clone.combined_queries = tuple(\n                [\n                    combined_query.resolve_expression(query, *args, **kwargs)\n                    for combined_query in clone.combined_queries\n                ]\n            )\n        for key, value in clone.annotations.items():\n            resolved = value.resolve_expression(query, *args, **kwargs)\n            if hasattr(resolved, \"external_aliases\"):\n                resolved.external_aliases.update(clone.external_aliases)\n            clone.annotations[key] = resolved\n        # Outer query's aliases are considered external.\n        for alias, table in query.alias_map.items():\n            clone.external_aliases[alias] = (\n                isinstance(table, Join)\n                and table.join_field.related_model._meta.db_table != alias\n            ) or (\n                isinstance(table, BaseTable) and table.table_name != table.table_alias\n            )\n        return clone\n\n    def get_external_cols(self):\n        exprs = chain(self.annotations.values(), self.where.children)\n        return [\n            col\n            for col in self._gen_cols(exprs, include_external=True)\n            if col.alias in self.external_aliases\n        ]\n\n    def get_group_by_cols(self, wrapper=None):\n        # If wrapper is referenced by an alias for an explicit GROUP BY through\n        # values() a reference to this expression and not the self must be\n        # returned to ensure external column references are not grouped against\n        # as well.\n        external_cols = self.get_external_cols()\n        if any(col.possibly_multivalued for col in external_cols):\n            return [wrapper or self]\n        return external_cols\n\n    def as_sql(self, compiler, connection):\n        # Some backends (e.g. Oracle) raise an error when a subquery contains\n        # unnecessary ORDER BY clause.\n        if (\n            self.subquery\n            and not connection.features.ignores_unnecessary_order_by_in_subqueries\n        ):\n            self.clear_ordering(force=False)\n            for query in self.combined_queries:\n                query.clear_ordering(force=False)\n        sql, params = self.get_compiler(connection=connection).as_sql()\n        if self.subquery:\n            sql = \"(%s)\" % sql\n        return sql, params\n\n    def resolve_lookup_value(self, value, can_reuse, allow_joins, summarize=False):\n        if hasattr(value, \"resolve_expression\"):\n            value = value.resolve_expression(\n                self,\n                reuse=can_reuse,\n                allow_joins=allow_joins,\n                summarize=summarize,\n            )\n        elif isinstance(value, (list, tuple)):\n            # The items of the iterable may be expressions and therefore need\n            # to be resolved independently.\n            values = (\n                self.resolve_lookup_value(sub_value, can_reuse, allow_joins, summarize)\n                for sub_value in value\n            )\n            type_ = type(value)\n            if hasattr(type_, \"_make\"):  # namedtuple\n                return type_(*values)\n            return type_(values)\n        return value\n\n    def solve_lookup_type(self, lookup, summarize=False):\n        \"\"\"\n        Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').\n        \"\"\"\n        lookup_splitted = lookup.split(LOOKUP_SEP)\n        if self.annotations:\n            annotation, expression_lookups = refs_expression(\n                lookup_splitted, self.annotations\n            )\n            if annotation:\n                expression = self.annotations[annotation]\n                if summarize:\n                    expression = Ref(annotation, expression)\n                return expression_lookups, (), expression\n        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())\n        field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)]\n        if len(lookup_parts) > 1 and not field_parts:\n            raise FieldError(\n                'Invalid lookup \"%s\" for model %s\".'\n                % (lookup, self.get_meta().model.__name__)\n            )\n        return lookup_parts, field_parts, False\n\n    def check_query_object_type(self, value, opts, field):\n        \"\"\"\n        Check whether the object passed while querying is of the correct type.\n        If not, raise a ValueError specifying the wrong object.\n        \"\"\"\n        if hasattr(value, \"_meta\"):\n            if not check_rel_lookup_compatibility(value._meta.model, opts, field):\n                raise ValueError(\n                    'Cannot query \"%s\": Must be \"%s\" instance.'\n                    % (value, opts.object_name)\n                )\n\n    def check_related_objects(self, field, value, opts):\n        \"\"\"Check the type of object passed to query relations.\"\"\"\n        if field.is_relation:\n            # Check that the field and the queryset use the same model in a\n            # query like .filter(author=Author.objects.all()). For example, the\n            # opts would be Author's (from the author field) and value.model\n            # would be Author.objects.all() queryset's .model (Author also).\n            # The field is the related field on the lhs side.\n            if (\n                isinstance(value, Query)\n                and not value.has_select_fields\n                and not check_rel_lookup_compatibility(value.model, opts, field)\n            ):\n                raise ValueError(\n                    'Cannot use QuerySet for \"%s\": Use a QuerySet for \"%s\".'\n                    % (value.model._meta.object_name, opts.object_name)\n                )\n            elif hasattr(value, \"_meta\"):\n                self.check_query_object_type(value, opts, field)\n            elif hasattr(value, \"__iter__\"):\n                for v in value:\n                    self.check_query_object_type(v, opts, field)\n\n    def check_filterable(self, expression):\n        \"\"\"Raise an error if expression cannot be used in a WHERE clause.\"\"\"\n        if hasattr(expression, \"resolve_expression\") and not getattr(\n            expression, \"filterable\", True\n        ):\n            raise NotSupportedError(\n                expression.__class__.__name__ + \" is disallowed in the filter \"\n                \"clause.\"\n            )\n        if hasattr(expression, \"get_source_expressions\"):\n            for expr in expression.get_source_expressions():\n                self.check_filterable(expr)\n\n    def build_lookup(self, lookups, lhs, rhs):\n        \"\"\"\n        Try to extract transforms and lookup from given lhs.\n\n        The lhs value is something that works like SQLExpression.\n        The rhs value is what the lookup is going to compare against.\n        The lookups is a list of names to extract using get_lookup()\n        and get_transform().\n        \"\"\"\n        # __exact is the default lookup if one isn't given.\n        *transforms, lookup_name = lookups or [\"exact\"]\n        for name in transforms:\n            lhs = self.try_transform(lhs, name, lookups)\n        # First try get_lookup() so that the lookup takes precedence if the lhs\n        # supports both transform and lookup for the name.\n        lookup_class = lhs.get_lookup(lookup_name)\n        if not lookup_class:\n            # A lookup wasn't found. Try to interpret the name as a transform\n            # and do an Exact lookup against it.\n            lhs = self.try_transform(lhs, lookup_name)\n            lookup_name = \"exact\"\n            lookup_class = lhs.get_lookup(lookup_name)\n            if not lookup_class:\n                return\n\n        lookup = lookup_class(lhs, rhs)\n        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all\n        # uses of None as a query value unless the lookup supports it.\n        if lookup.rhs is None and not lookup.can_use_none_as_rhs:\n            if lookup_name not in (\"exact\", \"iexact\"):\n                raise ValueError(\"Cannot use None as a query value\")\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        # For Oracle '' is equivalent to null. The check must be done at this\n        # stage because join promotion can't be done in the compiler. Using\n        # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.\n        # A similar thing is done in is_nullable(), too.\n        if (\n            lookup_name in (\"exact\", \"iexact\")\n            and lookup.rhs == \"\"\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        ):\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        return lookup\n\n    def try_transform(self, lhs, name, lookups=None):\n        \"\"\"\n        Helper method for build_lookup(). Try to fetch and initialize\n        a transform for name parameter from lhs.\n        \"\"\"\n        transform_class = lhs.get_transform(name)\n        if transform_class:\n            return transform_class(lhs)\n        else:\n            output_field = lhs.output_field.__class__\n            suggested_lookups = difflib.get_close_matches(\n                name, lhs.output_field.get_lookups()\n            )\n            if suggested_lookups:\n                suggestion = \", perhaps you meant %s?\" % \" or \".join(suggested_lookups)\n            else:\n                suggestion = \".\"\n            if lookups is not None:\n                name_index = lookups.index(name)\n                unsupported_lookup = LOOKUP_SEP.join(lookups[name_index:])\n            else:\n                unsupported_lookup = name\n            raise FieldError(\n                \"Unsupported lookup '%s' for %s or join on the field not \"\n                \"permitted%s\" % (unsupported_lookup, output_field.__name__, suggestion)\n            )\n\n    def build_filter(\n        self,\n        filter_expr,\n        branch_negated=False,\n        current_negated=False,\n        can_reuse=None,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"\n        Build a WhereNode for a single filter clause but don't add it\n        to this Query. Query.add_q() will then add this filter to the where\n        Node.\n\n        The 'branch_negated' tells us if the current branch contains any\n        negations. This will be used to determine if subqueries are needed.\n\n        The 'current_negated' is used to determine if the current filter is\n        negated or not and this will be used to determine if IS NULL filtering\n        is needed.\n\n        The difference between current_negated and branch_negated is that\n        branch_negated is set on first negation, but current_negated is\n        flipped for each negation.\n\n        Note that add_filter will not do any negating itself, that is done\n        upper in the code by add_q().\n\n        The 'can_reuse' is a set of reusable joins for multijoins.\n\n        The method will create a filter clause that can be added to the current\n        query. However, if the filter isn't added to the query then the caller\n        is responsible for unreffing the joins used.\n        \"\"\"\n        if isinstance(filter_expr, dict):\n            raise FieldError(\"Cannot parse keyword query as dict\")\n        if isinstance(filter_expr, Q):\n            return self._add_q(\n                filter_expr,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                used_aliases=can_reuse,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n        if hasattr(filter_expr, \"resolve_expression\"):\n            if not getattr(filter_expr, \"conditional\", False):\n                raise TypeError(\"Cannot filter against a non-conditional expression.\")\n            condition = filter_expr.resolve_expression(\n                self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize\n            )\n            if not isinstance(condition, Lookup):\n                condition = self.build_lookup([\"exact\"], condition, True)\n            return WhereNode([condition], connector=AND), []\n        arg, value = filter_expr\n        if not arg:\n            raise FieldError(\"Cannot parse keyword query %r\" % arg)\n        lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize)\n\n        if check_filterable:\n            self.check_filterable(reffed_expression)\n\n        if not allow_joins and len(parts) > 1:\n            raise FieldError(\"Joined field references are not permitted in this query\")\n\n        pre_joins = self.alias_refcount.copy()\n        value = self.resolve_lookup_value(value, can_reuse, allow_joins, summarize)\n        used_joins = {\n            k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)\n        }\n\n        if check_filterable:\n            self.check_filterable(value)\n\n        if reffed_expression:\n            condition = self.build_lookup(lookups, reffed_expression, value)\n            return WhereNode([condition], connector=AND), []\n\n        opts = self.get_meta()\n        alias = self.get_initial_alias()\n        allow_many = not branch_negated or not split_subq\n\n        try:\n            join_info = self.setup_joins(\n                parts,\n                opts,\n                alias,\n                can_reuse=can_reuse,\n                allow_many=allow_many,\n            )\n\n            # Prevent iterator from being consumed by check_related_objects()\n            if isinstance(value, Iterator):\n                value = list(value)\n            self.check_related_objects(join_info.final_field, value, join_info.opts)\n\n            # split_exclude() needs to know which joins were generated for the\n            # lookup parts\n            self._lookup_joins = join_info.joins\n        except MultiJoin as e:\n            return self.split_exclude(filter_expr, can_reuse, e.names_with_path)\n\n        # Update used_joins before trimming since they are reused to determine\n        # which joins could be later promoted to INNER.\n        used_joins.update(join_info.joins)\n        targets, alias, join_list = self.trim_joins(\n            join_info.targets, join_info.joins, join_info.path\n        )\n        if can_reuse is not None:\n            can_reuse.update(join_list)\n\n        if join_info.final_field.is_relation:\n            if len(targets) == 1:\n                col = self._get_col(targets[0], join_info.final_field, alias)\n            else:\n                col = ColPairs(alias, targets, join_info.targets, join_info.final_field)\n        else:\n            col = self._get_col(targets[0], join_info.final_field, alias)\n\n        condition = self.build_lookup(lookups, col, value)\n        lookup_type = condition.lookup_name\n        clause = WhereNode([condition], connector=AND)\n\n        require_outer = (\n            lookup_type == \"isnull\" and condition.rhs is True and not current_negated\n        )\n        if (\n            current_negated\n            and (lookup_type != \"isnull\" or condition.rhs is False)\n            and condition.rhs is not None\n        ):\n            require_outer = True\n            if lookup_type != \"isnull\":\n                # The condition added here will be SQL like this:\n                # NOT (col IS NOT NULL), where the first NOT is added in\n                # upper layers of code. The reason for addition is that if col\n                # is null, then col != someval will result in SQL \"unknown\"\n                # which isn't the same as in Python. The Python None handling\n                # is wanted, and it can be gotten by\n                # (col IS NULL OR col != someval)\n                #   <=>\n                # NOT (col IS NOT NULL AND col = someval).\n                if (\n                    self.is_nullable(targets[0])\n                    or self.alias_map[join_list[-1]].join_type == LOUTER\n                ):\n                    lookup_class = targets[0].get_lookup(\"isnull\")\n                    col = self._get_col(targets[0], join_info.targets[0], alias)\n                    # Use OR + IS NULL when RHS `in` values include None.\n                    if (\n                        lookup_type == \"in\"\n                        # Check containers (not strings or bytes).\n                        and isinstance(condition.rhs, Iterable)\n                        and not isinstance(condition.rhs, (str, bytes))\n                        and any(v is None for v in condition.rhs)\n                    ):\n                        clause.add(lookup_class(col, True), OR)\n                    else:\n                        clause.add(lookup_class(col, False), AND)\n                # If someval is a nullable column, someval IS NOT NULL is\n                # added.\n                if isinstance(value, Col) and self.is_nullable(value.target):\n                    lookup_class = value.target.get_lookup(\"isnull\")\n                    clause.add(lookup_class(value, False), AND)\n        return clause, used_joins if not require_outer else ()\n\n    def add_filter(self, filter_lhs, filter_rhs):\n        self.add_q(Q((filter_lhs, filter_rhs)))\n\n    def add_q(self, q_object, reuse_all=False):\n        \"\"\"\n        A preprocessor for the internal _add_q(). Responsible for doing final\n        join promotion.\n        \"\"\"\n        # For join promotion this case is doing an AND for the added q_object\n        # and existing conditions. So, any existing inner join forces the join\n        # type to remain inner. Existing outer joins can however be demoted.\n        # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if\n        # rel_a doesn't produce any rows, then the whole condition must fail.\n        # So, demotion is OK.\n        existing_inner = {\n            a for a in self.alias_map if self.alias_map[a].join_type == INNER\n        }\n        if reuse_all:\n            can_reuse = set(self.alias_map)\n        else:\n            can_reuse = self.used_aliases\n        clause, _ = self._add_q(q_object, can_reuse)\n        if clause:\n            self.where.add(clause, AND)\n        self.demote_joins(existing_inner)\n\n    def build_where(self, filter_expr):\n        return self.build_filter(filter_expr, allow_joins=False)[0]\n\n    def clear_where(self):\n        self.where = WhereNode()\n\n    def _add_q(\n        self,\n        q_object,\n        used_aliases,\n        branch_negated=False,\n        current_negated=False,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"Add a Q-object to the current filter.\"\"\"\n        connector = q_object.connector\n        current_negated ^= q_object.negated\n        branch_negated = branch_negated or q_object.negated\n        target_clause = WhereNode(connector=connector, negated=q_object.negated)\n        joinpromoter = JoinPromoter(\n            q_object.connector, len(q_object.children), current_negated\n        )\n        for child in q_object.children:\n            child_clause, needed_inner = self.build_filter(\n                child,\n                can_reuse=used_aliases,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n            joinpromoter.add_votes(needed_inner)\n            if child_clause:\n                target_clause.add(child_clause, connector)\n        if update_join_types:\n            needed_inner = joinpromoter.update_join_types(self)\n        else:\n            needed_inner = []\n        return target_clause, needed_inner\n\n    def add_filtered_relation(self, filtered_relation, alias):\n        if \".\" in alias:\n            raise ValueError(\n                \"FilteredRelation doesn't support aliases with periods \"\n                \"(got %r).\" % alias\n            )\n        self.check_alias(alias)\n        filtered_relation.alias = alias\n        relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(\n            filtered_relation.relation_name\n        )\n        if relation_lookup_parts:\n            raise ValueError(\n                \"FilteredRelation's relation_name cannot contain lookups \"\n                \"(got %r).\" % filtered_relation.relation_name\n            )\n        for lookup in get_children_from_q(filtered_relation.condition):\n            lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)\n            shift = 2 if not lookup_parts else 1\n            lookup_field_path = lookup_field_parts[:-shift]\n            for idx, lookup_field_part in enumerate(lookup_field_path):\n                if len(relation_field_parts) > idx:\n                    if relation_field_parts[idx] != lookup_field_part:\n                        raise ValueError(\n                            \"FilteredRelation's condition doesn't support \"\n                            \"relations outside the %r (got %r).\"\n                            % (filtered_relation.relation_name, lookup)\n                        )\n            if len(lookup_field_parts) > len(relation_field_parts) + 1:\n                raise ValueError(\n                    \"FilteredRelation's condition doesn't support nested \"\n                    \"relations deeper than the relation_name (got %r for \"\n                    \"%r).\" % (lookup, filtered_relation.relation_name)\n                )\n        filtered_relation = filtered_relation.clone()\n        filtered_relation.condition = rename_prefix_from_q(\n            filtered_relation.relation_name,\n            alias,\n            filtered_relation.condition,\n        )\n        self._filtered_relations[filtered_relation.alias] = filtered_relation\n\n    def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):\n        \"\"\"\n        Walk the list of names and turns them into PathInfo tuples. A single\n        name in 'names' can generate multiple PathInfos (m2m, for example).\n\n        'names' is the path of names to travel, 'opts' is the model Options we\n        start the name resolving from, 'allow_many' is as for setup_joins().\n        If fail_on_missing is set to True, then a name that can't be resolved\n        will generate a FieldError.\n\n        Return a list of PathInfo tuples. In addition return the final field\n        (the last used join field) and target (which is a field guaranteed to\n        contain the same value as the final field). Finally, return those names\n        that weren't found (which are likely transforms and the final lookup).\n        \"\"\"\n        path, names_with_path = [], []\n        for pos, name in enumerate(names):\n            cur_names_with_path = (name, [])\n            if name == \"pk\" and opts is not None:\n                name = opts.pk.name\n\n            field = None\n            filtered_relation = None\n            try:\n                if opts is None:\n                    raise FieldDoesNotExist\n                field = opts.get_field(name)\n            except FieldDoesNotExist:\n                if name in self.annotations:\n                    field = self.annotations[name].output_field\n                elif name in self._filtered_relations and pos == 0:\n                    filtered_relation = self._filtered_relations[name]\n                    if LOOKUP_SEP in filtered_relation.relation_name:\n                        parts = filtered_relation.relation_name.split(LOOKUP_SEP)\n                        filtered_relation_path, field, _, _ = self.names_to_path(\n                            parts,\n                            opts,\n                            allow_many,\n                            fail_on_missing,\n                        )\n                        path.extend(filtered_relation_path[:-1])\n                    else:\n                        field = opts.get_field(filtered_relation.relation_name)\n            if field is not None:\n                # Fields that contain one-to-many relations with a generic\n                # model (like a GenericForeignKey) cannot generate reverse\n                # relations and therefore cannot be used for reverse querying.\n                if field.is_relation and not field.related_model:\n                    raise FieldError(\n                        \"Field %r does not generate an automatic reverse \"\n                        \"relation and therefore cannot be used for reverse \"\n                        \"querying. If it is a GenericForeignKey, consider \"\n                        \"adding a GenericRelation.\" % name\n                    )\n                try:\n                    model = field.model._meta.concrete_model\n                except AttributeError:\n                    # QuerySet.annotate() may introduce fields that aren't\n                    # attached to a model.\n                    model = None\n            else:\n                # We didn't find the current field, so move position back\n                # one step.\n                pos -= 1\n                if pos == -1 or fail_on_missing:\n                    available = sorted(\n                        [\n                            *get_field_names_from_opts(opts),\n                            *self.annotations,\n                            *self._filtered_relations,\n                        ]\n                    )\n                    raise FieldError(\n                        \"Cannot resolve keyword '%s' into field. \"\n                        \"Choices are: %s\" % (name, \", \".join(available))\n                    )\n                break\n            # Check if we need any joins for concrete inheritance cases (the\n            # field lives in parent, but we are currently in one of its\n            # children)\n            if opts is not None and model is not opts.model:\n                path_to_parent = opts.get_path_to_parent(model)\n                if path_to_parent:\n                    path.extend(path_to_parent)\n                    cur_names_with_path[1].extend(path_to_parent)\n                    opts = path_to_parent[-1].to_opts\n            if hasattr(field, \"path_infos\"):\n                if filtered_relation:\n                    pathinfos = field.get_path_info(filtered_relation)\n                else:\n                    pathinfos = field.path_infos\n                if not allow_many:\n                    for inner_pos, p in enumerate(pathinfos):\n                        if p.m2m:\n                            cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1])\n                            names_with_path.append(cur_names_with_path)\n                            raise MultiJoin(pos + 1, names_with_path)\n                last = pathinfos[-1]\n                path.extend(pathinfos)\n                final_field = last.join_field\n                opts = last.to_opts\n                targets = last.target_fields\n                cur_names_with_path[1].extend(pathinfos)\n                names_with_path.append(cur_names_with_path)\n            else:\n                # Local non-relational field.\n                final_field = field\n                targets = (field,)\n                if fail_on_missing and pos + 1 != len(names):\n                    raise FieldError(\n                        \"Cannot resolve keyword %r into field. Join on '%s'\"\n                        \" not permitted.\" % (names[pos + 1], name)\n                    )\n                break\n        return path, final_field, targets, names[pos + 1 :]\n\n    def setup_joins(\n        self,\n        names,\n        opts,\n        alias,\n        can_reuse=None,\n        allow_many=True,\n    ):\n        \"\"\"\n        Compute the necessary table joins for the passage through the fields\n        given in 'names'. 'opts' is the Options class for the current model\n        (which gives the table we are starting from), 'alias' is the alias for\n        the table to start the joining from.\n\n        The 'can_reuse' defines the reverse foreign key joins we can reuse. It\n        can be None in which case all joins are reusable or a set of aliases\n        that can be reused. Note that non-reverse foreign keys are always\n        reusable when using setup_joins().\n\n        If 'allow_many' is False, then any reverse foreign key seen will\n        generate a MultiJoin exception.\n\n        Return the final field involved in the joins, the target field (used\n        for any 'where' constraint), the final 'opts' value, the joins, the\n        field path traveled to generate the joins, and a transform function\n        that takes a field and alias and is equivalent to\n        `field.get_col(alias)` in the simple case but wraps field transforms if\n        they were included in names.\n\n        The target field is the field containing the concrete value. Final\n        field can be something different, for example foreign key pointing to\n        that value. Final field is needed for example in some value\n        conversions (convert 'obj' in fk__id=obj to pk val using the foreign\n        key field for example).\n        \"\"\"\n        joins = [alias]\n        # The transform can't be applied yet, as joins must be trimmed later.\n        # To avoid making every caller of this method look up transforms\n        # directly, compute transforms here and create a partial that converts\n        # fields to the appropriate wrapped version.\n\n        def final_transformer(field, alias):\n            if not self.alias_cols:\n                alias = None\n            return field.get_col(alias)\n\n        # Try resolving all the names as fields first. If there's an error,\n        # treat trailing names as lookups until a field can be resolved.\n        last_field_exception = None\n        for pivot in range(len(names), 0, -1):\n            try:\n                path, final_field, targets, rest = self.names_to_path(\n                    names[:pivot],\n                    opts,\n                    allow_many,\n                    fail_on_missing=True,\n                )\n            except FieldError as exc:\n                if pivot == 1:\n                    # The first item cannot be a lookup, so it's safe\n                    # to raise the field error here.\n                    raise\n                else:\n                    last_field_exception = exc\n            else:\n                # The transforms are the remaining items that couldn't be\n                # resolved into fields.\n                transforms = names[pivot:]\n                break\n        for name in transforms:\n\n            def transform(field, alias, *, name, previous):\n                try:\n                    wrapped = previous(field, alias)\n                    return self.try_transform(wrapped, name)\n                except FieldError:\n                    # FieldError is raised if the transform doesn't exist.\n                    if isinstance(final_field, Field) and last_field_exception:\n                        raise last_field_exception\n                    else:\n                        raise\n\n            final_transformer = functools.partial(\n                transform, name=name, previous=final_transformer\n            )\n            final_transformer.has_transforms = True\n        # Then, add the path to the query's joins. Note that we can't trim\n        # joins at this stage - we will need the information about join type\n        # of the trimmed joins.\n        for join in path:\n            if join.filtered_relation:\n                filtered_relation = join.filtered_relation.clone()\n                table_alias = filtered_relation.alias\n            else:\n                filtered_relation = None\n                table_alias = None\n            opts = join.to_opts\n            if join.direct:\n                nullable = self.is_nullable(join.join_field)\n            else:\n                nullable = True\n            connection = self.join_class(\n                opts.db_table,\n                alias,\n                table_alias,\n                INNER,\n                join.join_field,\n                nullable,\n                filtered_relation=filtered_relation,\n            )\n            reuse = can_reuse if join.m2m else None\n            alias = self.join(connection, reuse=reuse)\n            joins.append(alias)\n            if join.filtered_relation and can_reuse is not None:\n                can_reuse.add(alias)\n        return JoinInfo(final_field, targets, opts, joins, path, final_transformer)\n\n    def trim_joins(self, targets, joins, path):\n        \"\"\"\n        The 'target' parameter is the final field being joined to, 'joins'\n        is the full list of join aliases. The 'path' contain the PathInfos\n        used to create the joins.\n\n        Return the final target field and table alias and the new active\n        joins.\n\n        Always trim any direct join if the target column is already in the\n        previous table. Can't trim reverse joins as it's unknown if there's\n        anything on the other side of the join.\n        \"\"\"\n        joins = joins[:]\n        for pos, info in enumerate(reversed(path)):\n            if len(joins) == 1 or not info.direct:\n                break\n            if info.filtered_relation:\n                break\n            join_targets = {t.column for t in info.join_field.foreign_related_fields}\n            cur_targets = {t.column for t in targets}\n            if not cur_targets.issubset(join_targets):\n                break\n            targets_dict = {\n                r[1].column: r[0]\n                for r in info.join_field.related_fields\n                if r[1].column in cur_targets\n            }\n            targets = tuple(targets_dict[t.column] for t in targets)\n            self.unref_alias(joins.pop())\n        return targets, joins[-1], joins\n\n    @classmethod\n    def _gen_cols(cls, exprs, include_external=False, resolve_refs=True):\n        for expr in exprs:\n            if isinstance(expr, Col):\n                yield expr\n            elif include_external and callable(\n                getattr(expr, \"get_external_cols\", None)\n            ):\n                yield from expr.get_external_cols()\n            elif hasattr(expr, \"get_source_expressions\"):\n                if not resolve_refs and isinstance(expr, Ref):\n                    continue\n                yield from cls._gen_cols(\n                    expr.get_source_expressions(),\n                    include_external=include_external,\n                    resolve_refs=resolve_refs,\n                )\n\n    @classmethod\n    def _gen_col_aliases(cls, exprs):\n        yield from (expr.alias for expr in cls._gen_cols(exprs))\n\n    def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):\n        annotation = self.annotations.get(name)\n        if annotation is not None:\n            if not allow_joins:\n                for alias in self._gen_col_aliases([annotation]):\n                    if isinstance(self.alias_map[alias], Join):\n                        raise FieldError(\n                            \"Joined field references are not permitted in this query\"\n                        )\n            if summarize:\n                # Summarize currently means we are doing an aggregate() query\n                # which is executed as a wrapped subquery if any of the\n                # aggregate() elements reference an existing annotation. In\n                # that case we need to return a Ref to the subquery's\n                # annotation.\n                if name not in self.annotation_select:\n                    raise FieldError(\n                        \"Cannot aggregate over the '%s' alias. Use annotate() \"\n                        \"to promote it.\" % name\n                    )\n                return Ref(name, self.annotation_select[name])\n            else:\n                return annotation\n        else:\n            field_list = name.split(LOOKUP_SEP)\n            annotation = self.annotations.get(field_list[0])\n            if annotation is not None:\n                for transform in field_list[1:]:\n                    annotation = self.try_transform(annotation, transform)\n                return annotation\n            join_info = self.setup_joins(\n                field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse\n            )\n            targets, final_alias, join_list = self.trim_joins(\n                join_info.targets, join_info.joins, join_info.path\n            )\n            if not allow_joins and len(join_list) > 1:\n                raise FieldError(\n                    \"Joined field references are not permitted in this query\"\n                )\n            if len(targets) > 1:\n                raise FieldError(\n                    \"Referencing multicolumn fields with F() objects isn't supported\"\n                )\n            # Verify that the last lookup in name is a field or a transform:\n            # transform_function() raises FieldError if not.\n            transform = join_info.transform_function(targets[0], final_alias)\n            if reuse is not None:\n                reuse.update(join_list)\n            return transform\n\n    def split_exclude(self, filter_expr, can_reuse, names_with_path):\n        \"\"\"\n        When doing an exclude against any kind of N-to-many relation, we need\n        to use a subquery. This method constructs the nested query, given the\n        original exclude filter (filter_expr) and the portion up to the first\n        N-to-many relation field.\n\n        For example, if the origin filter is ~Q(child__name='foo'), filter_expr\n        is ('child__name', 'foo') and can_reuse is a set of joins usable for\n        filters in the original query.\n\n        We will turn this into equivalent of:\n            WHERE NOT EXISTS(\n                SELECT 1\n                FROM child\n                WHERE name = 'foo' AND child.parent_id = parent.id\n                LIMIT 1\n            )\n        \"\"\"\n        # Generate the inner query.\n        query = self.__class__(self.model)\n        query._filtered_relations = self._filtered_relations\n        filter_lhs, filter_rhs = filter_expr\n        if isinstance(filter_rhs, OuterRef):\n            filter_rhs = OuterRef(filter_rhs)\n        elif isinstance(filter_rhs, F):\n            filter_rhs = OuterRef(filter_rhs.name)\n        query.add_filter(filter_lhs, filter_rhs)\n        query.clear_ordering(force=True)\n        # Try to have as simple as possible subquery -> trim leading joins from\n        # the subquery.\n        trimmed_prefix, contains_louter = query.trim_start(names_with_path)\n\n        col = query.select[0]\n        select_field = col.target\n        alias = col.alias\n        if alias in can_reuse:\n            pk = select_field.model._meta.pk\n            # Need to add a restriction so that outer query's filters are in\n            # effect for the subquery, too.\n            query.bump_prefix(self)\n            lookup_class = select_field.get_lookup(\"exact\")\n            # Note that the query.select[0].alias is different from alias\n            # due to bump_prefix above.\n            lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias))\n            query.where.add(lookup, AND)\n            query.external_aliases[alias] = True\n        else:\n            lookup_class = select_field.get_lookup(\"exact\")\n            lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix))\n            query.where.add(lookup, AND)\n\n        condition, needed_inner = self.build_filter(Exists(query))\n\n        if contains_louter:\n            or_null_condition, _ = self.build_filter(\n                (\"%s__isnull\" % trimmed_prefix, True),\n                current_negated=True,\n                branch_negated=True,\n                can_reuse=can_reuse,\n            )\n            condition.add(or_null_condition, OR)\n            # Note that the end result will be:\n            #   NOT EXISTS (inner_q) OR outercol IS NULL\n            # this might look crazy but due to how NULL works, this seems to be\n            # correct. If the IS NULL check is removed, then if outercol\n            # IS NULL we will not match the row.\n        return condition, needed_inner\n\n    def set_empty(self):\n        self.where.add(NothingNode(), AND)\n        for query in self.combined_queries:\n            query.set_empty()\n\n    def is_empty(self):\n        return any(isinstance(c, NothingNode) for c in self.where.children)\n\n    def set_limits(self, low=None, high=None):\n        \"\"\"\n        Adjust the limits on the rows retrieved. Use low/high to set these,\n        as it makes it more Pythonic to read and write. When the SQL query is\n        created, convert them to the appropriate offset and limit values.\n\n        Apply any limits passed in here to the existing constraints. Add low\n        to the current low value and clamp both to any existing high value.\n        \"\"\"\n        if high is not None:\n            if self.high_mark is not None:\n                self.high_mark = min(self.high_mark, self.low_mark + high)\n            else:\n                self.high_mark = self.low_mark + high\n        if low is not None:\n            if self.high_mark is not None:\n                self.low_mark = min(self.high_mark, self.low_mark + low)\n            else:\n                self.low_mark = self.low_mark + low\n\n        if self.low_mark == self.high_mark:\n            self.set_empty()\n\n    def clear_limits(self):\n        \"\"\"Clear any existing limits.\"\"\"\n        self.low_mark, self.high_mark = 0, None\n\n    @property\n    def is_sliced(self):\n        return self.low_mark != 0 or self.high_mark is not None\n\n    def has_limit_one(self):\n        return self.high_mark is not None and (self.high_mark - self.low_mark) == 1\n\n    def can_filter(self):\n        \"\"\"\n        Return True if adding filters to this instance is still possible.\n\n        Typically, this means no limits or offsets have been put on the\n        results.\n        \"\"\"\n        return not self.is_sliced\n\n    def clear_select_clause(self):\n        \"\"\"Remove all fields from SELECT clause.\"\"\"\n        self.select = ()\n        self.default_cols = False\n        self.select_related = False\n        self.set_extra_mask(())\n        self.set_annotation_mask(())\n        self.selected = None\n\n    def clear_select_fields(self):\n        \"\"\"\n        Clear the list of fields to select (but not extra_select columns).\n        Some queryset types completely replace any existing list of select\n        columns.\n        \"\"\"\n        self.select = ()\n        self.values_select = ()\n        self.selected = None\n\n    def add_select_col(self, col, name):\n        self.select += (col,)\n        self.values_select += (name,)\n        self.selected[name] = len(self.select) - 1\n\n    def set_select(self, cols):\n        self.default_cols = False\n        self.select = tuple(cols)\n\n    def add_distinct_fields(self, *field_names):\n        \"\"\"\n        Add and resolve the given fields to the query's \"distinct on\" clause.\n        \"\"\"\n        self.distinct_fields = field_names\n        self.distinct = True\n\n    def add_fields(self, field_names, allow_m2m=True):\n        \"\"\"\n        Add the given (model) fields to the select set. Add the field names in\n        the order specified.\n        \"\"\"\n        alias = self.get_initial_alias()\n        opts = self.get_meta()\n\n        try:\n            cols = []\n            for name in field_names:\n                # Join promotion note - we must not remove any rows here, so\n                # if there is no existing joins, use outer join.\n                join_info = self.setup_joins(\n                    name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m\n                )\n                targets, final_alias, joins = self.trim_joins(\n                    join_info.targets,\n                    join_info.joins,\n                    join_info.path,\n                )\n                if len(targets) > 1:\n                    transformed_targets = [\n                        join_info.transform_function(target, final_alias)\n                        for target in targets\n                    ]\n                    cols.append(\n                        ColPairs(\n                            final_alias if self.alias_cols else None,\n                            [col.target for col in transformed_targets],\n                            [col.output_field for col in transformed_targets],\n                            join_info.final_field,\n                        )\n                    )\n                else:\n                    cols.append(join_info.transform_function(targets[0], final_alias))\n            if cols:\n                self.set_select(cols)\n        except MultiJoin:\n            raise FieldError(\"Invalid field name: '%s'\" % name)\n        except FieldError:\n            if LOOKUP_SEP in name:\n                # For lookups spanning over relationships, show the error\n                # from the model on which the lookup failed.\n                raise\n            else:\n                names = sorted(\n                    [\n                        *get_field_names_from_opts(opts),\n                        *self.extra,\n                        *self.annotation_select,\n                        *self._filtered_relations,\n                    ]\n                )\n                raise FieldError(\n                    \"Cannot resolve keyword %r into field. \"\n                    \"Choices are: %s\" % (name, \", \".join(names))\n                )\n\n    def add_ordering(self, *ordering):\n        \"\"\"\n        Add items from the 'ordering' sequence to the query's \"order by\"\n        clause. These items are either field names (not column names) --\n        possibly with a direction prefix ('-' or '?') -- or OrderBy\n        expressions.\n\n        If 'ordering' is empty, clear all ordering from the query.\n        \"\"\"\n        errors = []\n        for item in ordering:\n            if isinstance(item, str):\n                if item == \"?\":\n                    continue\n                item = item.removeprefix(\"-\")\n                if item in self.annotations:\n                    continue\n                if self.extra and item in self.extra:\n                    continue\n                # names_to_path() validates the lookup. A descriptive\n                # FieldError will be raise if it's not.\n                self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)\n            elif not hasattr(item, \"resolve_expression\"):\n                errors.append(item)\n            if getattr(item, \"contains_aggregate\", False):\n                raise FieldError(\n                    \"Using an aggregate in order_by() without also including \"\n                    \"it in annotate() is not allowed: %s\" % item\n                )\n        if errors:\n            raise FieldError(\"Invalid order_by arguments: %s\" % errors)\n        if ordering:\n            self.order_by += ordering\n        else:\n            self.default_ordering = False\n\n    @property\n    def orderby_issubset_groupby(self):\n        if self.extra_order_by:\n            # Raw SQL from extra(order_by=...) can't be reliably compared\n            # against resolved OrderBy/Col expressions. Treat as not a subset.\n            return False\n        if self.group_by in (None, True):\n            # There is either no aggregation at all (None), or the group by\n            # is generated automatically from model fields (True), in which\n            # case the order by is necessarily a subset of them.\n            return True\n        if not self.order_by:\n            # Although an empty set is always a subset, there's no point in\n            # clearing ordering when there isn't any. Avoid the clone() below.\n            return True\n        # Don't pollute the original query (might disrupt joins).\n        q = self.clone()\n        order_by_set = set()\n        for order_by in q.order_by:\n            if hasattr(order_by, \"resolve_expression\"):\n                order_by_set.add(order_by.resolve_expression(q))\n            elif order_by == \"?\":\n                # Random ordering can't be compared against group by.\n                return False\n            else:\n                order_by_set.add(F(order_by.removeprefix(\"-\")).resolve_expression(q))\n        return order_by_set.issubset(self.group_by)\n\n    def clear_ordering(self, force=False, clear_default=True):\n        \"\"\"\n        Remove any ordering settings if the current query allows it without\n        side effects, set 'force' to True to clear the ordering regardless.\n        If 'clear_default' is True, there will be no ordering in the resulting\n        query (not even the model's default).\n        \"\"\"\n        if not force and (\n            self.is_sliced or self.distinct_fields or self.select_for_update\n        ):\n            return\n        self.order_by = ()\n        self.extra_order_by = ()\n        if clear_default:\n            self.default_ordering = False\n        # Ordering is cleared on combined queries with clear_default=False\n        # when union() and analogues are called, so percolate any possible\n        # clear_default=True.\n        for query in self.combined_queries:\n            query.clear_ordering(force=False, clear_default=clear_default)\n\n    def set_group_by(self, allow_aliases=True):\n        \"\"\"\n        Expand the GROUP BY clause required by the query.\n\n        This will usually be the set of all non-aggregate fields in the\n        return data. If the database backend supports grouping by the\n        primary key, and the query would be equivalent, the optimization\n        will be made automatically.\n        \"\"\"\n        if allow_aliases and self.values_select:\n            # If grouping by aliases is allowed assign selected value aliases\n            # by moving them to annotations.\n            group_by_annotations = {}\n            values_select = {}\n            for alias, expr in zip(self.values_select, self.select):\n                if isinstance(expr, Col):\n                    values_select[alias] = expr\n                else:\n                    group_by_annotations[alias] = expr\n            self.annotations = {**group_by_annotations, **self.annotations}\n            self.append_annotation_mask(group_by_annotations)\n            self.select = tuple(values_select.values())\n            self.values_select = tuple(values_select)\n            if self.selected is not None:\n                for index, value_select in enumerate(values_select):\n                    self.selected[value_select] = index\n        group_by = list(self.select)\n        for alias, annotation in self.annotation_select.items():\n            if not (group_by_cols := annotation.get_group_by_cols()):\n                continue\n            if allow_aliases and not annotation.contains_aggregate:\n                group_by.append(Ref(alias, annotation))\n            else:\n                group_by.extend(group_by_cols)\n        self.group_by = tuple(group_by)\n\n    def add_select_related(self, fields):\n        \"\"\"\n        Set up the select_related data structure so that we only select\n        certain related models (as opposed to all models, when\n        self.select_related=True).\n        \"\"\"\n        if isinstance(self.select_related, bool):\n            field_dict = {}\n        else:\n            field_dict = self.select_related\n        for field in fields:\n            d = field_dict\n            for part in field.split(LOOKUP_SEP):\n                d = d.setdefault(part, {})\n        self.select_related = field_dict\n\n    def add_extra(self, select, select_params, where, params, tables, order_by):\n        \"\"\"\n        Add data to the various extra_* attributes for user-created additions\n        to the query.\n        \"\"\"\n        if select:\n            # We need to pair any placeholder markers in the 'select'\n            # dictionary with their parameters in 'select_params' so that\n            # subsequent updates to the select dictionary also adjust the\n            # parameters appropriately.\n            select_pairs = {}\n            if select_params:\n                param_iter = iter(select_params)\n            else:\n                param_iter = iter([])\n            for name, entry in select.items():\n                self.check_alias(name)\n                entry = str(entry)\n                entry_params = []\n                pos = entry.find(\"%s\")\n                while pos != -1:\n                    if pos == 0 or entry[pos - 1] != \"%\":\n                        entry_params.append(next(param_iter))\n                    pos = entry.find(\"%s\", pos + 2)\n                select_pairs[name] = (entry, entry_params)\n            self.extra.update(select_pairs)\n        if where or params:\n            self.where.add(ExtraWhere(where, params), AND)\n        if tables:\n            self.extra_tables += tuple(tables)\n        if order_by:\n            self.extra_order_by = order_by\n\n    def clear_deferred_loading(self):\n        \"\"\"Remove any fields from the deferred loading set.\"\"\"\n        self.deferred_loading = (frozenset(), True)\n\n    def add_deferred_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        exclude from loading from the database when automatic column selection\n        is done. Add the new field names to any existing field names that\n        are deferred (or removed from any existing field names that are marked\n        as the only ones for immediate loading).\n        \"\"\"\n        # Fields on related models are stored in the literal double-underscore\n        # format, so that we can use a set datastructure. We do the foo__bar\n        # splitting and handling when computing the SQL column names (as part\n        # of get_columns()).\n        existing, defer = self.deferred_loading\n        if defer:\n            # Add to existing deferred names.\n            self.deferred_loading = existing.union(field_names), True\n        else:\n            # Remove names from the set of any existing \"immediate load\" names.\n            if new_existing := existing.difference(field_names):\n                self.deferred_loading = new_existing, False\n            else:\n                self.clear_deferred_loading()\n                if new_only := set(field_names).difference(existing):\n                    self.deferred_loading = new_only, True\n\n    def add_immediate_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        retrieve when the SQL is executed (\"immediate loading\" fields). The\n        field names replace any existing immediate loading field names. If\n        there are field names already specified for deferred loading, remove\n        those names from the new field_names before storing the new names\n        for immediate loading. (That is, immediate loading overrides any\n        existing immediate values, but respects existing deferrals.)\n        \"\"\"\n        existing, defer = self.deferred_loading\n        field_names = set(field_names)\n        if \"pk\" in field_names:\n            field_names.remove(\"pk\")\n            field_names.add(self.get_meta().pk.name)\n\n        if defer:\n            # Remove any existing deferred names from the current set before\n            # setting the new names.\n            self.deferred_loading = field_names.difference(existing), False\n        else:\n            # Replace any existing \"immediate load\" field names.\n            self.deferred_loading = frozenset(field_names), False\n\n    def set_annotation_mask(self, names):\n        \"\"\"Set the mask of annotations that will be returned by the SELECT.\"\"\"\n        if names is None:\n            self.annotation_select_mask = None\n        else:\n            self.annotation_select_mask = set(names)\n            if self.selected:\n                # Prune the masked annotations.\n                self.selected = {\n                    key: value\n                    for key, value in self.selected.items()\n                    if not isinstance(value, str)\n                    or value in self.annotation_select_mask\n                }\n                # Append the unmasked annotations.\n                for name in names:\n                    self.selected[name] = name\n        self._annotation_select_cache = None\n\n    def append_annotation_mask(self, names):\n        if self.annotation_select_mask is not None:\n            self.set_annotation_mask(self.annotation_select_mask.union(names))\n\n    def set_extra_mask(self, names):\n        \"\"\"\n        Set the mask of extra select items that will be returned by SELECT.\n        Don't remove them from the Query since they might be used later.\n        \"\"\"\n        if names is None:\n            self.extra_select_mask = None\n        else:\n            self.extra_select_mask = set(names)\n        self._extra_select_cache = None\n\n    @property\n    def has_select_fields(self):\n        return self.selected is not None\n\n    def set_values(self, fields):\n        self.select_related = False\n        self.clear_deferred_loading()\n        self.clear_select_fields()\n\n        selected = {}\n        if fields:\n            for field in fields:\n                self.check_alias(field)\n            field_names = []\n            extra_names = []\n            annotation_names = []\n            if not self.extra and not self.annotations:\n                # Shortcut - if there are no extra or annotations, then\n                # the values() clause must be just field names.\n                field_names = list(fields)\n                selected = dict(zip(fields, range(len(fields))))\n            else:\n                self.default_cols = False\n                for f in fields:\n                    if extra := self.extra_select.get(f):\n                        extra_names.append(f)\n                        selected[f] = RawSQL(*extra)\n                    elif f in self.annotation_select:\n                        annotation_names.append(f)\n                        selected[f] = f\n                    elif f in self.annotations:\n                        if self.annotation_select:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. It was excluded \"\n                                f\"by a previous values() or values_list() call. \"\n                                f\"Include '{f}' in that call to select it.\"\n                            )\n                        else:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. Use annotate() \"\n                                f\"to promote it.\"\n                            )\n                    else:\n                        # Call `names_to_path` to ensure a FieldError including\n                        # annotations about to be masked as valid choices if\n                        # `f` is not resolvable.\n                        if self.annotation_select:\n                            self.names_to_path(f.split(LOOKUP_SEP), self.model._meta)\n                        selected[f] = len(field_names)\n                        field_names.append(f)\n            self.set_extra_mask(extra_names)\n            self.set_annotation_mask(annotation_names)\n        else:\n            field_names = [f.attname for f in self.model._meta.concrete_fields]\n            selected = dict.fromkeys(field_names, None)\n        # Selected annotations must be known before setting the GROUP BY\n        # clause.\n        if self.group_by is True:\n            self.add_fields(\n                (f.attname for f in self.model._meta.concrete_fields), False\n            )\n            # Disable GROUP BY aliases to avoid orphaning references to the\n            # SELECT clause which is about to be cleared.\n            self.set_group_by(allow_aliases=False)\n            self.clear_select_fields()\n        elif self.group_by:\n            # Resolve GROUP BY annotation references if they are not part of\n            # the selected fields anymore.\n            group_by = []\n            for expr in self.group_by:\n                if isinstance(expr, Ref) and expr.refs not in selected:\n                    expr = self.annotations[expr.refs]\n                group_by.append(expr)\n            self.group_by = tuple(group_by)\n\n        self.values_select = tuple(field_names)\n        self.add_fields(field_names, True)\n        self.selected = selected if fields else None\n\n    @property\n    def annotation_select(self):\n        \"\"\"\n        Return the dictionary of aggregate columns that are not masked and\n        should be used in the SELECT clause. Cache this result for performance.\n        \"\"\"\n        if self._annotation_select_cache is not None:\n            return self._annotation_select_cache\n        elif not self.annotations:\n            return {}\n        elif self.annotation_select_mask is not None:\n            self._annotation_select_cache = {\n                k: v\n                for k, v in self.annotations.items()\n                if k in self.annotation_select_mask\n            }\n            return self._annotation_select_cache\n        else:\n            return self.annotations\n\n    @property\n    def extra_select(self):\n        lI0O_2c00c90d = 0x15e7\n        lI0O_2c00c90d = (0 if (lI0O_2c00c90d ^ lI0O_2c00c90d) == 0 else 1) if (lI0O_2c00c90d & 0) == 0 else 2\n        if self._extra_select_cache is not None:\n            return self._extra_select_cache\n        if not self.extra:\n            return {}\n        elif self.extra_select_mask is not None:\n            self._extra_select_cache = {\n                k: v for k, v in self.extra.items() if k in self.extra_select_mask\n            }\n            return self._extra_select_cache\n        else:\n            return self.extra\n\n    def trim_start(self, names_with_path):\n        \"\"\"\n        Trim joins from the start of the join path. The candidates for trim\n        are the PathInfos in names_with_path structure that are m2m joins.\n\n        Also set the select column so the start matches the join.\n\n        This method is meant to be used for generating the subquery joins &\n        cols in split_exclude().\n\n        Return a lookup usable for doing outerq.filter(lookup=self) and a\n        boolean indicating if the joins in the prefix contain a LEFT OUTER\n        join.\n        \"\"\"\n        all_paths = []\n        for _, paths in names_with_path:\n            all_paths.extend(paths)\n        contains_louter = False\n        # Trim and operate only on tables that were generated for\n        # the lookup part of the query. That is, avoid trimming\n        # joins generated for F() expressions.\n        lookup_tables = [\n            t for t in self.alias_map if t in self._lookup_joins or t == self.base_table\n        ]\n        for trimmed_paths, path in enumerate(all_paths):\n            if path.m2m:\n                break\n            if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER:\n                contains_louter = True\n            alias = lookup_tables[trimmed_paths]\n            self.unref_alias(alias)\n        # The path.join_field is a Rel, lets get the other side's field\n        join_field = path.join_field.field\n        # Build the filter prefix.\n        paths_in_prefix = trimmed_paths\n        trimmed_prefix = []\n        for name, path in names_with_path:\n            if paths_in_prefix - len(path) < 0:\n                break\n            trimmed_prefix.append(name)\n            paths_in_prefix -= len(path)\n        trimmed_prefix.append(join_field.foreign_related_fields[0].name)\n        trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)\n        # Lets still see if we can trim the first join from the inner query\n        # (that is, self). We can't do this for:\n        # - LEFT JOINs because we would miss those rows that have nothing on\n        #   the outer side,\n        # - INNER JOINs from filtered relations because we would miss their\n        #   filters.\n        first_join = self.alias_map[lookup_tables[trimmed_paths + 1]]\n        if first_join.join_type != LOUTER and not first_join.filtered_relation:\n            select_fields = [r[0] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths + 1]\n            self.unref_alias(lookup_tables[trimmed_paths])\n            extra_restriction = join_field.get_extra_restriction(\n                None, lookup_tables[trimmed_paths + 1]\n            )\n            if extra_restriction:\n                self.where.add(extra_restriction, AND)\n        else:\n            # TODO: It might be possible to trim more joins from the start of\n            # the inner query if it happens to have a longer join chain\n            # containing the values in select_fields. Lets punt this one for\n            # now.\n            select_fields = [r[1] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths]\n        # The found starting point is likely a join_class instead of a\n        # base_table_class reference. But the first entry in the query's FROM\n        # clause must not be a JOIN.\n        for table in self.alias_map:\n            if self.alias_refcount[table] > 0:\n                self.alias_map[table] = self.base_table_class(\n                    self.alias_map[table].table_name,\n                    table,\n                )\n                break\n        self.set_select([f.get_col(select_alias) for f in select_fields])\n        return trimmed_prefix, contains_louter\n\n    def is_nullable(self, field):\n        \"\"\"\n        Check if the given field should be treated as nullable.\n\n        Some backends treat '' as null and Django treats such fields as\n        nullable for those backends. In such situations field.null can be\n        False even if we should treat the field as nullable.\n        \"\"\"\n        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have\n        # (nor should it have) knowledge of which connection is going to be\n        # used. The proper fix would be to defer all decisions where\n        # is_nullable() is needed to the compiler stage, but that is not easy\n        # to do currently.\n        return field.null or (\n            field.empty_strings_allowed\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-d737c5fea4d295f9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "b51b2242689cb43ae222a48d09a1e11e5349ad82f7d47c4db080dea77cbcf218", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 2604, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__Query__18c5a811.py", "order": 9, "original_content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "parent_variant_id": "pyint-82246794d74c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/query.py#L232-L2792", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 8}, "unit_kind": "class", "unit_name": "Query", "variant_id": "pyint-31a818c5a811-I09", "group_id": "py-d737c5fea4d295f9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 290, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3fffe2c96d79-I10", "source": "import copy\nimport difflib\nimport functools\nimport sys\nimport warnings\nfrom collections import Counter, namedtuple\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom itertools import chain, count, product\nfrom string import ascii_uppercase\nfrom django.core.exceptions import FieldDoesNotExist, FieldError\nfrom django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections\nfrom django.db.models.aggregates import Count\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import (     BaseExpression,     Col,\n    ColPairs,\n    Exists,     F,\n    OuterRef,\n    RawSQL,     Ref,     ResolvedOuterRef,\n    Value,\n)\nfrom django.db.models.fields import Field\nfrom django.db.models.lookups import Lookup\nfrom django.db.models.query_utils import (\n    Q,     check_rel_lookup_compatibility,     refs_expression,\n)\nfrom django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE\nfrom django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin\nfrom django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode\nfrom django.utils.deprecation import RemovedInDjango70Warning\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.tree import Node\nfrom django.utils.warnings import django_file_prefixes\nclass Query(BaseExpression):\n    \"\"\"A single SQL query.\"\"\"\n\n    alias_prefix = \"T\"\n    empty_result_set_value = None\n    subq_aliases = frozenset([alias_prefix])\n\n    compiler = \"SQLCompiler\"\n\n    base_table_class = BaseTable\n    join_class = Join\n    default_cols = True\n    default_ordering = True\n    standard_ordering = True\n\n    filter_is_sticky = False\n    subquery = False\n    contains_subquery = False\n    # SQL-related attributes.\n    # Select and related select clauses are expressions to use in the SELECT\n    # clause of the query. The select is used for cases where we want to set up\n    # the select clause to contain other than default fields (values(),\n    # subqueries...). Note that annotations go to annotations dictionary.\n    select = ()\n    # The group_by attribute can have one of the following forms:\n    #  - None: no group by at all in the query\n    #  - A tuple of expressions: group by (at least) those expressions.\n    #    String refs are also allowed for now.\n    #  - True: group by all select fields of the model\n    # See compiler.get_group_by() for details.\n    group_by = None\n    order_by = ()\n    low_mark = 0  # Used for offset/limit.\n    high_mark = None  # Used for offset/limit.\n    distinct = False\n    distinct_fields = ()\n    select_for_update = False\n    select_for_update_nowait = False\n    select_for_update_skip_locked = False\n    select_for_update_of = ()\n    select_for_no_key_update = False\n    select_related = False\n    # Arbitrary limit for select_related to prevents infinite recursion.\n    max_depth = 5\n    # Holds the selects defined by a call to values() or values_list()\n    # excluding annotation_select and extra_select.\n    values_select = ()\n    selected = None\n\n    # SQL annotation-related attributes.\n    annotation_select_mask = None\n    _annotation_select_cache = None\n\n    # Set combination attributes.\n    combinator = None\n    combinator_all = False\n    combined_queries = ()\n\n    # These are for extensions. The contents are more or less appended verbatim\n    # to the appropriate clause.\n    extra_select_mask = None\n    _extra_select_cache = None\n\n    extra_tables = ()\n    extra_order_by = ()\n\n    # A tuple that is a set of model field names and either True, if these are\n    # the fields to defer, or False if these are the only fields to load.\n    deferred_loading = (frozenset(), True)\n\n    explain_info = None\n    def __init__(self, model, alias_cols=True):\n        self.model = model\n        self.alias_refcount = {}\n        # alias_map is the most important data structure regarding joins.\n        # It's used for recording which joins exist in the query and what\n        # types they are. The key is the alias of the joined table (possibly\n        # the table name) and the value is a Join-like object (see\n        # sql.datastructures.Join for more information).\n        self.alias_map = {}\n        # Whether to provide alias to columns during reference resolving.\n        self.alias_cols = alias_cols\n        # Sometimes the query contains references to aliases in outer queries\n        # (as a result of split_exclude). Correct alias quoting needs to know\n        # these aliases too. Map external tables to whether they are aliased.\n        self.external_aliases = {}\n        self.table_map = {}  # Maps table names to list of aliases.\n        self.used_aliases = set()\n        self.where = WhereNode()\n        # Maps alias -> Annotation Expression.\n        self.annotations = {}\n        # These are for extensions. The contents are more or less appended\n        # verbatim to the appropriate clause.\n        self.extra = {}  # Maps col_alias -> (col_sql, params).\n\n        self._filtered_relations = {}\n\n    @property\n    def output_field(self):\n        if len(self.select) == 1:\n            select = self.select[0]\n            return getattr(select, \"target\", None) or select.field\n        elif len(self.annotation_select) == 1:\n            return next(iter(self.annotation_select.values())).output_field\n\n    @cached_property\n    def base_table(self):\n        for alias in self.alias_map:\n            return alias\n    def __str__(self):\n        \"\"\"\n        Return the query as a string of SQL with the parameter values\n        substituted in (use sql_with_params() to see the unsubstituted string).\n        Parameter values won't necessarily be quoted correctly, since that is\n        done by the database interface at execution time.\n        \"\"\"\n        sql, params = self.sql_with_params()\n        return sql % params\n\n    def sql_with_params(self):\n        \"\"\"\n        Return the query as an SQL string and the parameters that will be\n        substituted into the query.\n        \"\"\"\n        return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()\n    def __deepcopy__(self, memo):\n        \"\"\"Limit the amount of work when a Query is deepcopied.\"\"\"\n        result = self.clone()\n        memo[id(self)] = result\n        return result\n\n    def get_compiler(self, using=None, connection=None, elide_empty=True):\n        if using is None and connection is None:\n            raise ValueError(\"Need either using or connection\")\n        if using:\n            connection = connections[using]\n        return connection.ops.compiler(self.compiler)(\n            self, connection, using, elide_empty         )\n\n    def get_meta(self):\n        \"\"\"\n        Return the Options instance (the model._meta) from which to start\n        processing. Normally, this is self.model._meta, but it can be changed\n        by subclasses.\n        \"\"\"\n        if self.model:\n            return self.model._meta\n\n    def clone(self):\n        \"\"\"\n        Return a copy of the current Query. A lightweight alternative to\n        deepcopy().\n        \"\"\"\n        obj = Empty()\n        obj.__class__ = self.__class__\n        # Copy references to everything.\n        obj.__dict__ = self.__dict__.copy()\n        # Clone attributes that can't use shallow copy.\n        obj.alias_refcount = self.alias_refcount.copy()\n        obj.alias_map = self.alias_map.copy()\n        obj.external_aliases = self.external_aliases.copy()\n        obj.table_map = self.table_map.copy()\n        obj.where = self.where.clone()\n        obj.annotations = self.annotations.copy()\n        if self.annotation_select_mask is not None:\n            obj.annotation_select_mask = self.annotation_select_mask.copy()\n        if self.combined_queries:\n            obj.combined_queries = tuple(                 [query.clone() for query in self.combined_queries]\n            )\n        # _annotation_select_cache cannot be copied, as doing so breaks the\n        # (necessary) state in which both annotations and\n        # _annotation_select_cache point to the same underlying objects.\n        # It will get re-populated in the cloned queryset the next time it's\n        # used.\n        obj._annotation_select_cache = None\n        obj.extra = self.extra.copy()\n        if self.extra_select_mask is not None:\n            obj.extra_select_mask = self.extra_select_mask.copy()\n        if self._extra_select_cache is not None:\n            obj._extra_select_cache = self._extra_select_cache.copy()\n        if self.select_related is not False:\n            # Use deepcopy because select_related stores fields in nested\n            # dicts.\n            obj.select_related = copy.deepcopy(obj.select_related)\n        if \"subq_aliases\" in self.__dict__:\n            obj.subq_aliases = self.subq_aliases.copy()\n        obj.used_aliases = self.used_aliases.copy()\n        obj._filtered_relations = self._filtered_relations.copy()\n        # Clear the cached_property, if it exists.\n        obj.__dict__.pop(\"base_table\", None)\n        return obj\n    def chain(self, klass=None):\n        \"\"\"\n        Return a copy of the current Query that's ready for another operation.\n        The klass argument changes the type of the Query, e.g. UpdateQuery.\n        \"\"\"\n        obj = self.clone()\n        if klass and obj.__class__ != klass:\n            obj.__class__ = klass\n        if not obj.filter_is_sticky:\n            obj.used_aliases = set()\n        obj.filter_is_sticky = False\n        if hasattr(obj, \"_setup_query\"):\n            obj._setup_query()\n        return obj\n\n    def relabeled_clone(self, change_map):\n        clone = self.clone()\n        clone.change_aliases(change_map)\n        return clone\n    def _get_col(self, target, field, alias):\n        if not self.alias_cols:\n            alias = None\n        return target.get_col(alias, field)\n\n    def get_aggregation(self, using, aggregate_exprs):\n        \"\"\"\n        Return the dictionary with the values of the existing aggregations.\n        \"\"\"\n        if not aggregate_exprs:\n            return {}\n        # Store annotation mask prior to temporarily adding aggregations for\n        # resolving purpose to facilitate their subsequent removal.\n        refs_subquery = False\n        refs_window = False\n        replacements = {}\n        annotation_select_mask = self.annotation_select_mask\n        for alias, aggregate_expr in aggregate_exprs.items():\n            self.check_alias(alias)\n            aggregate = aggregate_expr.resolve_expression(                 self, allow_joins=True, reuse=None, summarize=True             )\n            if not aggregate.contains_aggregate:\n                raise TypeError(\"%s is not an aggregate expression\" % alias)\n            # Temporarily add aggregate to annotations to allow remaining\n            # members of `aggregates` to resolve against each others.\n            self.append_annotation_mask([alias])\n            aggregate_refs = aggregate.get_refs()\n            refs_subquery |= any(\n                getattr(self.annotations[ref], \"contains_subquery\", False)\n                for ref in aggregate_refs             )\n            refs_window |= any(\n                getattr(self.annotations[ref], \"contains_over_clause\", True)\n                for ref in aggregate_refs\n            )\n            aggregate = aggregate.replace_expressions(replacements)\n            self.annotations[alias] = aggregate\n            replacements[Ref(alias, aggregate)] = aggregate\n        # Stash resolved aggregates now that they have been allowed to resolve\n        # against each other.\n        aggregates = {alias: self.annotations.pop(alias) for alias in aggregate_exprs}\n        self.set_annotation_mask(annotation_select_mask)\n        # Existing usage of aggregation can be determined by the presence of\n        # selected aggregates but also by filters against aliased aggregates.\n        _, having, qualify = self.where.split_having_qualify()\n        has_existing_aggregation = (\n            any(                 getattr(annotation, \"contains_aggregate\", True)\n                for annotation in self.annotations.values()             )\n            or having\n        )\n        set_returning_annotations = {             alias\n            for alias, annotation in self.annotation_select.items()\n            if getattr(annotation, \"set_returning\", False)\n        }\n        # Decide if we need to use a subquery.\n        #\n        # Existing aggregations would cause incorrect results as\n        # get_aggregation() must produce just one result and thus must not use\n        # GROUP BY.\n        #\n        # If the query has limit or distinct, or uses set operations, then\n        # those operations must be done in a subquery so that the query\n        # aggregates on the limit and/or distinct results instead of applying\n        # the distinct and limit after the aggregation.\n        if (             isinstance(self.group_by, tuple)\n            or self.is_sliced\n            or has_existing_aggregation\n            or refs_subquery             or refs_window\n            or qualify\n            or self.distinct\n            or self.combinator\n            or set_returning_annotations\n        ):\n            from django.db.models.sql.subqueries import AggregateQuery\n            inner_query = self.clone()\n            inner_query.subquery = True\n            outer_query = AggregateQuery(self.model, inner_query)\n            inner_query.select_for_update = False\n            inner_query.select_related = False\n            inner_query.set_annotation_mask(self.annotation_select)\n            # Queries with distinct_fields need ordering and when a limit is\n            # applied we must take the slice from the ordered query. Otherwise\n            # no need for ordering.\n            if inner_query.orderby_issubset_groupby:\n                inner_query.clear_ordering(force=False)\n            if not inner_query.distinct:\n                # If the inner query uses default select and it has some\n                # aggregate annotations, then we must make sure the inner\n                # query is grouped by the main model's primary key. However,\n                # clearing the select clause can alter results if distinct is\n                # used.\n                if inner_query.default_cols and has_existing_aggregation:\n                    inner_query.group_by = (                         self.model._meta.pk.get_col(inner_query.get_initial_alias()),                     )\n                inner_query.default_cols = False\n                if not qualify and not self.combinator:\n                    # Mask existing annotations that are not referenced by\n                    # aggregates to be pushed to the outer query unless\n                    # filtering against window functions or if the query is\n                    # combined as both would require complex realiasing logic.\n                    annotation_mask = set()\n                    if isinstance(self.group_by, tuple):\n                        for expr in self.group_by:\n                            annotation_mask |= expr.get_refs()\n                    for aggregate in aggregates.values():\n                        annotation_mask |= aggregate.get_refs()\n                    # Avoid eliding expressions that might have an incidence on\n                    # the implicit grouping logic.\n                    for annotation_alias, annotation in self.annotation_select.items():\n                        if annotation.get_group_by_cols():\n                            annotation_mask.add(annotation_alias)\n                    inner_query.set_annotation_mask(annotation_mask)\n                    # Annotations that possibly return multiple rows cannot\n                    # be masked as they might have an incidence on the query.\n                    annotation_mask |= set_returning_annotations\n\n            # Add aggregates to the outer AggregateQuery. This requires making\n            # sure all columns referenced by the aggregates are selected in the\n            # inner query. It is achieved by retrieving all column references\n            # by the aggregates, explicitly selecting them in the inner query,\n            # and making sure the aggregates are repointed to them.\n            col_refs = {}\n            for alias, aggregate in aggregates.items():\n                replacements = {}\n                for col in self._gen_cols([aggregate], resolve_refs=False):\n                    if not (col_ref := col_refs.get(col)):\n                        index = len(col_refs) + 1\n                        col_alias = f\"__col{index}\"\n                        col_ref = Ref(col_alias, col)\n                        col_refs[col] = col_ref\n                        inner_query.add_annotation(col, col_alias)\n                    replacements[col] = col_ref\n                outer_query.annotations[alias] = aggregate.replace_expressions(                     replacements\n                )\n            if (\n                inner_query.select == ()\n                and not inner_query.default_cols                 and not inner_query.annotation_select_mask             ):\n                # In case of Model.objects[0:3].count(), there would be no\n                # field selected in the inner query, yet we must use a\n                # subquery. So, make sure at least one field is selected.\n                inner_query.select = (                     self.model._meta.pk.get_col(inner_query.get_initial_alias()),                 )\n        else:\n            outer_query = self\n            self.select = ()\n            self.selected = None\n            self.default_cols = False\n            self.extra = {}\n            if self.annotations:\n                # Inline reference to existing annotations and mask them as\n                # they are unnecessary given only the summarized aggregations\n                # are requested.\n                replacements = {\n                    Ref(alias, annotation): annotation                     for alias, annotation in self.annotations.items()                 }\n                self.annotations = {\n                    alias: aggregate.replace_expressions(replacements)\n                    for alias, aggregate in aggregates.items()\n                }\n            else:\n                self.annotations = aggregates\n            self.set_annotation_mask(aggregates)\n        empty_set_result = [\n            expression.empty_result_set_value\n            for expression in outer_query.annotation_select.values()\n        ]\n        elide_empty = not any(result is NotImplemented for result in empty_set_result)\n        outer_query.clear_ordering(force=True)\n        outer_query.clear_limits()\n        outer_query.select_for_update = False\n        outer_query.select_related = False\n        compiler = outer_query.get_compiler(using, elide_empty=elide_empty)\n        result = compiler.execute_sql(SINGLE)\n        if result is None:\n            result = empty_set_result\n        else:\n            cols = outer_query.annotation_select.values()\n            converters = compiler.get_converters(cols)\n            rows = compiler.apply_converters((result,), converters)\n            if compiler.has_composite_fields(cols):\n                rows = compiler.composite_fields_to_tuples(rows, cols)\n            result = next(rows)\n\n        return dict(zip(outer_query.annotation_select, result))\n\n    def get_count(self, using):\n        \"\"\"\n        Perform a COUNT() query using the current filter constraints.\n        \"\"\"\n        obj = self.clone()\n        return obj.get_aggregation(using, {\"__count\": Count(\"*\")})[\"__count\"]\n\n    def has_filters(self):\n        return self.where\n\n    def exists(self, limit=True):\n        q = self.clone()\n        if not (q.distinct and q.is_sliced):\n            if q.group_by is True:\n                q.add_fields(                     (f.attname for f in self.model._meta.concrete_fields), False                 )\n                # Disable GROUP BY aliases to avoid orphaning references to the\n                # SELECT clause which is about to be cleared.\n                q.set_group_by(allow_aliases=False)\n            q.clear_select_clause()\n        if q.combined_queries and q.combinator == \"union\":\n            q.combined_queries = tuple(                 combined_query.exists(limit=False)\n                for combined_query in q.combined_queries             )\n        q.clear_ordering(force=True)\n        if limit is True:\n            q.set_limits(high=1)\n        q.add_annotation(Value(1), \"a\")\n        return q\n    def has_results(self, using):\n        q = self.exists()\n        compiler = q.get_compiler(using=using)\n        return compiler.has_results()\n    def explain(self, using, format=None, **options):\n        q = self.clone()\n        for option_name in options:\n            if (\n                not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)                 or \"--\" in option_name             ):\n                raise ValueError(f\"Invalid option name: {option_name!r}.\")\n        q.explain_info = ExplainInfo(format, options)\n        compiler = q.get_compiler(using=using)\n        return \"\\n\".join(compiler.explain_query())\n    def combine(self, rhs, connector):\n        \"\"\"\n        Merge the 'rhs' query into the current one (with any 'rhs' effects\n        being applied *after* (that is, \"to the right of\") anything in the\n        current query. 'rhs' is not modified during a call to this function.\n\n        The 'connector' parameter describes how to connect filters from the\n        'rhs' query.\n        \"\"\"\n        if self.model != rhs.model:\n            raise TypeError(\"Cannot combine queries on two different base models.\")\n        if self.is_sliced:\n            raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n        if self.distinct != rhs.distinct:\n            raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n        if self.distinct_fields != rhs.distinct_fields:\n            raise TypeError(\"Cannot combine queries with different distinct fields.\")\n        # If lhs and rhs shares the same alias prefix, it is possible to have\n        # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up\n        # as T4 -> T6 while combining two querysets. To prevent this, change an\n        # alias prefix of the rhs and update current aliases accordingly,\n        # except if the alias is the base table since it must be present in the\n        # query on both sides.\n        initial_alias = self.get_initial_alias()\n        rhs = rhs.clone()\n        rhs.bump_prefix(self, exclude={initial_alias})\n\n        # Work out how to relabel the rhs aliases, if necessary.\n        change_map = {}\n        conjunction = connector == AND\n\n        # Determine which existing joins can be reused. When combining the\n        # query with AND we must recreate all joins for m2m filters. When\n        # combining with OR we can reuse joins. The reason is that in AND\n        # case a single row can't fulfill a condition like:\n        #     revrel__col=1 & revrel__col=2\n        # But, there might be two different related rows matching this\n        # condition. In OR case a single True is enough, so single row is\n        # enough, too.\n        #\n        # Note that we will be creating duplicate joins for non-m2m joins in\n        # the AND case. The results will be correct but this creates too many\n        # joins. This is something that could be fixed later on.\n        reuse = set() if conjunction else set(self.alias_map)\n        joinpromoter = JoinPromoter(connector, 2, False)\n        joinpromoter.add_votes(\n            j for j in self.alias_map if self.alias_map[j].join_type == INNER         )\n        rhs_votes = set()\n        # Now, add the joins from rhs query into the new query (skipping base\n        # table).\n        rhs_tables = list(rhs.alias_map)[1:]\n        for alias in rhs_tables:\n            join = rhs.alias_map[alias]\n            # If the left side of the join was already relabeled, use the\n            # updated alias.\n            join = join.relabeled_clone(change_map)\n            new_alias = self.join(join, reuse=reuse)\n            if join.join_type == INNER:\n                rhs_votes.add(new_alias)\n            # We can't reuse the same join again in the query. If we have two\n            # distinct joins for the same connection in rhs query, then the\n            # combined query must have two joins, too.\n            reuse.discard(new_alias)\n            if alias != new_alias:\n                change_map[alias] = new_alias\n            if not rhs.alias_refcount[alias]:\n                # The alias was unused in the rhs query. Unref it so that it\n                # will be unused in the new query, too. We have to add and\n                # unref the alias so that join promotion has information of\n                # the join type for the unused alias.\n                self.unref_alias(new_alias)\n        joinpromoter.add_votes(rhs_votes)\n        joinpromoter.update_join_types(self)\n        # Combine subqueries aliases to ensure aliases relabelling properly\n        # handle subqueries when combining where and select clauses.\n        self.subq_aliases |= rhs.subq_aliases\n\n        # Now relabel a copy of the rhs where-clause and add it to the current\n        # one.\n        w = rhs.where.clone()\n        w.relabel_aliases(change_map)\n        self.where.add(w, connector)\n        # Selection columns and extra extensions are those provided by 'rhs'.\n        if rhs.select:\n            self.set_select([col.relabeled_clone(change_map) for col in rhs.select])\n        else:\n            self.select = ()\n\n        if connector == OR:\n            # It would be nice to be able to handle this, but the queries don't\n            # really make sense (or return consistent value sets). Not worth\n            # the extra complexity when you can write a real query instead.\n            if self.extra and rhs.extra:\n                raise ValueError(                     \"When merging querysets using 'or', you cannot have \"                     \"extra(select=...) on both sides.\"\n                )\n        self.extra.update(rhs.extra)\n        extra_select_mask = set()\n        if self.extra_select_mask is not None:\n            extra_select_mask.update(self.extra_select_mask)\n        if rhs.extra_select_mask is not None:\n            extra_select_mask.update(rhs.extra_select_mask)\n        if extra_select_mask:\n            self.set_extra_mask(extra_select_mask)\n        self.extra_tables += rhs.extra_tables\n\n        # Ordering uses the 'rhs' ordering, unless it has none, in which case\n        # the current ordering is used.\n        self.order_by = rhs.order_by or self.order_by\n        self.extra_order_by = rhs.extra_order_by or self.extra_order_by\n\n    def _get_defer_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # All concrete fields and related objects that are not part of the\n        # defer mask must be included. If a relational field is encountered it\n        # gets added to the mask for it be considered if `select_related` and\n        # the cycle continues by recursively calling this function.\n        for field in opts.concrete_fields + opts.related_objects:\n            field_mask = mask.pop(field.name, None)\n            field_att_mask = None\n            if field_attname := getattr(field, \"attname\", None):\n                field_att_mask = mask.pop(field_attname, None)\n            if field_mask is None and field_att_mask is None:\n                select_mask.setdefault(field, {})\n            elif field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                # Virtual fields such as many-to-many and generic foreign keys\n                # cannot be effectively deferred. Historically, they were\n                # allowed to be passed to QuerySet.defer(). Ignore such field\n                # references until a layer of validation at mask alteration\n                # time is eventually implemented.\n                if field.many_to_many:\n                    continue\n                field_select_mask = select_mask.setdefault(field, {})\n                related_model = field.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask                 )\n        # Remaining defer entries must be references to filtered relations\n        # otherwise they are surfaced as missing field errors.\n        for field_name, field_mask in mask.items():\n            if filtered_relation := self._filtered_relations.get(field_name):\n                relation = opts.get_field(filtered_relation.relation_name)\n                field_select_mask = select_mask.setdefault((field_name, relation), {})\n                related_model = relation.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n            else:\n                opts.get_field(field_name)\n        return select_mask\n\n    def _get_only_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # Only include fields mentioned in the mask.\n        for field_name, field_mask in mask.items():\n            field = opts.get_field(field_name)\n            field_select_mask = select_mask.setdefault(field, {})\n            if field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                related_model = field.remote_field.model._meta.concrete_model\n                self._get_only_select_mask(                     related_model._meta, field_mask, field_select_mask\n                )\n        return select_mask\n\n    def get_select_mask(self):\n        \"\"\"\n        Convert the self.deferred_loading data structure to an alternate data\n        structure, describing the field that *will* be loaded. This is used to\n        compute the columns to select from the database and also by the\n        QuerySet class to work out which fields are being initialized on each\n        model. Models that have all their fields included aren't mentioned in\n        the result, only those that have field restrictions in place.\n        \"\"\"\n        field_names, defer = self.deferred_loading\n        if not field_names:\n            return {}\n        mask = {}\n        for field_name in field_names:\n            part_mask = mask\n            for part in field_name.split(LOOKUP_SEP):\n                part_mask = part_mask.setdefault(part, {})\n        opts = self.get_meta()\n        if defer:\n            return self._get_defer_select_mask(opts, mask)\n        return self._get_only_select_mask(opts, mask)\n\n    def table_alias(self, table_name, create=False, filtered_relation=None):\n        \"\"\"\n        Return a table alias for the given table_name and whether this is a\n        new alias or not.\n\n        If 'create' is true, a new alias is always created. Otherwise, the\n        most recently created alias for the table (if one exists) is reused.\n        \"\"\"\n        alias_list = self.table_map.get(table_name)\n        if not create and alias_list:\n            alias = alias_list[0]\n            self.alias_refcount[alias] += 1\n            return alias, False\n\n        # Create a new alias for this table.\n        if alias_list:\n            alias = \"%s%d\" % (self.alias_prefix, len(self.alias_map) + 1)\n            alias_list.append(alias)\n        else:\n            # The first occurrence of a table uses the table name directly.\n            alias = (\n                filtered_relation.alias if filtered_relation is not None else table_name\n            )\n            self.table_map[table_name] = [alias]\n        self.alias_refcount[alias] = 1\n        return alias, True\n\n    def ref_alias(self, alias):\n        \"\"\"Increases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] += 1\n\n    def unref_alias(self, alias, amount=1):\n        \"\"\"Decreases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] -= amount\n\n    def promote_joins(self, aliases):\n        \"\"\"\n        Promote recursively the join type of given aliases and its children to\n        an outer join. If 'unconditional' is False, only promote the join if\n        it is nullable or the parent join is an outer join.\n\n        The children promotion is done to avoid join chains that contain a\n        LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b\n        is promoted, then we must also promote b->c automatically, or otherwise\n        the promotion of a->b doesn't actually change anything in the query\n        results.\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type is None:\n                # This is the base table (first FROM entry) - this table\n                # isn't really joined at all in the query, so we should not\n                # alter its join type.\n                continue\n            # Only the first alias (skipped above) should have None join_type\n            assert self.alias_map[alias].join_type is not None\n            parent_alias = self.alias_map[alias].parent_alias\n            parent_louter = (\n                parent_alias and self.alias_map[parent_alias].join_type == LOUTER\n            )\n            already_louter = self.alias_map[alias].join_type == LOUTER\n            if (self.alias_map[alias].nullable or parent_louter) and not already_louter:\n                self.alias_map[alias] = self.alias_map[alias].promote()\n                # Join type of 'alias' changed, so re-examine all aliases that\n                # refer to this one.\n                aliases.extend(                     join\n                    for join in self.alias_map\n                    if self.alias_map[join].parent_alias == alias                     and join not in aliases\n                )\n    def demote_joins(self, aliases):\n        \"\"\"\n        Change join type from LOUTER to INNER for all joins in aliases.\n\n        Similarly to promote_joins(), this method must ensure no join chains\n        containing first an outer, then an inner join are generated. If we\n        are demoting b->c join in chain a LOUTER b LOUTER c then we must\n        demote a->b automatically, or otherwise the demotion of b->c doesn't\n        actually change anything in the query results. .\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type == LOUTER:\n                self.alias_map[alias] = self.alias_map[alias].demote()\n                parent_alias = self.alias_map[alias].parent_alias\n                if self.alias_map[parent_alias].join_type == INNER:\n                    aliases.append(parent_alias)\n    def reset_refcounts(self, to_counts):\n        \"\"\"\n        Reset reference counts for aliases so that they match the value passed\n        in `to_counts`.\n        \"\"\"\n        for alias, cur_refcount in self.alias_refcount.copy().items():\n            unref_amount = cur_refcount - to_counts.get(alias, 0)\n            self.unref_alias(alias, unref_amount)\n    def change_aliases(self, change_map):\n        \"\"\"\n        Change the aliases in change_map (which maps old-alias -> new-alias),\n        relabelling any references to them in select columns and the where\n        clause.\n        \"\"\"\n        if not change_map:\n            return self\n        # If keys and values of change_map were to intersect, an alias might be\n        # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending\n        # on their order in change_map.\n        assert set(change_map).isdisjoint(change_map.values())\n\n        # 1. Update references in \"select\" (normal columns plus aliases),\n        # \"group by\" and \"where\".\n        self.where.relabel_aliases(change_map)\n        if isinstance(self.group_by, tuple):\n            self.group_by = tuple(\n                [col.relabeled_clone(change_map) for col in self.group_by]\n            )\n        self.select = tuple([col.relabeled_clone(change_map) for col in self.select])\n        self.annotations = self.annotations and {\n            key: col.relabeled_clone(change_map)\n            for key, col in self.annotations.items()\n        }\n\n        # 2. Rename the alias in the internal table/alias datastructures.\n        for old_alias, new_alias in change_map.items():\n            if old_alias not in self.alias_map:\n                continue\n            alias_data = self.alias_map[old_alias].relabeled_clone(change_map)\n            self.alias_map[new_alias] = alias_data\n            self.alias_refcount[new_alias] = self.alias_refcount[old_alias]\n            del self.alias_refcount[old_alias]\n            del self.alias_map[old_alias]\n\n            table_aliases = self.table_map[alias_data.table_name]\n            for pos, alias in enumerate(table_aliases):\n                if alias == old_alias:\n                    table_aliases[pos] = new_alias\n                    break\n        # 3. Rename the direct external aliases and the ones of combined\n        # queries (union, intersection, difference).\n        self.external_aliases = {\n            # Table is aliased or it's being changed and thus is aliased.\n            change_map.get(alias, alias): (aliased or alias in change_map)             for alias, aliased in self.external_aliases.items()         }\n        for combined_query in self.combined_queries:\n            external_change_map = {                 alias: aliased\n                for alias, aliased in change_map.items()\n                if alias in combined_query.external_aliases\n            }\n            combined_query.change_aliases(external_change_map)\n\n    def bump_prefix(self, other_query, exclude=None):\n        \"\"\"\n        Change the alias prefix to the next letter in the alphabet in a way\n        that the other query's aliases and this query's aliases will not\n        conflict. Even tables that previously had no alias will get an alias\n        after this call. To prevent changing aliases use the exclude parameter.\n        \"\"\"\n        def prefix_gen():\n            \"\"\"\n            Generate a sequence of characters in alphabetical order:\n                -> 'A', 'B', 'C', ...\n\n            When the alphabet is finished, the sequence will continue with the\n            Cartesian product:\n                -> 'AA', 'AB', 'AC', ...\n            \"\"\"\n            alphabet = ascii_uppercase\n            prefix = chr(ord(self.alias_prefix) + 1)\n            yield prefix\n            for n in count(1):\n                seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet\n                for s in product(seq, repeat=n):\n                    yield \"\".join(s)\n                prefix = None\n\n        if self.alias_prefix != other_query.alias_prefix:\n            # No clashes between self and outer query should be possible.\n            return\n        # Explicitly avoid infinite loop. The constant divider is based on how\n        # much depth recursive subquery references add to the stack. This value\n        # might need to be adjusted when adding or removing function calls from\n        # the code path in charge of performing these operations.\n        local_recursion_limit = sys.getrecursionlimit() // 16\n        for pos, prefix in enumerate(prefix_gen()):\n            if prefix not in self.subq_aliases:\n                self.alias_prefix = prefix\n                break\n            if pos > local_recursion_limit:\n                raise RecursionError(                     \"Maximum recursion depth exceeded: too many subqueries.\"                 )\n        self.subq_aliases = self.subq_aliases.union([self.alias_prefix])\n        other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases)\n        if exclude is None:\n            exclude = {}\n        self.change_aliases(             {\n                alias: \"%s%d\" % (self.alias_prefix, pos)                 for pos, alias in enumerate(self.alias_map)                 if alias not in exclude\n            }\n        )\n    def get_initial_alias(self):\n        \"\"\"\n        Return the first alias for this query, after increasing its reference\n        count.\n        \"\"\"\n        if self.alias_map:\n            alias = self.base_table\n            self.ref_alias(alias)\n        elif self.model:\n            alias = self.join(self.base_table_class(self.get_meta().db_table, None))\n        else:\n            alias = None\n        return alias\n\n    def count_active_tables(self):\n        \"\"\"\n        Return the number of tables in this query with a non-zero reference\n        count. After execution, the reference counts are zeroed, so tables\n        added in compiler will not be seen by this method.\n        \"\"\"\n        return len([1 for count in self.alias_refcount.values() if count])\n\n    def join(self, join, reuse=None):\n        \"\"\"\n        Return an alias for the 'join', either reusing an existing alias for\n        that join or creating a new one. 'join' is either a base_table_class or\n        join_class.\n\n        The 'reuse' parameter can be either None which means all joins are\n        reusable, or it can be a set containing the aliases that can be reused.\n\n        A join is always created as LOUTER if the lhs alias is LOUTER to make\n        sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new\n        joins are created as LOUTER if the join is nullable.\n        \"\"\"\n        reuse_aliases = [\n            a\n            for a, j in self.alias_map.items()\n            if (reuse is None or a in reuse) and j == join\n        ]\n        if reuse_aliases:\n            if join.table_alias in reuse_aliases:\n                reuse_alias = join.table_alias\n            else:\n                # Reuse the most recent alias of the joined table\n                # (a many-to-many relation may be joined multiple times).\n                reuse_alias = reuse_aliases[-1]\n            self.ref_alias(reuse_alias)\n            return reuse_alias\n        # No reuse is possible, so we need a new alias.\n        alias, _ = self.table_alias(\n            join.table_name, create=True, filtered_relation=join.filtered_relation         )\n        if join.join_type:\n            if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:\n                join_type = LOUTER\n            else:\n                join_type = INNER\n            join.join_type = join_type\n        join.table_alias = alias\n        self.alias_map[alias] = join\n        if filtered_relation := join.filtered_relation:\n            resolve_reuse = reuse\n            if resolve_reuse is not None:\n                resolve_reuse = set(reuse) | {alias}\n            joins_len = len(self.alias_map)\n            join.filtered_relation = filtered_relation.resolve_expression(\n                self, reuse=resolve_reuse             )\n            # Some joins were during expression resolving, they must be present\n            # before the one we just added.\n            if joins_len < len(self.alias_map):\n                self.alias_map[alias] = self.alias_map.pop(alias)\n        return alias\n    def join_parent_model(self, opts, model, alias, seen):\n        \"\"\"\n        Make sure the given 'model' is joined in the query. If 'model' isn't\n        a parent of 'opts' or if it is None this method is a no-op.\n\n        The 'alias' is the root alias for starting the join, 'seen' is a dict\n        of model -> alias of existing joins. It must also contain a mapping\n        of None -> some alias. This will be returned in the no-op case.\n        \"\"\"\n        if model in seen:\n            return seen[model]\n        chain = opts.get_base_chain(model)\n        if not chain:\n            return alias\n        curr_opts = opts\n        for int_model in chain:\n            if int_model in seen:\n                curr_opts = int_model._meta\n                alias = seen[int_model]\n                continue\n            # Proxy model have elements in base chain\n            # with no parents, assign the new options\n            # object and skip to the next base in that\n            # case\n            if not curr_opts.parents[int_model]:\n                curr_opts = int_model._meta\n                continue\n            link_field = curr_opts.get_ancestor_link(int_model)\n            join_info = self.setup_joins([link_field.name], curr_opts, alias)\n            curr_opts = int_model._meta\n            alias = seen[int_model] = join_info.joins[-1]\n        return alias or seen[None]\n    def check_alias(self, alias):\n        # RemovedInDjango70Warning: When the deprecation ends, remove.\n        if \"%\" in alias:\n            warnings.warn(                 \"Using percent signs in a column alias is deprecated.\",\n                category=RemovedInDjango70Warning,\n                skip_file_prefixes=django_file_prefixes(),             )\n        if FORBIDDEN_ALIAS_PATTERN.search(alias):\n            raise ValueError(\n                \"Column aliases cannot contain whitespace characters, hashes, \"\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # \"control characters, quotation marks, semicolons, percent \"\n                # \"signs, or SQL comments.\"\n                \"control characters, quotation marks, semicolons, or SQL comments.\"\n            )\n\n    def add_annotation(self, annotation, alias, select=True):\n        \"\"\"Add a single annotation expression to the Query.\"\"\"\n        self.check_alias(alias)\n        annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None)\n        if select:\n            self.append_annotation_mask([alias])\n        else:\n            self.set_annotation_mask(set(self.annotation_select).difference({alias}))\n        self.annotations[alias] = annotation\n        if select and self.selected:\n            self.selected[alias] = alias\n    @property\n    def _subquery_fields_len(self):\n        if not self.has_select_fields or not self.select:\n            return len(self.model._meta.pk_fields)\n        return len(self.select) + sum(             len(expr.targets) - 1 for expr in self.select if isinstance(expr, ColPairs)\n        )\n\n    def resolve_expression(self, query, *args, **kwargs):\n        clone = self.clone()\n        # Subqueries need to use a different set of aliases than the outer\n        # query.\n        clone.bump_prefix(query)\n        clone.subquery = True\n        clone.where.resolve_expression(query, *args, **kwargs)\n        # Resolve combined queries.\n        if clone.combinator:\n            clone.combined_queries = tuple(                 [\n                    combined_query.resolve_expression(query, *args, **kwargs)\n                    for combined_query in clone.combined_queries\n                ]\n            )\n        for key, value in clone.annotations.items():\n            resolved = value.resolve_expression(query, *args, **kwargs)\n            if hasattr(resolved, \"external_aliases\"):\n                resolved.external_aliases.update(clone.external_aliases)\n            clone.annotations[key] = resolved\n        # Outer query's aliases are considered external.\n        for alias, table in query.alias_map.items():\n            clone.external_aliases[alias] = (                 isinstance(table, Join)\n                and table.join_field.related_model._meta.db_table != alias\n            ) or (                 isinstance(table, BaseTable) and table.table_name != table.table_alias             )\n        return clone\n    def get_external_cols(self):\n        exprs = chain(self.annotations.values(), self.where.children)\n        return [\n            col             for col in self._gen_cols(exprs, include_external=True)\n            if col.alias in self.external_aliases\n        ]\n\n    def get_group_by_cols(self, wrapper=None):\n        # If wrapper is referenced by an alias for an explicit GROUP BY through\n        # values() a reference to this expression and not the self must be\n        # returned to ensure external column references are not grouped against\n        # as well.\n        external_cols = self.get_external_cols()\n        if any(col.possibly_multivalued for col in external_cols):\n            return [wrapper or self]\n        return external_cols\n\n    def as_sql(self, compiler, connection):\n        # Some backends (e.g. Oracle) raise an error when a subquery contains\n        # unnecessary ORDER BY clause.\n        if (\n            self.subquery             and not connection.features.ignores_unnecessary_order_by_in_subqueries\n        ):\n            self.clear_ordering(force=False)\n            for query in self.combined_queries:\n                query.clear_ordering(force=False)\n        sql, params = self.get_compiler(connection=connection).as_sql()\n        if self.subquery:\n            sql = \"(%s)\" % sql\n        return sql, params\n\n    def resolve_lookup_value(self, value, can_reuse, allow_joins, summarize=False):\n        if hasattr(value, \"resolve_expression\"):\n            value = value.resolve_expression(                 self,                 reuse=can_reuse,\n                allow_joins=allow_joins,                 summarize=summarize,             )\n        elif isinstance(value, (list, tuple)):\n            # The items of the iterable may be expressions and therefore need\n            # to be resolved independently.\n            values = (\n                self.resolve_lookup_value(sub_value, can_reuse, allow_joins, summarize)\n                for sub_value in value\n            )\n            type_ = type(value)\n            if hasattr(type_, \"_make\"):  # namedtuple\n                return type_(*values)\n            return type_(values)\n        return value\n\n    def solve_lookup_type(self, lookup, summarize=False):\n        \"\"\"\n        Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').\n        \"\"\"\n        lookup_splitted = lookup.split(LOOKUP_SEP)\n        if self.annotations:\n            annotation, expression_lookups = refs_expression(\n                lookup_splitted, self.annotations\n            )\n            if annotation:\n                expression = self.annotations[annotation]\n                if summarize:\n                    expression = Ref(annotation, expression)\n                return expression_lookups, (), expression\n        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())\n        field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)]\n        if len(lookup_parts) > 1 and not field_parts:\n            raise FieldError(                 'Invalid lookup \"%s\" for model %s\".'\n                % (lookup, self.get_meta().model.__name__)\n            )\n        return lookup_parts, field_parts, False\n\n    def check_query_object_type(self, value, opts, field):\n        \"\"\"\n        Check whether the object passed while querying is of the correct type.\n        If not, raise a ValueError specifying the wrong object.\n        \"\"\"\n        if hasattr(value, \"_meta\"):\n            if not check_rel_lookup_compatibility(value._meta.model, opts, field):\n                raise ValueError(\n                    'Cannot query \"%s\": Must be \"%s\" instance.'\n                    % (value, opts.object_name)                 )\n\n    def check_related_objects(self, field, value, opts):\n        \"\"\"Check the type of object passed to query relations.\"\"\"\n        if field.is_relation:\n            # Check that the field and the queryset use the same model in a\n            # query like .filter(author=Author.objects.all()). For example, the\n            # opts would be Author's (from the author field) and value.model\n            # would be Author.objects.all() queryset's .model (Author also).\n            # The field is the related field on the lhs side.\n            if (                 isinstance(value, Query)                 and not value.has_select_fields                 and not check_rel_lookup_compatibility(value.model, opts, field)\n            ):\n                raise ValueError(                     'Cannot use QuerySet for \"%s\": Use a QuerySet for \"%s\".'\n                    % (value.model._meta.object_name, opts.object_name)                 )\n            elif hasattr(value, \"_meta\"):\n                self.check_query_object_type(value, opts, field)\n            elif hasattr(value, \"__iter__\"):\n                for v in value:\n                    self.check_query_object_type(v, opts, field)\n\n    def check_filterable(self, expression):\n        \"\"\"Raise an error if expression cannot be used in a WHERE clause.\"\"\"\n        if hasattr(expression, \"resolve_expression\") and not getattr(             expression, \"filterable\", True\n        ):\n            raise NotSupportedError(                 expression.__class__.__name__ + \" is disallowed in the filter \"\n                \"clause.\"\n            )\n        if hasattr(expression, \"get_source_expressions\"):\n            for expr in expression.get_source_expressions():\n                self.check_filterable(expr)\n    def build_lookup(self, lookups, lhs, rhs):\n        \"\"\"\n        Try to extract transforms and lookup from given lhs.\n\n        The lhs value is something that works like SQLExpression.\n        The rhs value is what the lookup is going to compare against.\n        The lookups is a list of names to extract using get_lookup()\n        and get_transform().\n        \"\"\"\n        # __exact is the default lookup if one isn't given.\n        *transforms, lookup_name = lookups or [\"exact\"]\n        for name in transforms:\n            lhs = self.try_transform(lhs, name, lookups)\n        # First try get_lookup() so that the lookup takes precedence if the lhs\n        # supports both transform and lookup for the name.\n        lookup_class = lhs.get_lookup(lookup_name)\n        if not lookup_class:\n            # A lookup wasn't found. Try to interpret the name as a transform\n            # and do an Exact lookup against it.\n            lhs = self.try_transform(lhs, lookup_name)\n            lookup_name = \"exact\"\n            lookup_class = lhs.get_lookup(lookup_name)\n            if not lookup_class:\n                return\n        lookup = lookup_class(lhs, rhs)\n        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all\n        # uses of None as a query value unless the lookup supports it.\n        if lookup.rhs is None and not lookup.can_use_none_as_rhs:\n            if lookup_name not in (\"exact\", \"iexact\"):\n                raise ValueError(\"Cannot use None as a query value\")\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        # For Oracle '' is equivalent to null. The check must be done at this\n        # stage because join promotion can't be done in the compiler. Using\n        # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.\n        # A similar thing is done in is_nullable(), too.\n        if (\n            lookup_name in (\"exact\", \"iexact\")             and lookup.rhs == \"\"\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        ):\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        return lookup\n    def try_transform(self, lhs, name, lookups=None):\n        \"\"\"\n        Helper method for build_lookup(). Try to fetch and initialize\n        a transform for name parameter from lhs.\n        \"\"\"\n        transform_class = lhs.get_transform(name)\n        if transform_class:\n            return transform_class(lhs)\n        else:\n            output_field = lhs.output_field.__class__\n            suggested_lookups = difflib.get_close_matches(\n                name, lhs.output_field.get_lookups()             )\n            if suggested_lookups:\n                suggestion = \", perhaps you meant %s?\" % \" or \".join(suggested_lookups)\n            else:\n                suggestion = \".\"\n            if lookups is not None:\n                name_index = lookups.index(name)\n                unsupported_lookup = LOOKUP_SEP.join(lookups[name_index:])\n            else:\n                unsupported_lookup = name\n            raise FieldError(\n                \"Unsupported lookup '%s' for %s or join on the field not \"\n                \"permitted%s\" % (unsupported_lookup, output_field.__name__, suggestion)\n            )\n    def build_filter(\n        self,\n        filter_expr,         branch_negated=False,\n        current_negated=False,         can_reuse=None,\n        allow_joins=True,         split_subq=True,         check_filterable=True,\n        summarize=False,         update_join_types=True,\n    ):\n        \"\"\"\n        Build a WhereNode for a single filter clause but don't add it\n        to this Query. Query.add_q() will then add this filter to the where\n        Node.\n        The 'branch_negated' tells us if the current branch contains any\n        negations. This will be used to determine if subqueries are needed.\n        The 'current_negated' is used to determine if the current filter is\n        negated or not and this will be used to determine if IS NULL filtering\n        is needed.\n\n        The difference between current_negated and branch_negated is that\n        branch_negated is set on first negation, but current_negated is\n        flipped for each negation.\n        Note that add_filter will not do any negating itself, that is done\n        upper in the code by add_q().\n        The 'can_reuse' is a set of reusable joins for multijoins.\n\n        The method will create a filter clause that can be added to the current\n        query. However, if the filter isn't added to the query then the caller\n        is responsible for unreffing the joins used.\n        \"\"\"\n        if isinstance(filter_expr, dict):\n            raise FieldError(\"Cannot parse keyword query as dict\")\n        if isinstance(filter_expr, Q):\n            return self._add_q(                 filter_expr,                 branch_negated=branch_negated,                 current_negated=current_negated,\n                used_aliases=can_reuse,                 allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,                 summarize=summarize,                 update_join_types=update_join_types,\n            )\n        if hasattr(filter_expr, \"resolve_expression\"):\n            if not getattr(filter_expr, \"conditional\", False):\n                raise TypeError(\"Cannot filter against a non-conditional expression.\")\n            condition = filter_expr.resolve_expression(                 self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize\n            )\n            if not isinstance(condition, Lookup):\n                condition = self.build_lookup([\"exact\"], condition, True)\n            return WhereNode([condition], connector=AND), []\n        arg, value = filter_expr\n        if not arg:\n            raise FieldError(\"Cannot parse keyword query %r\" % arg)\n        lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize)\n        if check_filterable:\n            self.check_filterable(reffed_expression)\n        if not allow_joins and len(parts) > 1:\n            raise FieldError(\"Joined field references are not permitted in this query\")\n        pre_joins = self.alias_refcount.copy()\n        value = self.resolve_lookup_value(value, can_reuse, allow_joins, summarize)\n        used_joins = {\n            k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)\n        }\n\n        if check_filterable:\n            self.check_filterable(value)\n        if reffed_expression:\n            condition = self.build_lookup(lookups, reffed_expression, value)\n            return WhereNode([condition], connector=AND), []\n\n        opts = self.get_meta()\n        alias = self.get_initial_alias()\n        allow_many = not branch_negated or not split_subq\n        try:\n            join_info = self.setup_joins(\n                parts,\n                opts,\n                alias,\n                can_reuse=can_reuse,\n                allow_many=allow_many,\n            )\n\n            # Prevent iterator from being consumed by check_related_objects()\n            if isinstance(value, Iterator):\n                value = list(value)\n            self.check_related_objects(join_info.final_field, value, join_info.opts)\n\n            # split_exclude() needs to know which joins were generated for the\n            # lookup parts\n            self._lookup_joins = join_info.joins\n        except MultiJoin as e:\n            return self.split_exclude(filter_expr, can_reuse, e.names_with_path)\n\n        # Update used_joins before trimming since they are reused to determine\n        # which joins could be later promoted to INNER.\n        used_joins.update(join_info.joins)\n        targets, alias, join_list = self.trim_joins(             join_info.targets, join_info.joins, join_info.path\n        )\n        if can_reuse is not None:\n            can_reuse.update(join_list)\n        if join_info.final_field.is_relation:\n            if len(targets) == 1:\n                col = self._get_col(targets[0], join_info.final_field, alias)\n            else:\n                col = ColPairs(alias, targets, join_info.targets, join_info.final_field)\n        else:\n            col = self._get_col(targets[0], join_info.final_field, alias)\n\n        condition = self.build_lookup(lookups, col, value)\n        lookup_type = condition.lookup_name\n        clause = WhereNode([condition], connector=AND)\n\n        require_outer = (\n            lookup_type == \"isnull\" and condition.rhs is True and not current_negated\n        )\n        if (\n            current_negated             and (lookup_type != \"isnull\" or condition.rhs is False)             and condition.rhs is not None\n        ):\n            require_outer = True\n            if lookup_type != \"isnull\":\n                # The condition added here will be SQL like this:\n                # NOT (col IS NOT NULL), where the first NOT is added in\n                # upper layers of code. The reason for addition is that if col\n                # is null, then col != someval will result in SQL \"unknown\"\n                # which isn't the same as in Python. The Python None handling\n                # is wanted, and it can be gotten by\n                # (col IS NULL OR col != someval)\n                #   <=>\n                # NOT (col IS NOT NULL AND col = someval).\n                if (\n                    self.is_nullable(targets[0])                     or self.alias_map[join_list[-1]].join_type == LOUTER\n                ):\n                    lookup_class = targets[0].get_lookup(\"isnull\")\n                    col = self._get_col(targets[0], join_info.targets[0], alias)\n                    # Use OR + IS NULL when RHS `in` values include None.\n                    if (\n                        lookup_type == \"in\"                         # Check containers (not strings or bytes).\n                        and isinstance(condition.rhs, Iterable)                         and not isinstance(condition.rhs, (str, bytes))\n                        and any(v is None for v in condition.rhs)\n                    ):\n                        clause.add(lookup_class(col, True), OR)\n                    else:\n                        clause.add(lookup_class(col, False), AND)\n                # If someval is a nullable column, someval IS NOT NULL is\n                # added.\n                if isinstance(value, Col) and self.is_nullable(value.target):\n                    lookup_class = value.target.get_lookup(\"isnull\")\n                    clause.add(lookup_class(value, False), AND)\n        return clause, used_joins if not require_outer else ()\n    def add_filter(self, filter_lhs, filter_rhs):\n        self.add_q(Q((filter_lhs, filter_rhs)))\n    def add_q(self, q_object, reuse_all=False):\n        \"\"\"\n        A preprocessor for the internal _add_q(). Responsible for doing final\n        join promotion.\n        \"\"\"\n        # For join promotion this case is doing an AND for the added q_object\n        # and existing conditions. So, any existing inner join forces the join\n        # type to remain inner. Existing outer joins can however be demoted.\n        # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if\n        # rel_a doesn't produce any rows, then the whole condition must fail.\n        # So, demotion is OK.\n        existing_inner = {\n            a for a in self.alias_map if self.alias_map[a].join_type == INNER         }\n        if reuse_all:\n            can_reuse = set(self.alias_map)\n        else:\n            can_reuse = self.used_aliases\n        clause, _ = self._add_q(q_object, can_reuse)\n        if clause:\n            self.where.add(clause, AND)\n        self.demote_joins(existing_inner)\n    def build_where(self, filter_expr):\n        return self.build_filter(filter_expr, allow_joins=False)[0]\n\n    def clear_where(self):\n        self.where = WhereNode()\n\n    def _add_q(\n        self,         q_object,\n        used_aliases,\n        branch_negated=False,\n        current_negated=False,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,         summarize=False,         update_join_types=True,\n    ):\n        \"\"\"Add a Q-object to the current filter.\"\"\"\n        connector = q_object.connector\n        current_negated ^= q_object.negated\n        branch_negated = branch_negated or q_object.negated\n        target_clause = WhereNode(connector=connector, negated=q_object.negated)\n        joinpromoter = JoinPromoter(             q_object.connector, len(q_object.children), current_negated\n        )\n        for child in q_object.children:\n            child_clause, needed_inner = self.build_filter(\n                child,\n                can_reuse=used_aliases,                 branch_negated=branch_negated,                 current_negated=current_negated,                 allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n            joinpromoter.add_votes(needed_inner)\n            if child_clause:\n                target_clause.add(child_clause, connector)\n        if update_join_types:\n            needed_inner = joinpromoter.update_join_types(self)\n        else:\n            needed_inner = []\n        return target_clause, needed_inner\n    def add_filtered_relation(self, filtered_relation, alias):\n        if \".\" in alias:\n            raise ValueError(\n                \"FilteredRelation doesn't support aliases with periods \"                 \"(got %r).\" % alias\n            )\n        self.check_alias(alias)\n        filtered_relation.alias = alias\n        relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(             filtered_relation.relation_name\n        )\n        if relation_lookup_parts:\n            raise ValueError(                 \"FilteredRelation's relation_name cannot contain lookups \"                 \"(got %r).\" % filtered_relation.relation_name\n            )\n        for lookup in get_children_from_q(filtered_relation.condition):\n            lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)\n            shift = 2 if not lookup_parts else 1\n            lookup_field_path = lookup_field_parts[:-shift]\n            for idx, lookup_field_part in enumerate(lookup_field_path):\n                if len(relation_field_parts) > idx:\n                    if relation_field_parts[idx] != lookup_field_part:\n                        raise ValueError(                             \"FilteredRelation's condition doesn't support \"\n                            \"relations outside the %r (got %r).\"                             % (filtered_relation.relation_name, lookup)\n                        )\n            if len(lookup_field_parts) > len(relation_field_parts) + 1:\n                raise ValueError(                     \"FilteredRelation's condition doesn't support nested \"                     \"relations deeper than the relation_name (got %r for \"                     \"%r).\" % (lookup, filtered_relation.relation_name)\n                )\n        filtered_relation = filtered_relation.clone()\n        filtered_relation.condition = rename_prefix_from_q(\n            filtered_relation.relation_name,             alias,             filtered_relation.condition,\n        )\n        self._filtered_relations[filtered_relation.alias] = filtered_relation\n\n    def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):\n        \"\"\"\n        Walk the list of names and turns them into PathInfo tuples. A single\n        name in 'names' can generate multiple PathInfos (m2m, for example).\n        'names' is the path of names to travel, 'opts' is the model Options we\n        start the name resolving from, 'allow_many' is as for setup_joins().\n        If fail_on_missing is set to True, then a name that can't be resolved\n        will generate a FieldError.\n        Return a list of PathInfo tuples. In addition return the final field\n        (the last used join field) and target (which is a field guaranteed to\n        contain the same value as the final field). Finally, return those names\n        that weren't found (which are likely transforms and the final lookup).\n        \"\"\"\n        path, names_with_path = [], []\n        for pos, name in enumerate(names):\n            cur_names_with_path = (name, [])\n            if name == \"pk\" and opts is not None:\n                name = opts.pk.name\n\n            field = None\n            filtered_relation = None\n            try:\n                if opts is None:\n                    raise FieldDoesNotExist\n                field = opts.get_field(name)\n            except FieldDoesNotExist:\n                if name in self.annotations:\n                    field = self.annotations[name].output_field\n                elif name in self._filtered_relations and pos == 0:\n                    filtered_relation = self._filtered_relations[name]\n                    if LOOKUP_SEP in filtered_relation.relation_name:\n                        parts = filtered_relation.relation_name.split(LOOKUP_SEP)\n                        filtered_relation_path, field, _, _ = self.names_to_path(\n                            parts,                             opts,\n                            allow_many,\n                            fail_on_missing,\n                        )\n                        path.extend(filtered_relation_path[:-1])\n                    else:\n                        field = opts.get_field(filtered_relation.relation_name)\n            if field is not None:\n                # Fields that contain one-to-many relations with a generic\n                # model (like a GenericForeignKey) cannot generate reverse\n                # relations and therefore cannot be used for reverse querying.\n                if field.is_relation and not field.related_model:\n                    raise FieldError(                         \"Field %r does not generate an automatic reverse \"\n                        \"relation and therefore cannot be used for reverse \"\n                        \"querying. If it is a GenericForeignKey, consider \"\n                        \"adding a GenericRelation.\" % name\n                    )\n                try:\n                    model = field.model._meta.concrete_model\n                except AttributeError:\n                    # QuerySet.annotate() may introduce fields that aren't\n                    # attached to a model.\n                    model = None\n            else:\n                # We didn't find the current field, so move position back\n                # one step.\n                pos -= 1\n                if pos == -1 or fail_on_missing:\n                    available = sorted(\n                        [\n                            *get_field_names_from_opts(opts),\n                            *self.annotations,                             *self._filtered_relations,                         ]                     )\n                    raise FieldError(                         \"Cannot resolve keyword '%s' into field. \"                         \"Choices are: %s\" % (name, \", \".join(available))\n                    )\n                break\n            # Check if we need any joins for concrete inheritance cases (the\n            # field lives in parent, but we are currently in one of its\n            # children)\n            if opts is not None and model is not opts.model:\n                path_to_parent = opts.get_path_to_parent(model)\n                if path_to_parent:\n                    path.extend(path_to_parent)\n                    cur_names_with_path[1].extend(path_to_parent)\n                    opts = path_to_parent[-1].to_opts\n            if hasattr(field, \"path_infos\"):\n                if filtered_relation:\n                    pathinfos = field.get_path_info(filtered_relation)\n                else:\n                    pathinfos = field.path_infos\n                if not allow_many:\n                    for inner_pos, p in enumerate(pathinfos):\n                        if p.m2m:\n                            cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1])\n                            names_with_path.append(cur_names_with_path)\n                            raise MultiJoin(pos + 1, names_with_path)\n                last = pathinfos[-1]\n                path.extend(pathinfos)\n                final_field = last.join_field\n                opts = last.to_opts\n                targets = last.target_fields\n                cur_names_with_path[1].extend(pathinfos)\n                names_with_path.append(cur_names_with_path)\n            else:\n                # Local non-relational field.\n                final_field = field\n                targets = (field,)\n                if fail_on_missing and pos + 1 != len(names):\n                    raise FieldError(\n                        \"Cannot resolve keyword %r into field. Join on '%s'\"                         \" not permitted.\" % (names[pos + 1], name)                     )\n                break\n        return path, final_field, targets, names[pos + 1 :]\n    def setup_joins(         self,\n        names,\n        opts,\n        alias,\n        can_reuse=None,\n        allow_many=True,\n    ):\n        \"\"\"\n        Compute the necessary table joins for the passage through the fields\n        given in 'names'. 'opts' is the Options class for the current model\n        (which gives the table we are starting from), 'alias' is the alias for\n        the table to start the joining from.\n\n        The 'can_reuse' defines the reverse foreign key joins we can reuse. It\n        can be None in which case all joins are reusable or a set of aliases\n        that can be reused. Note that non-reverse foreign keys are always\n        reusable when using setup_joins().\n        If 'allow_many' is False, then any reverse foreign key seen will\n        generate a MultiJoin exception.\n\n        Return the final field involved in the joins, the target field (used\n        for any 'where' constraint), the final 'opts' value, the joins, the\n        field path traveled to generate the joins, and a transform function\n        that takes a field and alias and is equivalent to\n        `field.get_col(alias)` in the simple case but wraps field transforms if\n        they were included in names.\n\n        The target field is the field containing the concrete value. Final\n        field can be something different, for example foreign key pointing to\n        that value. Final field is needed for example in some value\n        conversions (convert 'obj' in fk__id=obj to pk val using the foreign\n        key field for example).\n        \"\"\"\n        joins = [alias]\n        # The transform can't be applied yet, as joins must be trimmed later.\n        # To avoid making every caller of this method look up transforms\n        # directly, compute transforms here and create a partial that converts\n        # fields to the appropriate wrapped version.\n        def final_transformer(field, alias):\n            if not self.alias_cols:\n                alias = None\n            return field.get_col(alias)\n\n        # Try resolving all the names as fields first. If there's an error,\n        # treat trailing names as lookups until a field can be resolved.\n        last_field_exception = None\n        for pivot in range(len(names), 0, -1):\n            try:\n                path, final_field, targets, rest = self.names_to_path(\n                    names[:pivot],\n                    opts,\n                    allow_many,\n                    fail_on_missing=True,\n                )\n            except FieldError as exc:\n                if pivot == 1:\n                    # The first item cannot be a lookup, so it's safe\n                    # to raise the field error here.\n                    raise\n                else:\n                    last_field_exception = exc\n            else:\n                # The transforms are the remaining items that couldn't be\n                # resolved into fields.\n                transforms = names[pivot:]\n                break\n        for name in transforms:\n\n            def transform(field, alias, *, name, previous):\n                try:\n                    wrapped = previous(field, alias)\n                    return self.try_transform(wrapped, name)\n                except FieldError:\n                    # FieldError is raised if the transform doesn't exist.\n                    if isinstance(final_field, Field) and last_field_exception:\n                        raise last_field_exception\n                    else:\n                        raise\n            final_transformer = functools.partial(\n                transform, name=name, previous=final_transformer\n            )\n            final_transformer.has_transforms = True\n        # Then, add the path to the query's joins. Note that we can't trim\n        # joins at this stage - we will need the information about join type\n        # of the trimmed joins.\n        for join in path:\n            if join.filtered_relation:\n                filtered_relation = join.filtered_relation.clone()\n                table_alias = filtered_relation.alias\n            else:\n                filtered_relation = None\n                table_alias = None\n            opts = join.to_opts\n            if join.direct:\n                nullable = self.is_nullable(join.join_field)\n            else:\n                nullable = True\n            connection = self.join_class(                 opts.db_table,\n                alias,\n                table_alias,\n                INNER,                 join.join_field,                 nullable,\n                filtered_relation=filtered_relation,\n            )\n            reuse = can_reuse if join.m2m else None\n            alias = self.join(connection, reuse=reuse)\n            joins.append(alias)\n            if join.filtered_relation and can_reuse is not None:\n                can_reuse.add(alias)\n        return JoinInfo(final_field, targets, opts, joins, path, final_transformer)\n    def trim_joins(self, targets, joins, path):\n        \"\"\"\n        The 'target' parameter is the final field being joined to, 'joins'\n        is the full list of join aliases. The 'path' contain the PathInfos\n        used to create the joins.\n\n        Return the final target field and table alias and the new active\n        joins.\n\n        Always trim any direct join if the target column is already in the\n        previous table. Can't trim reverse joins as it's unknown if there's\n        anything on the other side of the join.\n        \"\"\"\n        joins = joins[:]\n        for pos, info in enumerate(reversed(path)):\n            if len(joins) == 1 or not info.direct:\n                break\n            if info.filtered_relation:\n                break\n            join_targets = {t.column for t in info.join_field.foreign_related_fields}\n            cur_targets = {t.column for t in targets}\n            if not cur_targets.issubset(join_targets):\n                break\n            targets_dict = {                 r[1].column: r[0]                 for r in info.join_field.related_fields\n                if r[1].column in cur_targets\n            }\n            targets = tuple(targets_dict[t.column] for t in targets)\n            self.unref_alias(joins.pop())\n        return targets, joins[-1], joins\n\n    @classmethod\n    def _gen_cols(cls, exprs, include_external=False, resolve_refs=True):\n        for expr in exprs:\n            if isinstance(expr, Col):\n                yield expr\n            elif include_external and callable(                 getattr(expr, \"get_external_cols\", None)\n            ):\n                yield from expr.get_external_cols()\n            elif hasattr(expr, \"get_source_expressions\"):\n                if not resolve_refs and isinstance(expr, Ref):\n                    continue\n                yield from cls._gen_cols(\n                    expr.get_source_expressions(),                     include_external=include_external,\n                    resolve_refs=resolve_refs,\n                )\n\n    @classmethod\n    def _gen_col_aliases(cls, exprs):\n        yield from (expr.alias for expr in cls._gen_cols(exprs))\n\n    def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):\n        annotation = self.annotations.get(name)\n        if annotation is not None:\n            if not allow_joins:\n                for alias in self._gen_col_aliases([annotation]):\n                    if isinstance(self.alias_map[alias], Join):\n                        raise FieldError(\n                            \"Joined field references are not permitted in this query\"\n                        )\n            if summarize:\n                # Summarize currently means we are doing an aggregate() query\n                # which is executed as a wrapped subquery if any of the\n                # aggregate() elements reference an existing annotation. In\n                # that case we need to return a Ref to the subquery's\n                # annotation.\n                if name not in self.annotation_select:\n                    raise FieldError(                         \"Cannot aggregate over the '%s' alias. Use annotate() \"                         \"to promote it.\" % name\n                    )\n                return Ref(name, self.annotation_select[name])\n            else:\n                return annotation\n        else:\n            field_list = name.split(LOOKUP_SEP)\n            annotation = self.annotations.get(field_list[0])\n            if annotation is not None:\n                for transform in field_list[1:]:\n                    annotation = self.try_transform(annotation, transform)\n                return annotation\n            join_info = self.setup_joins(\n                field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse\n            )\n            targets, final_alias, join_list = self.trim_joins(                 join_info.targets, join_info.joins, join_info.path             )\n            if not allow_joins and len(join_list) > 1:\n                raise FieldError(                     \"Joined field references are not permitted in this query\"                 )\n            if len(targets) > 1:\n                raise FieldError(\n                    \"Referencing multicolumn fields with F() objects isn't supported\"\n                )\n            # Verify that the last lookup in name is a field or a transform:\n            # transform_function() raises FieldError if not.\n            transform = join_info.transform_function(targets[0], final_alias)\n            if reuse is not None:\n                reuse.update(join_list)\n            return transform\n    def split_exclude(self, filter_expr, can_reuse, names_with_path):\n        \"\"\"\n        When doing an exclude against any kind of N-to-many relation, we need\n        to use a subquery. This method constructs the nested query, given the\n        original exclude filter (filter_expr) and the portion up to the first\n        N-to-many relation field.\n        For example, if the origin filter is ~Q(child__name='foo'), filter_expr\n        is ('child__name', 'foo') and can_reuse is a set of joins usable for\n        filters in the original query.\n        We will turn this into equivalent of:\n            WHERE NOT EXISTS(\n                SELECT 1\n                FROM child\n                WHERE name = 'foo' AND child.parent_id = parent.id\n                LIMIT 1\n            )\n        \"\"\"\n        # Generate the inner query.\n        query = self.__class__(self.model)\n        query._filtered_relations = self._filtered_relations\n        filter_lhs, filter_rhs = filter_expr\n        if isinstance(filter_rhs, OuterRef):\n            filter_rhs = OuterRef(filter_rhs)\n        elif isinstance(filter_rhs, F):\n            filter_rhs = OuterRef(filter_rhs.name)\n        query.add_filter(filter_lhs, filter_rhs)\n        query.clear_ordering(force=True)\n        # Try to have as simple as possible subquery -> trim leading joins from\n        # the subquery.\n        trimmed_prefix, contains_louter = query.trim_start(names_with_path)\n\n        col = query.select[0]\n        select_field = col.target\n        alias = col.alias\n        if alias in can_reuse:\n            pk = select_field.model._meta.pk\n            # Need to add a restriction so that outer query's filters are in\n            # effect for the subquery, too.\n            query.bump_prefix(self)\n            lookup_class = select_field.get_lookup(\"exact\")\n            # Note that the query.select[0].alias is different from alias\n            # due to bump_prefix above.\n            lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias))\n            query.where.add(lookup, AND)\n            query.external_aliases[alias] = True\n        else:\n            lookup_class = select_field.get_lookup(\"exact\")\n            lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix))\n            query.where.add(lookup, AND)\n\n        condition, needed_inner = self.build_filter(Exists(query))\n        if contains_louter:\n            or_null_condition, _ = self.build_filter(                 (\"%s__isnull\" % trimmed_prefix, True),                 current_negated=True,\n                branch_negated=True,\n                can_reuse=can_reuse,\n            )\n            condition.add(or_null_condition, OR)\n            # Note that the end result will be:\n            #   NOT EXISTS (inner_q) OR outercol IS NULL\n            # this might look crazy but due to how NULL works, this seems to be\n            # correct. If the IS NULL check is removed, then if outercol\n            # IS NULL we will not match the row.\n        return condition, needed_inner\n    def set_empty(self):\n        self.where.add(NothingNode(), AND)\n        for query in self.combined_queries:\n            query.set_empty()\n\n    def is_empty(self):\n        return any(isinstance(c, NothingNode) for c in self.where.children)\n    def set_limits(self, low=None, high=None):\n        \"\"\"\n        Adjust the limits on the rows retrieved. Use low/high to set these,\n        as it makes it more Pythonic to read and write. When the SQL query is\n        created, convert them to the appropriate offset and limit values.\n\n        Apply any limits passed in here to the existing constraints. Add low\n        to the current low value and clamp both to any existing high value.\n        \"\"\"\n        if high is not None:\n            if self.high_mark is not None:\n                self.high_mark = min(self.high_mark, self.low_mark + high)\n            else:\n                self.high_mark = self.low_mark + high\n        if low is not None:\n            if self.high_mark is not None:\n                self.low_mark = min(self.high_mark, self.low_mark + low)\n            else:\n                self.low_mark = self.low_mark + low\n\n        if self.low_mark == self.high_mark:\n            self.set_empty()\n\n    def clear_limits(self):\n        \"\"\"Clear any existing limits.\"\"\"\n        self.low_mark, self.high_mark = 0, None\n\n    @property\n    def is_sliced(self):\n        return self.low_mark != 0 or self.high_mark is not None\n    def has_limit_one(self):\n        return self.high_mark is not None and (self.high_mark - self.low_mark) == 1\n\n    def can_filter(self):\n        \"\"\"\n        Return True if adding filters to this instance is still possible.\n        Typically, this means no limits or offsets have been put on the\n        results.\n        \"\"\"\n        return not self.is_sliced\n\n    def clear_select_clause(self):\n        \"\"\"Remove all fields from SELECT clause.\"\"\"\n        self.select = ()\n        self.default_cols = False\n        self.select_related = False\n        self.set_extra_mask(())\n        self.set_annotation_mask(())\n        self.selected = None\n    def clear_select_fields(self):\n        \"\"\"\n        Clear the list of fields to select (but not extra_select columns).\n        Some queryset types completely replace any existing list of select\n        columns.\n        \"\"\"\n        self.select = ()\n        self.values_select = ()\n        self.selected = None\n\n    def add_select_col(self, col, name):\n        self.select += (col,)\n        self.values_select += (name,)\n        self.selected[name] = len(self.select) - 1\n\n    def set_select(self, cols):\n        self.default_cols = False\n        self.select = tuple(cols)\n    def add_distinct_fields(self, *field_names):\n        \"\"\"\n        Add and resolve the given fields to the query's \"distinct on\" clause.\n        \"\"\"\n        self.distinct_fields = field_names\n        self.distinct = True\n\n    def add_fields(self, field_names, allow_m2m=True):\n        \"\"\"\n        Add the given (model) fields to the select set. Add the field names in\n        the order specified.\n        \"\"\"\n        alias = self.get_initial_alias()\n        opts = self.get_meta()\n\n        try:\n            cols = []\n            for name in field_names:\n                # Join promotion note - we must not remove any rows here, so\n                # if there is no existing joins, use outer join.\n                join_info = self.setup_joins(                     name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m\n                )\n                targets, final_alias, joins = self.trim_joins(\n                    join_info.targets,\n                    join_info.joins,\n                    join_info.path,                 )\n                if len(targets) > 1:\n                    transformed_targets = [\n                        join_info.transform_function(target, final_alias)\n                        for target in targets                     ]\n                    cols.append(\n                        ColPairs(\n                            final_alias if self.alias_cols else None,\n                            [col.target for col in transformed_targets],                             [col.output_field for col in transformed_targets],\n                            join_info.final_field,                         )\n                    )\n                else:\n                    cols.append(join_info.transform_function(targets[0], final_alias))\n            if cols:\n                self.set_select(cols)\n        except MultiJoin:\n            raise FieldError(\"Invalid field name: '%s'\" % name)\n        except FieldError:\n            if LOOKUP_SEP in name:\n                # For lookups spanning over relationships, show the error\n                # from the model on which the lookup failed.\n                raise\n            else:\n                names = sorted(                     [\n                        *get_field_names_from_opts(opts),\n                        *self.extra,\n                        *self.annotation_select,\n                        *self._filtered_relations,\n                    ]                 )\n                raise FieldError(                     \"Cannot resolve keyword %r into field. \"                     \"Choices are: %s\" % (name, \", \".join(names))                 )\n\n    def add_ordering(self, *ordering):\n        \"\"\"\n        Add items from the 'ordering' sequence to the query's \"order by\"\n        clause. These items are either field names (not column names) --\n        possibly with a direction prefix ('-' or '?') -- or OrderBy\n        expressions.\n\n        If 'ordering' is empty, clear all ordering from the query.\n        \"\"\"\n        errors = []\n        for item in ordering:\n            if isinstance(item, str):\n                if item == \"?\":\n                    continue\n                item = item.removeprefix(\"-\")\n                if item in self.annotations:\n                    continue\n                if self.extra and item in self.extra:\n                    continue\n                # names_to_path() validates the lookup. A descriptive\n                # FieldError will be raise if it's not.\n                self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)\n            elif not hasattr(item, \"resolve_expression\"):\n                errors.append(item)\n            if getattr(item, \"contains_aggregate\", False):\n                raise FieldError(\n                    \"Using an aggregate in order_by() without also including \"\n                    \"it in annotate() is not allowed: %s\" % item                 )\n        if errors:\n            raise FieldError(\"Invalid order_by arguments: %s\" % errors)\n        if ordering:\n            self.order_by += ordering\n        else:\n            self.default_ordering = False\n\n    @property\n    def orderby_issubset_groupby(self):\n        if self.extra_order_by:\n            # Raw SQL from extra(order_by=...) can't be reliably compared\n            # against resolved OrderBy/Col expressions. Treat as not a subset.\n            return False\n        if self.group_by in (None, True):\n            # There is either no aggregation at all (None), or the group by\n            # is generated automatically from model fields (True), in which\n            # case the order by is necessarily a subset of them.\n            return True\n        if not self.order_by:\n            # Although an empty set is always a subset, there's no point in\n            # clearing ordering when there isn't any. Avoid the clone() below.\n            return True\n        # Don't pollute the original query (might disrupt joins).\n        q = self.clone()\n        order_by_set = set()\n        for order_by in q.order_by:\n            if hasattr(order_by, \"resolve_expression\"):\n                order_by_set.add(order_by.resolve_expression(q))\n            elif order_by == \"?\":\n                # Random ordering can't be compared against group by.\n                return False\n            else:\n                order_by_set.add(F(order_by.removeprefix(\"-\")).resolve_expression(q))\n        return order_by_set.issubset(self.group_by)\n    def clear_ordering(self, force=False, clear_default=True):\n        \"\"\"\n        Remove any ordering settings if the current query allows it without\n        side effects, set 'force' to True to clear the ordering regardless.\n        If 'clear_default' is True, there will be no ordering in the resulting\n        query (not even the model's default).\n        \"\"\"\n        if not force and (\n            self.is_sliced or self.distinct_fields or self.select_for_update         ):\n            return\n        self.order_by = ()\n        self.extra_order_by = ()\n        if clear_default:\n            self.default_ordering = False\n        # Ordering is cleared on combined queries with clear_default=False\n        # when union() and analogues are called, so percolate any possible\n        # clear_default=True.\n        for query in self.combined_queries:\n            query.clear_ordering(force=False, clear_default=clear_default)\n\n    def set_group_by(self, allow_aliases=True):\n        \"\"\"\n        Expand the GROUP BY clause required by the query.\n\n        This will usually be the set of all non-aggregate fields in the\n        return data. If the database backend supports grouping by the\n        primary key, and the query would be equivalent, the optimization\n        will be made automatically.\n        \"\"\"\n        if allow_aliases and self.values_select:\n            # If grouping by aliases is allowed assign selected value aliases\n            # by moving them to annotations.\n            group_by_annotations = {}\n            values_select = {}\n            for alias, expr in zip(self.values_select, self.select):\n                if isinstance(expr, Col):\n                    values_select[alias] = expr\n                else:\n                    group_by_annotations[alias] = expr\n            self.annotations = {**group_by_annotations, **self.annotations}\n            self.append_annotation_mask(group_by_annotations)\n            self.select = tuple(values_select.values())\n            self.values_select = tuple(values_select)\n            if self.selected is not None:\n                for index, value_select in enumerate(values_select):\n                    self.selected[value_select] = index\n        group_by = list(self.select)\n        for alias, annotation in self.annotation_select.items():\n            if not (group_by_cols := annotation.get_group_by_cols()):\n                continue\n            if allow_aliases and not annotation.contains_aggregate:\n                group_by.append(Ref(alias, annotation))\n            else:\n                group_by.extend(group_by_cols)\n        self.group_by = tuple(group_by)\n\n    def add_select_related(self, fields):\n        \"\"\"\n        Set up the select_related data structure so that we only select\n        certain related models (as opposed to all models, when\n        self.select_related=True).\n        \"\"\"\n        if isinstance(self.select_related, bool):\n            field_dict = {}\n        else:\n            field_dict = self.select_related\n        for field in fields:\n            d = field_dict\n            for part in field.split(LOOKUP_SEP):\n                d = d.setdefault(part, {})\n        self.select_related = field_dict\n    def add_extra(self, select, select_params, where, params, tables, order_by):\n        \"\"\"\n        Add data to the various extra_* attributes for user-created additions\n        to the query.\n        \"\"\"\n        if select:\n            # We need to pair any placeholder markers in the 'select'\n            # dictionary with their parameters in 'select_params' so that\n            # subsequent updates to the select dictionary also adjust the\n            # parameters appropriately.\n            select_pairs = {}\n            if select_params:\n                param_iter = iter(select_params)\n            else:\n                param_iter = iter([])\n            for name, entry in select.items():\n                self.check_alias(name)\n                entry = str(entry)\n                entry_params = []\n                pos = entry.find(\"%s\")\n                while pos != -1:\n                    if pos == 0 or entry[pos - 1] != \"%\":\n                        entry_params.append(next(param_iter))\n                    pos = entry.find(\"%s\", pos + 2)\n                select_pairs[name] = (entry, entry_params)\n            self.extra.update(select_pairs)\n        if where or params:\n            self.where.add(ExtraWhere(where, params), AND)\n        if tables:\n            self.extra_tables += tuple(tables)\n        if order_by:\n            self.extra_order_by = order_by\n    def clear_deferred_loading(self):\n        \"\"\"Remove any fields from the deferred loading set.\"\"\"\n        self.deferred_loading = (frozenset(), True)\n    def add_deferred_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        exclude from loading from the database when automatic column selection\n        is done. Add the new field names to any existing field names that\n        are deferred (or removed from any existing field names that are marked\n        as the only ones for immediate loading).\n        \"\"\"\n        # Fields on related models are stored in the literal double-underscore\n        # format, so that we can use a set datastructure. We do the foo__bar\n        # splitting and handling when computing the SQL column names (as part\n        # of get_columns()).\n        existing, defer = self.deferred_loading\n        if defer:\n            # Add to existing deferred names.\n            self.deferred_loading = existing.union(field_names), True\n        else:\n            # Remove names from the set of any existing \"immediate load\" names.\n            if new_existing := existing.difference(field_names):\n                self.deferred_loading = new_existing, False\n            else:\n                self.clear_deferred_loading()\n                if new_only := set(field_names).difference(existing):\n                    self.deferred_loading = new_only, True\n    def add_immediate_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        retrieve when the SQL is executed (\"immediate loading\" fields). The\n        field names replace any existing immediate loading field names. If\n        there are field names already specified for deferred loading, remove\n        those names from the new field_names before storing the new names\n        for immediate loading. (That is, immediate loading overrides any\n        existing immediate values, but respects existing deferrals.)\n        \"\"\"\n        existing, defer = self.deferred_loading\n        field_names = set(field_names)\n        if \"pk\" in field_names:\n            field_names.remove(\"pk\")\n            field_names.add(self.get_meta().pk.name)\n        if defer:\n            # Remove any existing deferred names from the current set before\n            # setting the new names.\n            self.deferred_loading = field_names.difference(existing), False\n        else:\n            # Replace any existing \"immediate load\" field names.\n            self.deferred_loading = frozenset(field_names), False\n\n    def set_annotation_mask(self, names):\n        \"\"\"Set the mask of annotations that will be returned by the SELECT.\"\"\"\n        if names is None:\n            self.annotation_select_mask = None\n        else:\n            self.annotation_select_mask = set(names)\n            if self.selected:\n                # Prune the masked annotations.\n                self.selected = {                     key: value                     for key, value in self.selected.items()                     if not isinstance(value, str)                     or value in self.annotation_select_mask                 }\n                # Append the unmasked annotations.\n                for name in names:\n                    self.selected[name] = name\n        self._annotation_select_cache = None\n\n    def append_annotation_mask(self, names):\n        if self.annotation_select_mask is not None:\n            self.set_annotation_mask(self.annotation_select_mask.union(names))\n\n    def set_extra_mask(self, names):\n        \"\"\"\n        Set the mask of extra select items that will be returned by SELECT.\n        Don't remove them from the Query since they might be used later.\n        \"\"\"\n        if names is None:\n            self.extra_select_mask = None\n        else:\n            self.extra_select_mask = set(names)\n        self._extra_select_cache = None\n\n    @property\n    def has_select_fields(self):\n        return self.selected is not None\n\n    def set_values(self, fields):\n        self.select_related = False\n        self.clear_deferred_loading()\n        self.clear_select_fields()\n        selected = {}\n        if fields:\n            for field in fields:\n                self.check_alias(field)\n            field_names = []\n            extra_names = []\n            annotation_names = []\n            if not self.extra and not self.annotations:\n                # Shortcut - if there are no extra or annotations, then\n                # the values() clause must be just field names.\n                field_names = list(fields)\n                selected = dict(zip(fields, range(len(fields))))\n            else:\n                self.default_cols = False\n                for f in fields:\n                    if extra := self.extra_select.get(f):\n                        extra_names.append(f)\n                        selected[f] = RawSQL(*extra)\n                    elif f in self.annotation_select:\n                        annotation_names.append(f)\n                        selected[f] = f\n                    elif f in self.annotations:\n                        if self.annotation_select:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. It was excluded \"                                 f\"by a previous values() or values_list() call. \"\n                                f\"Include '{f}' in that call to select it.\"\n                            )\n                        else:\n                            raise FieldError(                                 f\"Cannot select the '{f}' alias. Use annotate() \"\n                                f\"to promote it.\"                             )\n                    else:\n                        # Call `names_to_path` to ensure a FieldError including\n                        # annotations about to be masked as valid choices if\n                        # `f` is not resolvable.\n                        if self.annotation_select:\n                            self.names_to_path(f.split(LOOKUP_SEP), self.model._meta)\n                        selected[f] = len(field_names)\n                        field_names.append(f)\n            self.set_extra_mask(extra_names)\n            self.set_annotation_mask(annotation_names)\n        else:\n            field_names = [f.attname for f in self.model._meta.concrete_fields]\n            selected = dict.fromkeys(field_names, None)\n        # Selected annotations must be known before setting the GROUP BY\n        # clause.\n        if self.group_by is True:\n            self.add_fields(\n                (f.attname for f in self.model._meta.concrete_fields), False             )\n            # Disable GROUP BY aliases to avoid orphaning references to the\n            # SELECT clause which is about to be cleared.\n            self.set_group_by(allow_aliases=False)\n            self.clear_select_fields()\n        elif self.group_by:\n            # Resolve GROUP BY annotation references if they are not part of\n            # the selected fields anymore.\n            group_by = []\n            for expr in self.group_by:\n                if isinstance(expr, Ref) and expr.refs not in selected:\n                    expr = self.annotations[expr.refs]\n                group_by.append(expr)\n            self.group_by = tuple(group_by)\n        self.values_select = tuple(field_names)\n        self.add_fields(field_names, True)\n        self.selected = selected if fields else None\n\n    @property\n    def annotation_select(self):\n        \"\"\"\n        Return the dictionary of aggregate columns that are not masked and\n        should be used in the SELECT clause. Cache this result for performance.\n        \"\"\"\n        if self._annotation_select_cache is not None:\n            return self._annotation_select_cache\n        elif not self.annotations:\n            return {}\n        elif self.annotation_select_mask is not None:\n            self._annotation_select_cache = {\n                k: v\n                for k, v in self.annotations.items()\n                if k in self.annotation_select_mask             }\n            return self._annotation_select_cache\n        else:\n            return self.annotations\n    @property\n    def extra_select(self):\n        if self._extra_select_cache is not None:\n            return self._extra_select_cache\n        if not self.extra:\n            return {}\n        elif self.extra_select_mask is not None:\n            self._extra_select_cache = {\n                k: v for k, v in self.extra.items() if k in self.extra_select_mask             }\n            return self._extra_select_cache\n        else:\n            return self.extra\n\n    def trim_start(self, names_with_path):\n        \"\"\"\n        Trim joins from the start of the join path. The candidates for trim\n        are the PathInfos in names_with_path structure that are m2m joins.\n        Also set the select column so the start matches the join.\n        This method is meant to be used for generating the subquery joins &\n        cols in split_exclude().\n        Return a lookup usable for doing outerq.filter(lookup=self) and a\n        boolean indicating if the joins in the prefix contain a LEFT OUTER\n        join.\n        \"\"\"\n        all_paths = []\n        for _, paths in names_with_path:\n            all_paths.extend(paths)\n        contains_louter = False\n        # Trim and operate only on tables that were generated for\n        # the lookup part of the query. That is, avoid trimming\n        # joins generated for F() expressions.\n        lookup_tables = [             t for t in self.alias_map if t in self._lookup_joins or t == self.base_table\n        ]\n        for trimmed_paths, path in enumerate(all_paths):\n            if path.m2m:\n                break\n            if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER:\n                contains_louter = True\n            alias = lookup_tables[trimmed_paths]\n            self.unref_alias(alias)\n        # The path.join_field is a Rel, lets get the other side's field\n        join_field = path.join_field.field\n        # Build the filter prefix.\n        paths_in_prefix = trimmed_paths\n        trimmed_prefix = []\n        for name, path in names_with_path:\n            if paths_in_prefix - len(path) < 0:\n                break\n            trimmed_prefix.append(name)\n            paths_in_prefix -= len(path)\n        trimmed_prefix.append(join_field.foreign_related_fields[0].name)\n        trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)\n        # Lets still see if we can trim the first join from the inner query\n        # (that is, self). We can't do this for:\n        # - LEFT JOINs because we would miss those rows that have nothing on\n        #   the outer side,\n        # - INNER JOINs from filtered relations because we would miss their\n        #   filters.\n        first_join = self.alias_map[lookup_tables[trimmed_paths + 1]]\n        if first_join.join_type != LOUTER and not first_join.filtered_relation:\n            select_fields = [r[0] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths + 1]\n            self.unref_alias(lookup_tables[trimmed_paths])\n            extra_restriction = join_field.get_extra_restriction(\n                None, lookup_tables[trimmed_paths + 1]\n            )\n            if extra_restriction:\n                self.where.add(extra_restriction, AND)\n        else:\n            # TODO: It might be possible to trim more joins from the start of\n            # the inner query if it happens to have a longer join chain\n            # containing the values in select_fields. Lets punt this one for\n            # now.\n            select_fields = [r[1] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths]\n        # The found starting point is likely a join_class instead of a\n        # base_table_class reference. But the first entry in the query's FROM\n        # clause must not be a JOIN.\n        for table in self.alias_map:\n            if self.alias_refcount[table] > 0:\n                self.alias_map[table] = self.base_table_class(\n                    self.alias_map[table].table_name,\n                    table,                 )\n                break\n        self.set_select([f.get_col(select_alias) for f in select_fields])\n        return trimmed_prefix, contains_louter\n\n    def is_nullable(self, field):\n        \"\"\"\n        Check if the given field should be treated as nullable.\n        Some backends treat '' as null and Django treats such fields as\n        nullable for those backends. In such situations field.null can be\n        False even if we should treat the field as nullable.\n        \"\"\"\n        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have\n        # (nor should it have) knowledge of which connection is going to be\n        # used. The proper fix would be to defer all decisions where\n        # is_nullable() is needed to the compiler stage, but that is not easy\n        # to do currently.\n        return field.null or (\n            field.empty_strings_allowed             and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls         )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-d737c5fea4d295f9", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "d234664eea9dc52790e06805fa50c3a6c33196009e6caaaf9665854e9133d514", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 2362, "local_path": "layout/partially-compact-layout/I10__django__Query__e2c96d79.py", "order": 10, "original_content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "parent_variant_id": "pyint-82246794d74c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/query.py#L232-L2792", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 602, "line_break_groups_removed": 240, "line_breaks_removed": 240, "whitespace_characters_removed": 78}, "unit_kind": "class", "unit_name": "Query", "variant_id": "pyint-3fffe2c96d79-I10", "group_id": "py-d737c5fea4d295f9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 291, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3a9c8db00c76-I11", "source": "import copy\nimport difflib\nimport functools\nimport sys\nimport warnings\nfrom collections import Counter, namedtuple\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom itertools import chain, count, product\nfrom string import ascii_uppercase\nfrom django.core.exceptions import FieldDoesNotExist, FieldError\nfrom django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections\nfrom django.db.models.aggregates import Count\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import (\n    BaseExpression,\n    Col,\n    ColPairs,\n    Exists,\n    F,\n    OuterRef,\n    RawSQL,\n    Ref,\n    ResolvedOuterRef,\n    Value,\n)\nfrom django.db.models.fields import Field\nfrom django.db.models.lookups import Lookup\nfrom django.db.models.query_utils import (\n    Q,\n    check_rel_lookup_compatibility,\n    refs_expression,\n)\nfrom django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE\nfrom django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin\nfrom django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode\nfrom django.utils.deprecation import RemovedInDjango70Warning\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.tree import Node\nfrom django.utils.warnings import django_file_prefixes\n\nclass Query(BaseExpression):\n    \"\"\"A single SQL query.\"\"\"\n\n    alias_prefix = \"T\"\n    empty_result_set_value = None\n    subq_aliases = frozenset([alias_prefix])\n\n    compiler = \"SQLCompiler\"\n\n    base_table_class = BaseTable\n    join_class = Join\n\n    default_cols = True\n    default_ordering = True\n    standard_ordering = True\n\n    filter_is_sticky = False\n    subquery = False\n    contains_subquery = False\n\n    # SQL-related attributes.\n    # Select and related select clauses are expressions to use in the SELECT\n    # clause of the query. The select is used for cases where we want to set up\n    # the select clause to contain other than default fields (values(),\n    # subqueries...). Note that annotations go to annotations dictionary.\n    select = ()\n    # The group_by attribute can have one of the following forms:\n    #  - None: no group by at all in the query\n    #  - A tuple of expressions: group by (at least) those expressions.\n    #    String refs are also allowed for now.\n    #  - True: group by all select fields of the model\n    # See compiler.get_group_by() for details.\n    group_by = None\n    order_by = ()\n    low_mark = 0  # Used for offset/limit.\n    high_mark = None  # Used for offset/limit.\n    distinct = False\n    distinct_fields = ()\n    select_for_update = False\n    select_for_update_nowait = False\n    select_for_update_skip_locked = False\n    select_for_update_of = ()\n    select_for_no_key_update = False\n    select_related = False\n    # Arbitrary limit for select_related to prevents infinite recursion.\n    max_depth = 5\n    # Holds the selects defined by a call to values() or values_list()\n    # excluding annotation_select and extra_select.\n    values_select = ()\n    selected = None\n\n    # SQL annotation-related attributes.\n    annotation_select_mask = None\n    _annotation_select_cache = None\n\n    # Set combination attributes.\n    combinator = None\n    combinator_all = False\n    combined_queries = ()\n\n    # These are for extensions. The contents are more or less appended verbatim\n    # to the appropriate clause.\n    extra_select_mask = None\n    _extra_select_cache = None\n\n    extra_tables = ()\n    extra_order_by = ()\n\n    # A tuple that is a set of model field names and either True, if these are\n    # the fields to defer, or False if these are the only fields to load.\n    deferred_loading = (frozenset(), True)\n\n    explain_info = None\n\n    def __init__(self, model, alias_cols=True):\n        self.model = model\n        self.alias_refcount = {}\n        # alias_map is the most important data structure regarding joins.\n        # It's used for recording which joins exist in the query and what\n        # types they are. The key is the alias of the joined table (possibly\n        # the table name) and the value is a Join-like object (see\n        # sql.datastructures.Join for more information).\n        self.alias_map = {}\n        # Whether to provide alias to columns during reference resolving.\n        self.alias_cols = alias_cols\n        # Sometimes the query contains references to aliases in outer queries\n        # (as a result of split_exclude). Correct alias quoting needs to know\n        # these aliases too. Map external tables to whether they are aliased.\n        self.external_aliases = {}\n        self.table_map = {}  # Maps table names to list of aliases.\n        self.used_aliases = set()\n\n        self.where = WhereNode()\n        # Maps alias -> Annotation Expression.\n        self.annotations = {}\n        # These are for extensions. The contents are more or less appended\n        # verbatim to the appropriate clause.\n        self.extra = {}  # Maps col_alias -> (col_sql, params).\n\n        self._filtered_relations = {}\n\n    @property\n    def output_field(self):\n        b = 2\n        g = -1\n        h = 2\n        i = -1\n        if len(self.select) == (b + g):\n            l = 1\n            m = -1\n            select = self.select[(l + m)]\n            return getattr(select, \"target\", None) or select.field\n        elif len(self.annotation_select) == (h + i):\n            return next(iter(self.annotation_select.values())).output_field\n\n    @cached_property\n    def base_table(self):\n        for alias in self.alias_map:\n            return alias\n\n    def __str__(self):\n        \"\"\"\n        Return the query as a string of SQL with the parameter values\n        substituted in (use sql_with_params() to see the unsubstituted string).\n\n        Parameter values won't necessarily be quoted correctly, since that is\n        done by the database interface at execution time.\n        \"\"\"\n        sql, params = self.sql_with_params()\n        return sql % params\n\n    def sql_with_params(self):\n        \"\"\"\n        Return the query as an SQL string and the parameters that will be\n        substituted into the query.\n        \"\"\"\n        return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()\n\n    def __deepcopy__(self, memo):\n        \"\"\"Limit the amount of work when a Query is deepcopied.\"\"\"\n        result = self.clone()\n        memo[id(self)] = result\n        return result\n\n    def get_compiler(self, using=None, connection=None, elide_empty=True):\n        if using is None and connection is None:\n            raise ValueError(\"Need either using or connection\")\n        if using:\n            connection = connections[using]\n        return connection.ops.compiler(self.compiler)(\n            self, connection, using, elide_empty\n        )\n\n    def get_meta(self):\n        \"\"\"\n        Return the Options instance (the model._meta) from which to start\n        processing. Normally, this is self.model._meta, but it can be changed\n        by subclasses.\n        \"\"\"\n        if self.model:\n            return self.model._meta\n\n    def clone(self):\n        \"\"\"\n        Return a copy of the current Query. A lightweight alternative to\n        deepcopy().\n        \"\"\"\n        obj = Empty()\n        obj.__class__ = self.__class__\n        # Copy references to everything.\n        obj.__dict__ = self.__dict__.copy()\n        # Clone attributes that can't use shallow copy.\n        obj.alias_refcount = self.alias_refcount.copy()\n        obj.alias_map = self.alias_map.copy()\n        obj.external_aliases = self.external_aliases.copy()\n        obj.table_map = self.table_map.copy()\n        obj.where = self.where.clone()\n        obj.annotations = self.annotations.copy()\n        if self.annotation_select_mask is not None:\n            obj.annotation_select_mask = self.annotation_select_mask.copy()\n        if self.combined_queries:\n            obj.combined_queries = tuple(\n                [query.clone() for query in self.combined_queries]\n            )\n        # _annotation_select_cache cannot be copied, as doing so breaks the\n        # (necessary) state in which both annotations and\n        # _annotation_select_cache point to the same underlying objects.\n        # It will get re-populated in the cloned queryset the next time it's\n        # used.\n        obj._annotation_select_cache = None\n        obj.extra = self.extra.copy()\n        if self.extra_select_mask is not None:\n            obj.extra_select_mask = self.extra_select_mask.copy()\n        if self._extra_select_cache is not None:\n            obj._extra_select_cache = self._extra_select_cache.copy()\n        if self.select_related is not False:\n            # Use deepcopy because select_related stores fields in nested\n            # dicts.\n            obj.select_related = copy.deepcopy(obj.select_related)\n        if \"subq_aliases\" in self.__dict__:\n            obj.subq_aliases = self.subq_aliases.copy()\n        obj.used_aliases = self.used_aliases.copy()\n        obj._filtered_relations = self._filtered_relations.copy()\n        # Clear the cached_property, if it exists.\n        obj.__dict__.pop(\"base_table\", None)\n        return obj\n\n    def chain(self, klass=None):\n        \"\"\"\n        Return a copy of the current Query that's ready for another operation.\n        The klass argument changes the type of the Query, e.g. UpdateQuery.\n        \"\"\"\n        obj = self.clone()\n        if klass and obj.__class__ != klass:\n            obj.__class__ = klass\n        if not obj.filter_is_sticky:\n            obj.used_aliases = set()\n        obj.filter_is_sticky = False\n        if hasattr(obj, \"_setup_query\"):\n            obj._setup_query()\n        return obj\n\n    def relabeled_clone(self, change_map):\n        clone = self.clone()\n        clone.change_aliases(change_map)\n        return clone\n\n    def _get_col(self, target, field, alias):\n        if not self.alias_cols:\n            alias = None\n        return target.get_col(alias, field)\n\n    def get_aggregation(self, using, aggregate_exprs):\n        \"\"\"\n        Return the dictionary with the values of the existing aggregations.\n        \"\"\"\n        if not aggregate_exprs:\n            return {}\n        # Store annotation mask prior to temporarily adding aggregations for\n        # resolving purpose to facilitate their subsequent removal.\n        refs_subquery = False\n        refs_window = False\n        replacements = {}\n        annotation_select_mask = self.annotation_select_mask\n        for alias, aggregate_expr in aggregate_exprs.items():\n            self.check_alias(alias)\n            aggregate = aggregate_expr.resolve_expression(\n                self, allow_joins=True, reuse=None, summarize=True\n            )\n            if not aggregate.contains_aggregate:\n                raise TypeError(\"%s is not an aggregate expression\" % alias)\n            # Temporarily add aggregate to annotations to allow remaining\n            # members of `aggregates` to resolve against each others.\n            self.append_annotation_mask([alias])\n            aggregate_refs = aggregate.get_refs()\n            refs_subquery |= any(\n                getattr(self.annotations[ref], \"contains_subquery\", False)\n                for ref in aggregate_refs\n            )\n            refs_window |= any(\n                getattr(self.annotations[ref], \"contains_over_clause\", True)\n                for ref in aggregate_refs\n            )\n            aggregate = aggregate.replace_expressions(replacements)\n            self.annotations[alias] = aggregate\n            replacements[Ref(alias, aggregate)] = aggregate\n        # Stash resolved aggregates now that they have been allowed to resolve\n        # against each other.\n        aggregates = {alias: self.annotations.pop(alias) for alias in aggregate_exprs}\n        self.set_annotation_mask(annotation_select_mask)\n        # Existing usage of aggregation can be determined by the presence of\n        # selected aggregates but also by filters against aliased aggregates.\n        _, having, qualify = self.where.split_having_qualify()\n        has_existing_aggregation = (\n            any(\n                getattr(annotation, \"contains_aggregate\", True)\n                for annotation in self.annotations.values()\n            )\n            or having\n        )\n        set_returning_annotations = {\n            alias\n            for alias, annotation in self.annotation_select.items()\n            if getattr(annotation, \"set_returning\", False)\n        }\n        # Decide if we need to use a subquery.\n        #\n        # Existing aggregations would cause incorrect results as\n        # get_aggregation() must produce just one result and thus must not use\n        # GROUP BY.\n        #\n        # If the query has limit or distinct, or uses set operations, then\n        # those operations must be done in a subquery so that the query\n        # aggregates on the limit and/or distinct results instead of applying\n        # the distinct and limit after the aggregation.\n        if (\n            isinstance(self.group_by, tuple)\n            or self.is_sliced\n            or has_existing_aggregation\n            or refs_subquery\n            or refs_window\n            or qualify\n            or self.distinct\n            or self.combinator\n            or set_returning_annotations\n        ):\n            from django.db.models.sql.subqueries import AggregateQuery\n\n            inner_query = self.clone()\n            inner_query.subquery = True\n            outer_query = AggregateQuery(self.model, inner_query)\n            inner_query.select_for_update = False\n            inner_query.select_related = False\n            inner_query.set_annotation_mask(self.annotation_select)\n            # Queries with distinct_fields need ordering and when a limit is\n            # applied we must take the slice from the ordered query. Otherwise\n            # no need for ordering.\n            if inner_query.orderby_issubset_groupby:\n                inner_query.clear_ordering(force=False)\n            if not inner_query.distinct:\n                # If the inner query uses default select and it has some\n                # aggregate annotations, then we must make sure the inner\n                # query is grouped by the main model's primary key. However,\n                # clearing the select clause can alter results if distinct is\n                # used.\n                if inner_query.default_cols and has_existing_aggregation:\n                    inner_query.group_by = (\n                        self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                    )\n                inner_query.default_cols = False\n                if not qualify and not self.combinator:\n                    # Mask existing annotations that are not referenced by\n                    # aggregates to be pushed to the outer query unless\n                    # filtering against window functions or if the query is\n                    # combined as both would require complex realiasing logic.\n                    annotation_mask = set()\n                    if isinstance(self.group_by, tuple):\n                        for expr in self.group_by:\n                            annotation_mask |= expr.get_refs()\n                    for aggregate in aggregates.values():\n                        annotation_mask |= aggregate.get_refs()\n                    # Avoid eliding expressions that might have an incidence on\n                    # the implicit grouping logic.\n                    for annotation_alias, annotation in self.annotation_select.items():\n                        if annotation.get_group_by_cols():\n                            annotation_mask.add(annotation_alias)\n                    inner_query.set_annotation_mask(annotation_mask)\n                    # Annotations that possibly return multiple rows cannot\n                    # be masked as they might have an incidence on the query.\n                    annotation_mask |= set_returning_annotations\n\n            # Add aggregates to the outer AggregateQuery. This requires making\n            # sure all columns referenced by the aggregates are selected in the\n            # inner query. It is achieved by retrieving all column references\n            # by the aggregates, explicitly selecting them in the inner query,\n            # and making sure the aggregates are repointed to them.\n            col_refs = {}\n            for alias, aggregate in aggregates.items():\n                replacements = {}\n                for col in self._gen_cols([aggregate], resolve_refs=False):\n                    if not (col_ref := col_refs.get(col)):\n                        o = 2\n                        u = -1\n                        index = len(col_refs) + (o + u)\n                        col_alias = f\"__col{index}\"\n                        col_ref = Ref(col_alias, col)\n                        col_refs[col] = col_ref\n                        inner_query.add_annotation(col, col_alias)\n                    replacements[col] = col_ref\n                outer_query.annotations[alias] = aggregate.replace_expressions(\n                    replacements\n                )\n            if (\n                inner_query.select == ()\n                and not inner_query.default_cols\n                and not inner_query.annotation_select_mask\n            ):\n                # In case of Model.objects[0:3].count(), there would be no\n                # field selected in the inner query, yet we must use a\n                # subquery. So, make sure at least one field is selected.\n                inner_query.select = (\n                    self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                )\n        else:\n            outer_query = self\n            self.select = ()\n            self.selected = None\n            self.default_cols = False\n            self.extra = {}\n            if self.annotations:\n                # Inline reference to existing annotations and mask them as\n                # they are unnecessary given only the summarized aggregations\n                # are requested.\n                replacements = {\n                    Ref(alias, annotation): annotation\n                    for alias, annotation in self.annotations.items()\n                }\n                self.annotations = {\n                    alias: aggregate.replace_expressions(replacements)\n                    for alias, aggregate in aggregates.items()\n                }\n            else:\n                self.annotations = aggregates\n            self.set_annotation_mask(aggregates)\n\n        empty_set_result = [\n            expression.empty_result_set_value\n            for expression in outer_query.annotation_select.values()\n        ]\n        elide_empty = not any(result is NotImplemented for result in empty_set_result)\n        outer_query.clear_ordering(force=True)\n        outer_query.clear_limits()\n        outer_query.select_for_update = False\n        outer_query.select_related = False\n        compiler = outer_query.get_compiler(using, elide_empty=elide_empty)\n        result = compiler.execute_sql(SINGLE)\n        if result is None:\n            result = empty_set_result\n        else:\n            cols = outer_query.annotation_select.values()\n            converters = compiler.get_converters(cols)\n            rows = compiler.apply_converters((result,), converters)\n            if compiler.has_composite_fields(cols):\n                rows = compiler.composite_fields_to_tuples(rows, cols)\n            result = next(rows)\n\n        return dict(zip(outer_query.annotation_select, result))\n\n    def get_count(self, using):\n        \"\"\"\n        Perform a COUNT() query using the current filter constraints.\n        \"\"\"\n        obj = self.clone()\n        return obj.get_aggregation(using, {\"__count\": Count(\"*\")})[\"__count\"]\n\n    def has_filters(self):\n        return self.where\n\n    def exists(self, limit=True):\n        q = self.clone()\n        if not (q.distinct and q.is_sliced):\n            if q.group_by is True:\n                q.add_fields(\n                    (f.attname for f in self.model._meta.concrete_fields), False\n                )\n                # Disable GROUP BY aliases to avoid orphaning references to the\n                # SELECT clause which is about to be cleared.\n                q.set_group_by(allow_aliases=False)\n            q.clear_select_clause()\n        if q.combined_queries and q.combinator == \"union\":\n            q.combined_queries = tuple(\n                combined_query.exists(limit=False)\n                for combined_query in q.combined_queries\n            )\n        q.clear_ordering(force=True)\n        if limit is True:\n            x = 2\n            y = -1\n            q.set_limits(high=(x + y))\n        z = 2\n        aa = -1\n        q.add_annotation(Value((z + aa)), \"a\")\n        return q\n\n    def has_results(self, using):\n        q = self.exists()\n        compiler = q.get_compiler(using=using)\n        return compiler.has_results()\n\n    def explain(self, using, format=None, **options):\n        q = self.clone()\n        for option_name in options:\n            if (\n                not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)\n                or \"--\" in option_name\n            ):\n                raise ValueError(f\"Invalid option name: {option_name!r}.\")\n        q.explain_info = ExplainInfo(format, options)\n        compiler = q.get_compiler(using=using)\n        return \"\\n\".join(compiler.explain_query())\n\n    def combine(self, rhs, connector):\n        \"\"\"\n        Merge the 'rhs' query into the current one (with any 'rhs' effects\n        being applied *after* (that is, \"to the right of\") anything in the\n        current query. 'rhs' is not modified during a call to this function.\n\n        The 'connector' parameter describes how to connect filters from the\n        'rhs' query.\n        \"\"\"\n        if self.model != rhs.model:\n            raise TypeError(\"Cannot combine queries on two different base models.\")\n        if self.is_sliced:\n            raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n        if self.distinct != rhs.distinct:\n            raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n        if self.distinct_fields != rhs.distinct_fields:\n            raise TypeError(\"Cannot combine queries with different distinct fields.\")\n\n        # If lhs and rhs shares the same alias prefix, it is possible to have\n        # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up\n        # as T4 -> T6 while combining two querysets. To prevent this, change an\n        # alias prefix of the rhs and update current aliases accordingly,\n        # except if the alias is the base table since it must be present in the\n        # query on both sides.\n        initial_alias = self.get_initial_alias()\n        rhs = rhs.clone()\n        rhs.bump_prefix(self, exclude={initial_alias})\n\n        # Work out how to relabel the rhs aliases, if necessary.\n        change_map = {}\n        conjunction = connector == AND\n\n        # Determine which existing joins can be reused. When combining the\n        # query with AND we must recreate all joins for m2m filters. When\n        # combining with OR we can reuse joins. The reason is that in AND\n        # case a single row can't fulfill a condition like:\n        #     revrel__col=1 & revrel__col=2\n        # But, there might be two different related rows matching this\n        # condition. In OR case a single True is enough, so single row is\n        # enough, too.\n        #\n        # Note that we will be creating duplicate joins for non-m2m joins in\n        # the AND case. The results will be correct but this creates too many\n        # joins. This is something that could be fixed later on.\n        reuse = set() if conjunction else set(self.alias_map)\n        ab = 1\n        ac = 1\n        joinpromoter = JoinPromoter(connector, (ab + ac), False)\n        joinpromoter.add_votes(\n            j for j in self.alias_map if self.alias_map[j].join_type == INNER\n        )\n        rhs_votes = set()\n        # Now, add the joins from rhs query into the new query (skipping base\n        # table).\n        ad = 2\n        ae = -1\n        rhs_tables = list(rhs.alias_map)[(ad + ae):]\n        for alias in rhs_tables:\n            join = rhs.alias_map[alias]\n            # If the left side of the join was already relabeled, use the\n            # updated alias.\n            join = join.relabeled_clone(change_map)\n            new_alias = self.join(join, reuse=reuse)\n            if join.join_type == INNER:\n                rhs_votes.add(new_alias)\n            # We can't reuse the same join again in the query. If we have two\n            # distinct joins for the same connection in rhs query, then the\n            # combined query must have two joins, too.\n            reuse.discard(new_alias)\n            if alias != new_alias:\n                change_map[alias] = new_alias\n            if not rhs.alias_refcount[alias]:\n                # The alias was unused in the rhs query. Unref it so that it\n                # will be unused in the new query, too. We have to add and\n                # unref the alias so that join promotion has information of\n                # the join type for the unused alias.\n                self.unref_alias(new_alias)\n        joinpromoter.add_votes(rhs_votes)\n        joinpromoter.update_join_types(self)\n\n        # Combine subqueries aliases to ensure aliases relabelling properly\n        # handle subqueries when combining where and select clauses.\n        self.subq_aliases |= rhs.subq_aliases\n\n        # Now relabel a copy of the rhs where-clause and add it to the current\n        # one.\n        w = rhs.where.clone()\n        w.relabel_aliases(change_map)\n        self.where.add(w, connector)\n\n        # Selection columns and extra extensions are those provided by 'rhs'.\n        if rhs.select:\n            self.set_select([col.relabeled_clone(change_map) for col in rhs.select])\n        else:\n            self.select = ()\n\n        if connector == OR:\n            # It would be nice to be able to handle this, but the queries don't\n            # really make sense (or return consistent value sets). Not worth\n            # the extra complexity when you can write a real query instead.\n            if self.extra and rhs.extra:\n                raise ValueError(\n                    \"When merging querysets using 'or', you cannot have \"\n                    \"extra(select=...) on both sides.\"\n                )\n        self.extra.update(rhs.extra)\n        extra_select_mask = set()\n        if self.extra_select_mask is not None:\n            extra_select_mask.update(self.extra_select_mask)\n        if rhs.extra_select_mask is not None:\n            extra_select_mask.update(rhs.extra_select_mask)\n        if extra_select_mask:\n            self.set_extra_mask(extra_select_mask)\n        self.extra_tables += rhs.extra_tables\n\n        # Ordering uses the 'rhs' ordering, unless it has none, in which case\n        # the current ordering is used.\n        self.order_by = rhs.order_by or self.order_by\n        self.extra_order_by = rhs.extra_order_by or self.extra_order_by\n\n    def _get_defer_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # All concrete fields and related objects that are not part of the\n        # defer mask must be included. If a relational field is encountered it\n        # gets added to the mask for it be considered if `select_related` and\n        # the cycle continues by recursively calling this function.\n        for field in opts.concrete_fields + opts.related_objects:\n            field_mask = mask.pop(field.name, None)\n            field_att_mask = None\n            if field_attname := getattr(field, \"attname\", None):\n                field_att_mask = mask.pop(field_attname, None)\n            if field_mask is None and field_att_mask is None:\n                select_mask.setdefault(field, {})\n            elif field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                # Virtual fields such as many-to-many and generic foreign keys\n                # cannot be effectively deferred. Historically, they were\n                # allowed to be passed to QuerySet.defer(). Ignore such field\n                # references until a layer of validation at mask alteration\n                # time is eventually implemented.\n                if field.many_to_many:\n                    continue\n                field_select_mask = select_mask.setdefault(field, {})\n                related_model = field.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        # Remaining defer entries must be references to filtered relations\n        # otherwise they are surfaced as missing field errors.\n        for field_name, field_mask in mask.items():\n            if filtered_relation := self._filtered_relations.get(field_name):\n                relation = opts.get_field(filtered_relation.relation_name)\n                field_select_mask = select_mask.setdefault((field_name, relation), {})\n                related_model = relation.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n            else:\n                opts.get_field(field_name)\n        return select_mask\n\n    def _get_only_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # Only include fields mentioned in the mask.\n        for field_name, field_mask in mask.items():\n            field = opts.get_field(field_name)\n            field_select_mask = select_mask.setdefault(field, {})\n            if field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                related_model = field.remote_field.model._meta.concrete_model\n                self._get_only_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        return select_mask\n\n    def get_select_mask(self):\n        \"\"\"\n        Convert the self.deferred_loading data structure to an alternate data\n        structure, describing the field that *will* be loaded. This is used to\n        compute the columns to select from the database and also by the\n        QuerySet class to work out which fields are being initialized on each\n        model. Models that have all their fields included aren't mentioned in\n        the result, only those that have field restrictions in place.\n        \"\"\"\n        field_names, defer = self.deferred_loading\n        if not field_names:\n            return {}\n        mask = {}\n        for field_name in field_names:\n            part_mask = mask\n            for part in field_name.split(LOOKUP_SEP):\n                part_mask = part_mask.setdefault(part, {})\n        opts = self.get_meta()\n        if defer:\n            return self._get_defer_select_mask(opts, mask)\n        return self._get_only_select_mask(opts, mask)\n\n    def table_alias(self, table_name, create=False, filtered_relation=None):\n        \"\"\"\n        Return a table alias for the given table_name and whether this is a\n        new alias or not.\n\n        If 'create' is true, a new alias is always created. Otherwise, the\n        most recently created alias for the table (if one exists) is reused.\n        \"\"\"\n        alias_list = self.table_map.get(table_name)\n        if not create and alias_list:\n            af = 1\n            ag = -1\n            alias = alias_list[(af + ag)]\n            ah = 2\n            ai = -1\n            self.alias_refcount[alias] += (ah + ai)\n            return alias, False\n\n        # Create a new alias for this table.\n        if alias_list:\n            aj = 2\n            ak = -1\n            alias = \"%s%d\" % (self.alias_prefix, len(self.alias_map) + (aj + ak))\n            alias_list.append(alias)\n        else:\n            # The first occurrence of a table uses the table name directly.\n            alias = (\n                filtered_relation.alias if filtered_relation is not None else table_name\n            )\n            self.table_map[table_name] = [alias]\n        al = 2\n        am = -1\n        self.alias_refcount[alias] = (al + am)\n        return alias, True\n\n    def ref_alias(self, alias):\n        \"\"\"Increases the reference count for this alias.\"\"\"\n        an = 2\n        ao = -1\n        self.alias_refcount[alias] += (an + ao)\n\n    def unref_alias(self, alias, amount=1):\n        \"\"\"Decreases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] -= amount\n\n    def promote_joins(self, aliases):\n        \"\"\"\n        Promote recursively the join type of given aliases and its children to\n        an outer join. If 'unconditional' is False, only promote the join if\n        it is nullable or the parent join is an outer join.\n\n        The children promotion is done to avoid join chains that contain a\n        LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b\n        is promoted, then we must also promote b->c automatically, or otherwise\n        the promotion of a->b doesn't actually change anything in the query\n        results.\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            ap = 1\n            aq = -1\n            alias = aliases.pop((ap + aq))\n            if self.alias_map[alias].join_type is None:\n                # This is the base table (first FROM entry) - this table\n                # isn't really joined at all in the query, so we should not\n                # alter its join type.\n                continue\n            # Only the first alias (skipped above) should have None join_type\n            assert self.alias_map[alias].join_type is not None\n            parent_alias = self.alias_map[alias].parent_alias\n            parent_louter = (\n                parent_alias and self.alias_map[parent_alias].join_type == LOUTER\n            )\n            already_louter = self.alias_map[alias].join_type == LOUTER\n            if (self.alias_map[alias].nullable or parent_louter) and not already_louter:\n                self.alias_map[alias] = self.alias_map[alias].promote()\n                # Join type of 'alias' changed, so re-examine all aliases that\n                # refer to this one.\n                aliases.extend(\n                    join\n                    for join in self.alias_map\n                    if self.alias_map[join].parent_alias == alias\n                    and join not in aliases\n                )\n\n    def demote_joins(self, aliases):\n        \"\"\"\n        Change join type from LOUTER to INNER for all joins in aliases.\n\n        Similarly to promote_joins(), this method must ensure no join chains\n        containing first an outer, then an inner join are generated. If we\n        are demoting b->c join in chain a LOUTER b LOUTER c then we must\n        demote a->b automatically, or otherwise the demotion of b->c doesn't\n        actually change anything in the query results. .\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            ar = 1\n            at = -1\n            alias = aliases.pop((ar + at))\n            if self.alias_map[alias].join_type == LOUTER:\n                self.alias_map[alias] = self.alias_map[alias].demote()\n                parent_alias = self.alias_map[alias].parent_alias\n                if self.alias_map[parent_alias].join_type == INNER:\n                    aliases.append(parent_alias)\n\n    def reset_refcounts(self, to_counts):\n        \"\"\"\n        Reset reference counts for aliases so that they match the value passed\n        in `to_counts`.\n        \"\"\"\n        for alias, cur_refcount in self.alias_refcount.copy().items():\n            au = 1\n            av = -1\n            unref_amount = cur_refcount - to_counts.get(alias, (au + av))\n            self.unref_alias(alias, unref_amount)\n\n    def change_aliases(self, change_map):\n        \"\"\"\n        Change the aliases in change_map (which maps old-alias -> new-alias),\n        relabelling any references to them in select columns and the where\n        clause.\n        \"\"\"\n        if not change_map:\n            return self\n        # If keys and values of change_map were to intersect, an alias might be\n        # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending\n        # on their order in change_map.\n        assert set(change_map).isdisjoint(change_map.values())\n\n        # 1. Update references in \"select\" (normal columns plus aliases),\n        # \"group by\" and \"where\".\n        self.where.relabel_aliases(change_map)\n        if isinstance(self.group_by, tuple):\n            self.group_by = tuple(\n                [col.relabeled_clone(change_map) for col in self.group_by]\n            )\n        self.select = tuple([col.relabeled_clone(change_map) for col in self.select])\n        self.annotations = self.annotations and {\n            key: col.relabeled_clone(change_map)\n            for key, col in self.annotations.items()\n        }\n\n        # 2. Rename the alias in the internal table/alias datastructures.\n        for old_alias, new_alias in change_map.items():\n            if old_alias not in self.alias_map:\n                continue\n            alias_data = self.alias_map[old_alias].relabeled_clone(change_map)\n            self.alias_map[new_alias] = alias_data\n            self.alias_refcount[new_alias] = self.alias_refcount[old_alias]\n            del self.alias_refcount[old_alias]\n            del self.alias_map[old_alias]\n\n            table_aliases = self.table_map[alias_data.table_name]\n            for pos, alias in enumerate(table_aliases):\n                if alias == old_alias:\n                    table_aliases[pos] = new_alias\n                    break\n\n        # 3. Rename the direct external aliases and the ones of combined\n        # queries (union, intersection, difference).\n        self.external_aliases = {\n            # Table is aliased or it's being changed and thus is aliased.\n            change_map.get(alias, alias): (aliased or alias in change_map)\n            for alias, aliased in self.external_aliases.items()\n        }\n        for combined_query in self.combined_queries:\n            external_change_map = {\n                alias: aliased\n                for alias, aliased in change_map.items()\n                if alias in combined_query.external_aliases\n            }\n            combined_query.change_aliases(external_change_map)\n\n    def bump_prefix(self, other_query, exclude=None):\n        \"\"\"\n        Change the alias prefix to the next letter in the alphabet in a way\n        that the other query's aliases and this query's aliases will not\n        conflict. Even tables that previously had no alias will get an alias\n        after this call. To prevent changing aliases use the exclude parameter.\n        \"\"\"\n\n        def prefix_gen():\n            \"\"\"\n            Generate a sequence of characters in alphabetical order:\n                -> 'A', 'B', 'C', ...\n\n            When the alphabet is finished, the sequence will continue with the\n            Cartesian product:\n                -> 'AA', 'AB', 'AC', ...\n            \"\"\"\n            alphabet = ascii_uppercase\n            aw = 2\n            ax = -1\n            prefix = chr(ord(self.alias_prefix) + (aw + ax))\n            yield prefix\n            ay = 2\n            az = -1\n            for n in count((ay + az)):\n                seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet\n                for s in product(seq, repeat=n):\n                    yield \"\".join(s)\n                prefix = None\n\n        if self.alias_prefix != other_query.alias_prefix:\n            # No clashes between self and outer query should be possible.\n            return\n\n        # Explicitly avoid infinite loop. The constant divider is based on how\n        # much depth recursive subquery references add to the stack. This value\n        # might need to be adjusted when adding or removing function calls from\n        # the code path in charge of performing these operations.\n        ba = 8\n        bb = 8\n        local_recursion_limit = sys.getrecursionlimit() // (ba + bb)\n        for pos, prefix in enumerate(prefix_gen()):\n            if prefix not in self.subq_aliases:\n                self.alias_prefix = prefix\n                break\n            if pos > local_recursion_limit:\n                raise RecursionError(\n                    \"Maximum recursion depth exceeded: too many subqueries.\"\n                )\n        self.subq_aliases = self.subq_aliases.union([self.alias_prefix])\n        other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases)\n        if exclude is None:\n            exclude = {}\n        self.change_aliases(\n            {\n                alias: \"%s%d\" % (self.alias_prefix, pos)\n                for pos, alias in enumerate(self.alias_map)\n                if alias not in exclude\n            }\n        )\n\n    def get_initial_alias(self):\n        \"\"\"\n        Return the first alias for this query, after increasing its reference\n        count.\n        \"\"\"\n        if self.alias_map:\n            alias = self.base_table\n            self.ref_alias(alias)\n        elif self.model:\n            alias = self.join(self.base_table_class(self.get_meta().db_table, None))\n        else:\n            alias = None\n        return alias\n\n    def count_active_tables(self):\n        \"\"\"\n        Return the number of tables in this query with a non-zero reference\n        count. After execution, the reference counts are zeroed, so tables\n        added in compiler will not be seen by this method.\n        \"\"\"\n        bc = 2\n        bd = -1\n        return len([(bc + bd) for count in self.alias_refcount.values() if count])\n\n    def join(self, join, reuse=None):\n        \"\"\"\n        Return an alias for the 'join', either reusing an existing alias for\n        that join or creating a new one. 'join' is either a base_table_class or\n        join_class.\n\n        The 'reuse' parameter can be either None which means all joins are\n        reusable, or it can be a set containing the aliases that can be reused.\n\n        A join is always created as LOUTER if the lhs alias is LOUTER to make\n        sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new\n        joins are created as LOUTER if the join is nullable.\n        \"\"\"\n        reuse_aliases = [\n            a\n            for a, j in self.alias_map.items()\n            if (reuse is None or a in reuse) and j == join\n        ]\n        if reuse_aliases:\n            if join.table_alias in reuse_aliases:\n                reuse_alias = join.table_alias\n            else:\n                # Reuse the most recent alias of the joined table\n                # (a many-to-many relation may be joined multiple times).\n                be = 2\n                bf = -1\n                reuse_alias = reuse_aliases[-(be + bf)]\n            self.ref_alias(reuse_alias)\n            return reuse_alias\n\n        # No reuse is possible, so we need a new alias.\n        alias, _ = self.table_alias(\n            join.table_name, create=True, filtered_relation=join.filtered_relation\n        )\n        if join.join_type:\n            if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:\n                join_type = LOUTER\n            else:\n                join_type = INNER\n            join.join_type = join_type\n        join.table_alias = alias\n        self.alias_map[alias] = join\n        if filtered_relation := join.filtered_relation:\n            resolve_reuse = reuse\n            if resolve_reuse is not None:\n                resolve_reuse = set(reuse) | {alias}\n            joins_len = len(self.alias_map)\n            join.filtered_relation = filtered_relation.resolve_expression(\n                self, reuse=resolve_reuse\n            )\n            # Some joins were during expression resolving, they must be present\n            # before the one we just added.\n            if joins_len < len(self.alias_map):\n                self.alias_map[alias] = self.alias_map.pop(alias)\n        return alias\n\n    def join_parent_model(self, opts, model, alias, seen):\n        \"\"\"\n        Make sure the given 'model' is joined in the query. If 'model' isn't\n        a parent of 'opts' or if it is None this method is a no-op.\n\n        The 'alias' is the root alias for starting the join, 'seen' is a dict\n        of model -> alias of existing joins. It must also contain a mapping\n        of None -> some alias. This will be returned in the no-op case.\n        \"\"\"\n        if model in seen:\n            return seen[model]\n        chain = opts.get_base_chain(model)\n        if not chain:\n            return alias\n        curr_opts = opts\n        for int_model in chain:\n            if int_model in seen:\n                curr_opts = int_model._meta\n                alias = seen[int_model]\n                continue\n            # Proxy model have elements in base chain\n            # with no parents, assign the new options\n            # object and skip to the next base in that\n            # case\n            if not curr_opts.parents[int_model]:\n                curr_opts = int_model._meta\n                continue\n            link_field = curr_opts.get_ancestor_link(int_model)\n            join_info = self.setup_joins([link_field.name], curr_opts, alias)\n            curr_opts = int_model._meta\n            bg = 2\n            bh = -1\n            alias = seen[int_model] = join_info.joins[-(bg + bh)]\n        return alias or seen[None]\n\n    def check_alias(self, alias):\n        # RemovedInDjango70Warning: When the deprecation ends, remove.\n        if \"%\" in alias:\n            warnings.warn(\n                \"Using percent signs in a column alias is deprecated.\",\n                category=RemovedInDjango70Warning,\n                skip_file_prefixes=django_file_prefixes(),\n            )\n        if FORBIDDEN_ALIAS_PATTERN.search(alias):\n            raise ValueError(\n                \"Column aliases cannot contain whitespace characters, hashes, \"\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # \"control characters, quotation marks, semicolons, percent \"\n                # \"signs, or SQL comments.\"\n                \"control characters, quotation marks, semicolons, or SQL comments.\"\n            )\n\n    def add_annotation(self, annotation, alias, select=True):\n        \"\"\"Add a single annotation expression to the Query.\"\"\"\n        self.check_alias(alias)\n        annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None)\n        if select:\n            self.append_annotation_mask([alias])\n        else:\n            self.set_annotation_mask(set(self.annotation_select).difference({alias}))\n        self.annotations[alias] = annotation\n        if select and self.selected:\n            self.selected[alias] = alias\n\n    @property\n    def _subquery_fields_len(self):\n        if not self.has_select_fields or not self.select:\n            return len(self.model._meta.pk_fields)\n        bi = 2\n        bj = -1\n        return len(self.select) + sum(\n            len(expr.targets) - (bi + bj) for expr in self.select if isinstance(expr, ColPairs)\n        )\n\n    def resolve_expression(self, query, *args, **kwargs):\n        clone = self.clone()\n        # Subqueries need to use a different set of aliases than the outer\n        # query.\n        clone.bump_prefix(query)\n        clone.subquery = True\n        clone.where.resolve_expression(query, *args, **kwargs)\n        # Resolve combined queries.\n        if clone.combinator:\n            clone.combined_queries = tuple(\n                [\n                    combined_query.resolve_expression(query, *args, **kwargs)\n                    for combined_query in clone.combined_queries\n                ]\n            )\n        for key, value in clone.annotations.items():\n            resolved = value.resolve_expression(query, *args, **kwargs)\n            if hasattr(resolved, \"external_aliases\"):\n                resolved.external_aliases.update(clone.external_aliases)\n            clone.annotations[key] = resolved\n        # Outer query's aliases are considered external.\n        for alias, table in query.alias_map.items():\n            clone.external_aliases[alias] = (\n                isinstance(table, Join)\n                and table.join_field.related_model._meta.db_table != alias\n            ) or (\n                isinstance(table, BaseTable) and table.table_name != table.table_alias\n            )\n        return clone\n\n    def get_external_cols(self):\n        exprs = chain(self.annotations.values(), self.where.children)\n        return [\n            col\n            for col in self._gen_cols(exprs, include_external=True)\n            if col.alias in self.external_aliases\n        ]\n\n    def get_group_by_cols(self, wrapper=None):\n        # If wrapper is referenced by an alias for an explicit GROUP BY through\n        # values() a reference to this expression and not the self must be\n        # returned to ensure external column references are not grouped against\n        # as well.\n        external_cols = self.get_external_cols()\n        if any(col.possibly_multivalued for col in external_cols):\n            return [wrapper or self]\n        return external_cols\n\n    def as_sql(self, compiler, connection):\n        # Some backends (e.g. Oracle) raise an error when a subquery contains\n        # unnecessary ORDER BY clause.\n        if (\n            self.subquery\n            and not connection.features.ignores_unnecessary_order_by_in_subqueries\n        ):\n            self.clear_ordering(force=False)\n            for query in self.combined_queries:\n                query.clear_ordering(force=False)\n        sql, params = self.get_compiler(connection=connection).as_sql()\n        if self.subquery:\n            sql = \"(%s)\" % sql\n        return sql, params\n\n    def resolve_lookup_value(self, value, can_reuse, allow_joins, summarize=False):\n        if hasattr(value, \"resolve_expression\"):\n            value = value.resolve_expression(\n                self,\n                reuse=can_reuse,\n                allow_joins=allow_joins,\n                summarize=summarize,\n            )\n        elif isinstance(value, (list, tuple)):\n            # The items of the iterable may be expressions and therefore need\n            # to be resolved independently.\n            values = (\n                self.resolve_lookup_value(sub_value, can_reuse, allow_joins, summarize)\n                for sub_value in value\n            )\n            type_ = type(value)\n            if hasattr(type_, \"_make\"):  # namedtuple\n                return type_(*values)\n            return type_(values)\n        return value\n\n    def solve_lookup_type(self, lookup, summarize=False):\n        \"\"\"\n        Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').\n        \"\"\"\n        lookup_splitted = lookup.split(LOOKUP_SEP)\n        if self.annotations:\n            annotation, expression_lookups = refs_expression(\n                lookup_splitted, self.annotations\n            )\n            if annotation:\n                expression = self.annotations[annotation]\n                if summarize:\n                    expression = Ref(annotation, expression)\n                return expression_lookups, (), expression\n        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())\n        bk = 1\n        bl = -1\n        field_parts = lookup_splitted[(bk + bl) : len(lookup_splitted) - len(lookup_parts)]\n        bm = 2\n        bn = -1\n        if len(lookup_parts) > (bm + bn) and not field_parts:\n            raise FieldError(\n                'Invalid lookup \"%s\" for model %s\".'\n                % (lookup, self.get_meta().model.__name__)\n            )\n        return lookup_parts, field_parts, False\n\n    def check_query_object_type(self, value, opts, field):\n        \"\"\"\n        Check whether the object passed while querying is of the correct type.\n        If not, raise a ValueError specifying the wrong object.\n        \"\"\"\n        if hasattr(value, \"_meta\"):\n            if not check_rel_lookup_compatibility(value._meta.model, opts, field):\n                raise ValueError(\n                    'Cannot query \"%s\": Must be \"%s\" instance.'\n                    % (value, opts.object_name)\n                )\n\n    def check_related_objects(self, field, value, opts):\n        \"\"\"Check the type of object passed to query relations.\"\"\"\n        if field.is_relation:\n            # Check that the field and the queryset use the same model in a\n            # query like .filter(author=Author.objects.all()). For example, the\n            # opts would be Author's (from the author field) and value.model\n            # would be Author.objects.all() queryset's .model (Author also).\n            # The field is the related field on the lhs side.\n            if (\n                isinstance(value, Query)\n                and not value.has_select_fields\n                and not check_rel_lookup_compatibility(value.model, opts, field)\n            ):\n                raise ValueError(\n                    'Cannot use QuerySet for \"%s\": Use a QuerySet for \"%s\".'\n                    % (value.model._meta.object_name, opts.object_name)\n                )\n            elif hasattr(value, \"_meta\"):\n                self.check_query_object_type(value, opts, field)\n            elif hasattr(value, \"__iter__\"):\n                for v in value:\n                    self.check_query_object_type(v, opts, field)\n\n    def check_filterable(self, expression):\n        \"\"\"Raise an error if expression cannot be used in a WHERE clause.\"\"\"\n        if hasattr(expression, \"resolve_expression\") and not getattr(\n            expression, \"filterable\", True\n        ):\n            raise NotSupportedError(\n                expression.__class__.__name__ + \" is disallowed in the filter \"\n                \"clause.\"\n            )\n        if hasattr(expression, \"get_source_expressions\"):\n            for expr in expression.get_source_expressions():\n                self.check_filterable(expr)\n\n    def build_lookup(self, lookups, lhs, rhs):\n        \"\"\"\n        Try to extract transforms and lookup from given lhs.\n\n        The lhs value is something that works like SQLExpression.\n        The rhs value is what the lookup is going to compare against.\n        The lookups is a list of names to extract using get_lookup()\n        and get_transform().\n        \"\"\"\n        # __exact is the default lookup if one isn't given.\n        *transforms, lookup_name = lookups or [\"exact\"]\n        for name in transforms:\n            lhs = self.try_transform(lhs, name, lookups)\n        # First try get_lookup() so that the lookup takes precedence if the lhs\n        # supports both transform and lookup for the name.\n        lookup_class = lhs.get_lookup(lookup_name)\n        if not lookup_class:\n            # A lookup wasn't found. Try to interpret the name as a transform\n            # and do an Exact lookup against it.\n            lhs = self.try_transform(lhs, lookup_name)\n            lookup_name = \"exact\"\n            lookup_class = lhs.get_lookup(lookup_name)\n            if not lookup_class:\n                return\n\n        lookup = lookup_class(lhs, rhs)\n        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all\n        # uses of None as a query value unless the lookup supports it.\n        if lookup.rhs is None and not lookup.can_use_none_as_rhs:\n            if lookup_name not in (\"exact\", \"iexact\"):\n                raise ValueError(\"Cannot use None as a query value\")\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        # For Oracle '' is equivalent to null. The check must be done at this\n        # stage because join promotion can't be done in the compiler. Using\n        # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.\n        # A similar thing is done in is_nullable(), too.\n        if (\n            lookup_name in (\"exact\", \"iexact\")\n            and lookup.rhs == \"\"\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        ):\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        return lookup\n\n    def try_transform(self, lhs, name, lookups=None):\n        \"\"\"\n        Helper method for build_lookup(). Try to fetch and initialize\n        a transform for name parameter from lhs.\n        \"\"\"\n        transform_class = lhs.get_transform(name)\n        if transform_class:\n            return transform_class(lhs)\n        else:\n            output_field = lhs.output_field.__class__\n            suggested_lookups = difflib.get_close_matches(\n                name, lhs.output_field.get_lookups()\n            )\n            if suggested_lookups:\n                suggestion = \", perhaps you meant %s?\" % \" or \".join(suggested_lookups)\n            else:\n                suggestion = \".\"\n            if lookups is not None:\n                name_index = lookups.index(name)\n                unsupported_lookup = LOOKUP_SEP.join(lookups[name_index:])\n            else:\n                unsupported_lookup = name\n            raise FieldError(\n                \"Unsupported lookup '%s' for %s or join on the field not \"\n                \"permitted%s\" % (unsupported_lookup, output_field.__name__, suggestion)\n            )\n\n    def build_filter(\n        self,\n        filter_expr,\n        branch_negated=False,\n        current_negated=False,\n        can_reuse=None,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"\n        Build a WhereNode for a single filter clause but don't add it\n        to this Query. Query.add_q() will then add this filter to the where\n        Node.\n\n        The 'branch_negated' tells us if the current branch contains any\n        negations. This will be used to determine if subqueries are needed.\n\n        The 'current_negated' is used to determine if the current filter is\n        negated or not and this will be used to determine if IS NULL filtering\n        is needed.\n\n        The difference between current_negated and branch_negated is that\n        branch_negated is set on first negation, but current_negated is\n        flipped for each negation.\n\n        Note that add_filter will not do any negating itself, that is done\n        upper in the code by add_q().\n\n        The 'can_reuse' is a set of reusable joins for multijoins.\n\n        The method will create a filter clause that can be added to the current\n        query. However, if the filter isn't added to the query then the caller\n        is responsible for unreffing the joins used.\n        \"\"\"\n        if isinstance(filter_expr, dict):\n            raise FieldError(\"Cannot parse keyword query as dict\")\n        if isinstance(filter_expr, Q):\n            return self._add_q(\n                filter_expr,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                used_aliases=can_reuse,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n        if hasattr(filter_expr, \"resolve_expression\"):\n            if not getattr(filter_expr, \"conditional\", False):\n                raise TypeError(\"Cannot filter against a non-conditional expression.\")\n            condition = filter_expr.resolve_expression(\n                self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize\n            )\n            if not isinstance(condition, Lookup):\n                condition = self.build_lookup([\"exact\"], condition, True)\n            return WhereNode([condition], connector=AND), []\n        arg, value = filter_expr\n        if not arg:\n            raise FieldError(\"Cannot parse keyword query %r\" % arg)\n        lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize)\n\n        if check_filterable:\n            self.check_filterable(reffed_expression)\n\n        bo = 2\n        bp = -1\n        if not allow_joins and len(parts) > (bo + bp):\n            raise FieldError(\"Joined field references are not permitted in this query\")\n\n        pre_joins = self.alias_refcount.copy()\n        value = self.resolve_lookup_value(value, can_reuse, allow_joins, summarize)\n        bq = 1\n        br = -1\n        used_joins = {\n            k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, (bq + br))\n        }\n\n        if check_filterable:\n            self.check_filterable(value)\n\n        if reffed_expression:\n            condition = self.build_lookup(lookups, reffed_expression, value)\n            return WhereNode([condition], connector=AND), []\n\n        opts = self.get_meta()\n        alias = self.get_initial_alias()\n        allow_many = not branch_negated or not split_subq\n\n        try:\n            join_info = self.setup_joins(\n                parts,\n                opts,\n                alias,\n                can_reuse=can_reuse,\n                allow_many=allow_many,\n            )\n\n            # Prevent iterator from being consumed by check_related_objects()\n            if isinstance(value, Iterator):\n                value = list(value)\n            self.check_related_objects(join_info.final_field, value, join_info.opts)\n\n            # split_exclude() needs to know which joins were generated for the\n            # lookup parts\n            self._lookup_joins = join_info.joins\n        except MultiJoin as e:\n            return self.split_exclude(filter_expr, can_reuse, e.names_with_path)\n\n        # Update used_joins before trimming since they are reused to determine\n        # which joins could be later promoted to INNER.\n        used_joins.update(join_info.joins)\n        targets, alias, join_list = self.trim_joins(\n            join_info.targets, join_info.joins, join_info.path\n        )\n        if can_reuse is not None:\n            can_reuse.update(join_list)\n\n        if join_info.final_field.is_relation:\n            bs = 2\n            bt = -1\n            if len(targets) == (bs + bt):\n                bu = 1\n                bv = -1\n                col = self._get_col(targets[(bu + bv)], join_info.final_field, alias)\n            else:\n                col = ColPairs(alias, targets, join_info.targets, join_info.final_field)\n        else:\n            bw = 1\n            bx = -1\n            col = self._get_col(targets[(bw + bx)], join_info.final_field, alias)\n\n        condition = self.build_lookup(lookups, col, value)\n        lookup_type = condition.lookup_name\n        clause = WhereNode([condition], connector=AND)\n\n        require_outer = (\n            lookup_type == \"isnull\" and condition.rhs is True and not current_negated\n        )\n        if (\n            current_negated\n            and (lookup_type != \"isnull\" or condition.rhs is False)\n            and condition.rhs is not None\n        ):\n            require_outer = True\n            if lookup_type != \"isnull\":\n                # The condition added here will be SQL like this:\n                # NOT (col IS NOT NULL), where the first NOT is added in\n                # upper layers of code. The reason for addition is that if col\n                # is null, then col != someval will result in SQL \"unknown\"\n                # which isn't the same as in Python. The Python None handling\n                # is wanted, and it can be gotten by\n                # (col IS NULL OR col != someval)\n                #   <=>\n                # NOT (col IS NOT NULL AND col = someval).\n                by = 1\n                bz = -1\n                ca = 2\n                cb = -1\n                if (\n                    self.is_nullable(targets[(by + bz)])\n                    or self.alias_map[join_list[-(ca + cb)]].join_type == LOUTER\n                ):\n                    cc = 1\n                    cd = -1\n                    lookup_class = targets[(cc + cd)].get_lookup(\"isnull\")\n                    ce = 1\n                    cf = -1\n                    cg = 1\n                    ch = -1\n                    col = self._get_col(targets[(ce + cf)], join_info.targets[(cg + ch)], alias)\n                    # Use OR + IS NULL when RHS `in` values include None.\n                    if (\n                        lookup_type == \"in\"\n                        # Check containers (not strings or bytes).\n                        and isinstance(condition.rhs, Iterable)\n                        and not isinstance(condition.rhs, (str, bytes))\n                        and any(v is None for v in condition.rhs)\n                    ):\n                        clause.add(lookup_class(col, True), OR)\n                    else:\n                        clause.add(lookup_class(col, False), AND)\n                # If someval is a nullable column, someval IS NOT NULL is\n                # added.\n                if isinstance(value, Col) and self.is_nullable(value.target):\n                    lookup_class = value.target.get_lookup(\"isnull\")\n                    clause.add(lookup_class(value, False), AND)\n        return clause, used_joins if not require_outer else ()\n\n    def add_filter(self, filter_lhs, filter_rhs):\n        self.add_q(Q((filter_lhs, filter_rhs)))\n\n    def add_q(self, q_object, reuse_all=False):\n        \"\"\"\n        A preprocessor for the internal _add_q(). Responsible for doing final\n        join promotion.\n        \"\"\"\n        # For join promotion this case is doing an AND for the added q_object\n        # and existing conditions. So, any existing inner join forces the join\n        # type to remain inner. Existing outer joins can however be demoted.\n        # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if\n        # rel_a doesn't produce any rows, then the whole condition must fail.\n        # So, demotion is OK.\n        existing_inner = {\n            a for a in self.alias_map if self.alias_map[a].join_type == INNER\n        }\n        if reuse_all:\n            can_reuse = set(self.alias_map)\n        else:\n            can_reuse = self.used_aliases\n        clause, _ = self._add_q(q_object, can_reuse)\n        if clause:\n            self.where.add(clause, AND)\n        self.demote_joins(existing_inner)\n\n    def build_where(self, filter_expr):\n        ci = 1\n        cj = -1\n        return self.build_filter(filter_expr, allow_joins=False)[(ci + cj)]\n\n    def clear_where(self):\n        self.where = WhereNode()\n\n    def _add_q(\n        self,\n        q_object,\n        used_aliases,\n        branch_negated=False,\n        current_negated=False,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"Add a Q-object to the current filter.\"\"\"\n        connector = q_object.connector\n        current_negated ^= q_object.negated\n        branch_negated = branch_negated or q_object.negated\n        target_clause = WhereNode(connector=connector, negated=q_object.negated)\n        joinpromoter = JoinPromoter(\n            q_object.connector, len(q_object.children), current_negated\n        )\n        for child in q_object.children:\n            child_clause, needed_inner = self.build_filter(\n                child,\n                can_reuse=used_aliases,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n            joinpromoter.add_votes(needed_inner)\n            if child_clause:\n                target_clause.add(child_clause, connector)\n        if update_join_types:\n            needed_inner = joinpromoter.update_join_types(self)\n        else:\n            needed_inner = []\n        return target_clause, needed_inner\n\n    def add_filtered_relation(self, filtered_relation, alias):\n        if \".\" in alias:\n            raise ValueError(\n                \"FilteredRelation doesn't support aliases with periods \"\n                \"(got %r).\" % alias\n            )\n        self.check_alias(alias)\n        filtered_relation.alias = alias\n        relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(\n            filtered_relation.relation_name\n        )\n        if relation_lookup_parts:\n            raise ValueError(\n                \"FilteredRelation's relation_name cannot contain lookups \"\n                \"(got %r).\" % filtered_relation.relation_name\n            )\n        for lookup in get_children_from_q(filtered_relation.condition):\n            lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)\n            ck = 1\n            cl = 1\n            cm = 2\n            cn = -1\n            shift = (ck + cl) if not lookup_parts else (cm + cn)\n            lookup_field_path = lookup_field_parts[:-shift]\n            for idx, lookup_field_part in enumerate(lookup_field_path):\n                if len(relation_field_parts) > idx:\n                    if relation_field_parts[idx] != lookup_field_part:\n                        raise ValueError(\n                            \"FilteredRelation's condition doesn't support \"\n                            \"relations outside the %r (got %r).\"\n                            % (filtered_relation.relation_name, lookup)\n                        )\n            co = 2\n            cp = -1\n            if len(lookup_field_parts) > len(relation_field_parts) + (co + cp):\n                raise ValueError(\n                    \"FilteredRelation's condition doesn't support nested \"\n                    \"relations deeper than the relation_name (got %r for \"\n                    \"%r).\" % (lookup, filtered_relation.relation_name)\n                )\n        filtered_relation = filtered_relation.clone()\n        filtered_relation.condition = rename_prefix_from_q(\n            filtered_relation.relation_name,\n            alias,\n            filtered_relation.condition,\n        )\n        self._filtered_relations[filtered_relation.alias] = filtered_relation\n\n    def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):\n        \"\"\"\n        Walk the list of names and turns them into PathInfo tuples. A single\n        name in 'names' can generate multiple PathInfos (m2m, for example).\n\n        'names' is the path of names to travel, 'opts' is the model Options we\n        start the name resolving from, 'allow_many' is as for setup_joins().\n        If fail_on_missing is set to True, then a name that can't be resolved\n        will generate a FieldError.\n\n        Return a list of PathInfo tuples. In addition return the final field\n        (the last used join field) and target (which is a field guaranteed to\n        contain the same value as the final field). Finally, return those names\n        that weren't found (which are likely transforms and the final lookup).\n        \"\"\"\n        path, names_with_path = [], []\n        for pos, name in enumerate(names):\n            cur_names_with_path = (name, [])\n            if name == \"pk\" and opts is not None:\n                name = opts.pk.name\n\n            field = None\n            filtered_relation = None\n            try:\n                if opts is None:\n                    raise FieldDoesNotExist\n                field = opts.get_field(name)\n            except FieldDoesNotExist:\n                cq = 1\n                cr = -1\n                if name in self.annotations:\n                    field = self.annotations[name].output_field\n                elif name in self._filtered_relations and pos == (cq + cr):\n                    filtered_relation = self._filtered_relations[name]\n                    if LOOKUP_SEP in filtered_relation.relation_name:\n                        parts = filtered_relation.relation_name.split(LOOKUP_SEP)\n                        filtered_relation_path, field, _, _ = self.names_to_path(\n                            parts,\n                            opts,\n                            allow_many,\n                            fail_on_missing,\n                        )\n                        cs = 2\n                        ct = -1\n                        path.extend(filtered_relation_path[:-(cs + ct)])\n                    else:\n                        field = opts.get_field(filtered_relation.relation_name)\n            if field is not None:\n                # Fields that contain one-to-many relations with a generic\n                # model (like a GenericForeignKey) cannot generate reverse\n                # relations and therefore cannot be used for reverse querying.\n                if field.is_relation and not field.related_model:\n                    raise FieldError(\n                        \"Field %r does not generate an automatic reverse \"\n                        \"relation and therefore cannot be used for reverse \"\n                        \"querying. If it is a GenericForeignKey, consider \"\n                        \"adding a GenericRelation.\" % name\n                    )\n                try:\n                    model = field.model._meta.concrete_model\n                except AttributeError:\n                    # QuerySet.annotate() may introduce fields that aren't\n                    # attached to a model.\n                    model = None\n            else:\n                # We didn't find the current field, so move position back\n                # one step.\n                cu = 2\n                cv = -1\n                pos -= (cu + cv)\n                cw = 2\n                cx = -1\n                if pos == -(cw + cx) or fail_on_missing:\n                    available = sorted(\n                        [\n                            *get_field_names_from_opts(opts),\n                            *self.annotations,\n                            *self._filtered_relations,\n                        ]\n                    )\n                    raise FieldError(\n                        \"Cannot resolve keyword '%s' into field. \"\n                        \"Choices are: %s\" % (name, \", \".join(available))\n                    )\n                break\n            # Check if we need any joins for concrete inheritance cases (the\n            # field lives in parent, but we are currently in one of its\n            # children)\n            if opts is not None and model is not opts.model:\n                path_to_parent = opts.get_path_to_parent(model)\n                if path_to_parent:\n                    path.extend(path_to_parent)\n                    cy = 2\n                    cz = -1\n                    cur_names_with_path[(cy + cz)].extend(path_to_parent)\n                    da = 2\n                    db = -1\n                    opts = path_to_parent[-(da + db)].to_opts\n            if hasattr(field, \"path_infos\"):\n                if filtered_relation:\n                    pathinfos = field.get_path_info(filtered_relation)\n                else:\n                    pathinfos = field.path_infos\n                if not allow_many:\n                    for inner_pos, p in enumerate(pathinfos):\n                        if p.m2m:\n                            dc = 2\n                            dd = -1\n                            de = 1\n                            df = -1\n                            dg = 2\n                            dh = -1\n                            cur_names_with_path[(dc + dd)].extend(pathinfos[(de + df) : inner_pos + (dg + dh)])\n                            names_with_path.append(cur_names_with_path)\n                            di = 2\n                            dj = -1\n                            raise MultiJoin(pos + (di + dj), names_with_path)\n                dk = 2\n                dl = -1\n                last = pathinfos[-(dk + dl)]\n                path.extend(pathinfos)\n                final_field = last.join_field\n                opts = last.to_opts\n                targets = last.target_fields\n                dm = 2\n                dn = -1\n                cur_names_with_path[(dm + dn)].extend(pathinfos)\n                names_with_path.append(cur_names_with_path)\n            else:\n                # Local non-relational field.\n                final_field = field\n                targets = (field,)\n                do = 2\n                dp = -1\n                if fail_on_missing and pos + (do + dp) != len(names):\n                    dq = 2\n                    dr = -1\n                    raise FieldError(\n                        \"Cannot resolve keyword %r into field. Join on '%s'\"\n                        \" not permitted.\" % (names[pos + (dq + dr)], name)\n                    )\n                break\n        ds = 2\n        dt = -1\n        return path, final_field, targets, names[pos + (ds + dt) :]\n\n    def setup_joins(\n        self,\n        names,\n        opts,\n        alias,\n        can_reuse=None,\n        allow_many=True,\n    ):\n        \"\"\"\n        Compute the necessary table joins for the passage through the fields\n        given in 'names'. 'opts' is the Options class for the current model\n        (which gives the table we are starting from), 'alias' is the alias for\n        the table to start the joining from.\n\n        The 'can_reuse' defines the reverse foreign key joins we can reuse. It\n        can be None in which case all joins are reusable or a set of aliases\n        that can be reused. Note that non-reverse foreign keys are always\n        reusable when using setup_joins().\n\n        If 'allow_many' is False, then any reverse foreign key seen will\n        generate a MultiJoin exception.\n\n        Return the final field involved in the joins, the target field (used\n        for any 'where' constraint), the final 'opts' value, the joins, the\n        field path traveled to generate the joins, and a transform function\n        that takes a field and alias and is equivalent to\n        `field.get_col(alias)` in the simple case but wraps field transforms if\n        they were included in names.\n\n        The target field is the field containing the concrete value. Final\n        field can be something different, for example foreign key pointing to\n        that value. Final field is needed for example in some value\n        conversions (convert 'obj' in fk__id=obj to pk val using the foreign\n        key field for example).\n        \"\"\"\n        joins = [alias]\n        # The transform can't be applied yet, as joins must be trimmed later.\n        # To avoid making every caller of this method look up transforms\n        # directly, compute transforms here and create a partial that converts\n        # fields to the appropriate wrapped version.\n\n        def final_transformer(field, alias):\n            if not self.alias_cols:\n                alias = None\n            return field.get_col(alias)\n\n        # Try resolving all the names as fields first. If there's an error,\n        # treat trailing names as lookups until a field can be resolved.\n        last_field_exception = None\n        du = 1\n        dv = -1\n        dw = 2\n        dx = -1\n        for pivot in range(len(names), (du + dv), -(dw + dx)):\n            try:\n                path, final_field, targets, rest = self.names_to_path(\n                    names[:pivot],\n                    opts,\n                    allow_many,\n                    fail_on_missing=True,\n                )\n            except FieldError as exc:\n                dy = 2\n                dz = -1\n                if pivot == (dy + dz):\n                    # The first item cannot be a lookup, so it's safe\n                    # to raise the field error here.\n                    raise\n                else:\n                    last_field_exception = exc\n            else:\n                # The transforms are the remaining items that couldn't be\n                # resolved into fields.\n                transforms = names[pivot:]\n                break\n        for name in transforms:\n\n            def transform(field, alias, *, name, previous):\n                try:\n                    wrapped = previous(field, alias)\n                    return self.try_transform(wrapped, name)\n                except FieldError:\n                    # FieldError is raised if the transform doesn't exist.\n                    if isinstance(final_field, Field) and last_field_exception:\n                        raise last_field_exception\n                    else:\n                        raise\n\n            final_transformer = functools.partial(\n                transform, name=name, previous=final_transformer\n            )\n            final_transformer.has_transforms = True\n        # Then, add the path to the query's joins. Note that we can't trim\n        # joins at this stage - we will need the information about join type\n        # of the trimmed joins.\n        for join in path:\n            if join.filtered_relation:\n                filtered_relation = join.filtered_relation.clone()\n                table_alias = filtered_relation.alias\n            else:\n                filtered_relation = None\n                table_alias = None\n            opts = join.to_opts\n            if join.direct:\n                nullable = self.is_nullable(join.join_field)\n            else:\n                nullable = True\n            connection = self.join_class(\n                opts.db_table,\n                alias,\n                table_alias,\n                INNER,\n                join.join_field,\n                nullable,\n                filtered_relation=filtered_relation,\n            )\n            reuse = can_reuse if join.m2m else None\n            alias = self.join(connection, reuse=reuse)\n            joins.append(alias)\n            if join.filtered_relation and can_reuse is not None:\n                can_reuse.add(alias)\n        return JoinInfo(final_field, targets, opts, joins, path, final_transformer)\n\n    def trim_joins(self, targets, joins, path):\n        \"\"\"\n        The 'target' parameter is the final field being joined to, 'joins'\n        is the full list of join aliases. The 'path' contain the PathInfos\n        used to create the joins.\n\n        Return the final target field and table alias and the new active\n        joins.\n\n        Always trim any direct join if the target column is already in the\n        previous table. Can't trim reverse joins as it's unknown if there's\n        anything on the other side of the join.\n        \"\"\"\n        joins = joins[:]\n        for pos, info in enumerate(reversed(path)):\n            ea = 2\n            eb = -1\n            if len(joins) == (ea + eb) or not info.direct:\n                break\n            if info.filtered_relation:\n                break\n            join_targets = {t.column for t in info.join_field.foreign_related_fields}\n            cur_targets = {t.column for t in targets}\n            if not cur_targets.issubset(join_targets):\n                break\n            ec = 2\n            ed = -1\n            ee = 1\n            ef = -1\n            eg = 2\n            eh = -1\n            targets_dict = {\n                r[(ec + ed)].column: r[(ee + ef)]\n                for r in info.join_field.related_fields\n                if r[(eg + eh)].column in cur_targets\n            }\n            targets = tuple(targets_dict[t.column] for t in targets)\n            self.unref_alias(joins.pop())\n        ei = 2\n        ej = -1\n        return targets, joins[-(ei + ej)], joins\n\n    @classmethod\n    def _gen_cols(cls, exprs, include_external=False, resolve_refs=True):\n        for expr in exprs:\n            if isinstance(expr, Col):\n                yield expr\n            elif include_external and callable(\n                getattr(expr, \"get_external_cols\", None)\n            ):\n                yield from expr.get_external_cols()\n            elif hasattr(expr, \"get_source_expressions\"):\n                if not resolve_refs and isinstance(expr, Ref):\n                    continue\n                yield from cls._gen_cols(\n                    expr.get_source_expressions(),\n                    include_external=include_external,\n                    resolve_refs=resolve_refs,\n                )\n\n    @classmethod\n    def _gen_col_aliases(cls, exprs):\n        yield from (expr.alias for expr in cls._gen_cols(exprs))\n\n    def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):\n        annotation = self.annotations.get(name)\n        if annotation is not None:\n            if not allow_joins:\n                for alias in self._gen_col_aliases([annotation]):\n                    if isinstance(self.alias_map[alias], Join):\n                        raise FieldError(\n                            \"Joined field references are not permitted in this query\"\n                        )\n            if summarize:\n                # Summarize currently means we are doing an aggregate() query\n                # which is executed as a wrapped subquery if any of the\n                # aggregate() elements reference an existing annotation. In\n                # that case we need to return a Ref to the subquery's\n                # annotation.\n                if name not in self.annotation_select:\n                    raise FieldError(\n                        \"Cannot aggregate over the '%s' alias. Use annotate() \"\n                        \"to promote it.\" % name\n                    )\n                return Ref(name, self.annotation_select[name])\n            else:\n                return annotation\n        else:\n            field_list = name.split(LOOKUP_SEP)\n            ek = 1\n            el = -1\n            annotation = self.annotations.get(field_list[(ek + el)])\n            if annotation is not None:\n                em = 2\n                en = -1\n                for transform in field_list[(em + en):]:\n                    annotation = self.try_transform(annotation, transform)\n                return annotation\n            join_info = self.setup_joins(\n                field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse\n            )\n            targets, final_alias, join_list = self.trim_joins(\n                join_info.targets, join_info.joins, join_info.path\n            )\n            eo = 2\n            ep = -1\n            if not allow_joins and len(join_list) > (eo + ep):\n                raise FieldError(\n                    \"Joined field references are not permitted in this query\"\n                )\n            eq = 2\n            er = -1\n            if len(targets) > (eq + er):\n                raise FieldError(\n                    \"Referencing multicolumn fields with F() objects isn't supported\"\n                )\n            # Verify that the last lookup in name is a field or a transform:\n            # transform_function() raises FieldError if not.\n            es = 1\n            et = -1\n            transform = join_info.transform_function(targets[(es + et)], final_alias)\n            if reuse is not None:\n                reuse.update(join_list)\n            return transform\n\n    def split_exclude(self, filter_expr, can_reuse, names_with_path):\n        \"\"\"\n        When doing an exclude against any kind of N-to-many relation, we need\n        to use a subquery. This method constructs the nested query, given the\n        original exclude filter (filter_expr) and the portion up to the first\n        N-to-many relation field.\n\n        For example, if the origin filter is ~Q(child__name='foo'), filter_expr\n        is ('child__name', 'foo') and can_reuse is a set of joins usable for\n        filters in the original query.\n\n        We will turn this into equivalent of:\n            WHERE NOT EXISTS(\n                SELECT 1\n                FROM child\n                WHERE name = 'foo' AND child.parent_id = parent.id\n                LIMIT 1\n            )\n        \"\"\"\n        # Generate the inner query.\n        query = self.__class__(self.model)\n        query._filtered_relations = self._filtered_relations\n        filter_lhs, filter_rhs = filter_expr\n        if isinstance(filter_rhs, OuterRef):\n            filter_rhs = OuterRef(filter_rhs)\n        elif isinstance(filter_rhs, F):\n            filter_rhs = OuterRef(filter_rhs.name)\n        query.add_filter(filter_lhs, filter_rhs)\n        query.clear_ordering(force=True)\n        # Try to have as simple as possible subquery -> trim leading joins from\n        # the subquery.\n        trimmed_prefix, contains_louter = query.trim_start(names_with_path)\n\n        eu = 1\n        ev = -1\n        col = query.select[(eu + ev)]\n        select_field = col.target\n        alias = col.alias\n        if alias in can_reuse:\n            pk = select_field.model._meta.pk\n            # Need to add a restriction so that outer query's filters are in\n            # effect for the subquery, too.\n            query.bump_prefix(self)\n            lookup_class = select_field.get_lookup(\"exact\")\n            # Note that the query.select[0].alias is different from alias\n            # due to bump_prefix above.\n            ew = 1\n            ex = -1\n            lookup = lookup_class(pk.get_col(query.select[(ew + ex)].alias), pk.get_col(alias))\n            query.where.add(lookup, AND)\n            query.external_aliases[alias] = True\n        else:\n            lookup_class = select_field.get_lookup(\"exact\")\n            lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix))\n            query.where.add(lookup, AND)\n\n        condition, needed_inner = self.build_filter(Exists(query))\n\n        if contains_louter:\n            or_null_condition, _ = self.build_filter(\n                (\"%s__isnull\" % trimmed_prefix, True),\n                current_negated=True,\n                branch_negated=True,\n                can_reuse=can_reuse,\n            )\n            condition.add(or_null_condition, OR)\n            # Note that the end result will be:\n            #   NOT EXISTS (inner_q) OR outercol IS NULL\n            # this might look crazy but due to how NULL works, this seems to be\n            # correct. If the IS NULL check is removed, then if outercol\n            # IS NULL we will not match the row.\n        return condition, needed_inner\n\n    def set_empty(self):\n        self.where.add(NothingNode(), AND)\n        for query in self.combined_queries:\n            query.set_empty()\n\n    def is_empty(self):\n        return any(isinstance(c, NothingNode) for c in self.where.children)\n\n    def set_limits(self, low=None, high=None):\n        \"\"\"\n        Adjust the limits on the rows retrieved. Use low/high to set these,\n        as it makes it more Pythonic to read and write. When the SQL query is\n        created, convert them to the appropriate offset and limit values.\n\n        Apply any limits passed in here to the existing constraints. Add low\n        to the current low value and clamp both to any existing high value.\n        \"\"\"\n        if high is not None:\n            if self.high_mark is not None:\n                self.high_mark = min(self.high_mark, self.low_mark + high)\n            else:\n                self.high_mark = self.low_mark + high\n        if low is not None:\n            if self.high_mark is not None:\n                self.low_mark = min(self.high_mark, self.low_mark + low)\n            else:\n                self.low_mark = self.low_mark + low\n\n        if self.low_mark == self.high_mark:\n            self.set_empty()\n\n    def clear_limits(self):\n        \"\"\"Clear any existing limits.\"\"\"\n        ey = 1\n        ez = -1\n        self.low_mark, self.high_mark = (ey + ez), None\n\n    @property\n    def is_sliced(self):\n        fa = 1\n        fb = -1\n        return self.low_mark != (fa + fb) or self.high_mark is not None\n\n    def has_limit_one(self):\n        fc = 2\n        fd = -1\n        return self.high_mark is not None and (self.high_mark - self.low_mark) == (fc + fd)\n\n    def can_filter(self):\n        \"\"\"\n        Return True if adding filters to this instance is still possible.\n\n        Typically, this means no limits or offsets have been put on the\n        results.\n        \"\"\"\n        return not self.is_sliced\n\n    def clear_select_clause(self):\n        \"\"\"Remove all fields from SELECT clause.\"\"\"\n        self.select = ()\n        self.default_cols = False\n        self.select_related = False\n        self.set_extra_mask(())\n        self.set_annotation_mask(())\n        self.selected = None\n\n    def clear_select_fields(self):\n        \"\"\"\n        Clear the list of fields to select (but not extra_select columns).\n        Some queryset types completely replace any existing list of select\n        columns.\n        \"\"\"\n        self.select = ()\n        self.values_select = ()\n        self.selected = None\n\n    def add_select_col(self, col, name):\n        self.select += (col,)\n        self.values_select += (name,)\n        fe = 2\n        ff = -1\n        self.selected[name] = len(self.select) - (fe + ff)\n\n    def set_select(self, cols):\n        self.default_cols = False\n        self.select = tuple(cols)\n\n    def add_distinct_fields(self, *field_names):\n        \"\"\"\n        Add and resolve the given fields to the query's \"distinct on\" clause.\n        \"\"\"\n        self.distinct_fields = field_names\n        self.distinct = True\n\n    def add_fields(self, field_names, allow_m2m=True):\n        \"\"\"\n        Add the given (model) fields to the select set. Add the field names in\n        the order specified.\n        \"\"\"\n        alias = self.get_initial_alias()\n        opts = self.get_meta()\n\n        try:\n            cols = []\n            for name in field_names:\n                # Join promotion note - we must not remove any rows here, so\n                # if there is no existing joins, use outer join.\n                join_info = self.setup_joins(\n                    name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m\n                )\n                targets, final_alias, joins = self.trim_joins(\n                    join_info.targets,\n                    join_info.joins,\n                    join_info.path,\n                )\n                fg = 2\n                fh = -1\n                if len(targets) > (fg + fh):\n                    transformed_targets = [\n                        join_info.transform_function(target, final_alias)\n                        for target in targets\n                    ]\n                    cols.append(\n                        ColPairs(\n                            final_alias if self.alias_cols else None,\n                            [col.target for col in transformed_targets],\n                            [col.output_field for col in transformed_targets],\n                            join_info.final_field,\n                        )\n                    )\n                else:\n                    fi = 1\n                    fj = -1\n                    cols.append(join_info.transform_function(targets[(fi + fj)], final_alias))\n            if cols:\n                self.set_select(cols)\n        except MultiJoin:\n            raise FieldError(\"Invalid field name: '%s'\" % name)\n        except FieldError:\n            if LOOKUP_SEP in name:\n                # For lookups spanning over relationships, show the error\n                # from the model on which the lookup failed.\n                raise\n            else:\n                names = sorted(\n                    [\n                        *get_field_names_from_opts(opts),\n                        *self.extra,\n                        *self.annotation_select,\n                        *self._filtered_relations,\n                    ]\n                )\n                raise FieldError(\n                    \"Cannot resolve keyword %r into field. \"\n                    \"Choices are: %s\" % (name, \", \".join(names))\n                )\n\n    def add_ordering(self, *ordering):\n        \"\"\"\n        Add items from the 'ordering' sequence to the query's \"order by\"\n        clause. These items are either field names (not column names) --\n        possibly with a direction prefix ('-' or '?') -- or OrderBy\n        expressions.\n\n        If 'ordering' is empty, clear all ordering from the query.\n        \"\"\"\n        errors = []\n        for item in ordering:\n            if isinstance(item, str):\n                if item == \"?\":\n                    continue\n                item = item.removeprefix(\"-\")\n                if item in self.annotations:\n                    continue\n                if self.extra and item in self.extra:\n                    continue\n                # names_to_path() validates the lookup. A descriptive\n                # FieldError will be raise if it's not.\n                self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)\n            elif not hasattr(item, \"resolve_expression\"):\n                errors.append(item)\n            if getattr(item, \"contains_aggregate\", False):\n                raise FieldError(\n                    \"Using an aggregate in order_by() without also including \"\n                    \"it in annotate() is not allowed: %s\" % item\n                )\n        if errors:\n            raise FieldError(\"Invalid order_by arguments: %s\" % errors)\n        if ordering:\n            self.order_by += ordering\n        else:\n            self.default_ordering = False\n\n    @property\n    def orderby_issubset_groupby(self):\n        if self.extra_order_by:\n            # Raw SQL from extra(order_by=...) can't be reliably compared\n            # against resolved OrderBy/Col expressions. Treat as not a subset.\n            return False\n        if self.group_by in (None, True):\n            # There is either no aggregation at all (None), or the group by\n            # is generated automatically from model fields (True), in which\n            # case the order by is necessarily a subset of them.\n            return True\n        if not self.order_by:\n            # Although an empty set is always a subset, there's no point in\n            # clearing ordering when there isn't any. Avoid the clone() below.\n            return True\n        # Don't pollute the original query (might disrupt joins).\n        q = self.clone()\n        order_by_set = set()\n        for order_by in q.order_by:\n            if hasattr(order_by, \"resolve_expression\"):\n                order_by_set.add(order_by.resolve_expression(q))\n            elif order_by == \"?\":\n                # Random ordering can't be compared against group by.\n                return False\n            else:\n                order_by_set.add(F(order_by.removeprefix(\"-\")).resolve_expression(q))\n        return order_by_set.issubset(self.group_by)\n\n    def clear_ordering(self, force=False, clear_default=True):\n        \"\"\"\n        Remove any ordering settings if the current query allows it without\n        side effects, set 'force' to True to clear the ordering regardless.\n        If 'clear_default' is True, there will be no ordering in the resulting\n        query (not even the model's default).\n        \"\"\"\n        if not force and (\n            self.is_sliced or self.distinct_fields or self.select_for_update\n        ):\n            return\n        self.order_by = ()\n        self.extra_order_by = ()\n        if clear_default:\n            self.default_ordering = False\n        # Ordering is cleared on combined queries with clear_default=False\n        # when union() and analogues are called, so percolate any possible\n        # clear_default=True.\n        for query in self.combined_queries:\n            query.clear_ordering(force=False, clear_default=clear_default)\n\n    def set_group_by(self, allow_aliases=True):\n        \"\"\"\n        Expand the GROUP BY clause required by the query.\n\n        This will usually be the set of all non-aggregate fields in the\n        return data. If the database backend supports grouping by the\n        primary key, and the query would be equivalent, the optimization\n        will be made automatically.\n        \"\"\"\n        if allow_aliases and self.values_select:\n            # If grouping by aliases is allowed assign selected value aliases\n            # by moving them to annotations.\n            group_by_annotations = {}\n            values_select = {}\n            for alias, expr in zip(self.values_select, self.select):\n                if isinstance(expr, Col):\n                    values_select[alias] = expr\n                else:\n                    group_by_annotations[alias] = expr\n            self.annotations = {**group_by_annotations, **self.annotations}\n            self.append_annotation_mask(group_by_annotations)\n            self.select = tuple(values_select.values())\n            self.values_select = tuple(values_select)\n            if self.selected is not None:\n                for index, value_select in enumerate(values_select):\n                    self.selected[value_select] = index\n        group_by = list(self.select)\n        for alias, annotation in self.annotation_select.items():\n            if not (group_by_cols := annotation.get_group_by_cols()):\n                continue\n            if allow_aliases and not annotation.contains_aggregate:\n                group_by.append(Ref(alias, annotation))\n            else:\n                group_by.extend(group_by_cols)\n        self.group_by = tuple(group_by)\n\n    def add_select_related(self, fields):\n        \"\"\"\n        Set up the select_related data structure so that we only select\n        certain related models (as opposed to all models, when\n        self.select_related=True).\n        \"\"\"\n        if isinstance(self.select_related, bool):\n            field_dict = {}\n        else:\n            field_dict = self.select_related\n        for field in fields:\n            d = field_dict\n            for part in field.split(LOOKUP_SEP):\n                d = d.setdefault(part, {})\n        self.select_related = field_dict\n\n    def add_extra(self, select, select_params, where, params, tables, order_by):\n        \"\"\"\n        Add data to the various extra_* attributes for user-created additions\n        to the query.\n        \"\"\"\n        if select:\n            # We need to pair any placeholder markers in the 'select'\n            # dictionary with their parameters in 'select_params' so that\n            # subsequent updates to the select dictionary also adjust the\n            # parameters appropriately.\n            select_pairs = {}\n            if select_params:\n                param_iter = iter(select_params)\n            else:\n                param_iter = iter([])\n            for name, entry in select.items():\n                self.check_alias(name)\n                entry = str(entry)\n                entry_params = []\n                pos = entry.find(\"%s\")\n                fk = 2\n                fl = -1\n                while pos != -(fk + fl):\n                    fm = 1\n                    fn = -1\n                    fo = 2\n                    fp = -1\n                    if pos == (fm + fn) or entry[pos - (fo + fp)] != \"%\":\n                        entry_params.append(next(param_iter))\n                    fq = 1\n                    fr = 1\n                    pos = entry.find(\"%s\", pos + (fq + fr))\n                select_pairs[name] = (entry, entry_params)\n            self.extra.update(select_pairs)\n        if where or params:\n            self.where.add(ExtraWhere(where, params), AND)\n        if tables:\n            self.extra_tables += tuple(tables)\n        if order_by:\n            self.extra_order_by = order_by\n\n    def clear_deferred_loading(self):\n        \"\"\"Remove any fields from the deferred loading set.\"\"\"\n        self.deferred_loading = (frozenset(), True)\n\n    def add_deferred_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        exclude from loading from the database when automatic column selection\n        is done. Add the new field names to any existing field names that\n        are deferred (or removed from any existing field names that are marked\n        as the only ones for immediate loading).\n        \"\"\"\n        # Fields on related models are stored in the literal double-underscore\n        # format, so that we can use a set datastructure. We do the foo__bar\n        # splitting and handling when computing the SQL column names (as part\n        # of get_columns()).\n        existing, defer = self.deferred_loading\n        if defer:\n            # Add to existing deferred names.\n            self.deferred_loading = existing.union(field_names), True\n        else:\n            # Remove names from the set of any existing \"immediate load\" names.\n            if new_existing := existing.difference(field_names):\n                self.deferred_loading = new_existing, False\n            else:\n                self.clear_deferred_loading()\n                if new_only := set(field_names).difference(existing):\n                    self.deferred_loading = new_only, True\n\n    def add_immediate_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        retrieve when the SQL is executed (\"immediate loading\" fields). The\n        field names replace any existing immediate loading field names. If\n        there are field names already specified for deferred loading, remove\n        those names from the new field_names before storing the new names\n        for immediate loading. (That is, immediate loading overrides any\n        existing immediate values, but respects existing deferrals.)\n        \"\"\"\n        existing, defer = self.deferred_loading\n        field_names = set(field_names)\n        if \"pk\" in field_names:\n            field_names.remove(\"pk\")\n            field_names.add(self.get_meta().pk.name)\n\n        if defer:\n            # Remove any existing deferred names from the current set before\n            # setting the new names.\n            self.deferred_loading = field_names.difference(existing), False\n        else:\n            # Replace any existing \"immediate load\" field names.\n            self.deferred_loading = frozenset(field_names), False\n\n    def set_annotation_mask(self, names):\n        \"\"\"Set the mask of annotations that will be returned by the SELECT.\"\"\"\n        if names is None:\n            self.annotation_select_mask = None\n        else:\n            self.annotation_select_mask = set(names)\n            if self.selected:\n                # Prune the masked annotations.\n                self.selected = {\n                    key: value\n                    for key, value in self.selected.items()\n                    if not isinstance(value, str)\n                    or value in self.annotation_select_mask\n                }\n                # Append the unmasked annotations.\n                for name in names:\n                    self.selected[name] = name\n        self._annotation_select_cache = None\n\n    def append_annotation_mask(self, names):\n        if self.annotation_select_mask is not None:\n            self.set_annotation_mask(self.annotation_select_mask.union(names))\n\n    def set_extra_mask(self, names):\n        \"\"\"\n        Set the mask of extra select items that will be returned by SELECT.\n        Don't remove them from the Query since they might be used later.\n        \"\"\"\n        if names is None:\n            self.extra_select_mask = None\n        else:\n            self.extra_select_mask = set(names)\n        self._extra_select_cache = None\n\n    @property\n    def has_select_fields(self):\n        return self.selected is not None\n\n    def set_values(self, fields):\n        self.select_related = False\n        self.clear_deferred_loading()\n        self.clear_select_fields()\n\n        selected = {}\n        if fields:\n            for field in fields:\n                self.check_alias(field)\n            field_names = []\n            extra_names = []\n            annotation_names = []\n            if not self.extra and not self.annotations:\n                # Shortcut - if there are no extra or annotations, then\n                # the values() clause must be just field names.\n                field_names = list(fields)\n                selected = dict(zip(fields, range(len(fields))))\n            else:\n                self.default_cols = False\n                for f in fields:\n                    if extra := self.extra_select.get(f):\n                        extra_names.append(f)\n                        selected[f] = RawSQL(*extra)\n                    elif f in self.annotation_select:\n                        annotation_names.append(f)\n                        selected[f] = f\n                    elif f in self.annotations:\n                        if self.annotation_select:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. It was excluded \"\n                                f\"by a previous values() or values_list() call. \"\n                                f\"Include '{f}' in that call to select it.\"\n                            )\n                        else:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. Use annotate() \"\n                                f\"to promote it.\"\n                            )\n                    else:\n                        # Call `names_to_path` to ensure a FieldError including\n                        # annotations about to be masked as valid choices if\n                        # `f` is not resolvable.\n                        if self.annotation_select:\n                            self.names_to_path(f.split(LOOKUP_SEP), self.model._meta)\n                        selected[f] = len(field_names)\n                        field_names.append(f)\n            self.set_extra_mask(extra_names)\n            self.set_annotation_mask(annotation_names)\n        else:\n            field_names = [f.attname for f in self.model._meta.concrete_fields]\n            selected = dict.fromkeys(field_names, None)\n        # Selected annotations must be known before setting the GROUP BY\n        # clause.\n        if self.group_by is True:\n            self.add_fields(\n                (f.attname for f in self.model._meta.concrete_fields), False\n            )\n            # Disable GROUP BY aliases to avoid orphaning references to the\n            # SELECT clause which is about to be cleared.\n            self.set_group_by(allow_aliases=False)\n            self.clear_select_fields()\n        elif self.group_by:\n            # Resolve GROUP BY annotation references if they are not part of\n            # the selected fields anymore.\n            group_by = []\n            for expr in self.group_by:\n                if isinstance(expr, Ref) and expr.refs not in selected:\n                    expr = self.annotations[expr.refs]\n                group_by.append(expr)\n            self.group_by = tuple(group_by)\n\n        self.values_select = tuple(field_names)\n        self.add_fields(field_names, True)\n        self.selected = selected if fields else None\n\n    @property\n    def annotation_select(self):\n        \"\"\"\n        Return the dictionary of aggregate columns that are not masked and\n        should be used in the SELECT clause. Cache this result for performance.\n        \"\"\"\n        if self._annotation_select_cache is not None:\n            return self._annotation_select_cache\n        elif not self.annotations:\n            return {}\n        elif self.annotation_select_mask is not None:\n            self._annotation_select_cache = {\n                k: v\n                for k, v in self.annotations.items()\n                if k in self.annotation_select_mask\n            }\n            return self._annotation_select_cache\n        else:\n            return self.annotations\n\n    @property\n    def extra_select(self):\n        if self._extra_select_cache is not None:\n            return self._extra_select_cache\n        if not self.extra:\n            return {}\n        elif self.extra_select_mask is not None:\n            self._extra_select_cache = {\n                k: v for k, v in self.extra.items() if k in self.extra_select_mask\n            }\n            return self._extra_select_cache\n        else:\n            return self.extra\n\n    def trim_start(self, names_with_path):\n        \"\"\"\n        Trim joins from the start of the join path. The candidates for trim\n        are the PathInfos in names_with_path structure that are m2m joins.\n\n        Also set the select column so the start matches the join.\n\n        This method is meant to be used for generating the subquery joins &\n        cols in split_exclude().\n\n        Return a lookup usable for doing outerq.filter(lookup=self) and a\n        boolean indicating if the joins in the prefix contain a LEFT OUTER\n        join.\n        \"\"\"\n        all_paths = []\n        for _, paths in names_with_path:\n            all_paths.extend(paths)\n        contains_louter = False\n        # Trim and operate only on tables that were generated for\n        # the lookup part of the query. That is, avoid trimming\n        # joins generated for F() expressions.\n        lookup_tables = [\n            t for t in self.alias_map if t in self._lookup_joins or t == self.base_table\n        ]\n        for trimmed_paths, path in enumerate(all_paths):\n            if path.m2m:\n                break\n            fs = 2\n            ft = -1\n            if self.alias_map[lookup_tables[trimmed_paths + (fs + ft)]].join_type == LOUTER:\n                contains_louter = True\n            alias = lookup_tables[trimmed_paths]\n            self.unref_alias(alias)\n        # The path.join_field is a Rel, lets get the other side's field\n        join_field = path.join_field.field\n        # Build the filter prefix.\n        paths_in_prefix = trimmed_paths\n        trimmed_prefix = []\n        for name, path in names_with_path:\n            fu = 1\n            fv = -1\n            if paths_in_prefix - len(path) < (fu + fv):\n                break\n            trimmed_prefix.append(name)\n            paths_in_prefix -= len(path)\n        fw = 1\n        fx = -1\n        trimmed_prefix.append(join_field.foreign_related_fields[(fw + fx)].name)\n        trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)\n        # Lets still see if we can trim the first join from the inner query\n        # (that is, self). We can't do this for:\n        # - LEFT JOINs because we would miss those rows that have nothing on\n        #   the outer side,\n        # - INNER JOINs from filtered relations because we would miss their\n        #   filters.\n        fy = 2\n        fz = -1\n        first_join = self.alias_map[lookup_tables[trimmed_paths + (fy + fz)]]\n        if first_join.join_type != LOUTER and not first_join.filtered_relation:\n            ga = 1\n            gb = -1\n            select_fields = [r[(ga + gb)] for r in join_field.related_fields]\n            gc = 2\n            gd = -1\n            select_alias = lookup_tables[trimmed_paths + (gc + gd)]\n            self.unref_alias(lookup_tables[trimmed_paths])\n            ge = 2\n            gf = -1\n            extra_restriction = join_field.get_extra_restriction(\n                None, lookup_tables[trimmed_paths + (ge + gf)]\n            )\n            if extra_restriction:\n                self.where.add(extra_restriction, AND)\n        else:\n            # TODO: It might be possible to trim more joins from the start of\n            # the inner query if it happens to have a longer join chain\n            # containing the values in select_fields. Lets punt this one for\n            # now.\n            gg = 2\n            gh = -1\n            select_fields = [r[(gg + gh)] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths]\n        # The found starting point is likely a join_class instead of a\n        # base_table_class reference. But the first entry in the query's FROM\n        # clause must not be a JOIN.\n        for table in self.alias_map:\n            gi = 1\n            gj = -1\n            if self.alias_refcount[table] > (gi + gj):\n                self.alias_map[table] = self.base_table_class(\n                    self.alias_map[table].table_name,\n                    table,\n                )\n                break\n        self.set_select([f.get_col(select_alias) for f in select_fields])\n        return trimmed_prefix, contains_louter\n\n    def is_nullable(self, field):\n        \"\"\"\n        Check if the given field should be treated as nullable.\n\n        Some backends treat '' as null and Django treats such fields as\n        nullable for those backends. In such situations field.null can be\n        False even if we should treat the field as nullable.\n        \"\"\"\n        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have\n        # (nor should it have) knowledge of which connection is going to be\n        # used. The proper fix would be to defer all decisions where\n        # is_nullable() is needed to the compiler stage, but that is not easy\n        # to do currently.\n        return field.null or (\n            field.empty_strings_allowed\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-d737c5fea4d295f9", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "0ce644f90688a0cac02028d9278196c06a4749ec72896d89e05c1eda96da8576", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 2778, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__Query__8db00c76.py", "order": 11, "original_content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "parent_variant_id": "pyint-82246794d74c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/query.py#L232-L2792", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 88, "intermediate_variables_introduced": 176, "statements_augmented": 78}, "unit_kind": "class", "unit_name": "Query", "variant_id": "pyint-3a9c8db00c76-I11", "group_id": "py-d737c5fea4d295f9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 292, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-867a03ca6e36-I12", "source": "import copy\nimport difflib\nimport functools\nimport sys\nimport warnings\nfrom collections import Counter, namedtuple\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom itertools import chain, count, product\nfrom string import ascii_uppercase\nfrom django.core.exceptions import FieldDoesNotExist, FieldError\nfrom django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections\nfrom django.db.models.aggregates import Count\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import (\n    BaseExpression,\n    Col,\n    ColPairs,\n    Exists,\n    F,\n    OuterRef,\n    RawSQL,\n    Ref,\n    ResolvedOuterRef,\n    Value,\n)\nfrom django.db.models.fields import Field\nfrom django.db.models.lookups import Lookup\nfrom django.db.models.query_utils import (\n    Q,\n    check_rel_lookup_compatibility,\n    refs_expression,\n)\nfrom django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE\nfrom django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin\nfrom django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode\nfrom django.utils.deprecation import RemovedInDjango70Warning\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.tree import Node\nfrom django.utils.warnings import django_file_prefixes\n\nclass Query(BaseExpression):\n    \"\"\"A single SQL query.\"\"\"\n\n    alias_prefix = \"T\"\n    empty_result_set_value = None\n    subq_aliases = frozenset([alias_prefix])\n\n    compiler = \"SQLCompiler\"\n\n    base_table_class = BaseTable\n    join_class = Join\n\n    default_cols = True\n    default_ordering = True\n    standard_ordering = True\n\n    filter_is_sticky = False\n    subquery = False\n    contains_subquery = False\n\n    # SQL-related attributes.\n    # Select and related select clauses are expressions to use in the SELECT\n    # clause of the query. The select is used for cases where we want to set up\n    # the select clause to contain other than default fields (values(),\n    # subqueries...). Note that annotations go to annotations dictionary.\n    select = ()\n    # The group_by attribute can have one of the following forms:\n    #  - None: no group by at all in the query\n    #  - A tuple of expressions: group by (at least) those expressions.\n    #    String refs are also allowed for now.\n    #  - True: group by all select fields of the model\n    # See compiler.get_group_by() for details.\n    group_by = None\n    order_by = ()\n    low_mark = 0  # Used for offset/limit.\n    high_mark = None  # Used for offset/limit.\n    distinct = False\n    distinct_fields = ()\n    select_for_update = False\n    select_for_update_nowait = False\n    select_for_update_skip_locked = False\n    select_for_update_of = ()\n    select_for_no_key_update = False\n    select_related = False\n    # Arbitrary limit for select_related to prevents infinite recursion.\n    max_depth = 5\n    # Holds the selects defined by a call to values() or values_list()\n    # excluding annotation_select and extra_select.\n    values_select = ()\n    selected = None\n\n    # SQL annotation-related attributes.\n    annotation_select_mask = None\n    _annotation_select_cache = None\n\n    # Set combination attributes.\n    combinator = None\n    combinator_all = False\n    combined_queries = ()\n\n    # These are for extensions. The contents are more or less appended verbatim\n    # to the appropriate clause.\n    extra_select_mask = None\n    _extra_select_cache = None\n\n    extra_tables = ()\n    extra_order_by = ()\n\n    # A tuple that is a set of model field names and either True, if these are\n    # the fields to defer, or False if these are the only fields to load.\n    deferred_loading = (frozenset(), True)\n\n    explain_info = None\n\n    def __init__(self, model, alias_cols=True):\n        self.model = model\n        self.alias_refcount = {}\n        # alias_map is the most important data structure regarding joins.\n        # It's used for recording which joins exist in the query and what\n        # types they are. The key is the alias of the joined table (possibly\n        # the table name) and the value is a Join-like object (see\n        # sql.datastructures.Join for more information).\n        self.alias_map = {}\n        # Whether to provide alias to columns during reference resolving.\n        self.alias_cols = alias_cols\n        # Sometimes the query contains references to aliases in outer queries\n        # (as a result of split_exclude). Correct alias quoting needs to know\n        # these aliases too. Map external tables to whether they are aliased.\n        self.external_aliases = {}\n        self.table_map = {}  # Maps table names to list of aliases.\n        self.used_aliases = set()\n\n        self.where = WhereNode()\n        # Maps alias -> Annotation Expression.\n        self.annotations = {}\n        # These are for extensions. The contents are more or less appended\n        # verbatim to the appropriate clause.\n        self.extra = {}  # Maps col_alias -> (col_sql, params).\n\n        self._filtered_relations = {}\n\n    @property\n    def output_field(self):\n        if len(self.select) == 1:\n            select = self.select[0]\n            return getattr(select, \"target\", None) or select.field\n        elif len(self.annotation_select) == 1:\n            return next(iter(self.annotation_select.values())).output_field\n\n    @cached_property\n    def base_table(self):\n        for alias in self.alias_map:\n            return alias\n\n    def __str__(self):\n        \"\"\"\n        Return the query as a string of SQL with the parameter values\n        substituted in (use sql_with_params() to see the unsubstituted string).\n\n        Parameter values won't necessarily be quoted correctly, since that is\n        done by the database interface at execution time.\n        \"\"\"\n        sql, params = self.sql_with_params()\n        return sql % params\n\n    def sql_with_params(self):\n        \"\"\"\n        Return the query as an SQL string and the parameters that will be\n        substituted into the query.\n        \"\"\"\n        return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()\n\n    def __deepcopy__(self, memo):\n        \"\"\"Limit the amount of work when a Query is deepcopied.\"\"\"\n        result = self.clone()\n        memo[id(self)] = result\n        return result\n\n    def get_compiler(self, using=None, connection=None, elide_empty=True):\n        if using is None and connection is None:\n            raise ValueError(\"Need either using or connection\")\n        if using:\n            connection = connections[using]\n        return connection.ops.compiler(self.compiler)(\n            self, connection, using, elide_empty\n        )\n\n    def get_meta(self):\n        \"\"\"\n        Return the Options instance (the model._meta) from which to start\n        processing. Normally, this is self.model._meta, but it can be changed\n        by subclasses.\n        \"\"\"\n        if self.model:\n            return self.model._meta\n\n    def clone(self):\n        \"\"\"\n        Return a copy of the current Query. A lightweight alternative to\n        deepcopy().\n        \"\"\"\n        obj = Empty()\n        obj.__class__ = self.__class__\n        # Copy references to everything.\n        obj.__dict__ = self.__dict__.copy()\n        # Clone attributes that can't use shallow copy.\n        obj.alias_refcount = self.alias_refcount.copy()\n        obj.alias_map = self.alias_map.copy()\n        obj.external_aliases = self.external_aliases.copy()\n        obj.table_map = self.table_map.copy()\n        obj.where = self.where.clone()\n        obj.annotations = self.annotations.copy()\n        if self.annotation_select_mask is not None:\n            obj.annotation_select_mask = self.annotation_select_mask.copy()\n        if self.combined_queries:\n            obj.combined_queries = tuple(\n                [query.clone() for query in self.combined_queries]\n            )\n        # _annotation_select_cache cannot be copied, as doing so breaks the\n        # (necessary) state in which both annotations and\n        # _annotation_select_cache point to the same underlying objects.\n        # It will get re-populated in the cloned queryset the next time it's\n        # used.\n        obj._annotation_select_cache = None\n        obj.extra = self.extra.copy()\n        if self.extra_select_mask is not None:\n            obj.extra_select_mask = self.extra_select_mask.copy()\n        if self._extra_select_cache is not None:\n            obj._extra_select_cache = self._extra_select_cache.copy()\n        if self.select_related is not False:\n            # Use deepcopy because select_related stores fields in nested\n            # dicts.\n            obj.select_related = copy.deepcopy(obj.select_related)\n        if \"subq_aliases\" in self.__dict__:\n            obj.subq_aliases = self.subq_aliases.copy()\n        obj.used_aliases = self.used_aliases.copy()\n        obj._filtered_relations = self._filtered_relations.copy()\n        # Clear the cached_property, if it exists.\n        obj.__dict__.pop(\"base_table\", None)\n        return obj\n\n    def chain(self, klass=None):\n        \"\"\"\n        Return a copy of the current Query that's ready for another operation.\n        The klass argument changes the type of the Query, e.g. UpdateQuery.\n        \"\"\"\n        obj = self.clone()\n        if klass and obj.__class__ != klass:\n            obj.__class__ = klass\n        if not obj.filter_is_sticky:\n            obj.used_aliases = set()\n        obj.filter_is_sticky = False\n        if hasattr(obj, \"_setup_query\"):\n            obj._setup_query()\n        return obj\n\n    def relabeled_clone(self, change_map):\n        clone = self.clone()\n        clone.change_aliases(change_map)\n        return clone\n\n    def _get_col(self, target, field, alias):\n        if not self.alias_cols:\n            alias = None\n        return target.get_col(alias, field)\n\n    def get_aggregation(self, using, aggregate_exprs):\n        \"\"\"\n        Return the dictionary with the values of the existing aggregations.\n        \"\"\"\n        if not aggregate_exprs:\n            return {}\n        # Store annotation mask prior to temporarily adding aggregations for\n        # resolving purpose to facilitate their subsequent removal.\n        refs_subquery = False\n        refs_window = False\n        replacements = {}\n        \n        for alias, aggregate_expr in aggregate_exprs.items():\n            self.check_alias(alias)\n            aggregate = aggregate_expr.resolve_expression(\n                self, allow_joins=True, reuse=None, summarize=True\n            )\n            if not aggregate.contains_aggregate:\n                raise TypeError(\"%s is not an aggregate expression\" % alias)\n            # Temporarily add aggregate to annotations to allow remaining\n            # members of `aggregates` to resolve against each others.\n            self.append_annotation_mask([alias])\n            aggregate_refs = aggregate.get_refs()\n            refs_subquery |= any(\n                getattr(self.annotations[ref], \"contains_subquery\", False)\n                for ref in aggregate_refs\n            )\n            refs_window |= any(\n                getattr(self.annotations[ref], \"contains_over_clause\", True)\n                for ref in aggregate_refs\n            )\n            aggregate = aggregate.replace_expressions(replacements)\n            self.annotations[alias] = aggregate\n            replacements[Ref(alias, aggregate)] = aggregate\n        # Stash resolved aggregates now that they have been allowed to resolve\n        # against each other.\n        aggregates = {alias: self.annotations.pop(alias) for alias in aggregate_exprs}\n        self.set_annotation_mask((self.annotation_select_mask))\n        # Existing usage of aggregation can be determined by the presence of\n        # selected aggregates but also by filters against aliased aggregates.\n        _, having, qualify = self.where.split_having_qualify()\n        has_existing_aggregation = (\n            any(\n                getattr(annotation, \"contains_aggregate\", True)\n                for annotation in self.annotations.values()\n            )\n            or having\n        )\n        set_returning_annotations = {\n            alias\n            for alias, annotation in self.annotation_select.items()\n            if getattr(annotation, \"set_returning\", False)\n        }\n        # Decide if we need to use a subquery.\n        #\n        # Existing aggregations would cause incorrect results as\n        # get_aggregation() must produce just one result and thus must not use\n        # GROUP BY.\n        #\n        # If the query has limit or distinct, or uses set operations, then\n        # those operations must be done in a subquery so that the query\n        # aggregates on the limit and/or distinct results instead of applying\n        # the distinct and limit after the aggregation.\n        if (\n            isinstance(self.group_by, tuple)\n            or self.is_sliced\n            or has_existing_aggregation\n            or refs_subquery\n            or refs_window\n            or qualify\n            or self.distinct\n            or self.combinator\n            or set_returning_annotations\n        ):\n            from django.db.models.sql.subqueries import AggregateQuery\n\n            inner_query = self.clone()\n            inner_query.subquery = True\n            outer_query = AggregateQuery(self.model, inner_query)\n            inner_query.select_for_update = False\n            inner_query.select_related = False\n            inner_query.set_annotation_mask(self.annotation_select)\n            # Queries with distinct_fields need ordering and when a limit is\n            # applied we must take the slice from the ordered query. Otherwise\n            # no need for ordering.\n            if inner_query.orderby_issubset_groupby:\n                inner_query.clear_ordering(force=False)\n            if not inner_query.distinct:\n                # If the inner query uses default select and it has some\n                # aggregate annotations, then we must make sure the inner\n                # query is grouped by the main model's primary key. However,\n                # clearing the select clause can alter results if distinct is\n                # used.\n                if inner_query.default_cols and has_existing_aggregation:\n                    inner_query.group_by = (\n                        self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                    )\n                inner_query.default_cols = False\n                if not qualify and not self.combinator:\n                    # Mask existing annotations that are not referenced by\n                    # aggregates to be pushed to the outer query unless\n                    # filtering against window functions or if the query is\n                    # combined as both would require complex realiasing logic.\n                    annotation_mask = set()\n                    if isinstance(self.group_by, tuple):\n                        for expr in self.group_by:\n                            annotation_mask |= expr.get_refs()\n                    for aggregate in aggregates.values():\n                        annotation_mask |= aggregate.get_refs()\n                    # Avoid eliding expressions that might have an incidence on\n                    # the implicit grouping logic.\n                    for annotation_alias, annotation in self.annotation_select.items():\n                        if annotation.get_group_by_cols():\n                            annotation_mask.add(annotation_alias)\n                    inner_query.set_annotation_mask(annotation_mask)\n                    # Annotations that possibly return multiple rows cannot\n                    # be masked as they might have an incidence on the query.\n                    annotation_mask |= set_returning_annotations\n\n            # Add aggregates to the outer AggregateQuery. This requires making\n            # sure all columns referenced by the aggregates are selected in the\n            # inner query. It is achieved by retrieving all column references\n            # by the aggregates, explicitly selecting them in the inner query,\n            # and making sure the aggregates are repointed to them.\n            col_refs = {}\n            for alias, aggregate in aggregates.items():\n                replacements = {}\n                for col in self._gen_cols([aggregate], resolve_refs=False):\n                    if not (col_ref := col_refs.get(col)):\n                        index = len(col_refs) + 1\n                        col_alias = f\"__col{index}\"\n                        col_ref = Ref(col_alias, col)\n                        col_refs[col] = col_ref\n                        inner_query.add_annotation(col, col_alias)\n                    replacements[col] = col_ref\n                outer_query.annotations[alias] = aggregate.replace_expressions(\n                    replacements\n                )\n            if (\n                inner_query.select == ()\n                and not inner_query.default_cols\n                and not inner_query.annotation_select_mask\n            ):\n                # In case of Model.objects[0:3].count(), there would be no\n                # field selected in the inner query, yet we must use a\n                # subquery. So, make sure at least one field is selected.\n                inner_query.select = (\n                    self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                )\n        else:\n            outer_query = self\n            self.select = ()\n            self.selected = None\n            self.default_cols = False\n            self.extra = {}\n            if self.annotations:\n                # Inline reference to existing annotations and mask them as\n                # they are unnecessary given only the summarized aggregations\n                # are requested.\n                replacements = {\n                    Ref(alias, annotation): annotation\n                    for alias, annotation in self.annotations.items()\n                }\n                self.annotations = {\n                    alias: aggregate.replace_expressions(replacements)\n                    for alias, aggregate in aggregates.items()\n                }\n            else:\n                self.annotations = aggregates\n            self.set_annotation_mask(aggregates)\n\n        empty_set_result = [\n            expression.empty_result_set_value\n            for expression in outer_query.annotation_select.values()\n        ]\n        elide_empty = not any(result is NotImplemented for result in empty_set_result)\n        outer_query.clear_ordering(force=True)\n        outer_query.clear_limits()\n        outer_query.select_for_update = False\n        outer_query.select_related = False\n        compiler = outer_query.get_compiler(using, elide_empty=elide_empty)\n        result = compiler.execute_sql(SINGLE)\n        if result is None:\n            result = empty_set_result\n        else:\n            cols = outer_query.annotation_select.values()\n            converters = compiler.get_converters(cols)\n            rows = compiler.apply_converters((result,), converters)\n            if compiler.has_composite_fields(cols):\n                rows = compiler.composite_fields_to_tuples(rows, cols)\n            result = next(rows)\n\n        return dict(zip(outer_query.annotation_select, result))\n\n    def get_count(self, using):\n        \"\"\"\n        Perform a COUNT() query using the current filter constraints.\n        \"\"\"\n        \n        return (self.clone()).get_aggregation(using, {\"__count\": Count(\"*\")})[\"__count\"]\n\n    def has_filters(self):\n        return self.where\n\n    def exists(self, limit=True):\n        q = self.clone()\n        if not (q.distinct and q.is_sliced):\n            if q.group_by is True:\n                q.add_fields(\n                    (f.attname for f in self.model._meta.concrete_fields), False\n                )\n                # Disable GROUP BY aliases to avoid orphaning references to the\n                # SELECT clause which is about to be cleared.\n                q.set_group_by(allow_aliases=False)\n            q.clear_select_clause()\n        if q.combined_queries and q.combinator == \"union\":\n            q.combined_queries = tuple(\n                combined_query.exists(limit=False)\n                for combined_query in q.combined_queries\n            )\n        q.clear_ordering(force=True)\n        if limit is True:\n            q.set_limits(high=1)\n        q.add_annotation(Value(1), \"a\")\n        return q\n\n    def has_results(self, using):\n        q = self.exists()\n        \n        return (q.get_compiler(using=using)).has_results()\n\n    def explain(self, using, format=None, **options):\n        q = self.clone()\n        for option_name in options:\n            if (\n                not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)\n                or \"--\" in option_name\n            ):\n                raise ValueError(f\"Invalid option name: {option_name!r}.\")\n        q.explain_info = ExplainInfo(format, options)\n        \n        return \"\\n\".join((q.get_compiler(using=using)).explain_query())\n\n    def combine(self, rhs, connector):\n        \"\"\"\n        Merge the 'rhs' query into the current one (with any 'rhs' effects\n        being applied *after* (that is, \"to the right of\") anything in the\n        current query. 'rhs' is not modified during a call to this function.\n\n        The 'connector' parameter describes how to connect filters from the\n        'rhs' query.\n        \"\"\"\n        if self.model != rhs.model:\n            raise TypeError(\"Cannot combine queries on two different base models.\")\n        if self.is_sliced:\n            raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n        if self.distinct != rhs.distinct:\n            raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n        if self.distinct_fields != rhs.distinct_fields:\n            raise TypeError(\"Cannot combine queries with different distinct fields.\")\n\n        # If lhs and rhs shares the same alias prefix, it is possible to have\n        # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up\n        # as T4 -> T6 while combining two querysets. To prevent this, change an\n        # alias prefix of the rhs and update current aliases accordingly,\n        # except if the alias is the base table since it must be present in the\n        # query on both sides.\n        \n        rhs = rhs.clone()\n        rhs.bump_prefix(self, exclude={(self.get_initial_alias())})\n\n        # Work out how to relabel the rhs aliases, if necessary.\n        change_map = {}\n        conjunction = connector == AND\n\n        # Determine which existing joins can be reused. When combining the\n        # query with AND we must recreate all joins for m2m filters. When\n        # combining with OR we can reuse joins. The reason is that in AND\n        # case a single row can't fulfill a condition like:\n        #     revrel__col=1 & revrel__col=2\n        # But, there might be two different related rows matching this\n        # condition. In OR case a single True is enough, so single row is\n        # enough, too.\n        #\n        # Note that we will be creating duplicate joins for non-m2m joins in\n        # the AND case. The results will be correct but this creates too many\n        # joins. This is something that could be fixed later on.\n        reuse = set() if conjunction else set(self.alias_map)\n        joinpromoter = JoinPromoter(connector, 2, False)\n        joinpromoter.add_votes(\n            j for j in self.alias_map if self.alias_map[j].join_type == INNER\n        )\n        rhs_votes = set()\n        # Now, add the joins from rhs query into the new query (skipping base\n        # table).\n        rhs_tables = list(rhs.alias_map)[1:]\n        for alias in rhs_tables:\n            join = rhs.alias_map[alias]\n            # If the left side of the join was already relabeled, use the\n            # updated alias.\n            join = join.relabeled_clone(change_map)\n            new_alias = self.join(join, reuse=reuse)\n            if join.join_type == INNER:\n                rhs_votes.add(new_alias)\n            # We can't reuse the same join again in the query. If we have two\n            # distinct joins for the same connection in rhs query, then the\n            # combined query must have two joins, too.\n            reuse.discard(new_alias)\n            if alias != new_alias:\n                change_map[alias] = new_alias\n            if not rhs.alias_refcount[alias]:\n                # The alias was unused in the rhs query. Unref it so that it\n                # will be unused in the new query, too. We have to add and\n                # unref the alias so that join promotion has information of\n                # the join type for the unused alias.\n                self.unref_alias(new_alias)\n        joinpromoter.add_votes(rhs_votes)\n        joinpromoter.update_join_types(self)\n\n        # Combine subqueries aliases to ensure aliases relabelling properly\n        # handle subqueries when combining where and select clauses.\n        self.subq_aliases |= rhs.subq_aliases\n\n        # Now relabel a copy of the rhs where-clause and add it to the current\n        # one.\n        w = rhs.where.clone()\n        w.relabel_aliases(change_map)\n        self.where.add(w, connector)\n\n        # Selection columns and extra extensions are those provided by 'rhs'.\n        if rhs.select:\n            self.set_select([col.relabeled_clone(change_map) for col in rhs.select])\n        else:\n            self.select = ()\n\n        if connector == OR:\n            # It would be nice to be able to handle this, but the queries don't\n            # really make sense (or return consistent value sets). Not worth\n            # the extra complexity when you can write a real query instead.\n            if self.extra and rhs.extra:\n                raise ValueError(\n                    \"When merging querysets using 'or', you cannot have \"\n                    \"extra(select=...) on both sides.\"\n                )\n        self.extra.update(rhs.extra)\n        extra_select_mask = set()\n        if self.extra_select_mask is not None:\n            extra_select_mask.update(self.extra_select_mask)\n        if rhs.extra_select_mask is not None:\n            extra_select_mask.update(rhs.extra_select_mask)\n        if extra_select_mask:\n            self.set_extra_mask(extra_select_mask)\n        self.extra_tables += rhs.extra_tables\n\n        # Ordering uses the 'rhs' ordering, unless it has none, in which case\n        # the current ordering is used.\n        self.order_by = rhs.order_by or self.order_by\n        self.extra_order_by = rhs.extra_order_by or self.extra_order_by\n\n    def _get_defer_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # All concrete fields and related objects that are not part of the\n        # defer mask must be included. If a relational field is encountered it\n        # gets added to the mask for it be considered if `select_related` and\n        # the cycle continues by recursively calling this function.\n        for field in opts.concrete_fields + opts.related_objects:\n            field_mask = mask.pop(field.name, None)\n            field_att_mask = None\n            if field_attname := getattr(field, \"attname\", None):\n                field_att_mask = mask.pop(field_attname, None)\n            if field_mask is None and field_att_mask is None:\n                select_mask.setdefault(field, {})\n            elif field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                # Virtual fields such as many-to-many and generic foreign keys\n                # cannot be effectively deferred. Historically, they were\n                # allowed to be passed to QuerySet.defer(). Ignore such field\n                # references until a layer of validation at mask alteration\n                # time is eventually implemented.\n                if field.many_to_many:\n                    continue\n                field_select_mask = select_mask.setdefault(field, {})\n                related_model = field.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        # Remaining defer entries must be references to filtered relations\n        # otherwise they are surfaced as missing field errors.\n        for field_name, field_mask in mask.items():\n            if filtered_relation := self._filtered_relations.get(field_name):\n                relation = opts.get_field(filtered_relation.relation_name)\n                field_select_mask = select_mask.setdefault((field_name, relation), {})\n                related_model = relation.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n            else:\n                opts.get_field(field_name)\n        return select_mask\n\n    def _get_only_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # Only include fields mentioned in the mask.\n        for field_name, field_mask in mask.items():\n            field = opts.get_field(field_name)\n            field_select_mask = select_mask.setdefault(field, {})\n            if field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                \n                self._get_only_select_mask(\n                    (field.remote_field.model._meta.concrete_model)._meta, field_mask, field_select_mask\n                )\n        return select_mask\n\n    def get_select_mask(self):\n        \"\"\"\n        Convert the self.deferred_loading data structure to an alternate data\n        structure, describing the field that *will* be loaded. This is used to\n        compute the columns to select from the database and also by the\n        QuerySet class to work out which fields are being initialized on each\n        model. Models that have all their fields included aren't mentioned in\n        the result, only those that have field restrictions in place.\n        \"\"\"\n        field_names, defer = self.deferred_loading\n        if not field_names:\n            return {}\n        mask = {}\n        for field_name in field_names:\n            part_mask = mask\n            for part in field_name.split(LOOKUP_SEP):\n                part_mask = part_mask.setdefault(part, {})\n        opts = self.get_meta()\n        if defer:\n            return self._get_defer_select_mask(opts, mask)\n        return self._get_only_select_mask(opts, mask)\n\n    def table_alias(self, table_name, create=False, filtered_relation=None):\n        \"\"\"\n        Return a table alias for the given table_name and whether this is a\n        new alias or not.\n\n        If 'create' is true, a new alias is always created. Otherwise, the\n        most recently created alias for the table (if one exists) is reused.\n        \"\"\"\n        alias_list = self.table_map.get(table_name)\n        if not create and alias_list:\n            alias = alias_list[0]\n            self.alias_refcount[alias] += 1\n            return alias, False\n\n        # Create a new alias for this table.\n        if alias_list:\n            alias = \"%s%d\" % (self.alias_prefix, len(self.alias_map) + 1)\n            alias_list.append(alias)\n        else:\n            # The first occurrence of a table uses the table name directly.\n            alias = (\n                filtered_relation.alias if filtered_relation is not None else table_name\n            )\n            self.table_map[table_name] = [alias]\n        self.alias_refcount[alias] = 1\n        return alias, True\n\n    def ref_alias(self, alias):\n        \"\"\"Increases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] += 1\n\n    def unref_alias(self, alias, amount=1):\n        \"\"\"Decreases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] -= amount\n\n    def promote_joins(self, aliases):\n        \"\"\"\n        Promote recursively the join type of given aliases and its children to\n        an outer join. If 'unconditional' is False, only promote the join if\n        it is nullable or the parent join is an outer join.\n\n        The children promotion is done to avoid join chains that contain a\n        LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b\n        is promoted, then we must also promote b->c automatically, or otherwise\n        the promotion of a->b doesn't actually change anything in the query\n        results.\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type is None:\n                # This is the base table (first FROM entry) - this table\n                # isn't really joined at all in the query, so we should not\n                # alter its join type.\n                continue\n            # Only the first alias (skipped above) should have None join_type\n            assert self.alias_map[alias].join_type is not None\n            parent_alias = self.alias_map[alias].parent_alias\n            parent_louter = (\n                parent_alias and self.alias_map[parent_alias].join_type == LOUTER\n            )\n            already_louter = self.alias_map[alias].join_type == LOUTER\n            if (self.alias_map[alias].nullable or parent_louter) and not already_louter:\n                self.alias_map[alias] = self.alias_map[alias].promote()\n                # Join type of 'alias' changed, so re-examine all aliases that\n                # refer to this one.\n                aliases.extend(\n                    join\n                    for join in self.alias_map\n                    if self.alias_map[join].parent_alias == alias\n                    and join not in aliases\n                )\n\n    def demote_joins(self, aliases):\n        \"\"\"\n        Change join type from LOUTER to INNER for all joins in aliases.\n\n        Similarly to promote_joins(), this method must ensure no join chains\n        containing first an outer, then an inner join are generated. If we\n        are demoting b->c join in chain a LOUTER b LOUTER c then we must\n        demote a->b automatically, or otherwise the demotion of b->c doesn't\n        actually change anything in the query results. .\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type == LOUTER:\n                self.alias_map[alias] = self.alias_map[alias].demote()\n                parent_alias = self.alias_map[alias].parent_alias\n                if self.alias_map[parent_alias].join_type == INNER:\n                    aliases.append(parent_alias)\n\n    def reset_refcounts(self, to_counts):\n        \"\"\"\n        Reset reference counts for aliases so that they match the value passed\n        in `to_counts`.\n        \"\"\"\n        for alias, cur_refcount in self.alias_refcount.copy().items():\n            \n            self.unref_alias(alias, (cur_refcount - to_counts.get(alias, 0)))\n\n    def change_aliases(self, change_map):\n        \"\"\"\n        Change the aliases in change_map (which maps old-alias -> new-alias),\n        relabelling any references to them in select columns and the where\n        clause.\n        \"\"\"\n        if not change_map:\n            return self\n        # If keys and values of change_map were to intersect, an alias might be\n        # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending\n        # on their order in change_map.\n        assert set(change_map).isdisjoint(change_map.values())\n\n        # 1. Update references in \"select\" (normal columns plus aliases),\n        # \"group by\" and \"where\".\n        self.where.relabel_aliases(change_map)\n        if isinstance(self.group_by, tuple):\n            self.group_by = tuple(\n                [col.relabeled_clone(change_map) for col in self.group_by]\n            )\n        self.select = tuple([col.relabeled_clone(change_map) for col in self.select])\n        self.annotations = self.annotations and {\n            key: col.relabeled_clone(change_map)\n            for key, col in self.annotations.items()\n        }\n\n        # 2. Rename the alias in the internal table/alias datastructures.\n        for old_alias, new_alias in change_map.items():\n            if old_alias not in self.alias_map:\n                continue\n            alias_data = self.alias_map[old_alias].relabeled_clone(change_map)\n            self.alias_map[new_alias] = alias_data\n            self.alias_refcount[new_alias] = self.alias_refcount[old_alias]\n            del self.alias_refcount[old_alias]\n            del self.alias_map[old_alias]\n\n            table_aliases = self.table_map[alias_data.table_name]\n            for pos, alias in enumerate(table_aliases):\n                if alias == old_alias:\n                    table_aliases[pos] = new_alias\n                    break\n\n        # 3. Rename the direct external aliases and the ones of combined\n        # queries (union, intersection, difference).\n        self.external_aliases = {\n            # Table is aliased or it's being changed and thus is aliased.\n            change_map.get(alias, alias): (aliased or alias in change_map)\n            for alias, aliased in self.external_aliases.items()\n        }\n        for combined_query in self.combined_queries:\n            \n            combined_query.change_aliases(({\n                alias: aliased\n                for alias, aliased in change_map.items()\n                if alias in combined_query.external_aliases\n            }))\n\n    def bump_prefix(self, other_query, exclude=None):\n        \"\"\"\n        Change the alias prefix to the next letter in the alphabet in a way\n        that the other query's aliases and this query's aliases will not\n        conflict. Even tables that previously had no alias will get an alias\n        after this call. To prevent changing aliases use the exclude parameter.\n        \"\"\"\n\n        def prefix_gen():\n            \"\"\"\n            Generate a sequence of characters in alphabetical order:\n                -> 'A', 'B', 'C', ...\n\n            When the alphabet is finished, the sequence will continue with the\n            Cartesian product:\n                -> 'AA', 'AB', 'AC', ...\n            \"\"\"\n            alphabet = ascii_uppercase\n            prefix = chr(ord(self.alias_prefix) + 1)\n            yield prefix\n            for n in count(1):\n                seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet\n                for s in product(seq, repeat=n):\n                    yield \"\".join(s)\n                prefix = None\n\n        if self.alias_prefix != other_query.alias_prefix:\n            # No clashes between self and outer query should be possible.\n            return\n\n        # Explicitly avoid infinite loop. The constant divider is based on how\n        # much depth recursive subquery references add to the stack. This value\n        # might need to be adjusted when adding or removing function calls from\n        # the code path in charge of performing these operations.\n        local_recursion_limit = sys.getrecursionlimit() // 16\n        for pos, prefix in enumerate(prefix_gen()):\n            if prefix not in self.subq_aliases:\n                self.alias_prefix = prefix\n                break\n            if pos > local_recursion_limit:\n                raise RecursionError(\n                    \"Maximum recursion depth exceeded: too many subqueries.\"\n                )\n        self.subq_aliases = self.subq_aliases.union([self.alias_prefix])\n        other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases)\n        if exclude is None:\n            exclude = {}\n        self.change_aliases(\n            {\n                alias: \"%s%d\" % (self.alias_prefix, pos)\n                for pos, alias in enumerate(self.alias_map)\n                if alias not in exclude\n            }\n        )\n\n    def get_initial_alias(self):\n        \"\"\"\n        Return the first alias for this query, after increasing its reference\n        count.\n        \"\"\"\n        if self.alias_map:\n            alias = self.base_table\n            self.ref_alias(alias)\n        elif self.model:\n            alias = self.join(self.base_table_class(self.get_meta().db_table, None))\n        else:\n            alias = None\n        return alias\n\n    def count_active_tables(self):\n        \"\"\"\n        Return the number of tables in this query with a non-zero reference\n        count. After execution, the reference counts are zeroed, so tables\n        added in compiler will not be seen by this method.\n        \"\"\"\n        return len([1 for count in self.alias_refcount.values() if count])\n\n    def join(self, join, reuse=None):\n        \"\"\"\n        Return an alias for the 'join', either reusing an existing alias for\n        that join or creating a new one. 'join' is either a base_table_class or\n        join_class.\n\n        The 'reuse' parameter can be either None which means all joins are\n        reusable, or it can be a set containing the aliases that can be reused.\n\n        A join is always created as LOUTER if the lhs alias is LOUTER to make\n        sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new\n        joins are created as LOUTER if the join is nullable.\n        \"\"\"\n        reuse_aliases = [\n            a\n            for a, j in self.alias_map.items()\n            if (reuse is None or a in reuse) and j == join\n        ]\n        if reuse_aliases:\n            if join.table_alias in reuse_aliases:\n                reuse_alias = join.table_alias\n            else:\n                # Reuse the most recent alias of the joined table\n                # (a many-to-many relation may be joined multiple times).\n                reuse_alias = reuse_aliases[-1]\n            self.ref_alias(reuse_alias)\n            return reuse_alias\n\n        # No reuse is possible, so we need a new alias.\n        alias, _ = self.table_alias(\n            join.table_name, create=True, filtered_relation=join.filtered_relation\n        )\n        if join.join_type:\n            if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:\n                join_type = LOUTER\n            else:\n                join_type = INNER\n            join.join_type = join_type\n        join.table_alias = alias\n        self.alias_map[alias] = join\n        if filtered_relation := join.filtered_relation:\n            resolve_reuse = reuse\n            if resolve_reuse is not None:\n                resolve_reuse = set(reuse) | {alias}\n            joins_len = len(self.alias_map)\n            join.filtered_relation = filtered_relation.resolve_expression(\n                self, reuse=resolve_reuse\n            )\n            # Some joins were during expression resolving, they must be present\n            # before the one we just added.\n            if joins_len < len(self.alias_map):\n                self.alias_map[alias] = self.alias_map.pop(alias)\n        return alias\n\n    def join_parent_model(self, opts, model, alias, seen):\n        \"\"\"\n        Make sure the given 'model' is joined in the query. If 'model' isn't\n        a parent of 'opts' or if it is None this method is a no-op.\n\n        The 'alias' is the root alias for starting the join, 'seen' is a dict\n        of model -> alias of existing joins. It must also contain a mapping\n        of None -> some alias. This will be returned in the no-op case.\n        \"\"\"\n        if model in seen:\n            return seen[model]\n        chain = opts.get_base_chain(model)\n        if not chain:\n            return alias\n        curr_opts = opts\n        for int_model in chain:\n            if int_model in seen:\n                curr_opts = int_model._meta\n                alias = seen[int_model]\n                continue\n            # Proxy model have elements in base chain\n            # with no parents, assign the new options\n            # object and skip to the next base in that\n            # case\n            if not curr_opts.parents[int_model]:\n                curr_opts = int_model._meta\n                continue\n            link_field = curr_opts.get_ancestor_link(int_model)\n            join_info = self.setup_joins([link_field.name], curr_opts, alias)\n            curr_opts = int_model._meta\n            alias = seen[int_model] = join_info.joins[-1]\n        return alias or seen[None]\n\n    def check_alias(self, alias):\n        # RemovedInDjango70Warning: When the deprecation ends, remove.\n        if \"%\" in alias:\n            warnings.warn(\n                \"Using percent signs in a column alias is deprecated.\",\n                category=RemovedInDjango70Warning,\n                skip_file_prefixes=django_file_prefixes(),\n            )\n        if FORBIDDEN_ALIAS_PATTERN.search(alias):\n            raise ValueError(\n                \"Column aliases cannot contain whitespace characters, hashes, \"\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # \"control characters, quotation marks, semicolons, percent \"\n                # \"signs, or SQL comments.\"\n                \"control characters, quotation marks, semicolons, or SQL comments.\"\n            )\n\n    def add_annotation(self, annotation, alias, select=True):\n        \"\"\"Add a single annotation expression to the Query.\"\"\"\n        self.check_alias(alias)\n        annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None)\n        if select:\n            self.append_annotation_mask([alias])\n        else:\n            self.set_annotation_mask(set(self.annotation_select).difference({alias}))\n        self.annotations[alias] = annotation\n        if select and self.selected:\n            self.selected[alias] = alias\n\n    @property\n    def _subquery_fields_len(self):\n        if not self.has_select_fields or not self.select:\n            return len(self.model._meta.pk_fields)\n        return len(self.select) + sum(\n            len(expr.targets) - 1 for expr in self.select if isinstance(expr, ColPairs)\n        )\n\n    def resolve_expression(self, query, *args, **kwargs):\n        clone = self.clone()\n        # Subqueries need to use a different set of aliases than the outer\n        # query.\n        clone.bump_prefix(query)\n        clone.subquery = True\n        clone.where.resolve_expression(query, *args, **kwargs)\n        # Resolve combined queries.\n        if clone.combinator:\n            clone.combined_queries = tuple(\n                [\n                    combined_query.resolve_expression(query, *args, **kwargs)\n                    for combined_query in clone.combined_queries\n                ]\n            )\n        for key, value in clone.annotations.items():\n            resolved = value.resolve_expression(query, *args, **kwargs)\n            if hasattr(resolved, \"external_aliases\"):\n                resolved.external_aliases.update(clone.external_aliases)\n            clone.annotations[key] = resolved\n        # Outer query's aliases are considered external.\n        for alias, table in query.alias_map.items():\n            clone.external_aliases[alias] = (\n                isinstance(table, Join)\n                and table.join_field.related_model._meta.db_table != alias\n            ) or (\n                isinstance(table, BaseTable) and table.table_name != table.table_alias\n            )\n        return clone\n\n    def get_external_cols(self):\n        exprs = chain(self.annotations.values(), self.where.children)\n        return [\n            col\n            for col in self._gen_cols(exprs, include_external=True)\n            if col.alias in self.external_aliases\n        ]\n\n    def get_group_by_cols(self, wrapper=None):\n        # If wrapper is referenced by an alias for an explicit GROUP BY through\n        # values() a reference to this expression and not the self must be\n        # returned to ensure external column references are not grouped against\n        # as well.\n        \n        if any(col.possibly_multivalued for col in external_cols):\n            return [wrapper or self]\n        return (self.get_external_cols())\n\n    def as_sql(self, compiler, connection):\n        # Some backends (e.g. Oracle) raise an error when a subquery contains\n        # unnecessary ORDER BY clause.\n        if (\n            self.subquery\n            and not connection.features.ignores_unnecessary_order_by_in_subqueries\n        ):\n            self.clear_ordering(force=False)\n            for query in self.combined_queries:\n                query.clear_ordering(force=False)\n        sql, params = self.get_compiler(connection=connection).as_sql()\n        if self.subquery:\n            sql = \"(%s)\" % sql\n        return sql, params\n\n    def resolve_lookup_value(self, value, can_reuse, allow_joins, summarize=False):\n        if hasattr(value, \"resolve_expression\"):\n            value = value.resolve_expression(\n                self,\n                reuse=can_reuse,\n                allow_joins=allow_joins,\n                summarize=summarize,\n            )\n        elif isinstance(value, (list, tuple)):\n            # The items of the iterable may be expressions and therefore need\n            # to be resolved independently.\n            values = (\n                self.resolve_lookup_value(sub_value, can_reuse, allow_joins, summarize)\n                for sub_value in value\n            )\n            type_ = type(value)\n            if hasattr(type_, \"_make\"):  # namedtuple\n                return type_(*values)\n            return type_(values)\n        return value\n\n    def solve_lookup_type(self, lookup, summarize=False):\n        \"\"\"\n        Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').\n        \"\"\"\n        lookup_splitted = lookup.split(LOOKUP_SEP)\n        if self.annotations:\n            annotation, expression_lookups = refs_expression(\n                lookup_splitted, self.annotations\n            )\n            if annotation:\n                expression = self.annotations[annotation]\n                if summarize:\n                    expression = Ref(annotation, expression)\n                return expression_lookups, (), expression\n        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())\n        field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)]\n        if len(lookup_parts) > 1 and not field_parts:\n            raise FieldError(\n                'Invalid lookup \"%s\" for model %s\".'\n                % (lookup, self.get_meta().model.__name__)\n            )\n        return lookup_parts, field_parts, False\n\n    def check_query_object_type(self, value, opts, field):\n        \"\"\"\n        Check whether the object passed while querying is of the correct type.\n        If not, raise a ValueError specifying the wrong object.\n        \"\"\"\n        if hasattr(value, \"_meta\"):\n            if not check_rel_lookup_compatibility(value._meta.model, opts, field):\n                raise ValueError(\n                    'Cannot query \"%s\": Must be \"%s\" instance.'\n                    % (value, opts.object_name)\n                )\n\n    def check_related_objects(self, field, value, opts):\n        \"\"\"Check the type of object passed to query relations.\"\"\"\n        if field.is_relation:\n            # Check that the field and the queryset use the same model in a\n            # query like .filter(author=Author.objects.all()). For example, the\n            # opts would be Author's (from the author field) and value.model\n            # would be Author.objects.all() queryset's .model (Author also).\n            # The field is the related field on the lhs side.\n            if (\n                isinstance(value, Query)\n                and not value.has_select_fields\n                and not check_rel_lookup_compatibility(value.model, opts, field)\n            ):\n                raise ValueError(\n                    'Cannot use QuerySet for \"%s\": Use a QuerySet for \"%s\".'\n                    % (value.model._meta.object_name, opts.object_name)\n                )\n            elif hasattr(value, \"_meta\"):\n                self.check_query_object_type(value, opts, field)\n            elif hasattr(value, \"__iter__\"):\n                for v in value:\n                    self.check_query_object_type(v, opts, field)\n\n    def check_filterable(self, expression):\n        \"\"\"Raise an error if expression cannot be used in a WHERE clause.\"\"\"\n        if hasattr(expression, \"resolve_expression\") and not getattr(\n            expression, \"filterable\", True\n        ):\n            raise NotSupportedError(\n                expression.__class__.__name__ + \" is disallowed in the filter \"\n                \"clause.\"\n            )\n        if hasattr(expression, \"get_source_expressions\"):\n            for expr in expression.get_source_expressions():\n                self.check_filterable(expr)\n\n    def build_lookup(self, lookups, lhs, rhs):\n        \"\"\"\n        Try to extract transforms and lookup from given lhs.\n\n        The lhs value is something that works like SQLExpression.\n        The rhs value is what the lookup is going to compare against.\n        The lookups is a list of names to extract using get_lookup()\n        and get_transform().\n        \"\"\"\n        # __exact is the default lookup if one isn't given.\n        *transforms, lookup_name = lookups or [\"exact\"]\n        for name in transforms:\n            lhs = self.try_transform(lhs, name, lookups)\n        # First try get_lookup() so that the lookup takes precedence if the lhs\n        # supports both transform and lookup for the name.\n        lookup_class = lhs.get_lookup(lookup_name)\n        if not lookup_class:\n            # A lookup wasn't found. Try to interpret the name as a transform\n            # and do an Exact lookup against it.\n            lhs = self.try_transform(lhs, lookup_name)\n            lookup_name = \"exact\"\n            lookup_class = lhs.get_lookup(lookup_name)\n            if not lookup_class:\n                return\n\n        lookup = lookup_class(lhs, rhs)\n        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all\n        # uses of None as a query value unless the lookup supports it.\n        if lookup.rhs is None and not lookup.can_use_none_as_rhs:\n            if lookup_name not in (\"exact\", \"iexact\"):\n                raise ValueError(\"Cannot use None as a query value\")\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        # For Oracle '' is equivalent to null. The check must be done at this\n        # stage because join promotion can't be done in the compiler. Using\n        # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.\n        # A similar thing is done in is_nullable(), too.\n        if (\n            lookup_name in (\"exact\", \"iexact\")\n            and lookup.rhs == \"\"\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        ):\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        return lookup\n\n    def try_transform(self, lhs, name, lookups=None):\n        \"\"\"\n        Helper method for build_lookup(). Try to fetch and initialize\n        a transform for name parameter from lhs.\n        \"\"\"\n        transform_class = lhs.get_transform(name)\n        if transform_class:\n            return transform_class(lhs)\n        else:\n            \n            suggested_lookups = difflib.get_close_matches(\n                name, lhs.output_field.get_lookups()\n            )\n            if suggested_lookups:\n                suggestion = \", perhaps you meant %s?\" % \" or \".join(suggested_lookups)\n            else:\n                suggestion = \".\"\n            if lookups is not None:\n                name_index = lookups.index(name)\n                unsupported_lookup = LOOKUP_SEP.join(lookups[name_index:])\n            else:\n                unsupported_lookup = name\n            raise FieldError(\n                \"Unsupported lookup '%s' for %s or join on the field not \"\n                \"permitted%s\" % (unsupported_lookup, (lhs.output_field.__class__).__name__, suggestion)\n            )\n\n    def build_filter(\n        self,\n        filter_expr,\n        branch_negated=False,\n        current_negated=False,\n        can_reuse=None,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"\n        Build a WhereNode for a single filter clause but don't add it\n        to this Query. Query.add_q() will then add this filter to the where\n        Node.\n\n        The 'branch_negated' tells us if the current branch contains any\n        negations. This will be used to determine if subqueries are needed.\n\n        The 'current_negated' is used to determine if the current filter is\n        negated or not and this will be used to determine if IS NULL filtering\n        is needed.\n\n        The difference between current_negated and branch_negated is that\n        branch_negated is set on first negation, but current_negated is\n        flipped for each negation.\n\n        Note that add_filter will not do any negating itself, that is done\n        upper in the code by add_q().\n\n        The 'can_reuse' is a set of reusable joins for multijoins.\n\n        The method will create a filter clause that can be added to the current\n        query. However, if the filter isn't added to the query then the caller\n        is responsible for unreffing the joins used.\n        \"\"\"\n        if isinstance(filter_expr, dict):\n            raise FieldError(\"Cannot parse keyword query as dict\")\n        if isinstance(filter_expr, Q):\n            return self._add_q(\n                filter_expr,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                used_aliases=can_reuse,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n        if hasattr(filter_expr, \"resolve_expression\"):\n            if not getattr(filter_expr, \"conditional\", False):\n                raise TypeError(\"Cannot filter against a non-conditional expression.\")\n            condition = filter_expr.resolve_expression(\n                self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize\n            )\n            if not isinstance(condition, Lookup):\n                condition = self.build_lookup([\"exact\"], condition, True)\n            return WhereNode([condition], connector=AND), []\n        arg, value = filter_expr\n        if not arg:\n            raise FieldError(\"Cannot parse keyword query %r\" % arg)\n        lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize)\n\n        if check_filterable:\n            self.check_filterable(reffed_expression)\n\n        if not allow_joins and len(parts) > 1:\n            raise FieldError(\"Joined field references are not permitted in this query\")\n\n        pre_joins = self.alias_refcount.copy()\n        value = self.resolve_lookup_value(value, can_reuse, allow_joins, summarize)\n        used_joins = {\n            k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)\n        }\n\n        if check_filterable:\n            self.check_filterable(value)\n\n        if reffed_expression:\n            condition = self.build_lookup(lookups, reffed_expression, value)\n            return WhereNode([condition], connector=AND), []\n\n        opts = self.get_meta()\n        alias = self.get_initial_alias()\n        allow_many = not branch_negated or not split_subq\n\n        try:\n            join_info = self.setup_joins(\n                parts,\n                opts,\n                alias,\n                can_reuse=can_reuse,\n                allow_many=allow_many,\n            )\n\n            # Prevent iterator from being consumed by check_related_objects()\n            if isinstance(value, Iterator):\n                value = list(value)\n            self.check_related_objects(join_info.final_field, value, join_info.opts)\n\n            # split_exclude() needs to know which joins were generated for the\n            # lookup parts\n            self._lookup_joins = join_info.joins\n        except MultiJoin as e:\n            return self.split_exclude(filter_expr, can_reuse, e.names_with_path)\n\n        # Update used_joins before trimming since they are reused to determine\n        # which joins could be later promoted to INNER.\n        used_joins.update(join_info.joins)\n        targets, alias, join_list = self.trim_joins(\n            join_info.targets, join_info.joins, join_info.path\n        )\n        if can_reuse is not None:\n            can_reuse.update(join_list)\n\n        if join_info.final_field.is_relation:\n            if len(targets) == 1:\n                col = self._get_col(targets[0], join_info.final_field, alias)\n            else:\n                col = ColPairs(alias, targets, join_info.targets, join_info.final_field)\n        else:\n            col = self._get_col(targets[0], join_info.final_field, alias)\n\n        condition = self.build_lookup(lookups, col, value)\n        lookup_type = condition.lookup_name\n        clause = WhereNode([condition], connector=AND)\n\n        require_outer = (\n            lookup_type == \"isnull\" and condition.rhs is True and not current_negated\n        )\n        if (\n            current_negated\n            and (lookup_type != \"isnull\" or condition.rhs is False)\n            and condition.rhs is not None\n        ):\n            require_outer = True\n            if lookup_type != \"isnull\":\n                # The condition added here will be SQL like this:\n                # NOT (col IS NOT NULL), where the first NOT is added in\n                # upper layers of code. The reason for addition is that if col\n                # is null, then col != someval will result in SQL \"unknown\"\n                # which isn't the same as in Python. The Python None handling\n                # is wanted, and it can be gotten by\n                # (col IS NULL OR col != someval)\n                #   <=>\n                # NOT (col IS NOT NULL AND col = someval).\n                if (\n                    self.is_nullable(targets[0])\n                    or self.alias_map[join_list[-1]].join_type == LOUTER\n                ):\n                    lookup_class = targets[0].get_lookup(\"isnull\")\n                    col = self._get_col(targets[0], join_info.targets[0], alias)\n                    # Use OR + IS NULL when RHS `in` values include None.\n                    if (\n                        lookup_type == \"in\"\n                        # Check containers (not strings or bytes).\n                        and isinstance(condition.rhs, Iterable)\n                        and not isinstance(condition.rhs, (str, bytes))\n                        and any(v is None for v in condition.rhs)\n                    ):\n                        clause.add(lookup_class(col, True), OR)\n                    else:\n                        clause.add(lookup_class(col, False), AND)\n                # If someval is a nullable column, someval IS NOT NULL is\n                # added.\n                if isinstance(value, Col) and self.is_nullable(value.target):\n                    lookup_class = value.target.get_lookup(\"isnull\")\n                    clause.add(lookup_class(value, False), AND)\n        return clause, used_joins if not require_outer else ()\n\n    def add_filter(self, filter_lhs, filter_rhs):\n        self.add_q(Q((filter_lhs, filter_rhs)))\n\n    def add_q(self, q_object, reuse_all=False):\n        \"\"\"\n        A preprocessor for the internal _add_q(). Responsible for doing final\n        join promotion.\n        \"\"\"\n        # For join promotion this case is doing an AND for the added q_object\n        # and existing conditions. So, any existing inner join forces the join\n        # type to remain inner. Existing outer joins can however be demoted.\n        # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if\n        # rel_a doesn't produce any rows, then the whole condition must fail.\n        # So, demotion is OK.\n        \n        if reuse_all:\n            can_reuse = set(self.alias_map)\n        else:\n            can_reuse = self.used_aliases\n        clause, _ = self._add_q(q_object, can_reuse)\n        if clause:\n            self.where.add(clause, AND)\n        self.demote_joins(({\n            a for a in self.alias_map if self.alias_map[a].join_type == INNER\n        }))\n\n    def build_where(self, filter_expr):\n        return self.build_filter(filter_expr, allow_joins=False)[0]\n\n    def clear_where(self):\n        self.where = WhereNode()\n\n    def _add_q(\n        self,\n        q_object,\n        used_aliases,\n        branch_negated=False,\n        current_negated=False,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"Add a Q-object to the current filter.\"\"\"\n        connector = q_object.connector\n        current_negated ^= q_object.negated\n        branch_negated = branch_negated or q_object.negated\n        target_clause = WhereNode(connector=connector, negated=q_object.negated)\n        joinpromoter = JoinPromoter(\n            q_object.connector, len(q_object.children), current_negated\n        )\n        for child in q_object.children:\n            child_clause, needed_inner = self.build_filter(\n                child,\n                can_reuse=used_aliases,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n            joinpromoter.add_votes(needed_inner)\n            if child_clause:\n                target_clause.add(child_clause, connector)\n        if update_join_types:\n            needed_inner = joinpromoter.update_join_types(self)\n        else:\n            needed_inner = []\n        return target_clause, needed_inner\n\n    def add_filtered_relation(self, filtered_relation, alias):\n        if \".\" in alias:\n            raise ValueError(\n                \"FilteredRelation doesn't support aliases with periods \"\n                \"(got %r).\" % alias\n            )\n        self.check_alias(alias)\n        filtered_relation.alias = alias\n        relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(\n            filtered_relation.relation_name\n        )\n        if relation_lookup_parts:\n            raise ValueError(\n                \"FilteredRelation's relation_name cannot contain lookups \"\n                \"(got %r).\" % filtered_relation.relation_name\n            )\n        for lookup in get_children_from_q(filtered_relation.condition):\n            lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)\n            shift = 2 if not lookup_parts else 1\n            lookup_field_path = lookup_field_parts[:-shift]\n            for idx, lookup_field_part in enumerate(lookup_field_path):\n                if len(relation_field_parts) > idx:\n                    if relation_field_parts[idx] != lookup_field_part:\n                        raise ValueError(\n                            \"FilteredRelation's condition doesn't support \"\n                            \"relations outside the %r (got %r).\"\n                            % (filtered_relation.relation_name, lookup)\n                        )\n            if len(lookup_field_parts) > len(relation_field_parts) + 1:\n                raise ValueError(\n                    \"FilteredRelation's condition doesn't support nested \"\n                    \"relations deeper than the relation_name (got %r for \"\n                    \"%r).\" % (lookup, filtered_relation.relation_name)\n                )\n        filtered_relation = filtered_relation.clone()\n        filtered_relation.condition = rename_prefix_from_q(\n            filtered_relation.relation_name,\n            alias,\n            filtered_relation.condition,\n        )\n        self._filtered_relations[filtered_relation.alias] = filtered_relation\n\n    def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):\n        \"\"\"\n        Walk the list of names and turns them into PathInfo tuples. A single\n        name in 'names' can generate multiple PathInfos (m2m, for example).\n\n        'names' is the path of names to travel, 'opts' is the model Options we\n        start the name resolving from, 'allow_many' is as for setup_joins().\n        If fail_on_missing is set to True, then a name that can't be resolved\n        will generate a FieldError.\n\n        Return a list of PathInfo tuples. In addition return the final field\n        (the last used join field) and target (which is a field guaranteed to\n        contain the same value as the final field). Finally, return those names\n        that weren't found (which are likely transforms and the final lookup).\n        \"\"\"\n        path, names_with_path = [], []\n        for pos, name in enumerate(names):\n            cur_names_with_path = (name, [])\n            if name == \"pk\" and opts is not None:\n                name = opts.pk.name\n\n            field = None\n            filtered_relation = None\n            try:\n                if opts is None:\n                    raise FieldDoesNotExist\n                field = opts.get_field(name)\n            except FieldDoesNotExist:\n                if name in self.annotations:\n                    field = self.annotations[name].output_field\n                elif name in self._filtered_relations and pos == 0:\n                    filtered_relation = self._filtered_relations[name]\n                    if LOOKUP_SEP in filtered_relation.relation_name:\n                        parts = filtered_relation.relation_name.split(LOOKUP_SEP)\n                        filtered_relation_path, field, _, _ = self.names_to_path(\n                            parts,\n                            opts,\n                            allow_many,\n                            fail_on_missing,\n                        )\n                        path.extend(filtered_relation_path[:-1])\n                    else:\n                        field = opts.get_field(filtered_relation.relation_name)\n            if field is not None:\n                # Fields that contain one-to-many relations with a generic\n                # model (like a GenericForeignKey) cannot generate reverse\n                # relations and therefore cannot be used for reverse querying.\n                if field.is_relation and not field.related_model:\n                    raise FieldError(\n                        \"Field %r does not generate an automatic reverse \"\n                        \"relation and therefore cannot be used for reverse \"\n                        \"querying. If it is a GenericForeignKey, consider \"\n                        \"adding a GenericRelation.\" % name\n                    )\n                try:\n                    model = field.model._meta.concrete_model\n                except AttributeError:\n                    # QuerySet.annotate() may introduce fields that aren't\n                    # attached to a model.\n                    model = None\n            else:\n                # We didn't find the current field, so move position back\n                # one step.\n                pos -= 1\n                if pos == -1 or fail_on_missing:\n                    \n                    raise FieldError(\n                        \"Cannot resolve keyword '%s' into field. \"\n                        \"Choices are: %s\" % (name, \", \".join((sorted(\n                        [\n                            *get_field_names_from_opts(opts),\n                            *self.annotations,\n                            *self._filtered_relations,\n                        ]\n                    ))))\n                    )\n                break\n            # Check if we need any joins for concrete inheritance cases (the\n            # field lives in parent, but we are currently in one of its\n            # children)\n            if opts is not None and model is not opts.model:\n                path_to_parent = opts.get_path_to_parent(model)\n                if path_to_parent:\n                    path.extend(path_to_parent)\n                    cur_names_with_path[1].extend(path_to_parent)\n                    opts = path_to_parent[-1].to_opts\n            if hasattr(field, \"path_infos\"):\n                if filtered_relation:\n                    pathinfos = field.get_path_info(filtered_relation)\n                else:\n                    pathinfos = field.path_infos\n                if not allow_many:\n                    for inner_pos, p in enumerate(pathinfos):\n                        if p.m2m:\n                            cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1])\n                            names_with_path.append(cur_names_with_path)\n                            raise MultiJoin(pos + 1, names_with_path)\n                last = pathinfos[-1]\n                path.extend(pathinfos)\n                final_field = last.join_field\n                opts = last.to_opts\n                targets = last.target_fields\n                cur_names_with_path[1].extend(pathinfos)\n                names_with_path.append(cur_names_with_path)\n            else:\n                # Local non-relational field.\n                final_field = field\n                targets = (field,)\n                if fail_on_missing and pos + 1 != len(names):\n                    raise FieldError(\n                        \"Cannot resolve keyword %r into field. Join on '%s'\"\n                        \" not permitted.\" % (names[pos + 1], name)\n                    )\n                break\n        return path, final_field, targets, names[pos + 1 :]\n\n    def setup_joins(\n        self,\n        names,\n        opts,\n        alias,\n        can_reuse=None,\n        allow_many=True,\n    ):\n        \"\"\"\n        Compute the necessary table joins for the passage through the fields\n        given in 'names'. 'opts' is the Options class for the current model\n        (which gives the table we are starting from), 'alias' is the alias for\n        the table to start the joining from.\n\n        The 'can_reuse' defines the reverse foreign key joins we can reuse. It\n        can be None in which case all joins are reusable or a set of aliases\n        that can be reused. Note that non-reverse foreign keys are always\n        reusable when using setup_joins().\n\n        If 'allow_many' is False, then any reverse foreign key seen will\n        generate a MultiJoin exception.\n\n        Return the final field involved in the joins, the target field (used\n        for any 'where' constraint), the final 'opts' value, the joins, the\n        field path traveled to generate the joins, and a transform function\n        that takes a field and alias and is equivalent to\n        `field.get_col(alias)` in the simple case but wraps field transforms if\n        they were included in names.\n\n        The target field is the field containing the concrete value. Final\n        field can be something different, for example foreign key pointing to\n        that value. Final field is needed for example in some value\n        conversions (convert 'obj' in fk__id=obj to pk val using the foreign\n        key field for example).\n        \"\"\"\n        joins = [alias]\n        # The transform can't be applied yet, as joins must be trimmed later.\n        # To avoid making every caller of this method look up transforms\n        # directly, compute transforms here and create a partial that converts\n        # fields to the appropriate wrapped version.\n\n        def final_transformer(field, alias):\n            if not self.alias_cols:\n                alias = None\n            return field.get_col(alias)\n\n        # Try resolving all the names as fields first. If there's an error,\n        # treat trailing names as lookups until a field can be resolved.\n        last_field_exception = None\n        for pivot in range(len(names), 0, -1):\n            try:\n                path, final_field, targets, rest = self.names_to_path(\n                    names[:pivot],\n                    opts,\n                    allow_many,\n                    fail_on_missing=True,\n                )\n            except FieldError as exc:\n                if pivot == 1:\n                    # The first item cannot be a lookup, so it's safe\n                    # to raise the field error here.\n                    raise\n                else:\n                    last_field_exception = exc\n            else:\n                # The transforms are the remaining items that couldn't be\n                # resolved into fields.\n                transforms = names[pivot:]\n                break\n        for name in transforms:\n\n            def transform(field, alias, *, name, previous):\n                try:\n                    \n                    return self.try_transform((previous(field, alias)), name)\n                except FieldError:\n                    # FieldError is raised if the transform doesn't exist.\n                    if isinstance(final_field, Field) and last_field_exception:\n                        raise last_field_exception\n                    else:\n                        raise\n\n            final_transformer = functools.partial(\n                transform, name=name, previous=final_transformer\n            )\n            final_transformer.has_transforms = True\n        # Then, add the path to the query's joins. Note that we can't trim\n        # joins at this stage - we will need the information about join type\n        # of the trimmed joins.\n        for join in path:\n            if join.filtered_relation:\n                filtered_relation = join.filtered_relation.clone()\n                table_alias = filtered_relation.alias\n            else:\n                filtered_relation = None\n                table_alias = None\n            opts = join.to_opts\n            if join.direct:\n                nullable = self.is_nullable(join.join_field)\n            else:\n                nullable = True\n            connection = self.join_class(\n                opts.db_table,\n                alias,\n                table_alias,\n                INNER,\n                join.join_field,\n                nullable,\n                filtered_relation=filtered_relation,\n            )\n            reuse = can_reuse if join.m2m else None\n            alias = self.join(connection, reuse=reuse)\n            joins.append(alias)\n            if join.filtered_relation and can_reuse is not None:\n                can_reuse.add(alias)\n        return JoinInfo(final_field, targets, opts, joins, path, final_transformer)\n\n    def trim_joins(self, targets, joins, path):\n        \"\"\"\n        The 'target' parameter is the final field being joined to, 'joins'\n        is the full list of join aliases. The 'path' contain the PathInfos\n        used to create the joins.\n\n        Return the final target field and table alias and the new active\n        joins.\n\n        Always trim any direct join if the target column is already in the\n        previous table. Can't trim reverse joins as it's unknown if there's\n        anything on the other side of the join.\n        \"\"\"\n        joins = joins[:]\n        for pos, info in enumerate(reversed(path)):\n            if len(joins) == 1 or not info.direct:\n                break\n            if info.filtered_relation:\n                break\n            join_targets = {t.column for t in info.join_field.foreign_related_fields}\n            cur_targets = {t.column for t in targets}\n            if not cur_targets.issubset(join_targets):\n                break\n            targets_dict = {\n                r[1].column: r[0]\n                for r in info.join_field.related_fields\n                if r[1].column in cur_targets\n            }\n            targets = tuple(targets_dict[t.column] for t in targets)\n            self.unref_alias(joins.pop())\n        return targets, joins[-1], joins\n\n    @classmethod\n    def _gen_cols(cls, exprs, include_external=False, resolve_refs=True):\n        for expr in exprs:\n            if isinstance(expr, Col):\n                yield expr\n            elif include_external and callable(\n                getattr(expr, \"get_external_cols\", None)\n            ):\n                yield from expr.get_external_cols()\n            elif hasattr(expr, \"get_source_expressions\"):\n                if not resolve_refs and isinstance(expr, Ref):\n                    continue\n                yield from cls._gen_cols(\n                    expr.get_source_expressions(),\n                    include_external=include_external,\n                    resolve_refs=resolve_refs,\n                )\n\n    @classmethod\n    def _gen_col_aliases(cls, exprs):\n        yield from (expr.alias for expr in cls._gen_cols(exprs))\n\n    def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):\n        annotation = self.annotations.get(name)\n        if annotation is not None:\n            if not allow_joins:\n                for alias in self._gen_col_aliases([annotation]):\n                    if isinstance(self.alias_map[alias], Join):\n                        raise FieldError(\n                            \"Joined field references are not permitted in this query\"\n                        )\n            if summarize:\n                # Summarize currently means we are doing an aggregate() query\n                # which is executed as a wrapped subquery if any of the\n                # aggregate() elements reference an existing annotation. In\n                # that case we need to return a Ref to the subquery's\n                # annotation.\n                if name not in self.annotation_select:\n                    raise FieldError(\n                        \"Cannot aggregate over the '%s' alias. Use annotate() \"\n                        \"to promote it.\" % name\n                    )\n                return Ref(name, self.annotation_select[name])\n            else:\n                return annotation\n        else:\n            field_list = name.split(LOOKUP_SEP)\n            annotation = self.annotations.get(field_list[0])\n            if annotation is not None:\n                for transform in field_list[1:]:\n                    annotation = self.try_transform(annotation, transform)\n                return annotation\n            join_info = self.setup_joins(\n                field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse\n            )\n            targets, final_alias, join_list = self.trim_joins(\n                join_info.targets, join_info.joins, join_info.path\n            )\n            if not allow_joins and len(join_list) > 1:\n                raise FieldError(\n                    \"Joined field references are not permitted in this query\"\n                )\n            if len(targets) > 1:\n                raise FieldError(\n                    \"Referencing multicolumn fields with F() objects isn't supported\"\n                )\n            # Verify that the last lookup in name is a field or a transform:\n            # transform_function() raises FieldError if not.\n            transform = join_info.transform_function(targets[0], final_alias)\n            if reuse is not None:\n                reuse.update(join_list)\n            return transform\n\n    def split_exclude(self, filter_expr, can_reuse, names_with_path):\n        \"\"\"\n        When doing an exclude against any kind of N-to-many relation, we need\n        to use a subquery. This method constructs the nested query, given the\n        original exclude filter (filter_expr) and the portion up to the first\n        N-to-many relation field.\n\n        For example, if the origin filter is ~Q(child__name='foo'), filter_expr\n        is ('child__name', 'foo') and can_reuse is a set of joins usable for\n        filters in the original query.\n\n        We will turn this into equivalent of:\n            WHERE NOT EXISTS(\n                SELECT 1\n                FROM child\n                WHERE name = 'foo' AND child.parent_id = parent.id\n                LIMIT 1\n            )\n        \"\"\"\n        # Generate the inner query.\n        query = self.__class__(self.model)\n        query._filtered_relations = self._filtered_relations\n        filter_lhs, filter_rhs = filter_expr\n        if isinstance(filter_rhs, OuterRef):\n            filter_rhs = OuterRef(filter_rhs)\n        elif isinstance(filter_rhs, F):\n            filter_rhs = OuterRef(filter_rhs.name)\n        query.add_filter(filter_lhs, filter_rhs)\n        query.clear_ordering(force=True)\n        # Try to have as simple as possible subquery -> trim leading joins from\n        # the subquery.\n        trimmed_prefix, contains_louter = query.trim_start(names_with_path)\n\n        col = query.select[0]\n        select_field = col.target\n        alias = col.alias\n        if alias in can_reuse:\n            pk = select_field.model._meta.pk\n            # Need to add a restriction so that outer query's filters are in\n            # effect for the subquery, too.\n            query.bump_prefix(self)\n            lookup_class = select_field.get_lookup(\"exact\")\n            # Note that the query.select[0].alias is different from alias\n            # due to bump_prefix above.\n            lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias))\n            query.where.add(lookup, AND)\n            query.external_aliases[alias] = True\n        else:\n            lookup_class = select_field.get_lookup(\"exact\")\n            lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix))\n            query.where.add(lookup, AND)\n\n        condition, needed_inner = self.build_filter(Exists(query))\n\n        if contains_louter:\n            or_null_condition, _ = self.build_filter(\n                (\"%s__isnull\" % trimmed_prefix, True),\n                current_negated=True,\n                branch_negated=True,\n                can_reuse=can_reuse,\n            )\n            condition.add(or_null_condition, OR)\n            # Note that the end result will be:\n            #   NOT EXISTS (inner_q) OR outercol IS NULL\n            # this might look crazy but due to how NULL works, this seems to be\n            # correct. If the IS NULL check is removed, then if outercol\n            # IS NULL we will not match the row.\n        return condition, needed_inner\n\n    def set_empty(self):\n        self.where.add(NothingNode(), AND)\n        for query in self.combined_queries:\n            query.set_empty()\n\n    def is_empty(self):\n        return any(isinstance(c, NothingNode) for c in self.where.children)\n\n    def set_limits(self, low=None, high=None):\n        \"\"\"\n        Adjust the limits on the rows retrieved. Use low/high to set these,\n        as it makes it more Pythonic to read and write. When the SQL query is\n        created, convert them to the appropriate offset and limit values.\n\n        Apply any limits passed in here to the existing constraints. Add low\n        to the current low value and clamp both to any existing high value.\n        \"\"\"\n        if high is not None:\n            if self.high_mark is not None:\n                self.high_mark = min(self.high_mark, self.low_mark + high)\n            else:\n                self.high_mark = self.low_mark + high\n        if low is not None:\n            if self.high_mark is not None:\n                self.low_mark = min(self.high_mark, self.low_mark + low)\n            else:\n                self.low_mark = self.low_mark + low\n\n        if self.low_mark == self.high_mark:\n            self.set_empty()\n\n    def clear_limits(self):\n        \"\"\"Clear any existing limits.\"\"\"\n        self.low_mark, self.high_mark = 0, None\n\n    @property\n    def is_sliced(self):\n        return self.low_mark != 0 or self.high_mark is not None\n\n    def has_limit_one(self):\n        return self.high_mark is not None and (self.high_mark - self.low_mark) == 1\n\n    def can_filter(self):\n        \"\"\"\n        Return True if adding filters to this instance is still possible.\n\n        Typically, this means no limits or offsets have been put on the\n        results.\n        \"\"\"\n        return not self.is_sliced\n\n    def clear_select_clause(self):\n        \"\"\"Remove all fields from SELECT clause.\"\"\"\n        self.select = ()\n        self.default_cols = False\n        self.select_related = False\n        self.set_extra_mask(())\n        self.set_annotation_mask(())\n        self.selected = None\n\n    def clear_select_fields(self):\n        \"\"\"\n        Clear the list of fields to select (but not extra_select columns).\n        Some queryset types completely replace any existing list of select\n        columns.\n        \"\"\"\n        self.select = ()\n        self.values_select = ()\n        self.selected = None\n\n    def add_select_col(self, col, name):\n        self.select += (col,)\n        self.values_select += (name,)\n        self.selected[name] = len(self.select) - 1\n\n    def set_select(self, cols):\n        self.default_cols = False\n        self.select = tuple(cols)\n\n    def add_distinct_fields(self, *field_names):\n        \"\"\"\n        Add and resolve the given fields to the query's \"distinct on\" clause.\n        \"\"\"\n        self.distinct_fields = field_names\n        self.distinct = True\n\n    def add_fields(self, field_names, allow_m2m=True):\n        \"\"\"\n        Add the given (model) fields to the select set. Add the field names in\n        the order specified.\n        \"\"\"\n        alias = self.get_initial_alias()\n        opts = self.get_meta()\n\n        try:\n            cols = []\n            for name in field_names:\n                # Join promotion note - we must not remove any rows here, so\n                # if there is no existing joins, use outer join.\n                join_info = self.setup_joins(\n                    name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m\n                )\n                targets, final_alias, joins = self.trim_joins(\n                    join_info.targets,\n                    join_info.joins,\n                    join_info.path,\n                )\n                if len(targets) > 1:\n                    transformed_targets = [\n                        join_info.transform_function(target, final_alias)\n                        for target in targets\n                    ]\n                    cols.append(\n                        ColPairs(\n                            final_alias if self.alias_cols else None,\n                            [col.target for col in transformed_targets],\n                            [col.output_field for col in transformed_targets],\n                            join_info.final_field,\n                        )\n                    )\n                else:\n                    cols.append(join_info.transform_function(targets[0], final_alias))\n            if cols:\n                self.set_select(cols)\n        except MultiJoin:\n            raise FieldError(\"Invalid field name: '%s'\" % name)\n        except FieldError:\n            if LOOKUP_SEP in name:\n                # For lookups spanning over relationships, show the error\n                # from the model on which the lookup failed.\n                raise\n            else:\n                \n                raise FieldError(\n                    \"Cannot resolve keyword %r into field. \"\n                    \"Choices are: %s\" % (name, \", \".join((sorted(\n                    [\n                        *get_field_names_from_opts(opts),\n                        *self.extra,\n                        *self.annotation_select,\n                        *self._filtered_relations,\n                    ]\n                ))))\n                )\n\n    def add_ordering(self, *ordering):\n        \"\"\"\n        Add items from the 'ordering' sequence to the query's \"order by\"\n        clause. These items are either field names (not column names) --\n        possibly with a direction prefix ('-' or '?') -- or OrderBy\n        expressions.\n\n        If 'ordering' is empty, clear all ordering from the query.\n        \"\"\"\n        errors = []\n        for item in ordering:\n            if isinstance(item, str):\n                if item == \"?\":\n                    continue\n                item = item.removeprefix(\"-\")\n                if item in self.annotations:\n                    continue\n                if self.extra and item in self.extra:\n                    continue\n                # names_to_path() validates the lookup. A descriptive\n                # FieldError will be raise if it's not.\n                self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)\n            elif not hasattr(item, \"resolve_expression\"):\n                errors.append(item)\n            if getattr(item, \"contains_aggregate\", False):\n                raise FieldError(\n                    \"Using an aggregate in order_by() without also including \"\n                    \"it in annotate() is not allowed: %s\" % item\n                )\n        if errors:\n            raise FieldError(\"Invalid order_by arguments: %s\" % errors)\n        if ordering:\n            self.order_by += ordering\n        else:\n            self.default_ordering = False\n\n    @property\n    def orderby_issubset_groupby(self):\n        if self.extra_order_by:\n            # Raw SQL from extra(order_by=...) can't be reliably compared\n            # against resolved OrderBy/Col expressions. Treat as not a subset.\n            return False\n        if self.group_by in (None, True):\n            # There is either no aggregation at all (None), or the group by\n            # is generated automatically from model fields (True), in which\n            # case the order by is necessarily a subset of them.\n            return True\n        if not self.order_by:\n            # Although an empty set is always a subset, there's no point in\n            # clearing ordering when there isn't any. Avoid the clone() below.\n            return True\n        # Don't pollute the original query (might disrupt joins).\n        q = self.clone()\n        order_by_set = set()\n        for order_by in q.order_by:\n            if hasattr(order_by, \"resolve_expression\"):\n                order_by_set.add(order_by.resolve_expression(q))\n            elif order_by == \"?\":\n                # Random ordering can't be compared against group by.\n                return False\n            else:\n                order_by_set.add(F(order_by.removeprefix(\"-\")).resolve_expression(q))\n        return order_by_set.issubset(self.group_by)\n\n    def clear_ordering(self, force=False, clear_default=True):\n        \"\"\"\n        Remove any ordering settings if the current query allows it without\n        side effects, set 'force' to True to clear the ordering regardless.\n        If 'clear_default' is True, there will be no ordering in the resulting\n        query (not even the model's default).\n        \"\"\"\n        if not force and (\n            self.is_sliced or self.distinct_fields or self.select_for_update\n        ):\n            return\n        self.order_by = ()\n        self.extra_order_by = ()\n        if clear_default:\n            self.default_ordering = False\n        # Ordering is cleared on combined queries with clear_default=False\n        # when union() and analogues are called, so percolate any possible\n        # clear_default=True.\n        for query in self.combined_queries:\n            query.clear_ordering(force=False, clear_default=clear_default)\n\n    def set_group_by(self, allow_aliases=True):\n        \"\"\"\n        Expand the GROUP BY clause required by the query.\n\n        This will usually be the set of all non-aggregate fields in the\n        return data. If the database backend supports grouping by the\n        primary key, and the query would be equivalent, the optimization\n        will be made automatically.\n        \"\"\"\n        if allow_aliases and self.values_select:\n            # If grouping by aliases is allowed assign selected value aliases\n            # by moving them to annotations.\n            group_by_annotations = {}\n            values_select = {}\n            for alias, expr in zip(self.values_select, self.select):\n                if isinstance(expr, Col):\n                    values_select[alias] = expr\n                else:\n                    group_by_annotations[alias] = expr\n            self.annotations = {**group_by_annotations, **self.annotations}\n            self.append_annotation_mask(group_by_annotations)\n            self.select = tuple(values_select.values())\n            self.values_select = tuple(values_select)\n            if self.selected is not None:\n                for index, value_select in enumerate(values_select):\n                    self.selected[value_select] = index\n        group_by = list(self.select)\n        for alias, annotation in self.annotation_select.items():\n            if not (group_by_cols := annotation.get_group_by_cols()):\n                continue\n            if allow_aliases and not annotation.contains_aggregate:\n                group_by.append(Ref(alias, annotation))\n            else:\n                group_by.extend(group_by_cols)\n        self.group_by = tuple(group_by)\n\n    def add_select_related(self, fields):\n        \"\"\"\n        Set up the select_related data structure so that we only select\n        certain related models (as opposed to all models, when\n        self.select_related=True).\n        \"\"\"\n        if isinstance(self.select_related, bool):\n            field_dict = {}\n        else:\n            field_dict = self.select_related\n        for field in fields:\n            d = field_dict\n            for part in field.split(LOOKUP_SEP):\n                d = d.setdefault(part, {})\n        self.select_related = field_dict\n\n    def add_extra(self, select, select_params, where, params, tables, order_by):\n        \"\"\"\n        Add data to the various extra_* attributes for user-created additions\n        to the query.\n        \"\"\"\n        if select:\n            # We need to pair any placeholder markers in the 'select'\n            # dictionary with their parameters in 'select_params' so that\n            # subsequent updates to the select dictionary also adjust the\n            # parameters appropriately.\n            select_pairs = {}\n            if select_params:\n                param_iter = iter(select_params)\n            else:\n                param_iter = iter([])\n            for name, entry in select.items():\n                self.check_alias(name)\n                entry = str(entry)\n                entry_params = []\n                pos = entry.find(\"%s\")\n                while pos != -1:\n                    if pos == 0 or entry[pos - 1] != \"%\":\n                        entry_params.append(next(param_iter))\n                    pos = entry.find(\"%s\", pos + 2)\n                select_pairs[name] = (entry, entry_params)\n            self.extra.update(select_pairs)\n        if where or params:\n            self.where.add(ExtraWhere(where, params), AND)\n        if tables:\n            self.extra_tables += tuple(tables)\n        if order_by:\n            self.extra_order_by = order_by\n\n    def clear_deferred_loading(self):\n        \"\"\"Remove any fields from the deferred loading set.\"\"\"\n        self.deferred_loading = (frozenset(), True)\n\n    def add_deferred_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        exclude from loading from the database when automatic column selection\n        is done. Add the new field names to any existing field names that\n        are deferred (or removed from any existing field names that are marked\n        as the only ones for immediate loading).\n        \"\"\"\n        # Fields on related models are stored in the literal double-underscore\n        # format, so that we can use a set datastructure. We do the foo__bar\n        # splitting and handling when computing the SQL column names (as part\n        # of get_columns()).\n        existing, defer = self.deferred_loading\n        if defer:\n            # Add to existing deferred names.\n            self.deferred_loading = existing.union(field_names), True\n        else:\n            # Remove names from the set of any existing \"immediate load\" names.\n            if new_existing := existing.difference(field_names):\n                self.deferred_loading = new_existing, False\n            else:\n                self.clear_deferred_loading()\n                if new_only := set(field_names).difference(existing):\n                    self.deferred_loading = new_only, True\n\n    def add_immediate_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        retrieve when the SQL is executed (\"immediate loading\" fields). The\n        field names replace any existing immediate loading field names. If\n        there are field names already specified for deferred loading, remove\n        those names from the new field_names before storing the new names\n        for immediate loading. (That is, immediate loading overrides any\n        existing immediate values, but respects existing deferrals.)\n        \"\"\"\n        existing, defer = self.deferred_loading\n        field_names = set(field_names)\n        if \"pk\" in field_names:\n            field_names.remove(\"pk\")\n            field_names.add(self.get_meta().pk.name)\n\n        if defer:\n            # Remove any existing deferred names from the current set before\n            # setting the new names.\n            self.deferred_loading = field_names.difference(existing), False\n        else:\n            # Replace any existing \"immediate load\" field names.\n            self.deferred_loading = frozenset(field_names), False\n\n    def set_annotation_mask(self, names):\n        \"\"\"Set the mask of annotations that will be returned by the SELECT.\"\"\"\n        if names is None:\n            self.annotation_select_mask = None\n        else:\n            self.annotation_select_mask = set(names)\n            if self.selected:\n                # Prune the masked annotations.\n                self.selected = {\n                    key: value\n                    for key, value in self.selected.items()\n                    if not isinstance(value, str)\n                    or value in self.annotation_select_mask\n                }\n                # Append the unmasked annotations.\n                for name in names:\n                    self.selected[name] = name\n        self._annotation_select_cache = None\n\n    def append_annotation_mask(self, names):\n        if self.annotation_select_mask is not None:\n            self.set_annotation_mask(self.annotation_select_mask.union(names))\n\n    def set_extra_mask(self, names):\n        \"\"\"\n        Set the mask of extra select items that will be returned by SELECT.\n        Don't remove them from the Query since they might be used later.\n        \"\"\"\n        if names is None:\n            self.extra_select_mask = None\n        else:\n            self.extra_select_mask = set(names)\n        self._extra_select_cache = None\n\n    @property\n    def has_select_fields(self):\n        return self.selected is not None\n\n    def set_values(self, fields):\n        self.select_related = False\n        self.clear_deferred_loading()\n        self.clear_select_fields()\n\n        selected = {}\n        if fields:\n            for field in fields:\n                self.check_alias(field)\n            field_names = []\n            extra_names = []\n            annotation_names = []\n            if not self.extra and not self.annotations:\n                # Shortcut - if there are no extra or annotations, then\n                # the values() clause must be just field names.\n                field_names = list(fields)\n                selected = dict(zip(fields, range(len(fields))))\n            else:\n                self.default_cols = False\n                for f in fields:\n                    if extra := self.extra_select.get(f):\n                        extra_names.append(f)\n                        selected[f] = RawSQL(*extra)\n                    elif f in self.annotation_select:\n                        annotation_names.append(f)\n                        selected[f] = f\n                    elif f in self.annotations:\n                        if self.annotation_select:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. It was excluded \"\n                                f\"by a previous values() or values_list() call. \"\n                                f\"Include '{f}' in that call to select it.\"\n                            )\n                        else:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. Use annotate() \"\n                                f\"to promote it.\"\n                            )\n                    else:\n                        # Call `names_to_path` to ensure a FieldError including\n                        # annotations about to be masked as valid choices if\n                        # `f` is not resolvable.\n                        if self.annotation_select:\n                            self.names_to_path(f.split(LOOKUP_SEP), self.model._meta)\n                        selected[f] = len(field_names)\n                        field_names.append(f)\n            self.set_extra_mask(extra_names)\n            self.set_annotation_mask(annotation_names)\n        else:\n            field_names = [f.attname for f in self.model._meta.concrete_fields]\n            selected = dict.fromkeys(field_names, None)\n        # Selected annotations must be known before setting the GROUP BY\n        # clause.\n        if self.group_by is True:\n            self.add_fields(\n                (f.attname for f in self.model._meta.concrete_fields), False\n            )\n            # Disable GROUP BY aliases to avoid orphaning references to the\n            # SELECT clause which is about to be cleared.\n            self.set_group_by(allow_aliases=False)\n            self.clear_select_fields()\n        elif self.group_by:\n            # Resolve GROUP BY annotation references if they are not part of\n            # the selected fields anymore.\n            group_by = []\n            for expr in self.group_by:\n                if isinstance(expr, Ref) and expr.refs not in selected:\n                    expr = self.annotations[expr.refs]\n                group_by.append(expr)\n            self.group_by = tuple(group_by)\n\n        self.values_select = tuple(field_names)\n        self.add_fields(field_names, True)\n        self.selected = selected if fields else None\n\n    @property\n    def annotation_select(self):\n        \"\"\"\n        Return the dictionary of aggregate columns that are not masked and\n        should be used in the SELECT clause. Cache this result for performance.\n        \"\"\"\n        if self._annotation_select_cache is not None:\n            return self._annotation_select_cache\n        elif not self.annotations:\n            return {}\n        elif self.annotation_select_mask is not None:\n            self._annotation_select_cache = {\n                k: v\n                for k, v in self.annotations.items()\n                if k in self.annotation_select_mask\n            }\n            return self._annotation_select_cache\n        else:\n            return self.annotations\n\n    @property\n    def extra_select(self):\n        if self._extra_select_cache is not None:\n            return self._extra_select_cache\n        if not self.extra:\n            return {}\n        elif self.extra_select_mask is not None:\n            self._extra_select_cache = {\n                k: v for k, v in self.extra.items() if k in self.extra_select_mask\n            }\n            return self._extra_select_cache\n        else:\n            return self.extra\n\n    def trim_start(self, names_with_path):\n        \"\"\"\n        Trim joins from the start of the join path. The candidates for trim\n        are the PathInfos in names_with_path structure that are m2m joins.\n\n        Also set the select column so the start matches the join.\n\n        This method is meant to be used for generating the subquery joins &\n        cols in split_exclude().\n\n        Return a lookup usable for doing outerq.filter(lookup=self) and a\n        boolean indicating if the joins in the prefix contain a LEFT OUTER\n        join.\n        \"\"\"\n        all_paths = []\n        for _, paths in names_with_path:\n            all_paths.extend(paths)\n        contains_louter = False\n        # Trim and operate only on tables that were generated for\n        # the lookup part of the query. That is, avoid trimming\n        # joins generated for F() expressions.\n        lookup_tables = [\n            t for t in self.alias_map if t in self._lookup_joins or t == self.base_table\n        ]\n        for trimmed_paths, path in enumerate(all_paths):\n            if path.m2m:\n                break\n            if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER:\n                contains_louter = True\n            \n            self.unref_alias((lookup_tables[trimmed_paths]))\n        # The path.join_field is a Rel, lets get the other side's field\n        join_field = path.join_field.field\n        # Build the filter prefix.\n        paths_in_prefix = trimmed_paths\n        trimmed_prefix = []\n        for name, path in names_with_path:\n            if paths_in_prefix - len(path) < 0:\n                break\n            trimmed_prefix.append(name)\n            paths_in_prefix -= len(path)\n        trimmed_prefix.append(join_field.foreign_related_fields[0].name)\n        trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)\n        # Lets still see if we can trim the first join from the inner query\n        # (that is, self). We can't do this for:\n        # - LEFT JOINs because we would miss those rows that have nothing on\n        #   the outer side,\n        # - INNER JOINs from filtered relations because we would miss their\n        #   filters.\n        first_join = self.alias_map[lookup_tables[trimmed_paths + 1]]\n        if first_join.join_type != LOUTER and not first_join.filtered_relation:\n            select_fields = [r[0] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths + 1]\n            self.unref_alias(lookup_tables[trimmed_paths])\n            extra_restriction = join_field.get_extra_restriction(\n                None, lookup_tables[trimmed_paths + 1]\n            )\n            if extra_restriction:\n                self.where.add(extra_restriction, AND)\n        else:\n            # TODO: It might be possible to trim more joins from the start of\n            # the inner query if it happens to have a longer join chain\n            # containing the values in select_fields. Lets punt this one for\n            # now.\n            select_fields = [r[1] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths]\n        # The found starting point is likely a join_class instead of a\n        # base_table_class reference. But the first entry in the query's FROM\n        # clause must not be a JOIN.\n        for table in self.alias_map:\n            if self.alias_refcount[table] > 0:\n                self.alias_map[table] = self.base_table_class(\n                    self.alias_map[table].table_name,\n                    table,\n                )\n                break\n        self.set_select([f.get_col(select_alias) for f in select_fields])\n        return trimmed_prefix, contains_louter\n\n    def is_nullable(self, field):\n        \"\"\"\n        Check if the given field should be treated as nullable.\n\n        Some backends treat '' as null and Django treats such fields as\n        nullable for those backends. In such situations field.null can be\n        False even if we should treat the field as nullable.\n        \"\"\"\n        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have\n        # (nor should it have) knowledge of which connection is going to be\n        # used. The proper fix would be to defer all decisions where\n        # is_nullable() is needed to the compiler stage, but that is not easy\n        # to do currently.\n        return field.null or (\n            field.empty_strings_allowed\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-d737c5fea4d295f9", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "4f76c4c1776a0fc720b33488d9c6709df9127471a6dbae8cdd4245be30c531d8", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 2602, "local_path": "data-flow/inline-intermediate-variables/I12__django__Query__03ca6e36.py", "order": 12, "original_content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "parent_variant_id": "pyint-82246794d74c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/query.py#L232-L2792", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 15, "intermediate_variables_available": 15, "intermediate_variables_inlined": 15, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Query", "variant_id": "pyint-867a03ca6e36-I12", "group_id": "py-d737c5fea4d295f9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 293, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-530250af4076-I13", "source": "import copy\nimport difflib\nimport functools\nimport sys\nimport warnings\nfrom collections import Counter, namedtuple\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom itertools import chain, count, product\nfrom string import ascii_uppercase\nfrom django.core.exceptions import FieldDoesNotExist, FieldError\nfrom django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections\nfrom django.db.models.aggregates import Count\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import (\n    BaseExpression,\n    Col,\n    ColPairs,\n    Exists,\n    F,\n    OuterRef,\n    RawSQL,\n    Ref,\n    ResolvedOuterRef,\n    Value,\n)\nfrom django.db.models.fields import Field\nfrom django.db.models.lookups import Lookup\nfrom django.db.models.query_utils import (\n    Q,\n    check_rel_lookup_compatibility,\n    refs_expression,\n)\nfrom django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE\nfrom django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin\nfrom django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode\nfrom django.utils.deprecation import RemovedInDjango70Warning\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.tree import Node\nfrom django.utils.warnings import django_file_prefixes\n\nclass Query(BaseExpression):\n    \"\"\"A single SQL query.\"\"\"\n\n    alias_prefix = \"T\"\n    empty_result_set_value = None\n    subq_aliases = frozenset([alias_prefix])\n\n    compiler = \"SQLCompiler\"\n\n    base_table_class = BaseTable\n    join_class = Join\n\n    default_cols = True\n    default_ordering = True\n    standard_ordering = True\n\n    filter_is_sticky = False\n    subquery = False\n    contains_subquery = False\n\n    # SQL-related attributes.\n    # Select and related select clauses are expressions to use in the SELECT\n    # clause of the query. The select is used for cases where we want to set up\n    # the select clause to contain other than default fields (values(),\n    # subqueries...). Note that annotations go to annotations dictionary.\n    select = ()\n    # The group_by attribute can have one of the following forms:\n    #  - None: no group by at all in the query\n    #  - A tuple of expressions: group by (at least) those expressions.\n    #    String refs are also allowed for now.\n    #  - True: group by all select fields of the model\n    # See compiler.get_group_by() for details.\n    group_by = None\n    order_by = ()\n    low_mark = 0  # Used for offset/limit.\n    high_mark = None  # Used for offset/limit.\n    distinct = False\n    distinct_fields = ()\n    select_for_update = False\n    select_for_update_nowait = False\n    select_for_update_skip_locked = False\n    select_for_update_of = ()\n    select_for_no_key_update = False\n    select_related = False\n    # Arbitrary limit for select_related to prevents infinite recursion.\n    max_depth = 5\n    # Holds the selects defined by a call to values() or values_list()\n    # excluding annotation_select and extra_select.\n    values_select = ()\n    selected = None\n\n    # SQL annotation-related attributes.\n    annotation_select_mask = None\n    _annotation_select_cache = None\n\n    # Set combination attributes.\n    combinator = None\n    combinator_all = False\n    combined_queries = ()\n\n    # These are for extensions. The contents are more or less appended verbatim\n    # to the appropriate clause.\n    extra_select_mask = None\n    _extra_select_cache = None\n\n    extra_tables = ()\n    extra_order_by = ()\n\n    # A tuple that is a set of model field names and either True, if these are\n    # the fields to defer, or False if these are the only fields to load.\n    deferred_loading = (frozenset(), True)\n\n    explain_info = None\n\n    def __init__(self, model, alias_cols=True):\n        self.model = model\n        self.alias_refcount = {}\n        # alias_map is the most important data structure regarding joins.\n        # It's used for recording which joins exist in the query and what\n        # types they are. The key is the alias of the joined table (possibly\n        # the table name) and the value is a Join-like object (see\n        # sql.datastructures.Join for more information).\n        self.alias_map = {}\n        # Whether to provide alias to columns during reference resolving.\n        self.alias_cols = alias_cols\n        # Sometimes the query contains references to aliases in outer queries\n        # (as a result of split_exclude). Correct alias quoting needs to know\n        # these aliases too. Map external tables to whether they are aliased.\n        self.external_aliases = {}\n        self.table_map = {}  # Maps table names to list of aliases.\n        self.used_aliases = set()\n\n        self.where = WhereNode()\n        # Maps alias -> Annotation Expression.\n        self.annotations = {}\n        # These are for extensions. The contents are more or less appended\n        # verbatim to the appropriate clause.\n        self.extra = {}  # Maps col_alias -> (col_sql, params).\n\n        self._filtered_relations = {}\n\n    @property\n    def output_field(self):\n        if len(self.select) == 1:\n            select = self.select[0]\n            return getattr(select, \"target\", None) or select.field\n        elif len(self.annotation_select) == 1:\n            return next(iter(self.annotation_select.values())).output_field\n\n    @cached_property\n    def base_table(self):\n        loopIterator = __import__(\"builtins\").iter(self.alias_map)\n        while True:\n            try:\n                alias = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            return alias\n\n    def __str__(self):\n        \"\"\"\n        Return the query as a string of SQL with the parameter values\n        substituted in (use sql_with_params() to see the unsubstituted string).\n\n        Parameter values won't necessarily be quoted correctly, since that is\n        done by the database interface at execution time.\n        \"\"\"\n        sql, params = self.sql_with_params()\n        return sql % params\n\n    def sql_with_params(self):\n        \"\"\"\n        Return the query as an SQL string and the parameters that will be\n        substituted into the query.\n        \"\"\"\n        return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()\n\n    def __deepcopy__(self, memo):\n        \"\"\"Limit the amount of work when a Query is deepcopied.\"\"\"\n        result = self.clone()\n        memo[id(self)] = result\n        return result\n\n    def get_compiler(self, using=None, connection=None, elide_empty=True):\n        if using is None and connection is None:\n            raise ValueError(\"Need either using or connection\")\n        if using:\n            connection = connections[using]\n        return connection.ops.compiler(self.compiler)(\n            self, connection, using, elide_empty\n        )\n\n    def get_meta(self):\n        \"\"\"\n        Return the Options instance (the model._meta) from which to start\n        processing. Normally, this is self.model._meta, but it can be changed\n        by subclasses.\n        \"\"\"\n        if self.model:\n            return self.model._meta\n\n    def clone(self):\n        \"\"\"\n        Return a copy of the current Query. A lightweight alternative to\n        deepcopy().\n        \"\"\"\n        obj = Empty()\n        obj.__class__ = self.__class__\n        # Copy references to everything.\n        obj.__dict__ = self.__dict__.copy()\n        # Clone attributes that can't use shallow copy.\n        obj.alias_refcount = self.alias_refcount.copy()\n        obj.alias_map = self.alias_map.copy()\n        obj.external_aliases = self.external_aliases.copy()\n        obj.table_map = self.table_map.copy()\n        obj.where = self.where.clone()\n        obj.annotations = self.annotations.copy()\n        if self.annotation_select_mask is not None:\n            obj.annotation_select_mask = self.annotation_select_mask.copy()\n        if self.combined_queries:\n            obj.combined_queries = tuple(\n                [query.clone() for query in self.combined_queries]\n            )\n        # _annotation_select_cache cannot be copied, as doing so breaks the\n        # (necessary) state in which both annotations and\n        # _annotation_select_cache point to the same underlying objects.\n        # It will get re-populated in the cloned queryset the next time it's\n        # used.\n        obj._annotation_select_cache = None\n        obj.extra = self.extra.copy()\n        if self.extra_select_mask is not None:\n            obj.extra_select_mask = self.extra_select_mask.copy()\n        if self._extra_select_cache is not None:\n            obj._extra_select_cache = self._extra_select_cache.copy()\n        if self.select_related is not False:\n            # Use deepcopy because select_related stores fields in nested\n            # dicts.\n            obj.select_related = copy.deepcopy(obj.select_related)\n        if \"subq_aliases\" in self.__dict__:\n            obj.subq_aliases = self.subq_aliases.copy()\n        obj.used_aliases = self.used_aliases.copy()\n        obj._filtered_relations = self._filtered_relations.copy()\n        # Clear the cached_property, if it exists.\n        obj.__dict__.pop(\"base_table\", None)\n        return obj\n\n    def chain(self, klass=None):\n        \"\"\"\n        Return a copy of the current Query that's ready for another operation.\n        The klass argument changes the type of the Query, e.g. UpdateQuery.\n        \"\"\"\n        obj = self.clone()\n        if klass and obj.__class__ != klass:\n            obj.__class__ = klass\n        if not obj.filter_is_sticky:\n            obj.used_aliases = set()\n        obj.filter_is_sticky = False\n        if hasattr(obj, \"_setup_query\"):\n            obj._setup_query()\n        return obj\n\n    def relabeled_clone(self, change_map):\n        clone = self.clone()\n        clone.change_aliases(change_map)\n        return clone\n\n    def _get_col(self, target, field, alias):\n        if not self.alias_cols:\n            alias = None\n        return target.get_col(alias, field)\n\n    def get_aggregation(self, using, aggregate_exprs):\n        \"\"\"\n        Return the dictionary with the values of the existing aggregations.\n        \"\"\"\n        if not aggregate_exprs:\n            return {}\n        # Store annotation mask prior to temporarily adding aggregations for\n        # resolving purpose to facilitate their subsequent removal.\n        refs_subquery = False\n        refs_window = False\n        replacements = {}\n        annotation_select_mask = self.annotation_select_mask\n        for alias, aggregate_expr in aggregate_exprs.items():\n            self.check_alias(alias)\n            aggregate = aggregate_expr.resolve_expression(\n                self, allow_joins=True, reuse=None, summarize=True\n            )\n            if not aggregate.contains_aggregate:\n                raise TypeError(\"%s is not an aggregate expression\" % alias)\n            # Temporarily add aggregate to annotations to allow remaining\n            # members of `aggregates` to resolve against each others.\n            self.append_annotation_mask([alias])\n            aggregate_refs = aggregate.get_refs()\n            refs_subquery |= any(\n                getattr(self.annotations[ref], \"contains_subquery\", False)\n                for ref in aggregate_refs\n            )\n            refs_window |= any(\n                getattr(self.annotations[ref], \"contains_over_clause\", True)\n                for ref in aggregate_refs\n            )\n            aggregate = aggregate.replace_expressions(replacements)\n            self.annotations[alias] = aggregate\n            replacements[Ref(alias, aggregate)] = aggregate\n        # Stash resolved aggregates now that they have been allowed to resolve\n        # against each other.\n        aggregates = {alias: self.annotations.pop(alias) for alias in aggregate_exprs}\n        self.set_annotation_mask(annotation_select_mask)\n        # Existing usage of aggregation can be determined by the presence of\n        # selected aggregates but also by filters against aliased aggregates.\n        _, having, qualify = self.where.split_having_qualify()\n        has_existing_aggregation = (\n            any(\n                getattr(annotation, \"contains_aggregate\", True)\n                for annotation in self.annotations.values()\n            )\n            or having\n        )\n        set_returning_annotations = {\n            alias\n            for alias, annotation in self.annotation_select.items()\n            if getattr(annotation, \"set_returning\", False)\n        }\n        # Decide if we need to use a subquery.\n        #\n        # Existing aggregations would cause incorrect results as\n        # get_aggregation() must produce just one result and thus must not use\n        # GROUP BY.\n        #\n        # If the query has limit or distinct, or uses set operations, then\n        # those operations must be done in a subquery so that the query\n        # aggregates on the limit and/or distinct results instead of applying\n        # the distinct and limit after the aggregation.\n        if (\n            isinstance(self.group_by, tuple)\n            or self.is_sliced\n            or has_existing_aggregation\n            or refs_subquery\n            or refs_window\n            or qualify\n            or self.distinct\n            or self.combinator\n            or set_returning_annotations\n        ):\n            from django.db.models.sql.subqueries import AggregateQuery\n\n            inner_query = self.clone()\n            inner_query.subquery = True\n            outer_query = AggregateQuery(self.model, inner_query)\n            inner_query.select_for_update = False\n            inner_query.select_related = False\n            inner_query.set_annotation_mask(self.annotation_select)\n            # Queries with distinct_fields need ordering and when a limit is\n            # applied we must take the slice from the ordered query. Otherwise\n            # no need for ordering.\n            if inner_query.orderby_issubset_groupby:\n                inner_query.clear_ordering(force=False)\n            if not inner_query.distinct:\n                # If the inner query uses default select and it has some\n                # aggregate annotations, then we must make sure the inner\n                # query is grouped by the main model's primary key. However,\n                # clearing the select clause can alter results if distinct is\n                # used.\n                if inner_query.default_cols and has_existing_aggregation:\n                    inner_query.group_by = (\n                        self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                    )\n                inner_query.default_cols = False\n                if not qualify and not self.combinator:\n                    # Mask existing annotations that are not referenced by\n                    # aggregates to be pushed to the outer query unless\n                    # filtering against window functions or if the query is\n                    # combined as both would require complex realiasing logic.\n                    annotation_mask = set()\n                    if isinstance(self.group_by, tuple):\n                        loopIteratorA = __import__(\"builtins\").iter(self.group_by)\n                        while True:\n                            try:\n                                expr = __import__(\"builtins\").next(loopIteratorA)\n                            except __import__(\"builtins\").StopIteration:\n                                break\n                            annotation_mask |= expr.get_refs()\n                    loopIteratorB = __import__(\"builtins\").iter(aggregates.values())\n                    while True:\n                        try:\n                            aggregate = __import__(\"builtins\").next(loopIteratorB)\n                        except __import__(\"builtins\").StopIteration:\n                            break\n                        annotation_mask |= aggregate.get_refs()\n                    # Avoid eliding expressions that might have an incidence on\n                    # the implicit grouping logic.\n                    loopIteratorC = __import__(\"builtins\").iter(self.annotation_select.items())\n                    while True:\n                        try:\n                            annotation_alias, annotation = __import__(\"builtins\").next(loopIteratorC)\n                        except __import__(\"builtins\").StopIteration:\n                            break\n                        if annotation.get_group_by_cols():\n                            annotation_mask.add(annotation_alias)\n                    inner_query.set_annotation_mask(annotation_mask)\n                    # Annotations that possibly return multiple rows cannot\n                    # be masked as they might have an incidence on the query.\n                    annotation_mask |= set_returning_annotations\n\n            # Add aggregates to the outer AggregateQuery. This requires making\n            # sure all columns referenced by the aggregates are selected in the\n            # inner query. It is achieved by retrieving all column references\n            # by the aggregates, explicitly selecting them in the inner query,\n            # and making sure the aggregates are repointed to them.\n            col_refs = {}\n            loopIteratorAP = __import__(\"builtins\").iter(aggregates.items())\n            while True:\n                try:\n                    alias, aggregate = __import__(\"builtins\").next(loopIteratorAP)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                replacements = {}\n                loopIteratorD = __import__(\"builtins\").iter(self._gen_cols([aggregate], resolve_refs=False))\n                while True:\n                    try:\n                        col = __import__(\"builtins\").next(loopIteratorD)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    if not (col_ref := col_refs.get(col)):\n                        index = len(col_refs) + 1\n                        col_alias = f\"__col{index}\"\n                        col_ref = Ref(col_alias, col)\n                        col_refs[col] = col_ref\n                        inner_query.add_annotation(col, col_alias)\n                    replacements[col] = col_ref\n                outer_query.annotations[alias] = aggregate.replace_expressions(\n                    replacements\n                )\n            if (\n                inner_query.select == ()\n                and not inner_query.default_cols\n                and not inner_query.annotation_select_mask\n            ):\n                # In case of Model.objects[0:3].count(), there would be no\n                # field selected in the inner query, yet we must use a\n                # subquery. So, make sure at least one field is selected.\n                inner_query.select = (\n                    self.model._meta.pk.get_col(inner_query.get_initial_alias()),\n                )\n        else:\n            outer_query = self\n            self.select = ()\n            self.selected = None\n            self.default_cols = False\n            self.extra = {}\n            if self.annotations:\n                # Inline reference to existing annotations and mask them as\n                # they are unnecessary given only the summarized aggregations\n                # are requested.\n                replacements = {\n                    Ref(alias, annotation): annotation\n                    for alias, annotation in self.annotations.items()\n                }\n                self.annotations = {\n                    alias: aggregate.replace_expressions(replacements)\n                    for alias, aggregate in aggregates.items()\n                }\n            else:\n                self.annotations = aggregates\n            self.set_annotation_mask(aggregates)\n\n        empty_set_result = [\n            expression.empty_result_set_value\n            for expression in outer_query.annotation_select.values()\n        ]\n        elide_empty = not any(result is NotImplemented for result in empty_set_result)\n        outer_query.clear_ordering(force=True)\n        outer_query.clear_limits()\n        outer_query.select_for_update = False\n        outer_query.select_related = False\n        compiler = outer_query.get_compiler(using, elide_empty=elide_empty)\n        result = compiler.execute_sql(SINGLE)\n        if result is None:\n            result = empty_set_result\n        else:\n            cols = outer_query.annotation_select.values()\n            converters = compiler.get_converters(cols)\n            rows = compiler.apply_converters((result,), converters)\n            if compiler.has_composite_fields(cols):\n                rows = compiler.composite_fields_to_tuples(rows, cols)\n            result = next(rows)\n\n        return dict(zip(outer_query.annotation_select, result))\n\n    def get_count(self, using):\n        \"\"\"\n        Perform a COUNT() query using the current filter constraints.\n        \"\"\"\n        obj = self.clone()\n        return obj.get_aggregation(using, {\"__count\": Count(\"*\")})[\"__count\"]\n\n    def has_filters(self):\n        return self.where\n\n    def exists(self, limit=True):\n        q = self.clone()\n        if not (q.distinct and q.is_sliced):\n            if q.group_by is True:\n                q.add_fields(\n                    (f.attname for f in self.model._meta.concrete_fields), False\n                )\n                # Disable GROUP BY aliases to avoid orphaning references to the\n                # SELECT clause which is about to be cleared.\n                q.set_group_by(allow_aliases=False)\n            q.clear_select_clause()\n        if q.combined_queries and q.combinator == \"union\":\n            q.combined_queries = tuple(\n                combined_query.exists(limit=False)\n                for combined_query in q.combined_queries\n            )\n        q.clear_ordering(force=True)\n        if limit is True:\n            q.set_limits(high=1)\n        q.add_annotation(Value(1), \"a\")\n        return q\n\n    def has_results(self, using):\n        q = self.exists()\n        compiler = q.get_compiler(using=using)\n        return compiler.has_results()\n\n    def explain(self, using, format=None, **options):\n        q = self.clone()\n        loopIteratorE = __import__(\"builtins\").iter(options)\n        while True:\n            try:\n                option_name = __import__(\"builtins\").next(loopIteratorE)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if (\n                not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)\n                or \"--\" in option_name\n            ):\n                raise ValueError(f\"Invalid option name: {option_name!r}.\")\n        q.explain_info = ExplainInfo(format, options)\n        compiler = q.get_compiler(using=using)\n        return \"\\n\".join(compiler.explain_query())\n\n    def combine(self, rhs, connector):\n        \"\"\"\n        Merge the 'rhs' query into the current one (with any 'rhs' effects\n        being applied *after* (that is, \"to the right of\") anything in the\n        current query. 'rhs' is not modified during a call to this function.\n\n        The 'connector' parameter describes how to connect filters from the\n        'rhs' query.\n        \"\"\"\n        if self.model != rhs.model:\n            raise TypeError(\"Cannot combine queries on two different base models.\")\n        if self.is_sliced:\n            raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n        if self.distinct != rhs.distinct:\n            raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n        if self.distinct_fields != rhs.distinct_fields:\n            raise TypeError(\"Cannot combine queries with different distinct fields.\")\n\n        # If lhs and rhs shares the same alias prefix, it is possible to have\n        # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up\n        # as T4 -> T6 while combining two querysets. To prevent this, change an\n        # alias prefix of the rhs and update current aliases accordingly,\n        # except if the alias is the base table since it must be present in the\n        # query on both sides.\n        initial_alias = self.get_initial_alias()\n        rhs = rhs.clone()\n        rhs.bump_prefix(self, exclude={initial_alias})\n\n        # Work out how to relabel the rhs aliases, if necessary.\n        change_map = {}\n        conjunction = connector == AND\n\n        # Determine which existing joins can be reused. When combining the\n        # query with AND we must recreate all joins for m2m filters. When\n        # combining with OR we can reuse joins. The reason is that in AND\n        # case a single row can't fulfill a condition like:\n        #     revrel__col=1 & revrel__col=2\n        # But, there might be two different related rows matching this\n        # condition. In OR case a single True is enough, so single row is\n        # enough, too.\n        #\n        # Note that we will be creating duplicate joins for non-m2m joins in\n        # the AND case. The results will be correct but this creates too many\n        # joins. This is something that could be fixed later on.\n        reuse = set() if conjunction else set(self.alias_map)\n        joinpromoter = JoinPromoter(connector, 2, False)\n        joinpromoter.add_votes(\n            j for j in self.alias_map if self.alias_map[j].join_type == INNER\n        )\n        rhs_votes = set()\n        # Now, add the joins from rhs query into the new query (skipping base\n        # table).\n        rhs_tables = list(rhs.alias_map)[1:]\n        for alias in rhs_tables:\n            join = rhs.alias_map[alias]\n            # If the left side of the join was already relabeled, use the\n            # updated alias.\n            join = join.relabeled_clone(change_map)\n            new_alias = self.join(join, reuse=reuse)\n            if join.join_type == INNER:\n                rhs_votes.add(new_alias)\n            # We can't reuse the same join again in the query. If we have two\n            # distinct joins for the same connection in rhs query, then the\n            # combined query must have two joins, too.\n            reuse.discard(new_alias)\n            if alias != new_alias:\n                change_map[alias] = new_alias\n            if not rhs.alias_refcount[alias]:\n                # The alias was unused in the rhs query. Unref it so that it\n                # will be unused in the new query, too. We have to add and\n                # unref the alias so that join promotion has information of\n                # the join type for the unused alias.\n                self.unref_alias(new_alias)\n        joinpromoter.add_votes(rhs_votes)\n        joinpromoter.update_join_types(self)\n\n        # Combine subqueries aliases to ensure aliases relabelling properly\n        # handle subqueries when combining where and select clauses.\n        self.subq_aliases |= rhs.subq_aliases\n\n        # Now relabel a copy of the rhs where-clause and add it to the current\n        # one.\n        w = rhs.where.clone()\n        w.relabel_aliases(change_map)\n        self.where.add(w, connector)\n\n        # Selection columns and extra extensions are those provided by 'rhs'.\n        if rhs.select:\n            self.set_select([col.relabeled_clone(change_map) for col in rhs.select])\n        else:\n            self.select = ()\n\n        if connector == OR:\n            # It would be nice to be able to handle this, but the queries don't\n            # really make sense (or return consistent value sets). Not worth\n            # the extra complexity when you can write a real query instead.\n            if self.extra and rhs.extra:\n                raise ValueError(\n                    \"When merging querysets using 'or', you cannot have \"\n                    \"extra(select=...) on both sides.\"\n                )\n        self.extra.update(rhs.extra)\n        extra_select_mask = set()\n        if self.extra_select_mask is not None:\n            extra_select_mask.update(self.extra_select_mask)\n        if rhs.extra_select_mask is not None:\n            extra_select_mask.update(rhs.extra_select_mask)\n        if extra_select_mask:\n            self.set_extra_mask(extra_select_mask)\n        self.extra_tables += rhs.extra_tables\n\n        # Ordering uses the 'rhs' ordering, unless it has none, in which case\n        # the current ordering is used.\n        self.order_by = rhs.order_by or self.order_by\n        self.extra_order_by = rhs.extra_order_by or self.extra_order_by\n\n    def _get_defer_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # All concrete fields and related objects that are not part of the\n        # defer mask must be included. If a relational field is encountered it\n        # gets added to the mask for it be considered if `select_related` and\n        # the cycle continues by recursively calling this function.\n        for field in opts.concrete_fields + opts.related_objects:\n            field_mask = mask.pop(field.name, None)\n            field_att_mask = None\n            if field_attname := getattr(field, \"attname\", None):\n                field_att_mask = mask.pop(field_attname, None)\n            if field_mask is None and field_att_mask is None:\n                select_mask.setdefault(field, {})\n            elif field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                # Virtual fields such as many-to-many and generic foreign keys\n                # cannot be effectively deferred. Historically, they were\n                # allowed to be passed to QuerySet.defer(). Ignore such field\n                # references until a layer of validation at mask alteration\n                # time is eventually implemented.\n                if field.many_to_many:\n                    continue\n                field_select_mask = select_mask.setdefault(field, {})\n                related_model = field.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        # Remaining defer entries must be references to filtered relations\n        # otherwise they are surfaced as missing field errors.\n        loopIteratorF = __import__(\"builtins\").iter(mask.items())\n        while True:\n            try:\n                field_name, field_mask = __import__(\"builtins\").next(loopIteratorF)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if filtered_relation := self._filtered_relations.get(field_name):\n                relation = opts.get_field(filtered_relation.relation_name)\n                field_select_mask = select_mask.setdefault((field_name, relation), {})\n                related_model = relation.related_model._meta.concrete_model\n                self._get_defer_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n            else:\n                opts.get_field(field_name)\n        return select_mask\n\n    def _get_only_select_mask(self, opts, mask, select_mask=None):\n        if select_mask is None:\n            select_mask = {}\n        select_mask[opts.pk] = {}\n        # Only include fields mentioned in the mask.\n        loopIteratorG = __import__(\"builtins\").iter(mask.items())\n        while True:\n            try:\n                field_name, field_mask = __import__(\"builtins\").next(loopIteratorG)\n            except __import__(\"builtins\").StopIteration:\n                break\n            field = opts.get_field(field_name)\n            field_select_mask = select_mask.setdefault(field, {})\n            if field_mask:\n                if not field.is_relation:\n                    raise FieldError(next(iter(field_mask)))\n                related_model = field.remote_field.model._meta.concrete_model\n                self._get_only_select_mask(\n                    related_model._meta, field_mask, field_select_mask\n                )\n        return select_mask\n\n    def get_select_mask(self):\n        \"\"\"\n        Convert the self.deferred_loading data structure to an alternate data\n        structure, describing the field that *will* be loaded. This is used to\n        compute the columns to select from the database and also by the\n        QuerySet class to work out which fields are being initialized on each\n        model. Models that have all their fields included aren't mentioned in\n        the result, only those that have field restrictions in place.\n        \"\"\"\n        field_names, defer = self.deferred_loading\n        if not field_names:\n            return {}\n        mask = {}\n        loopIteratorAQ = __import__(\"builtins\").iter(field_names)\n        while True:\n            try:\n                field_name = __import__(\"builtins\").next(loopIteratorAQ)\n            except __import__(\"builtins\").StopIteration:\n                break\n            part_mask = mask\n            loopIteratorH = __import__(\"builtins\").iter(field_name.split(LOOKUP_SEP))\n            while True:\n                try:\n                    part = __import__(\"builtins\").next(loopIteratorH)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                part_mask = part_mask.setdefault(part, {})\n        opts = self.get_meta()\n        if defer:\n            return self._get_defer_select_mask(opts, mask)\n        return self._get_only_select_mask(opts, mask)\n\n    def table_alias(self, table_name, create=False, filtered_relation=None):\n        \"\"\"\n        Return a table alias for the given table_name and whether this is a\n        new alias or not.\n\n        If 'create' is true, a new alias is always created. Otherwise, the\n        most recently created alias for the table (if one exists) is reused.\n        \"\"\"\n        alias_list = self.table_map.get(table_name)\n        if not create and alias_list:\n            alias = alias_list[0]\n            self.alias_refcount[alias] += 1\n            return alias, False\n\n        # Create a new alias for this table.\n        if alias_list:\n            alias = \"%s%d\" % (self.alias_prefix, len(self.alias_map) + 1)\n            alias_list.append(alias)\n        else:\n            # The first occurrence of a table uses the table name directly.\n            alias = (\n                filtered_relation.alias if filtered_relation is not None else table_name\n            )\n            self.table_map[table_name] = [alias]\n        self.alias_refcount[alias] = 1\n        return alias, True\n\n    def ref_alias(self, alias):\n        \"\"\"Increases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] += 1\n\n    def unref_alias(self, alias, amount=1):\n        \"\"\"Decreases the reference count for this alias.\"\"\"\n        self.alias_refcount[alias] -= amount\n\n    def promote_joins(self, aliases):\n        \"\"\"\n        Promote recursively the join type of given aliases and its children to\n        an outer join. If 'unconditional' is False, only promote the join if\n        it is nullable or the parent join is an outer join.\n\n        The children promotion is done to avoid join chains that contain a\n        LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b\n        is promoted, then we must also promote b->c automatically, or otherwise\n        the promotion of a->b doesn't actually change anything in the query\n        results.\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type is None:\n                # This is the base table (first FROM entry) - this table\n                # isn't really joined at all in the query, so we should not\n                # alter its join type.\n                continue\n            # Only the first alias (skipped above) should have None join_type\n            assert self.alias_map[alias].join_type is not None\n            parent_alias = self.alias_map[alias].parent_alias\n            parent_louter = (\n                parent_alias and self.alias_map[parent_alias].join_type == LOUTER\n            )\n            already_louter = self.alias_map[alias].join_type == LOUTER\n            if (self.alias_map[alias].nullable or parent_louter) and not already_louter:\n                self.alias_map[alias] = self.alias_map[alias].promote()\n                # Join type of 'alias' changed, so re-examine all aliases that\n                # refer to this one.\n                aliases.extend(\n                    join\n                    for join in self.alias_map\n                    if self.alias_map[join].parent_alias == alias\n                    and join not in aliases\n                )\n\n    def demote_joins(self, aliases):\n        \"\"\"\n        Change join type from LOUTER to INNER for all joins in aliases.\n\n        Similarly to promote_joins(), this method must ensure no join chains\n        containing first an outer, then an inner join are generated. If we\n        are demoting b->c join in chain a LOUTER b LOUTER c then we must\n        demote a->b automatically, or otherwise the demotion of b->c doesn't\n        actually change anything in the query results. .\n        \"\"\"\n        aliases = list(aliases)\n        while aliases:\n            alias = aliases.pop(0)\n            if self.alias_map[alias].join_type == LOUTER:\n                self.alias_map[alias] = self.alias_map[alias].demote()\n                parent_alias = self.alias_map[alias].parent_alias\n                if self.alias_map[parent_alias].join_type == INNER:\n                    aliases.append(parent_alias)\n\n    def reset_refcounts(self, to_counts):\n        \"\"\"\n        Reset reference counts for aliases so that they match the value passed\n        in `to_counts`.\n        \"\"\"\n        loopIteratorI = __import__(\"builtins\").iter(self.alias_refcount.copy().items())\n        while True:\n            try:\n                alias, cur_refcount = __import__(\"builtins\").next(loopIteratorI)\n            except __import__(\"builtins\").StopIteration:\n                break\n            unref_amount = cur_refcount - to_counts.get(alias, 0)\n            self.unref_alias(alias, unref_amount)\n\n    def change_aliases(self, change_map):\n        \"\"\"\n        Change the aliases in change_map (which maps old-alias -> new-alias),\n        relabelling any references to them in select columns and the where\n        clause.\n        \"\"\"\n        if not change_map:\n            return self\n        # If keys and values of change_map were to intersect, an alias might be\n        # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending\n        # on their order in change_map.\n        assert set(change_map).isdisjoint(change_map.values())\n\n        # 1. Update references in \"select\" (normal columns plus aliases),\n        # \"group by\" and \"where\".\n        self.where.relabel_aliases(change_map)\n        if isinstance(self.group_by, tuple):\n            self.group_by = tuple(\n                [col.relabeled_clone(change_map) for col in self.group_by]\n            )\n        self.select = tuple([col.relabeled_clone(change_map) for col in self.select])\n        self.annotations = self.annotations and {\n            key: col.relabeled_clone(change_map)\n            for key, col in self.annotations.items()\n        }\n\n        # 2. Rename the alias in the internal table/alias datastructures.\n        loopIteratorAR = __import__(\"builtins\").iter(change_map.items())\n        while True:\n            try:\n                old_alias, new_alias = __import__(\"builtins\").next(loopIteratorAR)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if old_alias not in self.alias_map:\n                continue\n            alias_data = self.alias_map[old_alias].relabeled_clone(change_map)\n            self.alias_map[new_alias] = alias_data\n            self.alias_refcount[new_alias] = self.alias_refcount[old_alias]\n            del self.alias_refcount[old_alias]\n            del self.alias_map[old_alias]\n\n            table_aliases = self.table_map[alias_data.table_name]\n            loopIteratorJ = __import__(\"builtins\").iter(enumerate(table_aliases))\n            while True:\n                try:\n                    pos, alias = __import__(\"builtins\").next(loopIteratorJ)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                if alias == old_alias:\n                    table_aliases[pos] = new_alias\n                    break\n\n        # 3. Rename the direct external aliases and the ones of combined\n        # queries (union, intersection, difference).\n        self.external_aliases = {\n            # Table is aliased or it's being changed and thus is aliased.\n            change_map.get(alias, alias): (aliased or alias in change_map)\n            for alias, aliased in self.external_aliases.items()\n        }\n        loopIteratorK = __import__(\"builtins\").iter(self.combined_queries)\n        while True:\n            try:\n                combined_query = __import__(\"builtins\").next(loopIteratorK)\n            except __import__(\"builtins\").StopIteration:\n                break\n            external_change_map = {\n                alias: aliased\n                for alias, aliased in change_map.items()\n                if alias in combined_query.external_aliases\n            }\n            combined_query.change_aliases(external_change_map)\n\n    def bump_prefix(self, other_query, exclude=None):\n        \"\"\"\n        Change the alias prefix to the next letter in the alphabet in a way\n        that the other query's aliases and this query's aliases will not\n        conflict. Even tables that previously had no alias will get an alias\n        after this call. To prevent changing aliases use the exclude parameter.\n        \"\"\"\n\n        def prefix_gen():\n            \"\"\"\n            Generate a sequence of characters in alphabetical order:\n                -> 'A', 'B', 'C', ...\n\n            When the alphabet is finished, the sequence will continue with the\n            Cartesian product:\n                -> 'AA', 'AB', 'AC', ...\n            \"\"\"\n            alphabet = ascii_uppercase\n            prefix = chr(ord(self.alias_prefix) + 1)\n            yield prefix\n            loopIteratorAS = __import__(\"builtins\").iter(count(1))\n            while True:\n                try:\n                    n = __import__(\"builtins\").next(loopIteratorAS)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet\n                loopIteratorL = __import__(\"builtins\").iter(product(seq, repeat=n))\n                while True:\n                    try:\n                        s = __import__(\"builtins\").next(loopIteratorL)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    yield \"\".join(s)\n                prefix = None\n\n        if self.alias_prefix != other_query.alias_prefix:\n            # No clashes between self and outer query should be possible.\n            return\n\n        # Explicitly avoid infinite loop. The constant divider is based on how\n        # much depth recursive subquery references add to the stack. This value\n        # might need to be adjusted when adding or removing function calls from\n        # the code path in charge of performing these operations.\n        local_recursion_limit = sys.getrecursionlimit() // 16\n        loopIteratorM = __import__(\"builtins\").iter(enumerate(prefix_gen()))\n        while True:\n            try:\n                pos, prefix = __import__(\"builtins\").next(loopIteratorM)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if prefix not in self.subq_aliases:\n                self.alias_prefix = prefix\n                break\n            if pos > local_recursion_limit:\n                raise RecursionError(\n                    \"Maximum recursion depth exceeded: too many subqueries.\"\n                )\n        self.subq_aliases = self.subq_aliases.union([self.alias_prefix])\n        other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases)\n        if exclude is None:\n            exclude = {}\n        self.change_aliases(\n            {\n                alias: \"%s%d\" % (self.alias_prefix, pos)\n                for pos, alias in enumerate(self.alias_map)\n                if alias not in exclude\n            }\n        )\n\n    def get_initial_alias(self):\n        \"\"\"\n        Return the first alias for this query, after increasing its reference\n        count.\n        \"\"\"\n        if self.alias_map:\n            alias = self.base_table\n            self.ref_alias(alias)\n        elif self.model:\n            alias = self.join(self.base_table_class(self.get_meta().db_table, None))\n        else:\n            alias = None\n        return alias\n\n    def count_active_tables(self):\n        \"\"\"\n        Return the number of tables in this query with a non-zero reference\n        count. After execution, the reference counts are zeroed, so tables\n        added in compiler will not be seen by this method.\n        \"\"\"\n        return len([1 for count in self.alias_refcount.values() if count])\n\n    def join(self, join, reuse=None):\n        \"\"\"\n        Return an alias for the 'join', either reusing an existing alias for\n        that join or creating a new one. 'join' is either a base_table_class or\n        join_class.\n\n        The 'reuse' parameter can be either None which means all joins are\n        reusable, or it can be a set containing the aliases that can be reused.\n\n        A join is always created as LOUTER if the lhs alias is LOUTER to make\n        sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new\n        joins are created as LOUTER if the join is nullable.\n        \"\"\"\n        reuse_aliases = [\n            a\n            for a, j in self.alias_map.items()\n            if (reuse is None or a in reuse) and j == join\n        ]\n        if reuse_aliases:\n            if join.table_alias in reuse_aliases:\n                reuse_alias = join.table_alias\n            else:\n                # Reuse the most recent alias of the joined table\n                # (a many-to-many relation may be joined multiple times).\n                reuse_alias = reuse_aliases[-1]\n            self.ref_alias(reuse_alias)\n            return reuse_alias\n\n        # No reuse is possible, so we need a new alias.\n        alias, _ = self.table_alias(\n            join.table_name, create=True, filtered_relation=join.filtered_relation\n        )\n        if join.join_type:\n            if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:\n                join_type = LOUTER\n            else:\n                join_type = INNER\n            join.join_type = join_type\n        join.table_alias = alias\n        self.alias_map[alias] = join\n        if filtered_relation := join.filtered_relation:\n            resolve_reuse = reuse\n            if resolve_reuse is not None:\n                resolve_reuse = set(reuse) | {alias}\n            joins_len = len(self.alias_map)\n            join.filtered_relation = filtered_relation.resolve_expression(\n                self, reuse=resolve_reuse\n            )\n            # Some joins were during expression resolving, they must be present\n            # before the one we just added.\n            if joins_len < len(self.alias_map):\n                self.alias_map[alias] = self.alias_map.pop(alias)\n        return alias\n\n    def join_parent_model(self, opts, model, alias, seen):\n        \"\"\"\n        Make sure the given 'model' is joined in the query. If 'model' isn't\n        a parent of 'opts' or if it is None this method is a no-op.\n\n        The 'alias' is the root alias for starting the join, 'seen' is a dict\n        of model -> alias of existing joins. It must also contain a mapping\n        of None -> some alias. This will be returned in the no-op case.\n        \"\"\"\n        if model in seen:\n            return seen[model]\n        chain = opts.get_base_chain(model)\n        if not chain:\n            return alias\n        curr_opts = opts\n        for int_model in chain:\n            if int_model in seen:\n                curr_opts = int_model._meta\n                alias = seen[int_model]\n                continue\n            # Proxy model have elements in base chain\n            # with no parents, assign the new options\n            # object and skip to the next base in that\n            # case\n            if not curr_opts.parents[int_model]:\n                curr_opts = int_model._meta\n                continue\n            link_field = curr_opts.get_ancestor_link(int_model)\n            join_info = self.setup_joins([link_field.name], curr_opts, alias)\n            curr_opts = int_model._meta\n            alias = seen[int_model] = join_info.joins[-1]\n        return alias or seen[None]\n\n    def check_alias(self, alias):\n        # RemovedInDjango70Warning: When the deprecation ends, remove.\n        if \"%\" in alias:\n            warnings.warn(\n                \"Using percent signs in a column alias is deprecated.\",\n                category=RemovedInDjango70Warning,\n                skip_file_prefixes=django_file_prefixes(),\n            )\n        if FORBIDDEN_ALIAS_PATTERN.search(alias):\n            raise ValueError(\n                \"Column aliases cannot contain whitespace characters, hashes, \"\n                # RemovedInDjango70Warning: When the deprecation ends, replace\n                # with:\n                # \"control characters, quotation marks, semicolons, percent \"\n                # \"signs, or SQL comments.\"\n                \"control characters, quotation marks, semicolons, or SQL comments.\"\n            )\n\n    def add_annotation(self, annotation, alias, select=True):\n        \"\"\"Add a single annotation expression to the Query.\"\"\"\n        self.check_alias(alias)\n        annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None)\n        if select:\n            self.append_annotation_mask([alias])\n        else:\n            self.set_annotation_mask(set(self.annotation_select).difference({alias}))\n        self.annotations[alias] = annotation\n        if select and self.selected:\n            self.selected[alias] = alias\n\n    @property\n    def _subquery_fields_len(self):\n        if not self.has_select_fields or not self.select:\n            return len(self.model._meta.pk_fields)\n        return len(self.select) + sum(\n            len(expr.targets) - 1 for expr in self.select if isinstance(expr, ColPairs)\n        )\n\n    def resolve_expression(self, query, *args, **kwargs):\n        clone = self.clone()\n        # Subqueries need to use a different set of aliases than the outer\n        # query.\n        clone.bump_prefix(query)\n        clone.subquery = True\n        clone.where.resolve_expression(query, *args, **kwargs)\n        # Resolve combined queries.\n        if clone.combinator:\n            clone.combined_queries = tuple(\n                [\n                    combined_query.resolve_expression(query, *args, **kwargs)\n                    for combined_query in clone.combined_queries\n                ]\n            )\n        loopIteratorN = __import__(\"builtins\").iter(clone.annotations.items())\n        while True:\n            try:\n                key, value = __import__(\"builtins\").next(loopIteratorN)\n            except __import__(\"builtins\").StopIteration:\n                break\n            resolved = value.resolve_expression(query, *args, **kwargs)\n            if hasattr(resolved, \"external_aliases\"):\n                resolved.external_aliases.update(clone.external_aliases)\n            clone.annotations[key] = resolved\n        # Outer query's aliases are considered external.\n        loopIteratorO = __import__(\"builtins\").iter(query.alias_map.items())\n        while True:\n            try:\n                alias, table = __import__(\"builtins\").next(loopIteratorO)\n            except __import__(\"builtins\").StopIteration:\n                break\n            clone.external_aliases[alias] = (\n                isinstance(table, Join)\n                and table.join_field.related_model._meta.db_table != alias\n            ) or (\n                isinstance(table, BaseTable) and table.table_name != table.table_alias\n            )\n        return clone\n\n    def get_external_cols(self):\n        exprs = chain(self.annotations.values(), self.where.children)\n        return [\n            col\n            for col in self._gen_cols(exprs, include_external=True)\n            if col.alias in self.external_aliases\n        ]\n\n    def get_group_by_cols(self, wrapper=None):\n        # If wrapper is referenced by an alias for an explicit GROUP BY through\n        # values() a reference to this expression and not the self must be\n        # returned to ensure external column references are not grouped against\n        # as well.\n        external_cols = self.get_external_cols()\n        if any(col.possibly_multivalued for col in external_cols):\n            return [wrapper or self]\n        return external_cols\n\n    def as_sql(self, compiler, connection):\n        # Some backends (e.g. Oracle) raise an error when a subquery contains\n        # unnecessary ORDER BY clause.\n        if (\n            self.subquery\n            and not connection.features.ignores_unnecessary_order_by_in_subqueries\n        ):\n            self.clear_ordering(force=False)\n            loopIteratorP = __import__(\"builtins\").iter(self.combined_queries)\n            while True:\n                try:\n                    query = __import__(\"builtins\").next(loopIteratorP)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                query.clear_ordering(force=False)\n        sql, params = self.get_compiler(connection=connection).as_sql()\n        if self.subquery:\n            sql = \"(%s)\" % sql\n        return sql, params\n\n    def resolve_lookup_value(self, value, can_reuse, allow_joins, summarize=False):\n        if hasattr(value, \"resolve_expression\"):\n            value = value.resolve_expression(\n                self,\n                reuse=can_reuse,\n                allow_joins=allow_joins,\n                summarize=summarize,\n            )\n        elif isinstance(value, (list, tuple)):\n            # The items of the iterable may be expressions and therefore need\n            # to be resolved independently.\n            values = (\n                self.resolve_lookup_value(sub_value, can_reuse, allow_joins, summarize)\n                for sub_value in value\n            )\n            type_ = type(value)\n            if hasattr(type_, \"_make\"):  # namedtuple\n                return type_(*values)\n            return type_(values)\n        return value\n\n    def solve_lookup_type(self, lookup, summarize=False):\n        \"\"\"\n        Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').\n        \"\"\"\n        lookup_splitted = lookup.split(LOOKUP_SEP)\n        if self.annotations:\n            annotation, expression_lookups = refs_expression(\n                lookup_splitted, self.annotations\n            )\n            if annotation:\n                expression = self.annotations[annotation]\n                if summarize:\n                    expression = Ref(annotation, expression)\n                return expression_lookups, (), expression\n        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())\n        field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)]\n        if len(lookup_parts) > 1 and not field_parts:\n            raise FieldError(\n                'Invalid lookup \"%s\" for model %s\".'\n                % (lookup, self.get_meta().model.__name__)\n            )\n        return lookup_parts, field_parts, False\n\n    def check_query_object_type(self, value, opts, field):\n        \"\"\"\n        Check whether the object passed while querying is of the correct type.\n        If not, raise a ValueError specifying the wrong object.\n        \"\"\"\n        if hasattr(value, \"_meta\"):\n            if not check_rel_lookup_compatibility(value._meta.model, opts, field):\n                raise ValueError(\n                    'Cannot query \"%s\": Must be \"%s\" instance.'\n                    % (value, opts.object_name)\n                )\n\n    def check_related_objects(self, field, value, opts):\n        \"\"\"Check the type of object passed to query relations.\"\"\"\n        if field.is_relation:\n            # Check that the field and the queryset use the same model in a\n            # query like .filter(author=Author.objects.all()). For example, the\n            # opts would be Author's (from the author field) and value.model\n            # would be Author.objects.all() queryset's .model (Author also).\n            # The field is the related field on the lhs side.\n            if (\n                isinstance(value, Query)\n                and not value.has_select_fields\n                and not check_rel_lookup_compatibility(value.model, opts, field)\n            ):\n                raise ValueError(\n                    'Cannot use QuerySet for \"%s\": Use a QuerySet for \"%s\".'\n                    % (value.model._meta.object_name, opts.object_name)\n                )\n            elif hasattr(value, \"_meta\"):\n                self.check_query_object_type(value, opts, field)\n            elif hasattr(value, \"__iter__\"):\n                loopIteratorQ = __import__(\"builtins\").iter(value)\n                while True:\n                    try:\n                        v = __import__(\"builtins\").next(loopIteratorQ)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    self.check_query_object_type(v, opts, field)\n\n    def check_filterable(self, expression):\n        \"\"\"Raise an error if expression cannot be used in a WHERE clause.\"\"\"\n        if hasattr(expression, \"resolve_expression\") and not getattr(\n            expression, \"filterable\", True\n        ):\n            raise NotSupportedError(\n                expression.__class__.__name__ + \" is disallowed in the filter \"\n                \"clause.\"\n            )\n        if hasattr(expression, \"get_source_expressions\"):\n            loopIteratorR = __import__(\"builtins\").iter(expression.get_source_expressions())\n            while True:\n                try:\n                    expr = __import__(\"builtins\").next(loopIteratorR)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                self.check_filterable(expr)\n\n    def build_lookup(self, lookups, lhs, rhs):\n        \"\"\"\n        Try to extract transforms and lookup from given lhs.\n\n        The lhs value is something that works like SQLExpression.\n        The rhs value is what the lookup is going to compare against.\n        The lookups is a list of names to extract using get_lookup()\n        and get_transform().\n        \"\"\"\n        # __exact is the default lookup if one isn't given.\n        *transforms, lookup_name = lookups or [\"exact\"]\n        loopIteratorS = __import__(\"builtins\").iter(transforms)\n        while True:\n            try:\n                name = __import__(\"builtins\").next(loopIteratorS)\n            except __import__(\"builtins\").StopIteration:\n                break\n            lhs = self.try_transform(lhs, name, lookups)\n        # First try get_lookup() so that the lookup takes precedence if the lhs\n        # supports both transform and lookup for the name.\n        lookup_class = lhs.get_lookup(lookup_name)\n        if not lookup_class:\n            # A lookup wasn't found. Try to interpret the name as a transform\n            # and do an Exact lookup against it.\n            lhs = self.try_transform(lhs, lookup_name)\n            lookup_name = \"exact\"\n            lookup_class = lhs.get_lookup(lookup_name)\n            if not lookup_class:\n                return\n\n        lookup = lookup_class(lhs, rhs)\n        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all\n        # uses of None as a query value unless the lookup supports it.\n        if lookup.rhs is None and not lookup.can_use_none_as_rhs:\n            if lookup_name not in (\"exact\", \"iexact\"):\n                raise ValueError(\"Cannot use None as a query value\")\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        # For Oracle '' is equivalent to null. The check must be done at this\n        # stage because join promotion can't be done in the compiler. Using\n        # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.\n        # A similar thing is done in is_nullable(), too.\n        if (\n            lookup_name in (\"exact\", \"iexact\")\n            and lookup.rhs == \"\"\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        ):\n            return lhs.get_lookup(\"isnull\")(lhs, True)\n\n        return lookup\n\n    def try_transform(self, lhs, name, lookups=None):\n        \"\"\"\n        Helper method for build_lookup(). Try to fetch and initialize\n        a transform for name parameter from lhs.\n        \"\"\"\n        transform_class = lhs.get_transform(name)\n        if transform_class:\n            return transform_class(lhs)\n        else:\n            output_field = lhs.output_field.__class__\n            suggested_lookups = difflib.get_close_matches(\n                name, lhs.output_field.get_lookups()\n            )\n            if suggested_lookups:\n                suggestion = \", perhaps you meant %s?\" % \" or \".join(suggested_lookups)\n            else:\n                suggestion = \".\"\n            if lookups is not None:\n                name_index = lookups.index(name)\n                unsupported_lookup = LOOKUP_SEP.join(lookups[name_index:])\n            else:\n                unsupported_lookup = name\n            raise FieldError(\n                \"Unsupported lookup '%s' for %s or join on the field not \"\n                \"permitted%s\" % (unsupported_lookup, output_field.__name__, suggestion)\n            )\n\n    def build_filter(\n        self,\n        filter_expr,\n        branch_negated=False,\n        current_negated=False,\n        can_reuse=None,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"\n        Build a WhereNode for a single filter clause but don't add it\n        to this Query. Query.add_q() will then add this filter to the where\n        Node.\n\n        The 'branch_negated' tells us if the current branch contains any\n        negations. This will be used to determine if subqueries are needed.\n\n        The 'current_negated' is used to determine if the current filter is\n        negated or not and this will be used to determine if IS NULL filtering\n        is needed.\n\n        The difference between current_negated and branch_negated is that\n        branch_negated is set on first negation, but current_negated is\n        flipped for each negation.\n\n        Note that add_filter will not do any negating itself, that is done\n        upper in the code by add_q().\n\n        The 'can_reuse' is a set of reusable joins for multijoins.\n\n        The method will create a filter clause that can be added to the current\n        query. However, if the filter isn't added to the query then the caller\n        is responsible for unreffing the joins used.\n        \"\"\"\n        if isinstance(filter_expr, dict):\n            raise FieldError(\"Cannot parse keyword query as dict\")\n        if isinstance(filter_expr, Q):\n            return self._add_q(\n                filter_expr,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                used_aliases=can_reuse,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n        if hasattr(filter_expr, \"resolve_expression\"):\n            if not getattr(filter_expr, \"conditional\", False):\n                raise TypeError(\"Cannot filter against a non-conditional expression.\")\n            condition = filter_expr.resolve_expression(\n                self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize\n            )\n            if not isinstance(condition, Lookup):\n                condition = self.build_lookup([\"exact\"], condition, True)\n            return WhereNode([condition], connector=AND), []\n        arg, value = filter_expr\n        if not arg:\n            raise FieldError(\"Cannot parse keyword query %r\" % arg)\n        lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize)\n\n        if check_filterable:\n            self.check_filterable(reffed_expression)\n\n        if not allow_joins and len(parts) > 1:\n            raise FieldError(\"Joined field references are not permitted in this query\")\n\n        pre_joins = self.alias_refcount.copy()\n        value = self.resolve_lookup_value(value, can_reuse, allow_joins, summarize)\n        used_joins = {\n            k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)\n        }\n\n        if check_filterable:\n            self.check_filterable(value)\n\n        if reffed_expression:\n            condition = self.build_lookup(lookups, reffed_expression, value)\n            return WhereNode([condition], connector=AND), []\n\n        opts = self.get_meta()\n        alias = self.get_initial_alias()\n        allow_many = not branch_negated or not split_subq\n\n        try:\n            join_info = self.setup_joins(\n                parts,\n                opts,\n                alias,\n                can_reuse=can_reuse,\n                allow_many=allow_many,\n            )\n\n            # Prevent iterator from being consumed by check_related_objects()\n            if isinstance(value, Iterator):\n                value = list(value)\n            self.check_related_objects(join_info.final_field, value, join_info.opts)\n\n            # split_exclude() needs to know which joins were generated for the\n            # lookup parts\n            self._lookup_joins = join_info.joins\n        except MultiJoin as e:\n            return self.split_exclude(filter_expr, can_reuse, e.names_with_path)\n\n        # Update used_joins before trimming since they are reused to determine\n        # which joins could be later promoted to INNER.\n        used_joins.update(join_info.joins)\n        targets, alias, join_list = self.trim_joins(\n            join_info.targets, join_info.joins, join_info.path\n        )\n        if can_reuse is not None:\n            can_reuse.update(join_list)\n\n        if join_info.final_field.is_relation:\n            if len(targets) == 1:\n                col = self._get_col(targets[0], join_info.final_field, alias)\n            else:\n                col = ColPairs(alias, targets, join_info.targets, join_info.final_field)\n        else:\n            col = self._get_col(targets[0], join_info.final_field, alias)\n\n        condition = self.build_lookup(lookups, col, value)\n        lookup_type = condition.lookup_name\n        clause = WhereNode([condition], connector=AND)\n\n        require_outer = (\n            lookup_type == \"isnull\" and condition.rhs is True and not current_negated\n        )\n        if (\n            current_negated\n            and (lookup_type != \"isnull\" or condition.rhs is False)\n            and condition.rhs is not None\n        ):\n            require_outer = True\n            if lookup_type != \"isnull\":\n                # The condition added here will be SQL like this:\n                # NOT (col IS NOT NULL), where the first NOT is added in\n                # upper layers of code. The reason for addition is that if col\n                # is null, then col != someval will result in SQL \"unknown\"\n                # which isn't the same as in Python. The Python None handling\n                # is wanted, and it can be gotten by\n                # (col IS NULL OR col != someval)\n                #   <=>\n                # NOT (col IS NOT NULL AND col = someval).\n                if (\n                    self.is_nullable(targets[0])\n                    or self.alias_map[join_list[-1]].join_type == LOUTER\n                ):\n                    lookup_class = targets[0].get_lookup(\"isnull\")\n                    col = self._get_col(targets[0], join_info.targets[0], alias)\n                    # Use OR + IS NULL when RHS `in` values include None.\n                    if (\n                        lookup_type == \"in\"\n                        # Check containers (not strings or bytes).\n                        and isinstance(condition.rhs, Iterable)\n                        and not isinstance(condition.rhs, (str, bytes))\n                        and any(v is None for v in condition.rhs)\n                    ):\n                        clause.add(lookup_class(col, True), OR)\n                    else:\n                        clause.add(lookup_class(col, False), AND)\n                # If someval is a nullable column, someval IS NOT NULL is\n                # added.\n                if isinstance(value, Col) and self.is_nullable(value.target):\n                    lookup_class = value.target.get_lookup(\"isnull\")\n                    clause.add(lookup_class(value, False), AND)\n        return clause, used_joins if not require_outer else ()\n\n    def add_filter(self, filter_lhs, filter_rhs):\n        self.add_q(Q((filter_lhs, filter_rhs)))\n\n    def add_q(self, q_object, reuse_all=False):\n        \"\"\"\n        A preprocessor for the internal _add_q(). Responsible for doing final\n        join promotion.\n        \"\"\"\n        # For join promotion this case is doing an AND for the added q_object\n        # and existing conditions. So, any existing inner join forces the join\n        # type to remain inner. Existing outer joins can however be demoted.\n        # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if\n        # rel_a doesn't produce any rows, then the whole condition must fail.\n        # So, demotion is OK.\n        existing_inner = {\n            a for a in self.alias_map if self.alias_map[a].join_type == INNER\n        }\n        if reuse_all:\n            can_reuse = set(self.alias_map)\n        else:\n            can_reuse = self.used_aliases\n        clause, _ = self._add_q(q_object, can_reuse)\n        if clause:\n            self.where.add(clause, AND)\n        self.demote_joins(existing_inner)\n\n    def build_where(self, filter_expr):\n        return self.build_filter(filter_expr, allow_joins=False)[0]\n\n    def clear_where(self):\n        self.where = WhereNode()\n\n    def _add_q(\n        self,\n        q_object,\n        used_aliases,\n        branch_negated=False,\n        current_negated=False,\n        allow_joins=True,\n        split_subq=True,\n        check_filterable=True,\n        summarize=False,\n        update_join_types=True,\n    ):\n        \"\"\"Add a Q-object to the current filter.\"\"\"\n        connector = q_object.connector\n        current_negated ^= q_object.negated\n        branch_negated = branch_negated or q_object.negated\n        target_clause = WhereNode(connector=connector, negated=q_object.negated)\n        joinpromoter = JoinPromoter(\n            q_object.connector, len(q_object.children), current_negated\n        )\n        loopIteratorT = __import__(\"builtins\").iter(q_object.children)\n        while True:\n            try:\n                child = __import__(\"builtins\").next(loopIteratorT)\n            except __import__(\"builtins\").StopIteration:\n                break\n            child_clause, needed_inner = self.build_filter(\n                child,\n                can_reuse=used_aliases,\n                branch_negated=branch_negated,\n                current_negated=current_negated,\n                allow_joins=allow_joins,\n                split_subq=split_subq,\n                check_filterable=check_filterable,\n                summarize=summarize,\n                update_join_types=update_join_types,\n            )\n            joinpromoter.add_votes(needed_inner)\n            if child_clause:\n                target_clause.add(child_clause, connector)\n        if update_join_types:\n            needed_inner = joinpromoter.update_join_types(self)\n        else:\n            needed_inner = []\n        return target_clause, needed_inner\n\n    def add_filtered_relation(self, filtered_relation, alias):\n        if \".\" in alias:\n            raise ValueError(\n                \"FilteredRelation doesn't support aliases with periods \"\n                \"(got %r).\" % alias\n            )\n        self.check_alias(alias)\n        filtered_relation.alias = alias\n        relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(\n            filtered_relation.relation_name\n        )\n        if relation_lookup_parts:\n            raise ValueError(\n                \"FilteredRelation's relation_name cannot contain lookups \"\n                \"(got %r).\" % filtered_relation.relation_name\n            )\n        loopIteratorAT = __import__(\"builtins\").iter(get_children_from_q(filtered_relation.condition))\n        while True:\n            try:\n                lookup = __import__(\"builtins\").next(loopIteratorAT)\n            except __import__(\"builtins\").StopIteration:\n                break\n            lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)\n            shift = 2 if not lookup_parts else 1\n            lookup_field_path = lookup_field_parts[:-shift]\n            loopIteratorU = __import__(\"builtins\").iter(enumerate(lookup_field_path))\n            while True:\n                try:\n                    idx, lookup_field_part = __import__(\"builtins\").next(loopIteratorU)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                if len(relation_field_parts) > idx:\n                    if relation_field_parts[idx] != lookup_field_part:\n                        raise ValueError(\n                            \"FilteredRelation's condition doesn't support \"\n                            \"relations outside the %r (got %r).\"\n                            % (filtered_relation.relation_name, lookup)\n                        )\n            if len(lookup_field_parts) > len(relation_field_parts) + 1:\n                raise ValueError(\n                    \"FilteredRelation's condition doesn't support nested \"\n                    \"relations deeper than the relation_name (got %r for \"\n                    \"%r).\" % (lookup, filtered_relation.relation_name)\n                )\n        filtered_relation = filtered_relation.clone()\n        filtered_relation.condition = rename_prefix_from_q(\n            filtered_relation.relation_name,\n            alias,\n            filtered_relation.condition,\n        )\n        self._filtered_relations[filtered_relation.alias] = filtered_relation\n\n    def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):\n        \"\"\"\n        Walk the list of names and turns them into PathInfo tuples. A single\n        name in 'names' can generate multiple PathInfos (m2m, for example).\n\n        'names' is the path of names to travel, 'opts' is the model Options we\n        start the name resolving from, 'allow_many' is as for setup_joins().\n        If fail_on_missing is set to True, then a name that can't be resolved\n        will generate a FieldError.\n\n        Return a list of PathInfo tuples. In addition return the final field\n        (the last used join field) and target (which is a field guaranteed to\n        contain the same value as the final field). Finally, return those names\n        that weren't found (which are likely transforms and the final lookup).\n        \"\"\"\n        path, names_with_path = [], []\n        for pos, name in enumerate(names):\n            cur_names_with_path = (name, [])\n            if name == \"pk\" and opts is not None:\n                name = opts.pk.name\n\n            field = None\n            filtered_relation = None\n            try:\n                if opts is None:\n                    raise FieldDoesNotExist\n                field = opts.get_field(name)\n            except FieldDoesNotExist:\n                if name in self.annotations:\n                    field = self.annotations[name].output_field\n                elif name in self._filtered_relations and pos == 0:\n                    filtered_relation = self._filtered_relations[name]\n                    if LOOKUP_SEP in filtered_relation.relation_name:\n                        parts = filtered_relation.relation_name.split(LOOKUP_SEP)\n                        filtered_relation_path, field, _, _ = self.names_to_path(\n                            parts,\n                            opts,\n                            allow_many,\n                            fail_on_missing,\n                        )\n                        path.extend(filtered_relation_path[:-1])\n                    else:\n                        field = opts.get_field(filtered_relation.relation_name)\n            if field is not None:\n                # Fields that contain one-to-many relations with a generic\n                # model (like a GenericForeignKey) cannot generate reverse\n                # relations and therefore cannot be used for reverse querying.\n                if field.is_relation and not field.related_model:\n                    raise FieldError(\n                        \"Field %r does not generate an automatic reverse \"\n                        \"relation and therefore cannot be used for reverse \"\n                        \"querying. If it is a GenericForeignKey, consider \"\n                        \"adding a GenericRelation.\" % name\n                    )\n                try:\n                    model = field.model._meta.concrete_model\n                except AttributeError:\n                    # QuerySet.annotate() may introduce fields that aren't\n                    # attached to a model.\n                    model = None\n            else:\n                # We didn't find the current field, so move position back\n                # one step.\n                pos -= 1\n                if pos == -1 or fail_on_missing:\n                    available = sorted(\n                        [\n                            *get_field_names_from_opts(opts),\n                            *self.annotations,\n                            *self._filtered_relations,\n                        ]\n                    )\n                    raise FieldError(\n                        \"Cannot resolve keyword '%s' into field. \"\n                        \"Choices are: %s\" % (name, \", \".join(available))\n                    )\n                break\n            # Check if we need any joins for concrete inheritance cases (the\n            # field lives in parent, but we are currently in one of its\n            # children)\n            if opts is not None and model is not opts.model:\n                path_to_parent = opts.get_path_to_parent(model)\n                if path_to_parent:\n                    path.extend(path_to_parent)\n                    cur_names_with_path[1].extend(path_to_parent)\n                    opts = path_to_parent[-1].to_opts\n            if hasattr(field, \"path_infos\"):\n                if filtered_relation:\n                    pathinfos = field.get_path_info(filtered_relation)\n                else:\n                    pathinfos = field.path_infos\n                if not allow_many:\n                    loopIteratorV = __import__(\"builtins\").iter(enumerate(pathinfos))\n                    while True:\n                        try:\n                            inner_pos, p = __import__(\"builtins\").next(loopIteratorV)\n                        except __import__(\"builtins\").StopIteration:\n                            break\n                        if p.m2m:\n                            cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1])\n                            names_with_path.append(cur_names_with_path)\n                            raise MultiJoin(pos + 1, names_with_path)\n                last = pathinfos[-1]\n                path.extend(pathinfos)\n                final_field = last.join_field\n                opts = last.to_opts\n                targets = last.target_fields\n                cur_names_with_path[1].extend(pathinfos)\n                names_with_path.append(cur_names_with_path)\n            else:\n                # Local non-relational field.\n                final_field = field\n                targets = (field,)\n                if fail_on_missing and pos + 1 != len(names):\n                    raise FieldError(\n                        \"Cannot resolve keyword %r into field. Join on '%s'\"\n                        \" not permitted.\" % (names[pos + 1], name)\n                    )\n                break\n        return path, final_field, targets, names[pos + 1 :]\n\n    def setup_joins(\n        self,\n        names,\n        opts,\n        alias,\n        can_reuse=None,\n        allow_many=True,\n    ):\n        \"\"\"\n        Compute the necessary table joins for the passage through the fields\n        given in 'names'. 'opts' is the Options class for the current model\n        (which gives the table we are starting from), 'alias' is the alias for\n        the table to start the joining from.\n\n        The 'can_reuse' defines the reverse foreign key joins we can reuse. It\n        can be None in which case all joins are reusable or a set of aliases\n        that can be reused. Note that non-reverse foreign keys are always\n        reusable when using setup_joins().\n\n        If 'allow_many' is False, then any reverse foreign key seen will\n        generate a MultiJoin exception.\n\n        Return the final field involved in the joins, the target field (used\n        for any 'where' constraint), the final 'opts' value, the joins, the\n        field path traveled to generate the joins, and a transform function\n        that takes a field and alias and is equivalent to\n        `field.get_col(alias)` in the simple case but wraps field transforms if\n        they were included in names.\n\n        The target field is the field containing the concrete value. Final\n        field can be something different, for example foreign key pointing to\n        that value. Final field is needed for example in some value\n        conversions (convert 'obj' in fk__id=obj to pk val using the foreign\n        key field for example).\n        \"\"\"\n        joins = [alias]\n        # The transform can't be applied yet, as joins must be trimmed later.\n        # To avoid making every caller of this method look up transforms\n        # directly, compute transforms here and create a partial that converts\n        # fields to the appropriate wrapped version.\n\n        def final_transformer(field, alias):\n            if not self.alias_cols:\n                alias = None\n            return field.get_col(alias)\n\n        # Try resolving all the names as fields first. If there's an error,\n        # treat trailing names as lookups until a field can be resolved.\n        last_field_exception = None\n        for pivot in range(len(names), 0, -1):\n            try:\n                path, final_field, targets, rest = self.names_to_path(\n                    names[:pivot],\n                    opts,\n                    allow_many,\n                    fail_on_missing=True,\n                )\n            except FieldError as exc:\n                if pivot == 1:\n                    # The first item cannot be a lookup, so it's safe\n                    # to raise the field error here.\n                    raise\n                else:\n                    last_field_exception = exc\n            else:\n                # The transforms are the remaining items that couldn't be\n                # resolved into fields.\n                transforms = names[pivot:]\n                break\n        for name in transforms:\n\n            def transform(field, alias, *, name, previous):\n                try:\n                    wrapped = previous(field, alias)\n                    return self.try_transform(wrapped, name)\n                except FieldError:\n                    # FieldError is raised if the transform doesn't exist.\n                    if isinstance(final_field, Field) and last_field_exception:\n                        raise last_field_exception\n                    else:\n                        raise\n\n            final_transformer = functools.partial(\n                transform, name=name, previous=final_transformer\n            )\n            final_transformer.has_transforms = True\n        # Then, add the path to the query's joins. Note that we can't trim\n        # joins at this stage - we will need the information about join type\n        # of the trimmed joins.\n        loopIteratorW = __import__(\"builtins\").iter(path)\n        while True:\n            try:\n                join = __import__(\"builtins\").next(loopIteratorW)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if join.filtered_relation:\n                filtered_relation = join.filtered_relation.clone()\n                table_alias = filtered_relation.alias\n            else:\n                filtered_relation = None\n                table_alias = None\n            opts = join.to_opts\n            if join.direct:\n                nullable = self.is_nullable(join.join_field)\n            else:\n                nullable = True\n            connection = self.join_class(\n                opts.db_table,\n                alias,\n                table_alias,\n                INNER,\n                join.join_field,\n                nullable,\n                filtered_relation=filtered_relation,\n            )\n            reuse = can_reuse if join.m2m else None\n            alias = self.join(connection, reuse=reuse)\n            joins.append(alias)\n            if join.filtered_relation and can_reuse is not None:\n                can_reuse.add(alias)\n        return JoinInfo(final_field, targets, opts, joins, path, final_transformer)\n\n    def trim_joins(self, targets, joins, path):\n        \"\"\"\n        The 'target' parameter is the final field being joined to, 'joins'\n        is the full list of join aliases. The 'path' contain the PathInfos\n        used to create the joins.\n\n        Return the final target field and table alias and the new active\n        joins.\n\n        Always trim any direct join if the target column is already in the\n        previous table. Can't trim reverse joins as it's unknown if there's\n        anything on the other side of the join.\n        \"\"\"\n        joins = joins[:]\n        loopIteratorX = __import__(\"builtins\").iter(enumerate(reversed(path)))\n        while True:\n            try:\n                pos, info = __import__(\"builtins\").next(loopIteratorX)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if len(joins) == 1 or not info.direct:\n                break\n            if info.filtered_relation:\n                break\n            join_targets = {t.column for t in info.join_field.foreign_related_fields}\n            cur_targets = {t.column for t in targets}\n            if not cur_targets.issubset(join_targets):\n                break\n            targets_dict = {\n                r[1].column: r[0]\n                for r in info.join_field.related_fields\n                if r[1].column in cur_targets\n            }\n            targets = tuple(targets_dict[t.column] for t in targets)\n            self.unref_alias(joins.pop())\n        return targets, joins[-1], joins\n\n    @classmethod\n    def _gen_cols(cls, exprs, include_external=False, resolve_refs=True):\n        loopIteratorY = __import__(\"builtins\").iter(exprs)\n        while True:\n            try:\n                expr = __import__(\"builtins\").next(loopIteratorY)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if isinstance(expr, Col):\n                yield expr\n            elif include_external and callable(\n                getattr(expr, \"get_external_cols\", None)\n            ):\n                yield from expr.get_external_cols()\n            elif hasattr(expr, \"get_source_expressions\"):\n                if not resolve_refs and isinstance(expr, Ref):\n                    continue\n                yield from cls._gen_cols(\n                    expr.get_source_expressions(),\n                    include_external=include_external,\n                    resolve_refs=resolve_refs,\n                )\n\n    @classmethod\n    def _gen_col_aliases(cls, exprs):\n        yield from (expr.alias for expr in cls._gen_cols(exprs))\n\n    def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):\n        annotation = self.annotations.get(name)\n        if annotation is not None:\n            if not allow_joins:\n                loopIteratorZ = __import__(\"builtins\").iter(self._gen_col_aliases([annotation]))\n                while True:\n                    try:\n                        alias = __import__(\"builtins\").next(loopIteratorZ)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    if isinstance(self.alias_map[alias], Join):\n                        raise FieldError(\n                            \"Joined field references are not permitted in this query\"\n                        )\n            if summarize:\n                # Summarize currently means we are doing an aggregate() query\n                # which is executed as a wrapped subquery if any of the\n                # aggregate() elements reference an existing annotation. In\n                # that case we need to return a Ref to the subquery's\n                # annotation.\n                if name not in self.annotation_select:\n                    raise FieldError(\n                        \"Cannot aggregate over the '%s' alias. Use annotate() \"\n                        \"to promote it.\" % name\n                    )\n                return Ref(name, self.annotation_select[name])\n            else:\n                return annotation\n        else:\n            field_list = name.split(LOOKUP_SEP)\n            annotation = self.annotations.get(field_list[0])\n            if annotation is not None:\n                loopIteratorAA = __import__(\"builtins\").iter(field_list[1:])\n                while True:\n                    try:\n                        transform = __import__(\"builtins\").next(loopIteratorAA)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    annotation = self.try_transform(annotation, transform)\n                return annotation\n            join_info = self.setup_joins(\n                field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse\n            )\n            targets, final_alias, join_list = self.trim_joins(\n                join_info.targets, join_info.joins, join_info.path\n            )\n            if not allow_joins and len(join_list) > 1:\n                raise FieldError(\n                    \"Joined field references are not permitted in this query\"\n                )\n            if len(targets) > 1:\n                raise FieldError(\n                    \"Referencing multicolumn fields with F() objects isn't supported\"\n                )\n            # Verify that the last lookup in name is a field or a transform:\n            # transform_function() raises FieldError if not.\n            transform = join_info.transform_function(targets[0], final_alias)\n            if reuse is not None:\n                reuse.update(join_list)\n            return transform\n\n    def split_exclude(self, filter_expr, can_reuse, names_with_path):\n        \"\"\"\n        When doing an exclude against any kind of N-to-many relation, we need\n        to use a subquery. This method constructs the nested query, given the\n        original exclude filter (filter_expr) and the portion up to the first\n        N-to-many relation field.\n\n        For example, if the origin filter is ~Q(child__name='foo'), filter_expr\n        is ('child__name', 'foo') and can_reuse is a set of joins usable for\n        filters in the original query.\n\n        We will turn this into equivalent of:\n            WHERE NOT EXISTS(\n                SELECT 1\n                FROM child\n                WHERE name = 'foo' AND child.parent_id = parent.id\n                LIMIT 1\n            )\n        \"\"\"\n        # Generate the inner query.\n        query = self.__class__(self.model)\n        query._filtered_relations = self._filtered_relations\n        filter_lhs, filter_rhs = filter_expr\n        if isinstance(filter_rhs, OuterRef):\n            filter_rhs = OuterRef(filter_rhs)\n        elif isinstance(filter_rhs, F):\n            filter_rhs = OuterRef(filter_rhs.name)\n        query.add_filter(filter_lhs, filter_rhs)\n        query.clear_ordering(force=True)\n        # Try to have as simple as possible subquery -> trim leading joins from\n        # the subquery.\n        trimmed_prefix, contains_louter = query.trim_start(names_with_path)\n\n        col = query.select[0]\n        select_field = col.target\n        alias = col.alias\n        if alias in can_reuse:\n            pk = select_field.model._meta.pk\n            # Need to add a restriction so that outer query's filters are in\n            # effect for the subquery, too.\n            query.bump_prefix(self)\n            lookup_class = select_field.get_lookup(\"exact\")\n            # Note that the query.select[0].alias is different from alias\n            # due to bump_prefix above.\n            lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias))\n            query.where.add(lookup, AND)\n            query.external_aliases[alias] = True\n        else:\n            lookup_class = select_field.get_lookup(\"exact\")\n            lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix))\n            query.where.add(lookup, AND)\n\n        condition, needed_inner = self.build_filter(Exists(query))\n\n        if contains_louter:\n            or_null_condition, _ = self.build_filter(\n                (\"%s__isnull\" % trimmed_prefix, True),\n                current_negated=True,\n                branch_negated=True,\n                can_reuse=can_reuse,\n            )\n            condition.add(or_null_condition, OR)\n            # Note that the end result will be:\n            #   NOT EXISTS (inner_q) OR outercol IS NULL\n            # this might look crazy but due to how NULL works, this seems to be\n            # correct. If the IS NULL check is removed, then if outercol\n            # IS NULL we will not match the row.\n        return condition, needed_inner\n\n    def set_empty(self):\n        self.where.add(NothingNode(), AND)\n        loopIteratorAB = __import__(\"builtins\").iter(self.combined_queries)\n        while True:\n            try:\n                query = __import__(\"builtins\").next(loopIteratorAB)\n            except __import__(\"builtins\").StopIteration:\n                break\n            query.set_empty()\n\n    def is_empty(self):\n        return any(isinstance(c, NothingNode) for c in self.where.children)\n\n    def set_limits(self, low=None, high=None):\n        \"\"\"\n        Adjust the limits on the rows retrieved. Use low/high to set these,\n        as it makes it more Pythonic to read and write. When the SQL query is\n        created, convert them to the appropriate offset and limit values.\n\n        Apply any limits passed in here to the existing constraints. Add low\n        to the current low value and clamp both to any existing high value.\n        \"\"\"\n        if high is not None:\n            if self.high_mark is not None:\n                self.high_mark = min(self.high_mark, self.low_mark + high)\n            else:\n                self.high_mark = self.low_mark + high\n        if low is not None:\n            if self.high_mark is not None:\n                self.low_mark = min(self.high_mark, self.low_mark + low)\n            else:\n                self.low_mark = self.low_mark + low\n\n        if self.low_mark == self.high_mark:\n            self.set_empty()\n\n    def clear_limits(self):\n        \"\"\"Clear any existing limits.\"\"\"\n        self.low_mark, self.high_mark = 0, None\n\n    @property\n    def is_sliced(self):\n        return self.low_mark != 0 or self.high_mark is not None\n\n    def has_limit_one(self):\n        return self.high_mark is not None and (self.high_mark - self.low_mark) == 1\n\n    def can_filter(self):\n        \"\"\"\n        Return True if adding filters to this instance is still possible.\n\n        Typically, this means no limits or offsets have been put on the\n        results.\n        \"\"\"\n        return not self.is_sliced\n\n    def clear_select_clause(self):\n        \"\"\"Remove all fields from SELECT clause.\"\"\"\n        self.select = ()\n        self.default_cols = False\n        self.select_related = False\n        self.set_extra_mask(())\n        self.set_annotation_mask(())\n        self.selected = None\n\n    def clear_select_fields(self):\n        \"\"\"\n        Clear the list of fields to select (but not extra_select columns).\n        Some queryset types completely replace any existing list of select\n        columns.\n        \"\"\"\n        self.select = ()\n        self.values_select = ()\n        self.selected = None\n\n    def add_select_col(self, col, name):\n        self.select += (col,)\n        self.values_select += (name,)\n        self.selected[name] = len(self.select) - 1\n\n    def set_select(self, cols):\n        self.default_cols = False\n        self.select = tuple(cols)\n\n    def add_distinct_fields(self, *field_names):\n        \"\"\"\n        Add and resolve the given fields to the query's \"distinct on\" clause.\n        \"\"\"\n        self.distinct_fields = field_names\n        self.distinct = True\n\n    def add_fields(self, field_names, allow_m2m=True):\n        \"\"\"\n        Add the given (model) fields to the select set. Add the field names in\n        the order specified.\n        \"\"\"\n        alias = self.get_initial_alias()\n        opts = self.get_meta()\n\n        try:\n            cols = []\n            for name in field_names:\n                # Join promotion note - we must not remove any rows here, so\n                # if there is no existing joins, use outer join.\n                join_info = self.setup_joins(\n                    name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m\n                )\n                targets, final_alias, joins = self.trim_joins(\n                    join_info.targets,\n                    join_info.joins,\n                    join_info.path,\n                )\n                if len(targets) > 1:\n                    transformed_targets = [\n                        join_info.transform_function(target, final_alias)\n                        for target in targets\n                    ]\n                    cols.append(\n                        ColPairs(\n                            final_alias if self.alias_cols else None,\n                            [col.target for col in transformed_targets],\n                            [col.output_field for col in transformed_targets],\n                            join_info.final_field,\n                        )\n                    )\n                else:\n                    cols.append(join_info.transform_function(targets[0], final_alias))\n            if cols:\n                self.set_select(cols)\n        except MultiJoin:\n            raise FieldError(\"Invalid field name: '%s'\" % name)\n        except FieldError:\n            if LOOKUP_SEP in name:\n                # For lookups spanning over relationships, show the error\n                # from the model on which the lookup failed.\n                raise\n            else:\n                names = sorted(\n                    [\n                        *get_field_names_from_opts(opts),\n                        *self.extra,\n                        *self.annotation_select,\n                        *self._filtered_relations,\n                    ]\n                )\n                raise FieldError(\n                    \"Cannot resolve keyword %r into field. \"\n                    \"Choices are: %s\" % (name, \", \".join(names))\n                )\n\n    def add_ordering(self, *ordering):\n        \"\"\"\n        Add items from the 'ordering' sequence to the query's \"order by\"\n        clause. These items are either field names (not column names) --\n        possibly with a direction prefix ('-' or '?') -- or OrderBy\n        expressions.\n\n        If 'ordering' is empty, clear all ordering from the query.\n        \"\"\"\n        errors = []\n        for item in ordering:\n            if isinstance(item, str):\n                if item == \"?\":\n                    continue\n                item = item.removeprefix(\"-\")\n                if item in self.annotations:\n                    continue\n                if self.extra and item in self.extra:\n                    continue\n                # names_to_path() validates the lookup. A descriptive\n                # FieldError will be raise if it's not.\n                self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)\n            elif not hasattr(item, \"resolve_expression\"):\n                errors.append(item)\n            if getattr(item, \"contains_aggregate\", False):\n                raise FieldError(\n                    \"Using an aggregate in order_by() without also including \"\n                    \"it in annotate() is not allowed: %s\" % item\n                )\n        if errors:\n            raise FieldError(\"Invalid order_by arguments: %s\" % errors)\n        if ordering:\n            self.order_by += ordering\n        else:\n            self.default_ordering = False\n\n    @property\n    def orderby_issubset_groupby(self):\n        if self.extra_order_by:\n            # Raw SQL from extra(order_by=...) can't be reliably compared\n            # against resolved OrderBy/Col expressions. Treat as not a subset.\n            return False\n        if self.group_by in (None, True):\n            # There is either no aggregation at all (None), or the group by\n            # is generated automatically from model fields (True), in which\n            # case the order by is necessarily a subset of them.\n            return True\n        if not self.order_by:\n            # Although an empty set is always a subset, there's no point in\n            # clearing ordering when there isn't any. Avoid the clone() below.\n            return True\n        # Don't pollute the original query (might disrupt joins).\n        q = self.clone()\n        order_by_set = set()\n        for order_by in q.order_by:\n            if hasattr(order_by, \"resolve_expression\"):\n                order_by_set.add(order_by.resolve_expression(q))\n            elif order_by == \"?\":\n                # Random ordering can't be compared against group by.\n                return False\n            else:\n                order_by_set.add(F(order_by.removeprefix(\"-\")).resolve_expression(q))\n        return order_by_set.issubset(self.group_by)\n\n    def clear_ordering(self, force=False, clear_default=True):\n        \"\"\"\n        Remove any ordering settings if the current query allows it without\n        side effects, set 'force' to True to clear the ordering regardless.\n        If 'clear_default' is True, there will be no ordering in the resulting\n        query (not even the model's default).\n        \"\"\"\n        if not force and (\n            self.is_sliced or self.distinct_fields or self.select_for_update\n        ):\n            return\n        self.order_by = ()\n        self.extra_order_by = ()\n        if clear_default:\n            self.default_ordering = False\n        # Ordering is cleared on combined queries with clear_default=False\n        # when union() and analogues are called, so percolate any possible\n        # clear_default=True.\n        loopIteratorAC = __import__(\"builtins\").iter(self.combined_queries)\n        while True:\n            try:\n                query = __import__(\"builtins\").next(loopIteratorAC)\n            except __import__(\"builtins\").StopIteration:\n                break\n            query.clear_ordering(force=False, clear_default=clear_default)\n\n    def set_group_by(self, allow_aliases=True):\n        \"\"\"\n        Expand the GROUP BY clause required by the query.\n\n        This will usually be the set of all non-aggregate fields in the\n        return data. If the database backend supports grouping by the\n        primary key, and the query would be equivalent, the optimization\n        will be made automatically.\n        \"\"\"\n        if allow_aliases and self.values_select:\n            # If grouping by aliases is allowed assign selected value aliases\n            # by moving them to annotations.\n            group_by_annotations = {}\n            values_select = {}\n            loopIteratorAD = __import__(\"builtins\").iter(zip(self.values_select, self.select))\n            while True:\n                try:\n                    alias, expr = __import__(\"builtins\").next(loopIteratorAD)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                if isinstance(expr, Col):\n                    values_select[alias] = expr\n                else:\n                    group_by_annotations[alias] = expr\n            self.annotations = {**group_by_annotations, **self.annotations}\n            self.append_annotation_mask(group_by_annotations)\n            self.select = tuple(values_select.values())\n            self.values_select = tuple(values_select)\n            if self.selected is not None:\n                loopIteratorAE = __import__(\"builtins\").iter(enumerate(values_select))\n                while True:\n                    try:\n                        index, value_select = __import__(\"builtins\").next(loopIteratorAE)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    self.selected[value_select] = index\n        group_by = list(self.select)\n        loopIteratorAF = __import__(\"builtins\").iter(self.annotation_select.items())\n        while True:\n            try:\n                alias, annotation = __import__(\"builtins\").next(loopIteratorAF)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if not (group_by_cols := annotation.get_group_by_cols()):\n                continue\n            if allow_aliases and not annotation.contains_aggregate:\n                group_by.append(Ref(alias, annotation))\n            else:\n                group_by.extend(group_by_cols)\n        self.group_by = tuple(group_by)\n\n    def add_select_related(self, fields):\n        \"\"\"\n        Set up the select_related data structure so that we only select\n        certain related models (as opposed to all models, when\n        self.select_related=True).\n        \"\"\"\n        if isinstance(self.select_related, bool):\n            field_dict = {}\n        else:\n            field_dict = self.select_related\n        loopIteratorAU = __import__(\"builtins\").iter(fields)\n        while True:\n            try:\n                field = __import__(\"builtins\").next(loopIteratorAU)\n            except __import__(\"builtins\").StopIteration:\n                break\n            d = field_dict\n            loopIteratorAG = __import__(\"builtins\").iter(field.split(LOOKUP_SEP))\n            while True:\n                try:\n                    part = __import__(\"builtins\").next(loopIteratorAG)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                d = d.setdefault(part, {})\n        self.select_related = field_dict\n\n    def add_extra(self, select, select_params, where, params, tables, order_by):\n        \"\"\"\n        Add data to the various extra_* attributes for user-created additions\n        to the query.\n        \"\"\"\n        if select:\n            # We need to pair any placeholder markers in the 'select'\n            # dictionary with their parameters in 'select_params' so that\n            # subsequent updates to the select dictionary also adjust the\n            # parameters appropriately.\n            select_pairs = {}\n            if select_params:\n                param_iter = iter(select_params)\n            else:\n                param_iter = iter([])\n            loopIteratorAH = __import__(\"builtins\").iter(select.items())\n            while True:\n                try:\n                    name, entry = __import__(\"builtins\").next(loopIteratorAH)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                self.check_alias(name)\n                entry = str(entry)\n                entry_params = []\n                pos = entry.find(\"%s\")\n                while pos != -1:\n                    if pos == 0 or entry[pos - 1] != \"%\":\n                        entry_params.append(next(param_iter))\n                    pos = entry.find(\"%s\", pos + 2)\n                select_pairs[name] = (entry, entry_params)\n            self.extra.update(select_pairs)\n        if where or params:\n            self.where.add(ExtraWhere(where, params), AND)\n        if tables:\n            self.extra_tables += tuple(tables)\n        if order_by:\n            self.extra_order_by = order_by\n\n    def clear_deferred_loading(self):\n        \"\"\"Remove any fields from the deferred loading set.\"\"\"\n        self.deferred_loading = (frozenset(), True)\n\n    def add_deferred_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        exclude from loading from the database when automatic column selection\n        is done. Add the new field names to any existing field names that\n        are deferred (or removed from any existing field names that are marked\n        as the only ones for immediate loading).\n        \"\"\"\n        # Fields on related models are stored in the literal double-underscore\n        # format, so that we can use a set datastructure. We do the foo__bar\n        # splitting and handling when computing the SQL column names (as part\n        # of get_columns()).\n        existing, defer = self.deferred_loading\n        if defer:\n            # Add to existing deferred names.\n            self.deferred_loading = existing.union(field_names), True\n        else:\n            # Remove names from the set of any existing \"immediate load\" names.\n            if new_existing := existing.difference(field_names):\n                self.deferred_loading = new_existing, False\n            else:\n                self.clear_deferred_loading()\n                if new_only := set(field_names).difference(existing):\n                    self.deferred_loading = new_only, True\n\n    def add_immediate_loading(self, field_names):\n        \"\"\"\n        Add the given list of model field names to the set of fields to\n        retrieve when the SQL is executed (\"immediate loading\" fields). The\n        field names replace any existing immediate loading field names. If\n        there are field names already specified for deferred loading, remove\n        those names from the new field_names before storing the new names\n        for immediate loading. (That is, immediate loading overrides any\n        existing immediate values, but respects existing deferrals.)\n        \"\"\"\n        existing, defer = self.deferred_loading\n        field_names = set(field_names)\n        if \"pk\" in field_names:\n            field_names.remove(\"pk\")\n            field_names.add(self.get_meta().pk.name)\n\n        if defer:\n            # Remove any existing deferred names from the current set before\n            # setting the new names.\n            self.deferred_loading = field_names.difference(existing), False\n        else:\n            # Replace any existing \"immediate load\" field names.\n            self.deferred_loading = frozenset(field_names), False\n\n    def set_annotation_mask(self, names):\n        \"\"\"Set the mask of annotations that will be returned by the SELECT.\"\"\"\n        if names is None:\n            self.annotation_select_mask = None\n        else:\n            self.annotation_select_mask = set(names)\n            if self.selected:\n                # Prune the masked annotations.\n                self.selected = {\n                    key: value\n                    for key, value in self.selected.items()\n                    if not isinstance(value, str)\n                    or value in self.annotation_select_mask\n                }\n                # Append the unmasked annotations.\n                loopIteratorAI = __import__(\"builtins\").iter(names)\n                while True:\n                    try:\n                        name = __import__(\"builtins\").next(loopIteratorAI)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    self.selected[name] = name\n        self._annotation_select_cache = None\n\n    def append_annotation_mask(self, names):\n        if self.annotation_select_mask is not None:\n            self.set_annotation_mask(self.annotation_select_mask.union(names))\n\n    def set_extra_mask(self, names):\n        \"\"\"\n        Set the mask of extra select items that will be returned by SELECT.\n        Don't remove them from the Query since they might be used later.\n        \"\"\"\n        if names is None:\n            self.extra_select_mask = None\n        else:\n            self.extra_select_mask = set(names)\n        self._extra_select_cache = None\n\n    @property\n    def has_select_fields(self):\n        return self.selected is not None\n\n    def set_values(self, fields):\n        self.select_related = False\n        self.clear_deferred_loading()\n        self.clear_select_fields()\n\n        selected = {}\n        if fields:\n            loopIteratorAJ = __import__(\"builtins\").iter(fields)\n            while True:\n                try:\n                    field = __import__(\"builtins\").next(loopIteratorAJ)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                self.check_alias(field)\n            field_names = []\n            extra_names = []\n            annotation_names = []\n            if not self.extra and not self.annotations:\n                # Shortcut - if there are no extra or annotations, then\n                # the values() clause must be just field names.\n                field_names = list(fields)\n                selected = dict(zip(fields, range(len(fields))))\n            else:\n                self.default_cols = False\n                for f in fields:\n                    if extra := self.extra_select.get(f):\n                        extra_names.append(f)\n                        selected[f] = RawSQL(*extra)\n                    elif f in self.annotation_select:\n                        annotation_names.append(f)\n                        selected[f] = f\n                    elif f in self.annotations:\n                        if self.annotation_select:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. It was excluded \"\n                                f\"by a previous values() or values_list() call. \"\n                                f\"Include '{f}' in that call to select it.\"\n                            )\n                        else:\n                            raise FieldError(\n                                f\"Cannot select the '{f}' alias. Use annotate() \"\n                                f\"to promote it.\"\n                            )\n                    else:\n                        # Call `names_to_path` to ensure a FieldError including\n                        # annotations about to be masked as valid choices if\n                        # `f` is not resolvable.\n                        if self.annotation_select:\n                            self.names_to_path(f.split(LOOKUP_SEP), self.model._meta)\n                        selected[f] = len(field_names)\n                        field_names.append(f)\n            self.set_extra_mask(extra_names)\n            self.set_annotation_mask(annotation_names)\n        else:\n            field_names = [f.attname for f in self.model._meta.concrete_fields]\n            selected = dict.fromkeys(field_names, None)\n        # Selected annotations must be known before setting the GROUP BY\n        # clause.\n        if self.group_by is True:\n            self.add_fields(\n                (f.attname for f in self.model._meta.concrete_fields), False\n            )\n            # Disable GROUP BY aliases to avoid orphaning references to the\n            # SELECT clause which is about to be cleared.\n            self.set_group_by(allow_aliases=False)\n            self.clear_select_fields()\n        elif self.group_by:\n            # Resolve GROUP BY annotation references if they are not part of\n            # the selected fields anymore.\n            group_by = []\n            loopIteratorAK = __import__(\"builtins\").iter(self.group_by)\n            while True:\n                try:\n                    expr = __import__(\"builtins\").next(loopIteratorAK)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                if isinstance(expr, Ref) and expr.refs not in selected:\n                    expr = self.annotations[expr.refs]\n                group_by.append(expr)\n            self.group_by = tuple(group_by)\n\n        self.values_select = tuple(field_names)\n        self.add_fields(field_names, True)\n        self.selected = selected if fields else None\n\n    @property\n    def annotation_select(self):\n        \"\"\"\n        Return the dictionary of aggregate columns that are not masked and\n        should be used in the SELECT clause. Cache this result for performance.\n        \"\"\"\n        if self._annotation_select_cache is not None:\n            return self._annotation_select_cache\n        elif not self.annotations:\n            return {}\n        elif self.annotation_select_mask is not None:\n            self._annotation_select_cache = {\n                k: v\n                for k, v in self.annotations.items()\n                if k in self.annotation_select_mask\n            }\n            return self._annotation_select_cache\n        else:\n            return self.annotations\n\n    @property\n    def extra_select(self):\n        if self._extra_select_cache is not None:\n            return self._extra_select_cache\n        if not self.extra:\n            return {}\n        elif self.extra_select_mask is not None:\n            self._extra_select_cache = {\n                k: v for k, v in self.extra.items() if k in self.extra_select_mask\n            }\n            return self._extra_select_cache\n        else:\n            return self.extra\n\n    def trim_start(self, names_with_path):\n        \"\"\"\n        Trim joins from the start of the join path. The candidates for trim\n        are the PathInfos in names_with_path structure that are m2m joins.\n\n        Also set the select column so the start matches the join.\n\n        This method is meant to be used for generating the subquery joins &\n        cols in split_exclude().\n\n        Return a lookup usable for doing outerq.filter(lookup=self) and a\n        boolean indicating if the joins in the prefix contain a LEFT OUTER\n        join.\n        \"\"\"\n        all_paths = []\n        loopIteratorAL = __import__(\"builtins\").iter(names_with_path)\n        while True:\n            try:\n                _, paths = __import__(\"builtins\").next(loopIteratorAL)\n            except __import__(\"builtins\").StopIteration:\n                break\n            all_paths.extend(paths)\n        contains_louter = False\n        # Trim and operate only on tables that were generated for\n        # the lookup part of the query. That is, avoid trimming\n        # joins generated for F() expressions.\n        lookup_tables = [\n            t for t in self.alias_map if t in self._lookup_joins or t == self.base_table\n        ]\n        loopIteratorAM = __import__(\"builtins\").iter(enumerate(all_paths))\n        while True:\n            try:\n                trimmed_paths, path = __import__(\"builtins\").next(loopIteratorAM)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if path.m2m:\n                break\n            if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER:\n                contains_louter = True\n            alias = lookup_tables[trimmed_paths]\n            self.unref_alias(alias)\n        # The path.join_field is a Rel, lets get the other side's field\n        join_field = path.join_field.field\n        # Build the filter prefix.\n        paths_in_prefix = trimmed_paths\n        trimmed_prefix = []\n        loopIteratorAN = __import__(\"builtins\").iter(names_with_path)\n        while True:\n            try:\n                name, path = __import__(\"builtins\").next(loopIteratorAN)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if paths_in_prefix - len(path) < 0:\n                break\n            trimmed_prefix.append(name)\n            paths_in_prefix -= len(path)\n        trimmed_prefix.append(join_field.foreign_related_fields[0].name)\n        trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)\n        # Lets still see if we can trim the first join from the inner query\n        # (that is, self). We can't do this for:\n        # - LEFT JOINs because we would miss those rows that have nothing on\n        #   the outer side,\n        # - INNER JOINs from filtered relations because we would miss their\n        #   filters.\n        first_join = self.alias_map[lookup_tables[trimmed_paths + 1]]\n        if first_join.join_type != LOUTER and not first_join.filtered_relation:\n            select_fields = [r[0] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths + 1]\n            self.unref_alias(lookup_tables[trimmed_paths])\n            extra_restriction = join_field.get_extra_restriction(\n                None, lookup_tables[trimmed_paths + 1]\n            )\n            if extra_restriction:\n                self.where.add(extra_restriction, AND)\n        else:\n            # TODO: It might be possible to trim more joins from the start of\n            # the inner query if it happens to have a longer join chain\n            # containing the values in select_fields. Lets punt this one for\n            # now.\n            select_fields = [r[1] for r in join_field.related_fields]\n            select_alias = lookup_tables[trimmed_paths]\n        # The found starting point is likely a join_class instead of a\n        # base_table_class reference. But the first entry in the query's FROM\n        # clause must not be a JOIN.\n        loopIteratorAO = __import__(\"builtins\").iter(self.alias_map)\n        while True:\n            try:\n                table = __import__(\"builtins\").next(loopIteratorAO)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if self.alias_refcount[table] > 0:\n                self.alias_map[table] = self.base_table_class(\n                    self.alias_map[table].table_name,\n                    table,\n                )\n                break\n        self.set_select([f.get_col(select_alias) for f in select_fields])\n        return trimmed_prefix, contains_louter\n\n    def is_nullable(self, field):\n        \"\"\"\n        Check if the given field should be treated as nullable.\n\n        Some backends treat '' as null and Django treats such fields as\n        nullable for those backends. In such situations field.null can be\n        False even if we should treat the field as nullable.\n        \"\"\"\n        # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have\n        # (nor should it have) knowledge of which connection is going to be\n        # used. The proper fix would be to defer all decisions where\n        # is_nullable() is needed to the compiler stage, but that is not easy\n        # to do currently.\n        return field.null or (\n            field.empty_strings_allowed\n            and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-d737c5fea4d295f9", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b636522441dca687255b5098c8bfacafecd649f88b0486575093ace4b9f49e92", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 2842, "local_path": "control-flow/lower-for-to-while/I13__django__Query__50af4076.py", "order": 13, "original_content_sha256": "d00f17ab975c3cfd36039048ae3cbf0d8bc7527ac29bb64a26d1315afbbbbaf2", "parent_variant_id": "pyint-82246794d74c-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/sql/query.py#L232-L2792", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 48, "for_loops_skipped_for_comment": 11, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 48, "synchronous_for_loops_eligible": 48, "synchronous_for_loops_found": 59}, "unit_kind": "class", "unit_name": "Query", "variant_id": "pyint-530250af4076-I13", "group_id": "py-d737c5fea4d295f9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 294, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4df864e959a7-SRC", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OrValidator:\n    validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        for v in self.validators:\n            try:\n                v(inst, attr, value)\n            except Exception:  # noqa: BLE001, PERF203, S112\n                continue\n            else:\n                return\n\n        msg = f\"None of {self.validators!r} satisfied for value {value!r}\"\n        raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<or validator wrapping {self.validators!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-d7977138eebb46fa", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 27, "local_path": "source-original/SRC__attrs___OrValidator__64e959a7.py", "order": 0, "original_content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L724-L740", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_OrValidator", "variant_id": "pyint-4df864e959a7-SRC", "group_id": "py-d7977138eebb46fa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1289, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-109cf34cacc5-I01", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OrValidator:\n    validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        for v in self.validators:\n            try:\n                v(inst, attr, value)\n            except Exception:   \n                continue\n            else:\n                return\n\n        msg = f\"None of {self.validators!r} satisfied for value {value!r}\"\n        raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<or validator wrapping {self.validators!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-d7977138eebb46fa", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "1f8089e3ab47bf89b2b8a4f37dc9a85fb7e683213af2f3481577ce7ba1226a46", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 27, "local_path": "comments/remove-comments/I01__attrs___OrValidator__f34cacc5.py", "order": 1, "original_content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "parent_variant_id": "pyint-4df864e959a7-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L724-L740", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 28, "comments_removed": 1, "docstrings_removed": 0, "line_comments_removed": 1}, "unit_kind": "class", "unit_name": "_OrValidator", "variant_id": "pyint-109cf34cacc5-I01", "group_id": "py-d7977138eebb46fa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1290, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-74d70318bf9a-I02", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OrValidator:\n    validators = attrib()\n\n    def __call__(self, ins, att, val):\n        for v2 in self.validators:\n            try:\n                v2(ins, att, val)\n            except Exception:  # noqa: BLE001, PERF203, S112\n                continue\n            else:\n                return\n\n        msg2 = f\"None of {self.validators!r} satisfied for value {val!r}\"\n        raise ValueError(msg2)\n\n    def __repr__(self):\n        return f\"<or validator wrapping {self.validators!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-d7977138eebb46fa", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "21d326683f720537b589f778a29975de7f4948a248ee0bc63ac0ce8f4590cd4b", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 27, "local_path": "identifiers/shorten-identifiers/I02__attrs___OrValidator__0318bf9a.py", "order": 2, "original_content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "parent_variant_id": "pyint-4df864e959a7-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L724-L740", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 11, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "_OrValidator", "variant_id": "pyint-74d70318bf9a-I02", "group_id": "py-d7977138eebb46fa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1291, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a6470d458e81-I03", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OrValidator:\n    validators = attrib()\n\n    def __call__(self, data, user, order):\n        for map in self.validators:\n            try:\n                map(data, user, order)\n            except Exception:  # noqa: BLE001, PERF203, S112\n                continue\n            else:\n                return\n\n        key = f\"None of {self.validators!r} satisfied for value {order!r}\"\n        raise ValueError(key)\n\n    def __repr__(self):\n        return f\"<or validator wrapping {self.validators!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-d7977138eebb46fa", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "5b92e7a4ca451d07046a10d15a08181345f67055cf6fe0adae92013fa89d68da", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 27, "local_path": "identifiers/mislead-identifiers/I03__attrs___OrValidator__0d458e81.py", "order": 3, "original_content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "parent_variant_id": "pyint-4df864e959a7-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L724-L740", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 11, "identifiers_declared": 5, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 4, "local_random_pool_selections": 5, "local_total_length_difference": 2, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_OrValidator", "variant_id": "pyint-a6470d458e81-I03", "group_id": "py-d7977138eebb46fa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1292, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-82e778280098-I04", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OrValidator:\n    validators = attrib()\n\n    def __call__(self, a, b, c):\n        for d in self.validators:\n            try:\n                d(a, b, c)\n            except Exception:  # noqa: BLE001, PERF203, S112\n                continue\n            else:\n                return\n\n        e = f\"None of {self.validators!r} satisfied for value {c!r}\"\n        raise ValueError(e)\n\n    def __repr__(self):\n        return f\"<or validator wrapping {self.validators!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-d7977138eebb46fa", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "25d0f61a7a280af87a3459032d910782dcd139c7ef01560e0e531fcbd48eaad3", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 27, "local_path": "identifiers/garble-identifiers/I04__attrs___OrValidator__78280098.py", "order": 4, "original_content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "parent_variant_id": "pyint-4df864e959a7-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L724-L740", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 11, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "_OrValidator", "variant_id": "pyint-82e778280098-I04", "group_id": "py-d7977138eebb46fa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1293, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c9f1fcd5b1a3-I05", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OrValidator:\n    validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        for v in self.validators:\n            try:\n                v(inst, attr, value)\n            except Exception:  # noqa: BLE001, PERF203, S112\n                continue\n            else:\n                return\n\n        msg = f\"None of {self.validators!r} satisfied for value {value!r}\"\n        raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<or validator wrapping {self.validators!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-d7977138eebb46fa", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 27, "local_path": "expressions/encode-integer-literals/I05__attrs___OrValidator__fcd5b1a3.py", "order": 5, "original_content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "parent_variant_id": "pyint-4df864e959a7-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L724-L740", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "_OrValidator", "variant_id": "pyint-c9f1fcd5b1a3-I05", "group_id": "py-d7977138eebb46fa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1294, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2d3aa91488fa-I06", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OrValidator:\n    validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        for v in self.validators:\n            try:\n                v(inst, attr, value)\n            except Exception:  # noqa: BLE001, PERF203, S112\n                continue\n            else:\n                return\n\n        msg = f\"None of {self.validators!r} satisfied for value {value!r}\"\n        raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<or validator wrapping {self.validators!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-d7977138eebb46fa", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 27, "local_path": "expressions/invert-conditions/I06__attrs___OrValidator__a91488fa.py", "order": 6, "original_content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "parent_variant_id": "pyint-4df864e959a7-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L724-L740", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "_OrValidator", "variant_id": "pyint-2d3aa91488fa-I06", "group_id": "py-d7977138eebb46fa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1295, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-383458b3e393-I07", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OrValidator:\n    validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        if ((0x33c7 ^ 0x33c7) != 0):\n            raise AssertionError()\n        for v in self.validators:\n            try:\n                v(inst, attr, value)\n            except Exception:  # noqa: BLE001, PERF203, S112\n                continue\n            else:\n                return\n\n        msg = f\"None of {self.validators!r} satisfied for value {value!r}\"\n        raise ValueError(msg)\n\n    def __repr__(self):\n        if ((0x687d ^ 0x687d) != 0):\n            raise AssertionError()\n        return f\"<or validator wrapping {self.validators!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-d7977138eebb46fa", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "45ca4d3bd523d27506e92d1a13bbc541c23eba44568d6e4e18509def5125a6ba", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 31, "local_path": "code-injection/insert-dead-branches/I07__attrs___OrValidator__58b3e393.py", "order": 7, "original_content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "parent_variant_id": "pyint-4df864e959a7-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L724-L740", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "_OrValidator", "variant_id": "pyint-383458b3e393-I07", "group_id": "py-d7977138eebb46fa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1296, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-460a26b4d07c-I08", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OrValidator:\n    validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        feature_enabled = False\n        for toggle_count in range(3):\n            feature_enabled = not feature_enabled\n        for v in self.validators:\n            try:\n                v(inst, attr, value)\n            except Exception:  # noqa: BLE001, PERF203, S112\n                continue\n            else:\n                return\n\n        msg = f\"None of {self.validators!r} satisfied for value {value!r}\"\n        raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<or validator wrapping {self.validators!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-d7977138eebb46fa", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "c202266bf9dfef9b48eebd3b2ab5d2e3ec8a46008b23f18d71d724c7ccf96735", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 30, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___OrValidator__26b4d07c.py", "order": 8, "original_content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "parent_variant_id": "pyint-4df864e959a7-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L724-L740", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 7}, "unit_kind": "class", "unit_name": "_OrValidator", "variant_id": "pyint-460a26b4d07c-I08", "group_id": "py-d7977138eebb46fa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1297, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-81c8771dc685-I09", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OrValidator:\n    validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        lI0O_d8569027 = 0xdaeb\n        lI0O_d8569027 = ((lI0O_d8569027 ^ 0xdaeb) | 0) & -1\n        if (lI0O_d8569027 & 1) == 1:\n            lI0O_d8569027 ^= lI0O_d8569027\n        for v in self.validators:\n            try:\n                v(inst, attr, value)\n            except Exception:  # noqa: BLE001, PERF203, S112\n                continue\n            else:\n                return\n\n        msg = f\"None of {self.validators!r} satisfied for value {value!r}\"\n        raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<or validator wrapping {self.validators!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-d7977138eebb46fa", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "8ee44d0d60184aad2fd9e468625e3407975fec8a9f4bc7e4e6b0017ba924d566", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 31, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___OrValidator__771dc685.py", "order": 9, "original_content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "parent_variant_id": "pyint-4df864e959a7-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L724-L740", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 0}, "unit_kind": "class", "unit_name": "_OrValidator", "variant_id": "pyint-81c8771dc685-I09", "group_id": "py-d7977138eebb46fa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1298, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1d6ad872ef6d-I10", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OrValidator:\n    validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        for v in self.validators:\n            try:\n                v(inst, attr, value)\n            except Exception:  # noqa: BLE001, PERF203, S112\n                continue\n            else:\n                return\n\n        msg = f\"None of {self.validators!r} satisfied for value {value!r}\"\n        raise ValueError(msg)\n    def __repr__(self):\n        return f\"<or validator wrapping {self.validators!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-d7977138eebb46fa", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "88e7a14fd003e1e74a3a0e4148e2f183f927d35d22d7ae3fddf24e3973034bc8", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 26, "local_path": "layout/partially-compact-layout/I10__attrs___OrValidator__d872ef6d.py", "order": 10, "original_content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "parent_variant_id": "pyint-4df864e959a7-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L724-L740", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 4, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "_OrValidator", "variant_id": "pyint-1d6ad872ef6d-I10", "group_id": "py-d7977138eebb46fa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1299, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7e4a1013a291-I11", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OrValidator:\n    validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        for v in self.validators:\n            try:\n                v(inst, attr, value)\n            except Exception:  # noqa: BLE001, PERF203, S112\n                continue\n            else:\n                return\n\n        msg = f\"None of {self.validators!r} satisfied for value {value!r}\"\n        raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<or validator wrapping {self.validators!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-d7977138eebb46fa", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 27, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___OrValidator__1013a291.py", "order": 11, "original_content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "parent_variant_id": "pyint-4df864e959a7-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L724-L740", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "_OrValidator", "variant_id": "pyint-7e4a1013a291-I11", "group_id": "py-d7977138eebb46fa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1300, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-718c8ac7b580-I12", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OrValidator:\n    validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        for v in self.validators:\n            try:\n                v(inst, attr, value)\n            except Exception:  # noqa: BLE001, PERF203, S112\n                continue\n            else:\n                return\n\n        \n        raise ValueError((f\"None of {self.validators!r} satisfied for value {value!r}\"))\n\n    def __repr__(self):\n        return f\"<or validator wrapping {self.validators!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-d7977138eebb46fa", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ffa97c5519ff5daba72a99e257a5336e5ae749dd43da1b42df112875b56412d3", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 27, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___OrValidator__8ac7b580.py", "order": 12, "original_content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "parent_variant_id": "pyint-4df864e959a7-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L724-L740", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_OrValidator", "variant_id": "pyint-718c8ac7b580-I12", "group_id": "py-d7977138eebb46fa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1301, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-85add32b3b0e-I13", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, slots=True, unsafe_hash=True)\nclass _OrValidator:\n    validators = attrib()\n\n    def __call__(self, inst, attr, value):\n        for v in self.validators:\n            try:\n                v(inst, attr, value)\n            except Exception:  # noqa: BLE001, PERF203, S112\n                continue\n            else:\n                return\n\n        msg = f\"None of {self.validators!r} satisfied for value {value!r}\"\n        raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<or validator wrapping {self.validators!r}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-d7977138eebb46fa", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 27, "local_path": "control-flow/lower-for-to-while/I13__attrs___OrValidator__d32b3b0e.py", "order": 13, "original_content_sha256": "ac0b90c1e4e4d2a3ea6b759a1fd3d64441dfcb4abb01dea011d1c8c326492ea6", "parent_variant_id": "pyint-4df864e959a7-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L724-L740", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 1, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 1}, "unit_kind": "class", "unit_name": "_OrValidator", "variant_id": "pyint-85add32b3b0e-I13", "group_id": "py-d7977138eebb46fa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1302, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c20045673c45-SRC", "source": "from __future__ import annotations\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nclass Blueprint(Scaffold):\n    \"\"\"Represents a blueprint, a collection of routes and other\n    app-related functions that can be registered on a real application\n    later.\n\n    A blueprint is an object that allows defining application functions\n    without requiring an application object ahead of time. It uses the\n    same decorators as :class:`~flask.Flask`, but defers the need for an\n    application by recording them for later registration.\n\n    Decorating a function with a blueprint creates a deferred function\n    that is called with :class:`~flask.blueprints.BlueprintSetupState`\n    when the blueprint is registered on an application.\n\n    See :doc:`/blueprints` for more information.\n\n    :param name: The name of the blueprint. Will be prepended to each\n        endpoint name.\n    :param import_name: The name of the blueprint package, usually\n        ``__name__``. This helps locate the ``root_path`` for the\n        blueprint.\n    :param static_folder: A folder with static files that should be\n        served by the blueprint's static route. The path is relative to\n        the blueprint's root path. Blueprint static files are disabled\n        by default.\n    :param static_url_path: The url to serve static files from.\n        Defaults to ``static_folder``. If the blueprint does not have\n        a ``url_prefix``, the app's static route will take precedence,\n        and the blueprint's static files won't be accessible.\n    :param template_folder: A folder with templates that should be added\n        to the app's template search path. The path is relative to the\n        blueprint's root path. Blueprint templates are disabled by\n        default. Blueprint templates have a lower precedence than those\n        in the app's templates folder.\n    :param url_prefix: A path to prepend to all of the blueprint's URLs,\n        to make them distinct from the rest of the app's routes.\n    :param subdomain: A subdomain that blueprint routes will match on by\n        default.\n    :param url_defaults: A dict of default values that blueprint routes\n        will receive by default.\n    :param root_path: By default, the blueprint will automatically set\n        this based on ``import_name``. In certain situations this\n        automatic detection can fail, so the path can be specified\n        manually instead.\n\n    .. versionchanged:: 1.1.0\n        Blueprints have a ``cli`` group to register nested CLI commands.\n        The ``cli_group`` parameter controls the name of the group under\n        the ``flask`` command.\n\n    .. versionadded:: 0.7\n    \"\"\"\n\n    _got_registered_once = False\n\n    def __init__(\n        self,\n        name: str,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        url_prefix: str | None = None,\n        subdomain: str | None = None,\n        url_defaults: dict[str, t.Any] | None = None,\n        root_path: str | None = None,\n        cli_group: str | None = _sentinel,  # type: ignore[assignment]\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_folder=static_folder,\n            static_url_path=static_url_path,\n            template_folder=template_folder,\n            root_path=root_path,\n        )\n\n        if not name:\n            raise ValueError(\"'name' may not be empty.\")\n\n        if \".\" in name:\n            raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n        self.name = name\n        self.url_prefix = url_prefix\n        self.subdomain = subdomain\n        self.deferred_functions: list[DeferredSetupFunction] = []\n\n        if url_defaults is None:\n            url_defaults = {}\n\n        self.url_values_defaults = url_defaults\n        self.cli_group = cli_group\n        self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        if self._got_registered_once:\n            raise AssertionError(\n                f\"The setup method '{f_name}' can no longer be called on the blueprint\"\n                f\" '{self.name}'. It has already been registered at least once, any\"\n                \" changes will not be applied consistently.\\n\"\n                \"Make sure all imports, decorators, functions, etc. needed to set up\"\n                \" the blueprint are done before registering it.\"\n            )\n\n    @setupmethod\n    def record(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Registers a function that is called when the blueprint is\n        registered on the application.  This function is called with the\n        state as argument as returned by the :meth:`make_setup_state`\n        method.\n        \"\"\"\n        self.deferred_functions.append(func)\n\n    @setupmethod\n    def record_once(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Works like :meth:`record` but wraps the function in another\n        function that will ensure the function is only called once.  If the\n        blueprint is registered a second time on the application, the\n        function passed is not called.\n        \"\"\"\n\n        def wrapper(state: BlueprintSetupState) -> None:\n            if state.first_registration:\n                func(state)\n\n        self.record(update_wrapper(wrapper, func))\n\n    def make_setup_state(\n        self, app: App, options: dict[str, t.Any], first_registration: bool = False\n    ) -> BlueprintSetupState:\n        \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n        object that is later passed to the register callback functions.\n        Subclasses can override this to return a subclass of the setup state.\n        \"\"\"\n        return BlueprintSetupState(self, app, options, first_registration)\n\n    @setupmethod\n    def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:\n        \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n        arguments passed to this method will override the defaults set\n        on the blueprint.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if blueprint is self:\n            raise ValueError(\"Cannot register a blueprint on itself\")\n        self._blueprints.append((blueprint, options))\n\n    def register(self, app: App, options: dict[str, t.Any]) -> None:\n        \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n        views and callbacks registered on the blueprint with the\n        application. Creates a :class:`.BlueprintSetupState` and calls\n        each :meth:`record` callback with it.\n\n        :param app: The application this blueprint is being registered\n            with.\n        :param options: Keyword arguments forwarded from\n            :meth:`~Flask.register_blueprint`.\n\n        .. versionchanged:: 2.3\n            Nested blueprints now correctly apply subdomains.\n\n        .. versionchanged:: 2.1\n            Registering the same blueprint with the same name multiple\n            times is an error.\n\n        .. versionchanged:: 2.0.1\n            Nested blueprints are registered with their dotted name.\n            This allows different blueprints with the same name to be\n            nested at different locations.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n        \"\"\"\n        name_prefix = options.get(\"name_prefix\", \"\")\n        self_name = options.get(\"name\", self.name)\n        name = f\"{name_prefix}.{self_name}\".lstrip(\".\")\n\n        if name in app.blueprints:\n            bp_desc = \"this\" if app.blueprints[name] is self else \"a different\"\n            existing_at = f\" '{name}'\" if self_name != name else \"\"\n\n            raise ValueError(\n                f\"The name '{self_name}' is already registered for\"\n                f\" {bp_desc} blueprint{existing_at}. Use 'name=' to\"\n                f\" provide a unique name.\"\n            )\n\n        first_bp_registration = not any(bp is self for bp in app.blueprints.values())\n        first_name_registration = name not in app.blueprints\n\n        app.blueprints[name] = self\n        self._got_registered_once = True\n        state = self.make_setup_state(app, options, first_bp_registration)\n\n        if self.has_static_folder:\n            state.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                view_func=self.send_static_file,  # type: ignore[attr-defined]\n                endpoint=\"static\",\n            )\n\n        # Merge blueprint data into parent.\n        if first_bp_registration or first_name_registration:\n            self._merge_blueprint_funcs(app, name)\n\n        for deferred in self.deferred_functions:\n            deferred(state)\n\n        cli_resolved_group = options.get(\"cli_group\", self.cli_group)\n\n        if self.cli.commands:\n            if cli_resolved_group is None:\n                app.cli.commands.update(self.cli.commands)\n            elif cli_resolved_group is _sentinel:\n                self.cli.name = name\n                app.cli.add_command(self.cli)\n            else:\n                self.cli.name = cli_resolved_group\n                app.cli.add_command(self.cli)\n\n        for blueprint, bp_options in self._blueprints:\n            bp_options = bp_options.copy()\n            bp_url_prefix = bp_options.get(\"url_prefix\")\n            bp_subdomain = bp_options.get(\"subdomain\")\n\n            if bp_subdomain is None:\n                bp_subdomain = blueprint.subdomain\n\n            if state.subdomain is not None and bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain + \".\" + state.subdomain\n            elif bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain\n            elif state.subdomain is not None:\n                bp_options[\"subdomain\"] = state.subdomain\n\n            if bp_url_prefix is None:\n                bp_url_prefix = blueprint.url_prefix\n\n            if state.url_prefix is not None and bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = (\n                    state.url_prefix.rstrip(\"/\") + \"/\" + bp_url_prefix.lstrip(\"/\")\n                )\n            elif bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = bp_url_prefix\n            elif state.url_prefix is not None:\n                bp_options[\"url_prefix\"] = state.url_prefix\n\n            bp_options[\"name_prefix\"] = name\n            blueprint.register(app, bp_options)\n\n    def _merge_blueprint_funcs(self, app: App, name: str) -> None:\n        def extend(\n            bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n            parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n        ) -> None:\n            for key, values in bp_dict.items():\n                key = name if key is None else f\"{name}.{key}\"\n                parent_dict[key].extend(values)\n\n        for key, value in self.error_handler_spec.items():\n            key = name if key is None else f\"{name}.{key}\"\n            value = defaultdict(\n                dict,\n                {\n                    code: {exc_class: func for exc_class, func in code_values.items()}\n                    for code, code_values in value.items()\n                },\n            )\n            app.error_handler_spec[key] = value\n\n        for endpoint, func in self.view_functions.items():\n            app.view_functions[endpoint] = func\n\n        extend(self.before_request_funcs, app.before_request_funcs)\n        extend(self.after_request_funcs, app.after_request_funcs)\n        extend(\n            self.teardown_request_funcs,\n            app.teardown_request_funcs,\n        )\n        extend(self.url_default_functions, app.url_default_functions)\n        extend(self.url_value_preprocessors, app.url_value_preprocessors)\n        extend(self.template_context_processors, app.template_context_processors)\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n        full documentation.\n\n        The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n        used with :func:`url_for`, is prefixed with the blueprint's name.\n        \"\"\"\n        if endpoint and \".\" in endpoint:\n            raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n        if view_func and hasattr(view_func, \"__name__\") and \".\" in view_func.__name__:\n            raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n        self.record(\n            lambda s: s.add_url_rule(\n                rule,\n                endpoint,\n                view_func,\n                provide_automatic_options=provide_automatic_options,\n                **options,\n            )\n        )\n\n    @t.overload\n    def app_template_filter(self, name: T_template_filter) -> T_template_filter: ...\n    @t.overload\n    def app_template_filter(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_filter], T_template_filter]: ...\n    @setupmethod\n    def app_template_filter(\n        self, name: T_template_filter | str | None = None\n    ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n        \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_filter` method may be used to register a\n        function later rather than decorating.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_filter`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n        if callable(name):\n            self.add_app_template_filter(name)\n            return name\n\n        def decorator(f: T_template_filter) -> T_template_filter:\n            self.add_app_template_filter(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_filter(\n        self, f: ft.TemplateFilterCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja filter.\n\n        The :meth:`app_template_filter` decorator can be used to register a\n        function by decorating instead.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_filter`.\n\n        :param f: The function to register.\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n\n        def register_template_filter(state: BlueprintSetupState) -> None:\n            state.app.add_template_filter(f, name=name)\n\n        self.record_once(register_template_filter)\n\n    @t.overload\n    def app_template_test(self, name: T_template_test) -> T_template_test: ...\n    @t.overload\n    def app_template_test(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_test], T_template_test]: ...\n    @setupmethod\n    def app_template_test(\n        self, name: T_template_test | str | None = None\n    ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n        \"\"\"Decorate a function to register it as a custom Jinja test. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_test` method may be used to register a\n        function later rather than decorating.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_test`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_test(name)\n            return name\n\n        def decorator(f: T_template_test) -> T_template_test:\n            self.add_app_template_test(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_test(\n        self, f: ft.TemplateTestCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja test.\n\n        The :meth:`app_template_test` decorator can be used to register a\n        function by decorating instead.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_test`.\n\n        :param f: The function to register.\n        :param name: The name to register the test as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_test(state: BlueprintSetupState) -> None:\n            state.app.add_template_test(f, name=name)\n\n        self.record_once(register_template_test)\n\n    @t.overload\n    def app_template_global(self, name: T_template_global) -> T_template_global: ...\n    @t.overload\n    def app_template_global(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_global], T_template_global]: ...\n    @setupmethod\n    def app_template_global(\n        self, name: T_template_global | str | None = None\n    ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n        \"\"\"Decorate a function to register it as a custom Jinja global. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_global` method may be used to register a\n        function later rather than decorating.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_global`.\n\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_global(name)\n            return name\n\n        def decorator(f: T_template_global) -> T_template_global:\n            self.add_app_template_global(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_global(\n        self, f: ft.TemplateGlobalCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja global.\n\n        The :meth:`app_template_global` decorator can be used to register a function\n        by decorating instead.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_global`.\n\n        :param f: The function to register.\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_global(state: BlueprintSetupState) -> None:\n            state.app.add_template_global(f, name=name)\n\n        self.record_once(register_template_global)\n\n    @setupmethod\n    def before_app_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def after_app_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def teardown_app_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_context_processor(\n        self, f: T_template_context_processor\n    ) -> T_template_context_processor:\n        \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n        only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_errorhandler(\n        self, code: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            def from_blueprint(state: BlueprintSetupState) -> None:\n                state.app.errorhandler(code)(f)\n\n            self.record_once(from_blueprint)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def app_url_value_preprocessor(\n        self, f: T_url_value_preprocessor\n    ) -> T_url_value_preprocessor:\n        \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n        )\n        return f\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-d841e365cd245065", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 585, "local_path": "source-original/SRC__flask__Blueprint__45673c45.py", "order": 0, "original_content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/blueprints.py#L119-L692", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Blueprint", "variant_id": "pyint-c20045673c45-SRC", "group_id": "py-d841e365cd245065", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 645, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b59ad93a93de-I01", "source": "from __future__ import annotations\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nclass Blueprint(Scaffold):\n    \n\n    _got_registered_once = False\n\n    def __init__(\n        self,\n        name: str,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        url_prefix: str | None = None,\n        subdomain: str | None = None,\n        url_defaults: dict[str, t.Any] | None = None,\n        root_path: str | None = None,\n        cli_group: str | None = _sentinel,   \n    ):\n        super().__init__(\n            import_name=import_name,\n            static_folder=static_folder,\n            static_url_path=static_url_path,\n            template_folder=template_folder,\n            root_path=root_path,\n        )\n\n        if not name:\n            raise ValueError(\"'name' may not be empty.\")\n\n        if \".\" in name:\n            raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n        self.name = name\n        self.url_prefix = url_prefix\n        self.subdomain = subdomain\n        self.deferred_functions: list[DeferredSetupFunction] = []\n\n        if url_defaults is None:\n            url_defaults = {}\n\n        self.url_values_defaults = url_defaults\n        self.cli_group = cli_group\n        self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        if self._got_registered_once:\n            raise AssertionError(\n                f\"The setup method '{f_name}' can no longer be called on the blueprint\"\n                f\" '{self.name}'. It has already been registered at least once, any\"\n                \" changes will not be applied consistently.\\n\"\n                \"Make sure all imports, decorators, functions, etc. needed to set up\"\n                \" the blueprint are done before registering it.\"\n            )\n\n    @setupmethod\n    def record(self, func: DeferredSetupFunction) -> None:\n        \n        self.deferred_functions.append(func)\n\n    @setupmethod\n    def record_once(self, func: DeferredSetupFunction) -> None:\n        \n\n        def wrapper(state: BlueprintSetupState) -> None:\n            if state.first_registration:\n                func(state)\n\n        self.record(update_wrapper(wrapper, func))\n\n    def make_setup_state(\n        self, app: App, options: dict[str, t.Any], first_registration: bool = False\n    ) -> BlueprintSetupState:\n        \n        return BlueprintSetupState(self, app, options, first_registration)\n\n    @setupmethod\n    def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:\n        \n        if blueprint is self:\n            raise ValueError(\"Cannot register a blueprint on itself\")\n        self._blueprints.append((blueprint, options))\n\n    def register(self, app: App, options: dict[str, t.Any]) -> None:\n        \n        name_prefix = options.get(\"name_prefix\", \"\")\n        self_name = options.get(\"name\", self.name)\n        name = f\"{name_prefix}.{self_name}\".lstrip(\".\")\n\n        if name in app.blueprints:\n            bp_desc = \"this\" if app.blueprints[name] is self else \"a different\"\n            existing_at = f\" '{name}'\" if self_name != name else \"\"\n\n            raise ValueError(\n                f\"The name '{self_name}' is already registered for\"\n                f\" {bp_desc} blueprint{existing_at}. Use 'name=' to\"\n                f\" provide a unique name.\"\n            )\n\n        first_bp_registration = not any(bp is self for bp in app.blueprints.values())\n        first_name_registration = name not in app.blueprints\n\n        app.blueprints[name] = self\n        self._got_registered_once = True\n        state = self.make_setup_state(app, options, first_bp_registration)\n\n        if self.has_static_folder:\n            state.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                view_func=self.send_static_file,   \n                endpoint=\"static\",\n            )\n\n         \n        if first_bp_registration or first_name_registration:\n            self._merge_blueprint_funcs(app, name)\n\n        for deferred in self.deferred_functions:\n            deferred(state)\n\n        cli_resolved_group = options.get(\"cli_group\", self.cli_group)\n\n        if self.cli.commands:\n            if cli_resolved_group is None:\n                app.cli.commands.update(self.cli.commands)\n            elif cli_resolved_group is _sentinel:\n                self.cli.name = name\n                app.cli.add_command(self.cli)\n            else:\n                self.cli.name = cli_resolved_group\n                app.cli.add_command(self.cli)\n\n        for blueprint, bp_options in self._blueprints:\n            bp_options = bp_options.copy()\n            bp_url_prefix = bp_options.get(\"url_prefix\")\n            bp_subdomain = bp_options.get(\"subdomain\")\n\n            if bp_subdomain is None:\n                bp_subdomain = blueprint.subdomain\n\n            if state.subdomain is not None and bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain + \".\" + state.subdomain\n            elif bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain\n            elif state.subdomain is not None:\n                bp_options[\"subdomain\"] = state.subdomain\n\n            if bp_url_prefix is None:\n                bp_url_prefix = blueprint.url_prefix\n\n            if state.url_prefix is not None and bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = (\n                    state.url_prefix.rstrip(\"/\") + \"/\" + bp_url_prefix.lstrip(\"/\")\n                )\n            elif bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = bp_url_prefix\n            elif state.url_prefix is not None:\n                bp_options[\"url_prefix\"] = state.url_prefix\n\n            bp_options[\"name_prefix\"] = name\n            blueprint.register(app, bp_options)\n\n    def _merge_blueprint_funcs(self, app: App, name: str) -> None:\n        def extend(\n            bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n            parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n        ) -> None:\n            for key, values in bp_dict.items():\n                key = name if key is None else f\"{name}.{key}\"\n                parent_dict[key].extend(values)\n\n        for key, value in self.error_handler_spec.items():\n            key = name if key is None else f\"{name}.{key}\"\n            value = defaultdict(\n                dict,\n                {\n                    code: {exc_class: func for exc_class, func in code_values.items()}\n                    for code, code_values in value.items()\n                },\n            )\n            app.error_handler_spec[key] = value\n\n        for endpoint, func in self.view_functions.items():\n            app.view_functions[endpoint] = func\n\n        extend(self.before_request_funcs, app.before_request_funcs)\n        extend(self.after_request_funcs, app.after_request_funcs)\n        extend(\n            self.teardown_request_funcs,\n            app.teardown_request_funcs,\n        )\n        extend(self.url_default_functions, app.url_default_functions)\n        extend(self.url_value_preprocessors, app.url_value_preprocessors)\n        extend(self.template_context_processors, app.template_context_processors)\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \n        if endpoint and \".\" in endpoint:\n            raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n        if view_func and hasattr(view_func, \"__name__\") and \".\" in view_func.__name__:\n            raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n        self.record(\n            lambda s: s.add_url_rule(\n                rule,\n                endpoint,\n                view_func,\n                provide_automatic_options=provide_automatic_options,\n                **options,\n            )\n        )\n\n    @t.overload\n    def app_template_filter(self, name: T_template_filter) -> T_template_filter: ...\n    @t.overload\n    def app_template_filter(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_filter], T_template_filter]: ...\n    @setupmethod\n    def app_template_filter(\n        self, name: T_template_filter | str | None = None\n    ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n        \n        if callable(name):\n            self.add_app_template_filter(name)\n            return name\n\n        def decorator(f: T_template_filter) -> T_template_filter:\n            self.add_app_template_filter(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_filter(\n        self, f: ft.TemplateFilterCallable, name: str | None = None\n    ) -> None:\n        \n\n        def register_template_filter(state: BlueprintSetupState) -> None:\n            state.app.add_template_filter(f, name=name)\n\n        self.record_once(register_template_filter)\n\n    @t.overload\n    def app_template_test(self, name: T_template_test) -> T_template_test: ...\n    @t.overload\n    def app_template_test(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_test], T_template_test]: ...\n    @setupmethod\n    def app_template_test(\n        self, name: T_template_test | str | None = None\n    ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n        \n        if callable(name):\n            self.add_app_template_test(name)\n            return name\n\n        def decorator(f: T_template_test) -> T_template_test:\n            self.add_app_template_test(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_test(\n        self, f: ft.TemplateTestCallable, name: str | None = None\n    ) -> None:\n        \n\n        def register_template_test(state: BlueprintSetupState) -> None:\n            state.app.add_template_test(f, name=name)\n\n        self.record_once(register_template_test)\n\n    @t.overload\n    def app_template_global(self, name: T_template_global) -> T_template_global: ...\n    @t.overload\n    def app_template_global(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_global], T_template_global]: ...\n    @setupmethod\n    def app_template_global(\n        self, name: T_template_global | str | None = None\n    ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n        \n        if callable(name):\n            self.add_app_template_global(name)\n            return name\n\n        def decorator(f: T_template_global) -> T_template_global:\n            self.add_app_template_global(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_global(\n        self, f: ft.TemplateGlobalCallable, name: str | None = None\n    ) -> None:\n        \n\n        def register_template_global(state: BlueprintSetupState) -> None:\n            state.app.add_template_global(f, name=name)\n\n        self.record_once(register_template_global)\n\n    @setupmethod\n    def before_app_request(self, f: T_before_request) -> T_before_request:\n        \n        self.record_once(\n            lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def after_app_request(self, f: T_after_request) -> T_after_request:\n        \n        self.record_once(\n            lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def teardown_app_request(self, f: T_teardown) -> T_teardown:\n        \n        self.record_once(\n            lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_context_processor(\n        self, f: T_template_context_processor\n    ) -> T_template_context_processor:\n        \n        self.record_once(\n            lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_errorhandler(\n        self, code: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            def from_blueprint(state: BlueprintSetupState) -> None:\n                state.app.errorhandler(code)(f)\n\n            self.record_once(from_blueprint)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def app_url_value_preprocessor(\n        self, f: T_url_value_preprocessor\n    ) -> T_url_value_preprocessor:\n        \n        self.record_once(\n            lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \n        self.record_once(\n            lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n        )\n        return f\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-d841e365cd245065", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "34972608047c05c0ea08cf00889f49ef4257b1395984380c6568b2f7a4e8ee9f", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 393, "local_path": "comments/remove-comments/I01__flask__Blueprint__d93a93de.py", "order": 1, "original_content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "parent_variant_id": "pyint-c20045673c45-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/blueprints.py#L119-L692", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 9581, "comments_removed": 23, "docstrings_removed": 20, "line_comments_removed": 3}, "unit_kind": "class", "unit_name": "Blueprint", "variant_id": "pyint-b59ad93a93de-I01", "group_id": "py-d841e365cd245065", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 646, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fa930ad82277-I02", "source": "from __future__ import annotations\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nclass Blueprint(Scaffold):\n    \"\"\"Represents a blueprint, a collection of routes and other\n    app-related functions that can be registered on a real application\n    later.\n\n    A blueprint is an object that allows defining application functions\n    without requiring an application object ahead of time. It uses the\n    same decorators as :class:`~flask.Flask`, but defers the need for an\n    application by recording them for later registration.\n\n    Decorating a function with a blueprint creates a deferred function\n    that is called with :class:`~flask.blueprints.BlueprintSetupState`\n    when the blueprint is registered on an application.\n\n    See :doc:`/blueprints` for more information.\n\n    :param name: The name of the blueprint. Will be prepended to each\n        endpoint name.\n    :param import_name: The name of the blueprint package, usually\n        ``__name__``. This helps locate the ``root_path`` for the\n        blueprint.\n    :param static_folder: A folder with static files that should be\n        served by the blueprint's static route. The path is relative to\n        the blueprint's root path. Blueprint static files are disabled\n        by default.\n    :param static_url_path: The url to serve static files from.\n        Defaults to ``static_folder``. If the blueprint does not have\n        a ``url_prefix``, the app's static route will take precedence,\n        and the blueprint's static files won't be accessible.\n    :param template_folder: A folder with templates that should be added\n        to the app's template search path. The path is relative to the\n        blueprint's root path. Blueprint templates are disabled by\n        default. Blueprint templates have a lower precedence than those\n        in the app's templates folder.\n    :param url_prefix: A path to prepend to all of the blueprint's URLs,\n        to make them distinct from the rest of the app's routes.\n    :param subdomain: A subdomain that blueprint routes will match on by\n        default.\n    :param url_defaults: A dict of default values that blueprint routes\n        will receive by default.\n    :param root_path: By default, the blueprint will automatically set\n        this based on ``import_name``. In certain situations this\n        automatic detection can fail, so the path can be specified\n        manually instead.\n\n    .. versionchanged:: 1.1.0\n        Blueprints have a ``cli`` group to register nested CLI commands.\n        The ``cli_group`` parameter controls the name of the group under\n        the ``flask`` command.\n\n    .. versionadded:: 0.7\n    \"\"\"\n\n    _got_registered_once = False\n\n    def __init__(\n        self,\n        nam: str,\n        import2: str,\n        static: str | os.PathLike[str] | None = None,\n        static2: str | None = None,\n        template: str | os.PathLike[str] | None = None,\n        url: str | None = None,\n        sub: str | None = None,\n        url2: dict[str, t.Any] | None = None,\n        root: str | None = None,\n        cli2: str | None = _sentinel,  # type: ignore[assignment]\n    ):\n        super().__init__(\n            import_name=import2,\n            static_folder=static,\n            static_url_path=static2,\n            template_folder=template,\n            root_path=root,\n        )\n\n        if not nam:\n            raise ValueError(\"'name' may not be empty.\")\n\n        if \".\" in nam:\n            raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n        self.name = nam\n        self.url_prefix = url\n        self.subdomain = sub\n        self.deferred_functions: list[DeferredSetupFunction] = []\n\n        if url2 is None:\n            url2 = {}\n\n        self.url_values_defaults = url2\n        self.cli_group = cli2\n        self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []\n\n    def check(self, f2: str) -> None:\n        if self._got_registered_once:\n            raise AssertionError(\n                f\"The setup method '{f2}' can no longer be called on the blueprint\"\n                f\" '{self.name}'. It has already been registered at least once, any\"\n                \" changes will not be applied consistently.\\n\"\n                \"Make sure all imports, decorators, functions, etc. needed to set up\"\n                \" the blueprint are done before registering it.\"\n            )\n\n    @setupmethod\n    def rec(self, fun: DeferredSetupFunction) -> None:\n        \"\"\"Registers a function that is called when the blueprint is\n        registered on the application.  This function is called with the\n        state as argument as returned by the :meth:`make_setup_state`\n        method.\n        \"\"\"\n        self.deferred_functions.append(fun)\n\n    @setupmethod\n    def record2(self, fun2: DeferredSetupFunction) -> None:\n        \"\"\"Works like :meth:`record` but wraps the function in another\n        function that will ensure the function is only called once.  If the\n        blueprint is registered a second time on the application, the\n        function passed is not called.\n        \"\"\"\n\n        def wrapper(sta: BlueprintSetupState) -> None:\n            if sta.first_registration:\n                func(sta)\n\n        self.rec(update_wrapper(wrapper, fun2))\n\n    def make(\n        self, app15: App, opt: dict[str, t.Any], first: bool = False\n    ) -> BlueprintSetupState:\n        \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n        object that is later passed to the register callback functions.\n        Subclasses can override this to return a subclass of the setup state.\n        \"\"\"\n        return BlueprintSetupState(self, app15, opt, first)\n\n    @setupmethod\n    def register2(self, blu: Blueprint, **opt2: t.Any) -> None:\n        \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n        arguments passed to this method will override the defaults set\n        on the blueprint.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if blu is self:\n            raise ValueError(\"Cannot register a blueprint on itself\")\n        self._blueprints.append((blu, opt2))\n\n    def reg(self, app16: App, opt3: dict[str, t.Any]) -> None:\n        \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n        views and callbacks registered on the blueprint with the\n        application. Creates a :class:`.BlueprintSetupState` and calls\n        each :meth:`record` callback with it.\n\n        :param app: The application this blueprint is being registered\n            with.\n        :param options: Keyword arguments forwarded from\n            :meth:`~Flask.register_blueprint`.\n\n        .. versionchanged:: 2.3\n            Nested blueprints now correctly apply subdomains.\n\n        .. versionchanged:: 2.1\n            Registering the same blueprint with the same name multiple\n            times is an error.\n\n        .. versionchanged:: 2.0.1\n            Nested blueprints are registered with their dotted name.\n            This allows different blueprints with the same name to be\n            nested at different locations.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n        \"\"\"\n        name2 = opt3.get(\"name_prefix\", \"\")\n        self2 = opt3.get(\"name\", self.name)\n        nam2 = f\"{name2}.{self2}\".lstrip(\".\")\n\n        if nam2 in app16.blueprints:\n            bp2 = \"this\" if app16.blueprints[nam2] is self else \"a different\"\n            existing = f\" '{nam2}'\" if self2 != nam2 else \"\"\n\n            raise ValueError(\n                f\"The name '{self2}' is already registered for\"\n                f\" {bp2} blueprint{existing}. Use 'name=' to\"\n                f\" provide a unique name.\"\n            )\n\n        first2 = not any(bp3 is self for bp3 in app16.blueprints.values())\n        first3 = nam2 not in app16.blueprints\n\n        app16.blueprints[nam2] = self\n        self._got_registered_once = True\n        sta2 = self.make(app16, opt3, first2)\n\n        if self.has_static_folder:\n            sta2.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                view_func=self.send_static_file,  # type: ignore[attr-defined]\n                endpoint=\"static\",\n            )\n\n        # Merge blueprint data into parent.\n        if first2 or first3:\n            self.merge(app16, nam2)\n\n        for def2 in self.deferred_functions:\n            def2(sta2)\n\n        cli3 = opt3.get(\"cli_group\", self.cli_group)\n\n        if self.cli.commands:\n            if cli3 is None:\n                app16.cli.commands.update(self.cli.commands)\n            elif cli3 is _sentinel:\n                self.cli.name = nam2\n                app16.cli.add_command(self.cli)\n            else:\n                self.cli.name = cli3\n                app16.cli.add_command(self.cli)\n\n        for blu2, bp4 in self._blueprints:\n            bp4 = bp4.copy()\n            bp5 = bp4.get(\"url_prefix\")\n            bp6 = bp4.get(\"subdomain\")\n\n            if bp6 is None:\n                bp6 = blu2.subdomain\n\n            if sta2.subdomain is not None and bp6 is not None:\n                bp4[\"subdomain\"] = bp6 + \".\" + sta2.subdomain\n            elif bp6 is not None:\n                bp4[\"subdomain\"] = bp6\n            elif sta2.subdomain is not None:\n                bp4[\"subdomain\"] = sta2.subdomain\n\n            if bp5 is None:\n                bp5 = blu2.url_prefix\n\n            if sta2.url_prefix is not None and bp5 is not None:\n                bp4[\"url_prefix\"] = (\n                    sta2.url_prefix.rstrip(\"/\") + \"/\" + bp5.lstrip(\"/\")\n                )\n            elif bp5 is not None:\n                bp4[\"url_prefix\"] = bp5\n            elif sta2.url_prefix is not None:\n                bp4[\"url_prefix\"] = sta2.url_prefix\n\n            bp4[\"name_prefix\"] = nam2\n            blu2.register(app16, bp4)\n\n    def merge(self, app17: App, nam3: str) -> None:\n        def extend(\n            bp7: dict[ft.AppOrBlueprintKey, list[t.Any]],\n            parent: dict[ft.AppOrBlueprintKey, list[t.Any]],\n        ) -> None:\n            for key3, val2 in bp7.items():\n                key3 = name if key3 is None else f\"{name}.{key3}\"\n                parent[key3].extend(val2)\n\n        for key2, val in self.error_handler_spec.items():\n            key2 = nam3 if key2 is None else f\"{nam3}.{key2}\"\n            val = defaultdict(\n                dict,\n                {\n                    cod: {exc: fun3 for exc, fun3 in code2.items()}\n                    for cod, code2 in val.items()\n                },\n            )\n            app17.error_handler_spec[key2] = val\n\n        for end, fun3 in self.view_functions.items():\n            app17.view_functions[end] = fun3\n\n        extend(self.before_request_funcs, app17.before_request_funcs)\n        extend(self.after_request_funcs, app17.after_request_funcs)\n        extend(\n            self.teardown_request_funcs,\n            app17.teardown_request_funcs,\n        )\n        extend(self.url_default_functions, app17.url_default_functions)\n        extend(self.url_value_preprocessors, app17.url_value_preprocessors)\n        extend(self.template_context_processors, app17.template_context_processors)\n\n    @setupmethod\n    def add(\n        self,\n        rul: str,\n        end2: str | None = None,\n        view: ft.RouteCallable | None = None,\n        provide: bool | None = None,\n        **opt4: t.Any,\n    ) -> None:\n        \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n        full documentation.\n\n        The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n        used with :func:`url_for`, is prefixed with the blueprint's name.\n        \"\"\"\n        if end2 and \".\" in end2:\n            raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n        if view and hasattr(view, \"__name__\") and \".\" in view.__name__:\n            raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n        self.rec(\n            lambda s: s.add_url_rule(\n                rul,\n                end2,\n                view,\n                provide_automatic_options=provide,\n                **opt4,\n            )\n        )\n\n    @t.overload\n    def app4(self, nam4: T_template_filter) -> T_template_filter: ...\n    @t.overload\n    def app4(\n        self, nam5: str | None = None\n    ) -> t.Callable[[T_template_filter], T_template_filter]: ...\n    @setupmethod\n    def app4(\n        self, nam6: T_template_filter | str | None = None\n    ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n        \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_filter` method may be used to register a\n        function later rather than decorating.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_filter`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n        if callable(nam6):\n            self.add2(nam6)\n            return nam6\n\n        def decorator(f3: T_template_filter) -> T_template_filter:\n            self.add2(f3, name=name)\n            return f3\n\n        return decorator\n\n    @setupmethod\n    def add2(\n        self, f4: ft.TemplateFilterCallable, nam7: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja filter.\n\n        The :meth:`app_template_filter` decorator can be used to register a\n        function by decorating instead.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_filter`.\n\n        :param f: The function to register.\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n\n        def register_template_filter(sta3: BlueprintSetupState) -> None:\n            sta3.app.add_template_filter(f, name=name)\n\n        self.record2(register_template_filter)\n\n    @t.overload\n    def app7(self, nam8: T_template_test) -> T_template_test: ...\n    @t.overload\n    def app7(\n        self, nam9: str | None = None\n    ) -> t.Callable[[T_template_test], T_template_test]: ...\n    @setupmethod\n    def app7(\n        self, nam10: T_template_test | str | None = None\n    ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n        \"\"\"Decorate a function to register it as a custom Jinja test. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_test` method may be used to register a\n        function later rather than decorating.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_test`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(nam10):\n            self.add3(nam10)\n            return nam10\n\n        def decorator(f5: T_template_test) -> T_template_test:\n            self.add3(f5, name=name)\n            return f5\n\n        return decorator\n\n    @setupmethod\n    def add3(\n        self, f6: ft.TemplateTestCallable, nam11: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja test.\n\n        The :meth:`app_template_test` decorator can be used to register a\n        function by decorating instead.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_test`.\n\n        :param f: The function to register.\n        :param name: The name to register the test as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_test(sta4: BlueprintSetupState) -> None:\n            sta4.app.add_template_test(f, name=name)\n\n        self.record2(register_template_test)\n\n    @t.overload\n    def app10(self, nam12: T_template_global) -> T_template_global: ...\n    @t.overload\n    def app10(\n        self, nam13: str | None = None\n    ) -> t.Callable[[T_template_global], T_template_global]: ...\n    @setupmethod\n    def app10(\n        self, nam14: T_template_global | str | None = None\n    ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n        \"\"\"Decorate a function to register it as a custom Jinja global. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_global` method may be used to register a\n        function later rather than decorating.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_global`.\n\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(nam14):\n            self.add4(nam14)\n            return nam14\n\n        def decorator(f7: T_template_global) -> T_template_global:\n            self.add4(f7, name=name)\n            return f7\n\n        return decorator\n\n    @setupmethod\n    def add4(\n        self, f8: ft.TemplateGlobalCallable, nam15: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja global.\n\n        The :meth:`app_template_global` decorator can be used to register a function\n        by decorating instead.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_global`.\n\n        :param f: The function to register.\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_global(sta5: BlueprintSetupState) -> None:\n            sta5.app.add_template_global(f, name=name)\n\n        self.record2(register_template_global)\n\n    @setupmethod\n    def before(self, f9: T_before_request) -> T_before_request:\n        \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n        \"\"\"\n        self.record2(\n            lambda s: s.app.before_request_funcs.setdefault(None, []).append(f9)\n        )\n        return f9\n\n    @setupmethod\n    def after(self, f10: T_after_request) -> T_after_request:\n        \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n        \"\"\"\n        self.record2(\n            lambda s: s.app.after_request_funcs.setdefault(None, []).append(f10)\n        )\n        return f10\n\n    @setupmethod\n    def teardown(self, f11: T_teardown) -> T_teardown:\n        \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n        \"\"\"\n        self.record2(\n            lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f11)\n        )\n        return f11\n\n    @setupmethod\n    def app11(\n        self, f12: T_template_context_processor\n    ) -> T_template_context_processor:\n        \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n        only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n        \"\"\"\n        self.record2(\n            lambda s: s.app.template_context_processors.setdefault(None, []).append(f12)\n        )\n        return f12\n\n    @setupmethod\n    def app12(\n        self, cod2: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n        \"\"\"\n\n        def decorator(f13: T_error_handler) -> T_error_handler:\n            def from_blueprint(sta6: BlueprintSetupState) -> None:\n                sta6.app.errorhandler(code)(f)\n\n            self.record2(from_blueprint)\n            return f13\n\n        return decorator\n\n    @setupmethod\n    def app13(\n        self, f14: T_url_value_preprocessor\n    ) -> T_url_value_preprocessor:\n        \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n        \"\"\"\n        self.record2(\n            lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f14)\n        )\n        return f14\n\n    @setupmethod\n    def app14(self, f15: T_url_defaults) -> T_url_defaults:\n        \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n        \"\"\"\n        self.record2(\n            lambda s: s.app.url_default_functions.setdefault(None, []).append(f15)\n        )\n        return f15\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-d841e365cd245065", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "efa77d169c6ff900612a07448f0b41b028fe88508bacc5876d33344d17315dd3", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 585, "local_path": "identifiers/shorten-identifiers/I02__flask__Blueprint__0ad82277.py", "order": 2, "original_content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "parent_variant_id": "pyint-c20045673c45-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/blueprints.py#L119-L692", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 304, "identifiers_declared": 111}, "unit_kind": "class", "unit_name": "Blueprint", "variant_id": "pyint-fa930ad82277-I02", "group_id": "py-d841e365cd245065", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 647, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-13cdfc6ec1ef-I03", "source": "from __future__ import annotations\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nclass Blueprint(Scaffold):\n    \"\"\"Represents a blueprint, a collection of routes and other\n    app-related functions that can be registered on a real application\n    later.\n\n    A blueprint is an object that allows defining application functions\n    without requiring an application object ahead of time. It uses the\n    same decorators as :class:`~flask.Flask`, but defers the need for an\n    application by recording them for later registration.\n\n    Decorating a function with a blueprint creates a deferred function\n    that is called with :class:`~flask.blueprints.BlueprintSetupState`\n    when the blueprint is registered on an application.\n\n    See :doc:`/blueprints` for more information.\n\n    :param name: The name of the blueprint. Will be prepended to each\n        endpoint name.\n    :param import_name: The name of the blueprint package, usually\n        ``__name__``. This helps locate the ``root_path`` for the\n        blueprint.\n    :param static_folder: A folder with static files that should be\n        served by the blueprint's static route. The path is relative to\n        the blueprint's root path. Blueprint static files are disabled\n        by default.\n    :param static_url_path: The url to serve static files from.\n        Defaults to ``static_folder``. If the blueprint does not have\n        a ``url_prefix``, the app's static route will take precedence,\n        and the blueprint's static files won't be accessible.\n    :param template_folder: A folder with templates that should be added\n        to the app's template search path. The path is relative to the\n        blueprint's root path. Blueprint templates are disabled by\n        default. Blueprint templates have a lower precedence than those\n        in the app's templates folder.\n    :param url_prefix: A path to prepend to all of the blueprint's URLs,\n        to make them distinct from the rest of the app's routes.\n    :param subdomain: A subdomain that blueprint routes will match on by\n        default.\n    :param url_defaults: A dict of default values that blueprint routes\n        will receive by default.\n    :param root_path: By default, the blueprint will automatically set\n        this based on ``import_name``. In certain situations this\n        automatic detection can fail, so the path can be specified\n        manually instead.\n\n    .. versionchanged:: 1.1.0\n        Blueprints have a ``cli`` group to register nested CLI commands.\n        The ``cli_group`` parameter controls the name of the group under\n        the ``flask`` command.\n\n    .. versionadded:: 0.7\n    \"\"\"\n\n    _got_registered_once = False\n\n    def __init__(\n        self,\n        item: str,\n        finalRecord: str,\n        remoteMessage: str | os.PathLike[str] | None = None,\n        primaryRequest: str | None = None,\n        currentRequest: str | os.PathLike[str] | None = None,\n        activePath: str | None = None,\n        sharedKey: str | None = None,\n        recentResult: dict[str, t.Any] | None = None,\n        nextScore: str | None = None,\n        secureKey: str | None = _sentinel,  # type: ignore[assignment]\n    ):\n        super().__init__(\n            import_name=finalRecord,\n            static_folder=remoteMessage,\n            static_url_path=primaryRequest,\n            template_folder=currentRequest,\n            root_path=nextScore,\n        )\n\n        if not item:\n            raise ValueError(\"'name' may not be empty.\")\n\n        if \".\" in item:\n            raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n        self.name = item\n        self.url_prefix = activePath\n        self.subdomain = sharedKey\n        self.deferred_functions: list[DeferredSetupFunction] = []\n\n        if recentResult is None:\n            recentResult = {}\n\n        self.url_values_defaults = recentResult\n        self.cli_group = secureKey\n        self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []\n\n    def validateAddress(self, region: str) -> None:\n        if self._got_registered_once:\n            raise AssertionError(\n                f\"The setup method '{region}' can no longer be called on the blueprint\"\n                f\" '{self.name}'. It has already been registered at least once, any\"\n                \" changes will not be applied consistently.\\n\"\n                \"Make sure all imports, decorators, functions, etc. needed to set up\"\n                \" the blueprint are done before registering it.\"\n            )\n\n    @setupmethod\n    def create(self, path: DeferredSetupFunction) -> None:\n        \"\"\"Registers a function that is called when the blueprint is\n        registered on the application.  This function is called with the\n        state as argument as returned by the :meth:`make_setup_state`\n        method.\n        \"\"\"\n        self.deferred_functions.append(path)\n\n    @setupmethod\n    def saveRequest(self, node: DeferredSetupFunction) -> None:\n        \"\"\"Works like :meth:`record` but wraps the function in another\n        function that will ensure the function is only called once.  If the\n        blueprint is registered a second time on the application, the\n        function passed is not called.\n        \"\"\"\n\n        def wrapper(price: BlueprintSetupState) -> None:\n            if price.first_registration:\n                func(price)\n\n        self.create(update_wrapper(wrapper, node))\n\n    def validateBalance(\n        self, map: App, summary: dict[str, t.Any], primarySession: bool = False\n    ) -> BlueprintSetupState:\n        \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n        object that is later passed to the register callback functions.\n        Subclasses can override this to return a subclass of the setup state.\n        \"\"\"\n        return BlueprintSetupState(self, map, summary, primarySession)\n\n    @setupmethod\n    def validateSession(self, localMode: Blueprint, **balance: t.Any) -> None:\n        \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n        arguments passed to this method will override the defaults set\n        on the blueprint.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if localMode is self:\n            raise ValueError(\"Cannot register a blueprint on itself\")\n        self._blueprints.append((localMode, balance))\n\n    def findData(self, map: App, nextKey: dict[str, t.Any]) -> None:\n        \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n        views and callbacks registered on the blueprint with the\n        application. Creates a :class:`.BlueprintSetupState` and calls\n        each :meth:`record` callback with it.\n\n        :param app: The application this blueprint is being registered\n            with.\n        :param options: Keyword arguments forwarded from\n            :meth:`~Flask.register_blueprint`.\n\n        .. versionchanged:: 2.3\n            Nested blueprints now correctly apply subdomains.\n\n        .. versionchanged:: 2.1\n            Registering the same blueprint with the same name multiple\n            times is an error.\n\n        .. versionchanged:: 2.0.1\n            Nested blueprints are registered with their dotted name.\n            This allows different blueprints with the same name to be\n            nested at different locations.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n        \"\"\"\n        remoteToken = nextKey.get(\"name_prefix\", \"\")\n        finalUser = nextKey.get(\"name\", self.name)\n        step = f\"{remoteToken}.{finalUser}\".lstrip(\".\")\n\n        if step in map.blueprints:\n            profile = \"this\" if map.blueprints[step] is self else \"a different\"\n            secureOrder = f\" '{step}'\" if finalUser != step else \"\"\n\n            raise ValueError(\n                f\"The name '{finalUser}' is already registered for\"\n                f\" {profile} blueprint{secureOrder}. Use 'name=' to\"\n                f\" provide a unique name.\"\n            )\n\n        primaryBalance = not any(key is self for key in map.blueprints.values())\n        currentAddress = step not in map.blueprints\n\n        map.blueprints[step] = self\n        self._got_registered_once = True\n        price = self.validateBalance(map, nextKey, primaryBalance)\n\n        if self.has_static_folder:\n            price.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                view_func=self.send_static_file,  # type: ignore[attr-defined]\n                endpoint=\"static\",\n            )\n\n        # Merge blueprint data into parent.\n        if primaryBalance or currentAddress:\n            self.validateAccount(map, step)\n\n        for nextData in self.deferred_functions:\n            nextData(price)\n\n        pendingAccount = nextKey.get(\"cli_group\", self.cli_group)\n\n        if self.cli.commands:\n            if pendingAccount is None:\n                map.cli.commands.update(self.cli.commands)\n            elif pendingAccount is _sentinel:\n                self.cli.name = step\n                map.cli.add_command(self.cli)\n            else:\n                self.cli.name = pendingAccount\n                map.cli.add_command(self.cli)\n\n        for secureKey, recentData in self._blueprints:\n            recentData = recentData.copy()\n            activeMessage = recentData.get(\"url_prefix\")\n            activeBuffer = recentData.get(\"subdomain\")\n\n            if activeBuffer is None:\n                activeBuffer = secureKey.subdomain\n\n            if price.subdomain is not None and activeBuffer is not None:\n                recentData[\"subdomain\"] = activeBuffer + \".\" + price.subdomain\n            elif activeBuffer is not None:\n                recentData[\"subdomain\"] = activeBuffer\n            elif price.subdomain is not None:\n                recentData[\"subdomain\"] = price.subdomain\n\n            if activeMessage is None:\n                activeMessage = secureKey.url_prefix\n\n            if price.url_prefix is not None and activeMessage is not None:\n                recentData[\"url_prefix\"] = (\n                    price.url_prefix.rstrip(\"/\") + \"/\" + activeMessage.lstrip(\"/\")\n                )\n            elif activeMessage is not None:\n                recentData[\"url_prefix\"] = activeMessage\n            elif price.url_prefix is not None:\n                recentData[\"url_prefix\"] = price.url_prefix\n\n            recentData[\"name_prefix\"] = step\n            secureKey.register(map, recentData)\n\n    def validateAccount(self, age: App, date: str) -> None:\n        def extend(\n            summary: dict[ft.AppOrBlueprintKey, list[t.Any]],\n            secureToken: dict[ft.AppOrBlueprintKey, list[t.Any]],\n        ) -> None:\n            for map, option in summary.items():\n                map = name if map is None else f\"{name}.{map}\"\n                secureToken[map].extend(option)\n\n        for map, cache in self.error_handler_spec.items():\n            map = date if map is None else f\"{date}.{map}\"\n            cache = defaultdict(\n                dict,\n                {\n                    size: {localUser: user for localUser, user in defaultUser.items()}\n                    for size, defaultUser in cache.items()\n                },\n            )\n            age.error_handler_spec[map] = cache\n\n        for finalKey, user in self.view_functions.items():\n            age.view_functions[finalKey] = user\n\n        extend(self.before_request_funcs, age.before_request_funcs)\n        extend(self.after_request_funcs, age.after_request_funcs)\n        extend(\n            self.teardown_request_funcs,\n            age.teardown_request_funcs,\n        )\n        extend(self.url_default_functions, age.url_default_functions)\n        extend(self.url_value_preprocessors, age.url_value_preprocessors)\n        extend(self.template_context_processors, age.template_context_processors)\n\n    @setupmethod\n    def refreshBatch(\n        self,\n        data: str,\n        customer: str | None = None,\n        timestamp: ft.RouteCallable | None = None,\n        pendingRequest: bool | None = None,\n        **session: t.Any,\n    ) -> None:\n        \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n        full documentation.\n\n        The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n        used with :func:`url_for`, is prefixed with the blueprint's name.\n        \"\"\"\n        if customer and \".\" in customer:\n            raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n        if timestamp and hasattr(timestamp, \"__name__\") and \".\" in timestamp.__name__:\n            raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n        self.create(\n            lambda s: s.add_url_rule(\n                data,\n                customer,\n                timestamp,\n                provide_automatic_options=pendingRequest,\n                **session,\n            )\n        )\n\n    @t.overload\n    def validateClient(self, path: T_template_filter) -> T_template_filter: ...\n    @t.overload\n    def validateClient(\n        self, user: str | None = None\n    ) -> t.Callable[[T_template_filter], T_template_filter]: ...\n    @setupmethod\n    def validateClient(\n        self, date: T_template_filter | str | None = None\n    ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n        \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_filter` method may be used to register a\n        function later rather than decorating.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_filter`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n        if callable(date):\n            self.refreshAddress(date)\n            return date\n\n        def decorator(map: T_template_filter) -> T_template_filter:\n            self.refreshAddress(map, name=name)\n            return map\n\n        return decorator\n\n    @setupmethod\n    def refreshAddress(\n        self, key: ft.TemplateFilterCallable, size: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja filter.\n\n        The :meth:`app_template_filter` decorator can be used to register a\n        function by decorating instead.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_filter`.\n\n        :param f: The function to register.\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n\n        def register_template_filter(batch: BlueprintSetupState) -> None:\n            batch.app.add_template_filter(f, name=name)\n\n        self.saveRequest(register_template_filter)\n\n    @t.overload\n    def validateResult(self, date: T_template_test) -> T_template_test: ...\n    @t.overload\n    def validateResult(\n        self, step: str | None = None\n    ) -> t.Callable[[T_template_test], T_template_test]: ...\n    @setupmethod\n    def validateResult(\n        self, user: T_template_test | str | None = None\n    ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n        \"\"\"Decorate a function to register it as a custom Jinja test. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_test` method may be used to register a\n        function later rather than decorating.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_test`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(user):\n            self.validateConfig(user)\n            return user\n\n        def decorator(map: T_template_test) -> T_template_test:\n            self.validateConfig(map, name=name)\n            return map\n\n        return decorator\n\n    @setupmethod\n    def validateConfig(\n        self, map: ft.TemplateTestCallable, date: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja test.\n\n        The :meth:`app_template_test` decorator can be used to register a\n        function by decorating instead.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_test`.\n\n        :param f: The function to register.\n        :param name: The name to register the test as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_test(count: BlueprintSetupState) -> None:\n            count.app.add_template_test(f, name=name)\n\n        self.saveRequest(register_template_test)\n\n    @t.overload\n    def refreshAccount(self, path: T_template_global) -> T_template_global: ...\n    @t.overload\n    def refreshAccount(\n        self, path: str | None = None\n    ) -> t.Callable[[T_template_global], T_template_global]: ...\n    @setupmethod\n    def refreshAccount(\n        self, step: T_template_global | str | None = None\n    ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n        \"\"\"Decorate a function to register it as a custom Jinja global. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_global` method may be used to register a\n        function later rather than decorating.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_global`.\n\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(step):\n            self.refreshBalance(step)\n            return step\n\n        def decorator(age: T_template_global) -> T_template_global:\n            self.refreshBalance(age, name=name)\n            return age\n\n        return decorator\n\n    @setupmethod\n    def refreshBalance(\n        self, key: ft.TemplateGlobalCallable, item: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja global.\n\n        The :meth:`app_template_global` decorator can be used to register a function\n        by decorating instead.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_global`.\n\n        :param f: The function to register.\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_global(order: BlueprintSetupState) -> None:\n            order.app.add_template_global(f, name=name)\n\n        self.saveRequest(register_template_global)\n\n    @setupmethod\n    def validateWindow(self, key: T_before_request) -> T_before_request:\n        \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n        \"\"\"\n        self.saveRequest(\n            lambda s: s.app.before_request_funcs.setdefault(None, []).append(key)\n        )\n        return key\n\n    @setupmethod\n    def refreshSession(self, key: T_after_request) -> T_after_request:\n        \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n        \"\"\"\n        self.saveRequest(\n            lambda s: s.app.after_request_funcs.setdefault(None, []).append(key)\n        )\n        return key\n\n    @setupmethod\n    def validateRecord(self, age: T_teardown) -> T_teardown:\n        \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n        \"\"\"\n        self.saveRequest(\n            lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(age)\n        )\n        return age\n\n    @setupmethod\n    def validateIndex(\n        self, key: T_template_context_processor\n    ) -> T_template_context_processor:\n        \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n        only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n        \"\"\"\n        self.saveRequest(\n            lambda s: s.app.template_context_processors.setdefault(None, []).append(key)\n        )\n        return key\n\n    @setupmethod\n    def removeAccount(\n        self, size: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n        \"\"\"\n\n        def decorator(key: T_error_handler) -> T_error_handler:\n            def from_blueprint(entry: BlueprintSetupState) -> None:\n                entry.app.errorhandler(code)(f)\n\n            self.saveRequest(from_blueprint)\n            return key\n\n        return decorator\n\n    @setupmethod\n    def refreshWindow(\n        self, map: T_url_value_preprocessor\n    ) -> T_url_value_preprocessor:\n        \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n        \"\"\"\n        self.saveRequest(\n            lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(map)\n        )\n        return map\n\n    @setupmethod\n    def updateRequest(self, map: T_url_defaults) -> T_url_defaults:\n        \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n        \"\"\"\n        self.saveRequest(\n            lambda s: s.app.url_default_functions.setdefault(None, []).append(map)\n        )\n        return map\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-d841e365cd245065", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "301414f373ed817fd5f76a874e375b4c89417669f252639901e3c6d274f19923", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 585, "local_path": "identifiers/mislead-identifiers/I03__flask__Blueprint__fc6ec1ef.py", "order": 3, "original_content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "parent_variant_id": "pyint-c20045673c45-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/blueprints.py#L119-L692", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 304, "identifiers_declared": 111, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 1, "local_exact_length_matches": 63, "local_random_pool_selections": 84, "local_total_length_difference": 64, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 171, "method_exact_length_matches": 4, "method_random_pool_selections": 27, "method_total_length_difference": 95}, "unit_kind": "class", "unit_name": "Blueprint", "variant_id": "pyint-13cdfc6ec1ef-I03", "group_id": "py-d841e365cd245065", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 648, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8849942bfe3f-I04", "source": "from __future__ import annotations\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nclass Blueprint(Scaffold):\n    \"\"\"Represents a blueprint, a collection of routes and other\n    app-related functions that can be registered on a real application\n    later.\n\n    A blueprint is an object that allows defining application functions\n    without requiring an application object ahead of time. It uses the\n    same decorators as :class:`~flask.Flask`, but defers the need for an\n    application by recording them for later registration.\n\n    Decorating a function with a blueprint creates a deferred function\n    that is called with :class:`~flask.blueprints.BlueprintSetupState`\n    when the blueprint is registered on an application.\n\n    See :doc:`/blueprints` for more information.\n\n    :param name: The name of the blueprint. Will be prepended to each\n        endpoint name.\n    :param import_name: The name of the blueprint package, usually\n        ``__name__``. This helps locate the ``root_path`` for the\n        blueprint.\n    :param static_folder: A folder with static files that should be\n        served by the blueprint's static route. The path is relative to\n        the blueprint's root path. Blueprint static files are disabled\n        by default.\n    :param static_url_path: The url to serve static files from.\n        Defaults to ``static_folder``. If the blueprint does not have\n        a ``url_prefix``, the app's static route will take precedence,\n        and the blueprint's static files won't be accessible.\n    :param template_folder: A folder with templates that should be added\n        to the app's template search path. The path is relative to the\n        blueprint's root path. Blueprint templates are disabled by\n        default. Blueprint templates have a lower precedence than those\n        in the app's templates folder.\n    :param url_prefix: A path to prepend to all of the blueprint's URLs,\n        to make them distinct from the rest of the app's routes.\n    :param subdomain: A subdomain that blueprint routes will match on by\n        default.\n    :param url_defaults: A dict of default values that blueprint routes\n        will receive by default.\n    :param root_path: By default, the blueprint will automatically set\n        this based on ``import_name``. In certain situations this\n        automatic detection can fail, so the path can be specified\n        manually instead.\n\n    .. versionchanged:: 1.1.0\n        Blueprints have a ``cli`` group to register nested CLI commands.\n        The ``cli_group`` parameter controls the name of the group under\n        the ``flask`` command.\n\n    .. versionadded:: 0.7\n    \"\"\"\n\n    _got_registered_once = False\n\n    def __init__(\n        self,\n        E: str,\n        F: str,\n        G: str | os.PathLike[str] | None = None,\n        H: str | None = None,\n        I: str | os.PathLike[str] | None = None,\n        J: str | None = None,\n        K: str | None = None,\n        L: dict[str, t.Any] | None = None,\n        M: str | None = None,\n        N: str | None = _sentinel,  # type: ignore[assignment]\n    ):\n        super().__init__(\n            import_name=F,\n            static_folder=G,\n            static_url_path=H,\n            template_folder=I,\n            root_path=M,\n        )\n\n        if not E:\n            raise ValueError(\"'name' may not be empty.\")\n\n        if \".\" in E:\n            raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n        self.name = E\n        self.url_prefix = J\n        self.subdomain = K\n        self.deferred_functions: list[DeferredSetupFunction] = []\n\n        if L is None:\n            L = {}\n\n        self.url_values_defaults = L\n        self.cli_group = N\n        self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []\n\n    def a(self, O: str) -> None:\n        if self._got_registered_once:\n            raise AssertionError(\n                f\"The setup method '{O}' can no longer be called on the blueprint\"\n                f\" '{self.name}'. It has already been registered at least once, any\"\n                \" changes will not be applied consistently.\\n\"\n                \"Make sure all imports, decorators, functions, etc. needed to set up\"\n                \" the blueprint are done before registering it.\"\n            )\n\n    @setupmethod\n    def b(self, P: DeferredSetupFunction) -> None:\n        \"\"\"Registers a function that is called when the blueprint is\n        registered on the application.  This function is called with the\n        state as argument as returned by the :meth:`make_setup_state`\n        method.\n        \"\"\"\n        self.deferred_functions.append(P)\n\n    @setupmethod\n    def c(self, Q: DeferredSetupFunction) -> None:\n        \"\"\"Works like :meth:`record` but wraps the function in another\n        function that will ensure the function is only called once.  If the\n        blueprint is registered a second time on the application, the\n        function passed is not called.\n        \"\"\"\n\n        def wrapper(R: BlueprintSetupState) -> None:\n            if R.first_registration:\n                func(R)\n\n        self.b(update_wrapper(wrapper, Q))\n\n    def d(\n        self, S: App, T: dict[str, t.Any], U: bool = False\n    ) -> BlueprintSetupState:\n        \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n        object that is later passed to the register callback functions.\n        Subclasses can override this to return a subclass of the setup state.\n        \"\"\"\n        return BlueprintSetupState(self, S, T, U)\n\n    @setupmethod\n    def e(self, V: Blueprint, **W: t.Any) -> None:\n        \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n        arguments passed to this method will override the defaults set\n        on the blueprint.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if V is self:\n            raise ValueError(\"Cannot register a blueprint on itself\")\n        self._blueprints.append((V, W))\n\n    def g(self, X: App, Y: dict[str, t.Any]) -> None:\n        \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n        views and callbacks registered on the blueprint with the\n        application. Creates a :class:`.BlueprintSetupState` and calls\n        each :meth:`record` callback with it.\n\n        :param app: The application this blueprint is being registered\n            with.\n        :param options: Keyword arguments forwarded from\n            :meth:`~Flask.register_blueprint`.\n\n        .. versionchanged:: 2.3\n            Nested blueprints now correctly apply subdomains.\n\n        .. versionchanged:: 2.1\n            Registering the same blueprint with the same name multiple\n            times is an error.\n\n        .. versionchanged:: 2.0.1\n            Nested blueprints are registered with their dotted name.\n            This allows different blueprints with the same name to be\n            nested at different locations.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n        \"\"\"\n        Z = Y.get(\"name_prefix\", \"\")\n        aa = Y.get(\"name\", self.name)\n        ab = f\"{Z}.{aa}\".lstrip(\".\")\n\n        if ab in X.blueprints:\n            ac = \"this\" if X.blueprints[ab] is self else \"a different\"\n            ad = f\" '{ab}'\" if aa != ab else \"\"\n\n            raise ValueError(\n                f\"The name '{aa}' is already registered for\"\n                f\" {ac} blueprint{ad}. Use 'name=' to\"\n                f\" provide a unique name.\"\n            )\n\n        ae = not any(af is self for af in X.blueprints.values())\n        ag = ab not in X.blueprints\n\n        X.blueprints[ab] = self\n        self._got_registered_once = True\n        ah = self.d(X, Y, ae)\n\n        if self.has_static_folder:\n            ah.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                view_func=self.send_static_file,  # type: ignore[attr-defined]\n                endpoint=\"static\",\n            )\n\n        # Merge blueprint data into parent.\n        if ae or ag:\n            self.h(X, ab)\n\n        for ai in self.deferred_functions:\n            ai(ah)\n\n        aj = Y.get(\"cli_group\", self.cli_group)\n\n        if self.cli.commands:\n            if aj is None:\n                X.cli.commands.update(self.cli.commands)\n            elif aj is _sentinel:\n                self.cli.name = ab\n                X.cli.add_command(self.cli)\n            else:\n                self.cli.name = aj\n                X.cli.add_command(self.cli)\n\n        for ak, al in self._blueprints:\n            al = al.copy()\n            am = al.get(\"url_prefix\")\n            an = al.get(\"subdomain\")\n\n            if an is None:\n                an = ak.subdomain\n\n            if ah.subdomain is not None and an is not None:\n                al[\"subdomain\"] = an + \".\" + ah.subdomain\n            elif an is not None:\n                al[\"subdomain\"] = an\n            elif ah.subdomain is not None:\n                al[\"subdomain\"] = ah.subdomain\n\n            if am is None:\n                am = ak.url_prefix\n\n            if ah.url_prefix is not None and am is not None:\n                al[\"url_prefix\"] = (\n                    ah.url_prefix.rstrip(\"/\") + \"/\" + am.lstrip(\"/\")\n                )\n            elif am is not None:\n                al[\"url_prefix\"] = am\n            elif ah.url_prefix is not None:\n                al[\"url_prefix\"] = ah.url_prefix\n\n            al[\"name_prefix\"] = ab\n            ak.register(X, al)\n\n    def h(self, ao: App, ap: str) -> None:\n        def extend(\n            ay: dict[ft.AppOrBlueprintKey, list[t.Any]],\n            az: dict[ft.AppOrBlueprintKey, list[t.Any]],\n        ) -> None:\n            for aA, aB in ay.items():\n                aA = name if aA is None else f\"{name}.{aA}\"\n                az[aA].extend(aB)\n\n        for aq, ar in self.error_handler_spec.items():\n            aq = ap if aq is None else f\"{ap}.{aq}\"\n            ar = defaultdict(\n                dict,\n                {\n                    au: {at: ax for at, ax in av.items()}\n                    for au, av in ar.items()\n                },\n            )\n            ao.error_handler_spec[aq] = ar\n\n        for aw, ax in self.view_functions.items():\n            ao.view_functions[aw] = ax\n\n        extend(self.before_request_funcs, ao.before_request_funcs)\n        extend(self.after_request_funcs, ao.after_request_funcs)\n        extend(\n            self.teardown_request_funcs,\n            ao.teardown_request_funcs,\n        )\n        extend(self.url_default_functions, ao.url_default_functions)\n        extend(self.url_value_preprocessors, ao.url_value_preprocessors)\n        extend(self.template_context_processors, ao.template_context_processors)\n\n    @setupmethod\n    def i(\n        self,\n        aC: str,\n        aD: str | None = None,\n        aE: ft.RouteCallable | None = None,\n        aF: bool | None = None,\n        **aG: t.Any,\n    ) -> None:\n        \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n        full documentation.\n\n        The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n        used with :func:`url_for`, is prefixed with the blueprint's name.\n        \"\"\"\n        if aD and \".\" in aD:\n            raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n        if aE and hasattr(aE, \"__name__\") and \".\" in aE.__name__:\n            raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n        self.b(\n            lambda s: s.add_url_rule(\n                aC,\n                aD,\n                aE,\n                provide_automatic_options=aF,\n                **aG,\n            )\n        )\n\n    @t.overload\n    def l(self, aH: T_template_filter) -> T_template_filter: ...\n    @t.overload\n    def l(\n        self, aI: str | None = None\n    ) -> t.Callable[[T_template_filter], T_template_filter]: ...\n    @setupmethod\n    def l(\n        self, aJ: T_template_filter | str | None = None\n    ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n        \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_filter` method may be used to register a\n        function later rather than decorating.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_filter`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n        if callable(aJ):\n            self.m(aJ)\n            return aJ\n\n        def decorator(aK: T_template_filter) -> T_template_filter:\n            self.m(aK, name=name)\n            return aK\n\n        return decorator\n\n    @setupmethod\n    def m(\n        self, aL: ft.TemplateFilterCallable, aM: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja filter.\n\n        The :meth:`app_template_filter` decorator can be used to register a\n        function by decorating instead.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_filter`.\n\n        :param f: The function to register.\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n\n        def register_template_filter(aN: BlueprintSetupState) -> None:\n            aN.app.add_template_filter(f, name=name)\n\n        self.c(register_template_filter)\n\n    @t.overload\n    def p(self, aO: T_template_test) -> T_template_test: ...\n    @t.overload\n    def p(\n        self, aP: str | None = None\n    ) -> t.Callable[[T_template_test], T_template_test]: ...\n    @setupmethod\n    def p(\n        self, aQ: T_template_test | str | None = None\n    ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n        \"\"\"Decorate a function to register it as a custom Jinja test. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_test` method may be used to register a\n        function later rather than decorating.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_test`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(aQ):\n            self.q(aQ)\n            return aQ\n\n        def decorator(aR: T_template_test) -> T_template_test:\n            self.q(aR, name=name)\n            return aR\n\n        return decorator\n\n    @setupmethod\n    def q(\n        self, aS: ft.TemplateTestCallable, aT: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja test.\n\n        The :meth:`app_template_test` decorator can be used to register a\n        function by decorating instead.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_test`.\n\n        :param f: The function to register.\n        :param name: The name to register the test as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_test(aU: BlueprintSetupState) -> None:\n            aU.app.add_template_test(f, name=name)\n\n        self.c(register_template_test)\n\n    @t.overload\n    def v(self, aV: T_template_global) -> T_template_global: ...\n    @t.overload\n    def v(\n        self, aW: str | None = None\n    ) -> t.Callable[[T_template_global], T_template_global]: ...\n    @setupmethod\n    def v(\n        self, aX: T_template_global | str | None = None\n    ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n        \"\"\"Decorate a function to register it as a custom Jinja global. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_global` method may be used to register a\n        function later rather than decorating.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_global`.\n\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(aX):\n            self.w(aX)\n            return aX\n\n        def decorator(aY: T_template_global) -> T_template_global:\n            self.w(aY, name=name)\n            return aY\n\n        return decorator\n\n    @setupmethod\n    def w(\n        self, aZ: ft.TemplateGlobalCallable, ba: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja global.\n\n        The :meth:`app_template_global` decorator can be used to register a function\n        by decorating instead.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_global`.\n\n        :param f: The function to register.\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_global(bb: BlueprintSetupState) -> None:\n            bb.app.add_template_global(f, name=name)\n\n        self.c(register_template_global)\n\n    @setupmethod\n    def x(self, bc: T_before_request) -> T_before_request:\n        \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n        \"\"\"\n        self.c(\n            lambda s: s.app.before_request_funcs.setdefault(None, []).append(bc)\n        )\n        return bc\n\n    @setupmethod\n    def y(self, bd: T_after_request) -> T_after_request:\n        \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n        \"\"\"\n        self.c(\n            lambda s: s.app.after_request_funcs.setdefault(None, []).append(bd)\n        )\n        return bd\n\n    @setupmethod\n    def z(self, be: T_teardown) -> T_teardown:\n        \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n        \"\"\"\n        self.c(\n            lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(be)\n        )\n        return be\n\n    @setupmethod\n    def A(\n        self, bf: T_template_context_processor\n    ) -> T_template_context_processor:\n        \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n        only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n        \"\"\"\n        self.c(\n            lambda s: s.app.template_context_processors.setdefault(None, []).append(bf)\n        )\n        return bf\n\n    @setupmethod\n    def B(\n        self, bg: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n        \"\"\"\n\n        def decorator(bh: T_error_handler) -> T_error_handler:\n            def from_blueprint(bi: BlueprintSetupState) -> None:\n                bi.app.errorhandler(code)(f)\n\n            self.c(from_blueprint)\n            return bh\n\n        return decorator\n\n    @setupmethod\n    def C(\n        self, bj: T_url_value_preprocessor\n    ) -> T_url_value_preprocessor:\n        \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n        \"\"\"\n        self.c(\n            lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(bj)\n        )\n        return bj\n\n    @setupmethod\n    def D(self, bk: T_url_defaults) -> T_url_defaults:\n        \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n        \"\"\"\n        self.c(\n            lambda s: s.app.url_default_functions.setdefault(None, []).append(bk)\n        )\n        return bk\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-d841e365cd245065", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "becd12a0eb9261480513d67b24bc13ac3e18c9ebad5180e19e64d5e8d1779f50", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 585, "local_path": "identifiers/garble-identifiers/I04__flask__Blueprint__942bfe3f.py", "order": 4, "original_content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "parent_variant_id": "pyint-c20045673c45-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/blueprints.py#L119-L692", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 304, "identifiers_declared": 111}, "unit_kind": "class", "unit_name": "Blueprint", "variant_id": "pyint-8849942bfe3f-I04", "group_id": "py-d841e365cd245065", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 649, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-aabbef153eda-I05", "source": "from __future__ import annotations\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nclass Blueprint(Scaffold):\n    \"\"\"Represents a blueprint, a collection of routes and other\n    app-related functions that can be registered on a real application\n    later.\n\n    A blueprint is an object that allows defining application functions\n    without requiring an application object ahead of time. It uses the\n    same decorators as :class:`~flask.Flask`, but defers the need for an\n    application by recording them for later registration.\n\n    Decorating a function with a blueprint creates a deferred function\n    that is called with :class:`~flask.blueprints.BlueprintSetupState`\n    when the blueprint is registered on an application.\n\n    See :doc:`/blueprints` for more information.\n\n    :param name: The name of the blueprint. Will be prepended to each\n        endpoint name.\n    :param import_name: The name of the blueprint package, usually\n        ``__name__``. This helps locate the ``root_path`` for the\n        blueprint.\n    :param static_folder: A folder with static files that should be\n        served by the blueprint's static route. The path is relative to\n        the blueprint's root path. Blueprint static files are disabled\n        by default.\n    :param static_url_path: The url to serve static files from.\n        Defaults to ``static_folder``. If the blueprint does not have\n        a ``url_prefix``, the app's static route will take precedence,\n        and the blueprint's static files won't be accessible.\n    :param template_folder: A folder with templates that should be added\n        to the app's template search path. The path is relative to the\n        blueprint's root path. Blueprint templates are disabled by\n        default. Blueprint templates have a lower precedence than those\n        in the app's templates folder.\n    :param url_prefix: A path to prepend to all of the blueprint's URLs,\n        to make them distinct from the rest of the app's routes.\n    :param subdomain: A subdomain that blueprint routes will match on by\n        default.\n    :param url_defaults: A dict of default values that blueprint routes\n        will receive by default.\n    :param root_path: By default, the blueprint will automatically set\n        this based on ``import_name``. In certain situations this\n        automatic detection can fail, so the path can be specified\n        manually instead.\n\n    .. versionchanged:: 1.1.0\n        Blueprints have a ``cli`` group to register nested CLI commands.\n        The ``cli_group`` parameter controls the name of the group under\n        the ``flask`` command.\n\n    .. versionadded:: 0.7\n    \"\"\"\n\n    _got_registered_once = False\n\n    def __init__(\n        self,\n        name: str,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        url_prefix: str | None = None,\n        subdomain: str | None = None,\n        url_defaults: dict[str, t.Any] | None = None,\n        root_path: str | None = None,\n        cli_group: str | None = _sentinel,  # type: ignore[assignment]\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_folder=static_folder,\n            static_url_path=static_url_path,\n            template_folder=template_folder,\n            root_path=root_path,\n        )\n\n        if not name:\n            raise ValueError(\"'name' may not be empty.\")\n\n        if \".\" in name:\n            raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n        self.name = name\n        self.url_prefix = url_prefix\n        self.subdomain = subdomain\n        self.deferred_functions: list[DeferredSetupFunction] = []\n\n        if url_defaults is None:\n            url_defaults = {}\n\n        self.url_values_defaults = url_defaults\n        self.cli_group = cli_group\n        self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        if self._got_registered_once:\n            raise AssertionError(\n                f\"The setup method '{f_name}' can no longer be called on the blueprint\"\n                f\" '{self.name}'. It has already been registered at least once, any\"\n                \" changes will not be applied consistently.\\n\"\n                \"Make sure all imports, decorators, functions, etc. needed to set up\"\n                \" the blueprint are done before registering it.\"\n            )\n\n    @setupmethod\n    def record(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Registers a function that is called when the blueprint is\n        registered on the application.  This function is called with the\n        state as argument as returned by the :meth:`make_setup_state`\n        method.\n        \"\"\"\n        self.deferred_functions.append(func)\n\n    @setupmethod\n    def record_once(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Works like :meth:`record` but wraps the function in another\n        function that will ensure the function is only called once.  If the\n        blueprint is registered a second time on the application, the\n        function passed is not called.\n        \"\"\"\n\n        def wrapper(state: BlueprintSetupState) -> None:\n            if state.first_registration:\n                func(state)\n\n        self.record(update_wrapper(wrapper, func))\n\n    def make_setup_state(\n        self, app: App, options: dict[str, t.Any], first_registration: bool = False\n    ) -> BlueprintSetupState:\n        \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n        object that is later passed to the register callback functions.\n        Subclasses can override this to return a subclass of the setup state.\n        \"\"\"\n        return BlueprintSetupState(self, app, options, first_registration)\n\n    @setupmethod\n    def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:\n        \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n        arguments passed to this method will override the defaults set\n        on the blueprint.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if blueprint is self:\n            raise ValueError(\"Cannot register a blueprint on itself\")\n        self._blueprints.append((blueprint, options))\n\n    def register(self, app: App, options: dict[str, t.Any]) -> None:\n        \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n        views and callbacks registered on the blueprint with the\n        application. Creates a :class:`.BlueprintSetupState` and calls\n        each :meth:`record` callback with it.\n\n        :param app: The application this blueprint is being registered\n            with.\n        :param options: Keyword arguments forwarded from\n            :meth:`~Flask.register_blueprint`.\n\n        .. versionchanged:: 2.3\n            Nested blueprints now correctly apply subdomains.\n\n        .. versionchanged:: 2.1\n            Registering the same blueprint with the same name multiple\n            times is an error.\n\n        .. versionchanged:: 2.0.1\n            Nested blueprints are registered with their dotted name.\n            This allows different blueprints with the same name to be\n            nested at different locations.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n        \"\"\"\n        name_prefix = options.get(\"name_prefix\", \"\")\n        self_name = options.get(\"name\", self.name)\n        name = f\"{name_prefix}.{self_name}\".lstrip(\".\")\n\n        if name in app.blueprints:\n            bp_desc = \"this\" if app.blueprints[name] is self else \"a different\"\n            existing_at = f\" '{name}'\" if self_name != name else \"\"\n\n            raise ValueError(\n                f\"The name '{self_name}' is already registered for\"\n                f\" {bp_desc} blueprint{existing_at}. Use 'name=' to\"\n                f\" provide a unique name.\"\n            )\n\n        first_bp_registration = not any(bp is self for bp in app.blueprints.values())\n        first_name_registration = name not in app.blueprints\n\n        app.blueprints[name] = self\n        self._got_registered_once = True\n        state = self.make_setup_state(app, options, first_bp_registration)\n\n        if self.has_static_folder:\n            state.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                view_func=self.send_static_file,  # type: ignore[attr-defined]\n                endpoint=\"static\",\n            )\n\n        # Merge blueprint data into parent.\n        if first_bp_registration or first_name_registration:\n            self._merge_blueprint_funcs(app, name)\n\n        for deferred in self.deferred_functions:\n            deferred(state)\n\n        cli_resolved_group = options.get(\"cli_group\", self.cli_group)\n\n        if self.cli.commands:\n            if cli_resolved_group is None:\n                app.cli.commands.update(self.cli.commands)\n            elif cli_resolved_group is _sentinel:\n                self.cli.name = name\n                app.cli.add_command(self.cli)\n            else:\n                self.cli.name = cli_resolved_group\n                app.cli.add_command(self.cli)\n\n        for blueprint, bp_options in self._blueprints:\n            bp_options = bp_options.copy()\n            bp_url_prefix = bp_options.get(\"url_prefix\")\n            bp_subdomain = bp_options.get(\"subdomain\")\n\n            if bp_subdomain is None:\n                bp_subdomain = blueprint.subdomain\n\n            if state.subdomain is not None and bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain + \".\" + state.subdomain\n            elif bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain\n            elif state.subdomain is not None:\n                bp_options[\"subdomain\"] = state.subdomain\n\n            if bp_url_prefix is None:\n                bp_url_prefix = blueprint.url_prefix\n\n            if state.url_prefix is not None and bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = (\n                    state.url_prefix.rstrip(\"/\") + \"/\" + bp_url_prefix.lstrip(\"/\")\n                )\n            elif bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = bp_url_prefix\n            elif state.url_prefix is not None:\n                bp_options[\"url_prefix\"] = state.url_prefix\n\n            bp_options[\"name_prefix\"] = name\n            blueprint.register(app, bp_options)\n\n    def _merge_blueprint_funcs(self, app: App, name: str) -> None:\n        def extend(\n            bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n            parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n        ) -> None:\n            for key, values in bp_dict.items():\n                key = name if key is None else f\"{name}.{key}\"\n                parent_dict[key].extend(values)\n\n        for key, value in self.error_handler_spec.items():\n            key = name if key is None else f\"{name}.{key}\"\n            value = defaultdict(\n                dict,\n                {\n                    code: {exc_class: func for exc_class, func in code_values.items()}\n                    for code, code_values in value.items()\n                },\n            )\n            app.error_handler_spec[key] = value\n\n        for endpoint, func in self.view_functions.items():\n            app.view_functions[endpoint] = func\n\n        extend(self.before_request_funcs, app.before_request_funcs)\n        extend(self.after_request_funcs, app.after_request_funcs)\n        extend(\n            self.teardown_request_funcs,\n            app.teardown_request_funcs,\n        )\n        extend(self.url_default_functions, app.url_default_functions)\n        extend(self.url_value_preprocessors, app.url_value_preprocessors)\n        extend(self.template_context_processors, app.template_context_processors)\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n        full documentation.\n\n        The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n        used with :func:`url_for`, is prefixed with the blueprint's name.\n        \"\"\"\n        if endpoint and \".\" in endpoint:\n            raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n        if view_func and hasattr(view_func, \"__name__\") and \".\" in view_func.__name__:\n            raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n        self.record(\n            lambda s: s.add_url_rule(\n                rule,\n                endpoint,\n                view_func,\n                provide_automatic_options=provide_automatic_options,\n                **options,\n            )\n        )\n\n    @t.overload\n    def app_template_filter(self, name: T_template_filter) -> T_template_filter: ...\n    @t.overload\n    def app_template_filter(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_filter], T_template_filter]: ...\n    @setupmethod\n    def app_template_filter(\n        self, name: T_template_filter | str | None = None\n    ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n        \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_filter` method may be used to register a\n        function later rather than decorating.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_filter`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n        if callable(name):\n            self.add_app_template_filter(name)\n            return name\n\n        def decorator(f: T_template_filter) -> T_template_filter:\n            self.add_app_template_filter(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_filter(\n        self, f: ft.TemplateFilterCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja filter.\n\n        The :meth:`app_template_filter` decorator can be used to register a\n        function by decorating instead.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_filter`.\n\n        :param f: The function to register.\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n\n        def register_template_filter(state: BlueprintSetupState) -> None:\n            state.app.add_template_filter(f, name=name)\n\n        self.record_once(register_template_filter)\n\n    @t.overload\n    def app_template_test(self, name: T_template_test) -> T_template_test: ...\n    @t.overload\n    def app_template_test(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_test], T_template_test]: ...\n    @setupmethod\n    def app_template_test(\n        self, name: T_template_test | str | None = None\n    ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n        \"\"\"Decorate a function to register it as a custom Jinja test. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_test` method may be used to register a\n        function later rather than decorating.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_test`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_test(name)\n            return name\n\n        def decorator(f: T_template_test) -> T_template_test:\n            self.add_app_template_test(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_test(\n        self, f: ft.TemplateTestCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja test.\n\n        The :meth:`app_template_test` decorator can be used to register a\n        function by decorating instead.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_test`.\n\n        :param f: The function to register.\n        :param name: The name to register the test as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_test(state: BlueprintSetupState) -> None:\n            state.app.add_template_test(f, name=name)\n\n        self.record_once(register_template_test)\n\n    @t.overload\n    def app_template_global(self, name: T_template_global) -> T_template_global: ...\n    @t.overload\n    def app_template_global(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_global], T_template_global]: ...\n    @setupmethod\n    def app_template_global(\n        self, name: T_template_global | str | None = None\n    ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n        \"\"\"Decorate a function to register it as a custom Jinja global. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_global` method may be used to register a\n        function later rather than decorating.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_global`.\n\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_global(name)\n            return name\n\n        def decorator(f: T_template_global) -> T_template_global:\n            self.add_app_template_global(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_global(\n        self, f: ft.TemplateGlobalCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja global.\n\n        The :meth:`app_template_global` decorator can be used to register a function\n        by decorating instead.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_global`.\n\n        :param f: The function to register.\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_global(state: BlueprintSetupState) -> None:\n            state.app.add_template_global(f, name=name)\n\n        self.record_once(register_template_global)\n\n    @setupmethod\n    def before_app_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def after_app_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def teardown_app_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_context_processor(\n        self, f: T_template_context_processor\n    ) -> T_template_context_processor:\n        \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n        only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_errorhandler(\n        self, code: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            def from_blueprint(state: BlueprintSetupState) -> None:\n                state.app.errorhandler(code)(f)\n\n            self.record_once(from_blueprint)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def app_url_value_preprocessor(\n        self, f: T_url_value_preprocessor\n    ) -> T_url_value_preprocessor:\n        \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n        )\n        return f\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-d841e365cd245065", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 585, "local_path": "expressions/encode-integer-literals/I05__flask__Blueprint__ef153eda.py", "order": 5, "original_content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "parent_variant_id": "pyint-c20045673c45-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/blueprints.py#L119-L692", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "Blueprint", "variant_id": "pyint-aabbef153eda-I05", "group_id": "py-d841e365cd245065", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 650, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3cb2e34c224f-I06", "source": "from __future__ import annotations\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nclass Blueprint(Scaffold):\n    \"\"\"Represents a blueprint, a collection of routes and other\n    app-related functions that can be registered on a real application\n    later.\n\n    A blueprint is an object that allows defining application functions\n    without requiring an application object ahead of time. It uses the\n    same decorators as :class:`~flask.Flask`, but defers the need for an\n    application by recording them for later registration.\n\n    Decorating a function with a blueprint creates a deferred function\n    that is called with :class:`~flask.blueprints.BlueprintSetupState`\n    when the blueprint is registered on an application.\n\n    See :doc:`/blueprints` for more information.\n\n    :param name: The name of the blueprint. Will be prepended to each\n        endpoint name.\n    :param import_name: The name of the blueprint package, usually\n        ``__name__``. This helps locate the ``root_path`` for the\n        blueprint.\n    :param static_folder: A folder with static files that should be\n        served by the blueprint's static route. The path is relative to\n        the blueprint's root path. Blueprint static files are disabled\n        by default.\n    :param static_url_path: The url to serve static files from.\n        Defaults to ``static_folder``. If the blueprint does not have\n        a ``url_prefix``, the app's static route will take precedence,\n        and the blueprint's static files won't be accessible.\n    :param template_folder: A folder with templates that should be added\n        to the app's template search path. The path is relative to the\n        blueprint's root path. Blueprint templates are disabled by\n        default. Blueprint templates have a lower precedence than those\n        in the app's templates folder.\n    :param url_prefix: A path to prepend to all of the blueprint's URLs,\n        to make them distinct from the rest of the app's routes.\n    :param subdomain: A subdomain that blueprint routes will match on by\n        default.\n    :param url_defaults: A dict of default values that blueprint routes\n        will receive by default.\n    :param root_path: By default, the blueprint will automatically set\n        this based on ``import_name``. In certain situations this\n        automatic detection can fail, so the path can be specified\n        manually instead.\n\n    .. versionchanged:: 1.1.0\n        Blueprints have a ``cli`` group to register nested CLI commands.\n        The ``cli_group`` parameter controls the name of the group under\n        the ``flask`` command.\n\n    .. versionadded:: 0.7\n    \"\"\"\n\n    _got_registered_once = False\n\n    def __init__(\n        self,\n        name: str,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        url_prefix: str | None = None,\n        subdomain: str | None = None,\n        url_defaults: dict[str, t.Any] | None = None,\n        root_path: str | None = None,\n        cli_group: str | None = _sentinel,  # type: ignore[assignment]\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_folder=static_folder,\n            static_url_path=static_url_path,\n            template_folder=template_folder,\n            root_path=root_path,\n        )\n\n        if not (not name):\n            pass\n        else:\n            raise ValueError(\"'name' may not be empty.\")\n\n        if not (\".\" in name):\n            pass\n        else:\n            raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n        self.name = name\n        self.url_prefix = url_prefix\n        self.subdomain = subdomain\n        self.deferred_functions: list[DeferredSetupFunction] = []\n\n        if not (url_defaults is None):\n            pass\n        else:\n            url_defaults = {}\n\n        self.url_values_defaults = url_defaults\n        self.cli_group = cli_group\n        self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        if not (self._got_registered_once):\n            pass\n        else:\n            raise AssertionError(\n                f\"The setup method '{f_name}' can no longer be called on the blueprint\"\n                f\" '{self.name}'. It has already been registered at least once, any\"\n                \" changes will not be applied consistently.\\n\"\n                \"Make sure all imports, decorators, functions, etc. needed to set up\"\n                \" the blueprint are done before registering it.\"\n            )\n\n    @setupmethod\n    def record(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Registers a function that is called when the blueprint is\n        registered on the application.  This function is called with the\n        state as argument as returned by the :meth:`make_setup_state`\n        method.\n        \"\"\"\n        self.deferred_functions.append(func)\n\n    @setupmethod\n    def record_once(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Works like :meth:`record` but wraps the function in another\n        function that will ensure the function is only called once.  If the\n        blueprint is registered a second time on the application, the\n        function passed is not called.\n        \"\"\"\n\n        def wrapper(state: BlueprintSetupState) -> None:\n            if not (state.first_registration):\n                pass\n            else:\n                func(state)\n\n        self.record(update_wrapper(wrapper, func))\n\n    def make_setup_state(\n        self, app: App, options: dict[str, t.Any], first_registration: bool = False\n    ) -> BlueprintSetupState:\n        \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n        object that is later passed to the register callback functions.\n        Subclasses can override this to return a subclass of the setup state.\n        \"\"\"\n        return BlueprintSetupState(self, app, options, first_registration)\n\n    @setupmethod\n    def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:\n        \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n        arguments passed to this method will override the defaults set\n        on the blueprint.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if not (blueprint is self):\n            pass\n        else:\n            raise ValueError(\"Cannot register a blueprint on itself\")\n        self._blueprints.append((blueprint, options))\n\n    def register(self, app: App, options: dict[str, t.Any]) -> None:\n        \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n        views and callbacks registered on the blueprint with the\n        application. Creates a :class:`.BlueprintSetupState` and calls\n        each :meth:`record` callback with it.\n\n        :param app: The application this blueprint is being registered\n            with.\n        :param options: Keyword arguments forwarded from\n            :meth:`~Flask.register_blueprint`.\n\n        .. versionchanged:: 2.3\n            Nested blueprints now correctly apply subdomains.\n\n        .. versionchanged:: 2.1\n            Registering the same blueprint with the same name multiple\n            times is an error.\n\n        .. versionchanged:: 2.0.1\n            Nested blueprints are registered with their dotted name.\n            This allows different blueprints with the same name to be\n            nested at different locations.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n        \"\"\"\n        name_prefix = options.get(\"name_prefix\", \"\")\n        self_name = options.get(\"name\", self.name)\n        name = f\"{name_prefix}.{self_name}\".lstrip(\".\")\n\n        if not (name in app.blueprints):\n            pass\n        else:\n            bp_desc = \"this\" if app.blueprints[name] is self else \"a different\"\n            existing_at = f\" '{name}'\" if self_name != name else \"\"\n\n            raise ValueError(\n                f\"The name '{self_name}' is already registered for\"\n                f\" {bp_desc} blueprint{existing_at}. Use 'name=' to\"\n                f\" provide a unique name.\"\n            )\n\n        first_bp_registration = not any(bp is self for bp in app.blueprints.values())\n        first_name_registration = name not in app.blueprints\n\n        app.blueprints[name] = self\n        self._got_registered_once = True\n        state = self.make_setup_state(app, options, first_bp_registration)\n\n        if not (self.has_static_folder):\n            pass\n        else:\n            state.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                view_func=self.send_static_file,  # type: ignore[attr-defined]\n                endpoint=\"static\",\n            )\n\n        # Merge blueprint data into parent.\n        if not (first_bp_registration or first_name_registration):\n            pass\n        else:\n            self._merge_blueprint_funcs(app, name)\n\n        for deferred in self.deferred_functions:\n            deferred(state)\n\n        cli_resolved_group = options.get(\"cli_group\", self.cli_group)\n\n        if not (self.cli.commands):\n            pass\n        else:\n            if cli_resolved_group is None:\n                app.cli.commands.update(self.cli.commands)\n            elif cli_resolved_group is _sentinel:\n                self.cli.name = name\n                app.cli.add_command(self.cli)\n            else:\n                self.cli.name = cli_resolved_group\n                app.cli.add_command(self.cli)\n\n        for blueprint, bp_options in self._blueprints:\n            bp_options = bp_options.copy()\n            bp_url_prefix = bp_options.get(\"url_prefix\")\n            bp_subdomain = bp_options.get(\"subdomain\")\n\n            if not (bp_subdomain is None):\n                pass\n            else:\n                bp_subdomain = blueprint.subdomain\n\n            if state.subdomain is not None and bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain + \".\" + state.subdomain\n            elif bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain\n            elif state.subdomain is not None:\n                bp_options[\"subdomain\"] = state.subdomain\n\n            if not (bp_url_prefix is None):\n                pass\n            else:\n                bp_url_prefix = blueprint.url_prefix\n\n            if state.url_prefix is not None and bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = (\n                    state.url_prefix.rstrip(\"/\") + \"/\" + bp_url_prefix.lstrip(\"/\")\n                )\n            elif bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = bp_url_prefix\n            elif state.url_prefix is not None:\n                bp_options[\"url_prefix\"] = state.url_prefix\n\n            bp_options[\"name_prefix\"] = name\n            blueprint.register(app, bp_options)\n\n    def _merge_blueprint_funcs(self, app: App, name: str) -> None:\n        def extend(\n            bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n            parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n        ) -> None:\n            for key, values in bp_dict.items():\n                key = name if key is None else f\"{name}.{key}\"\n                parent_dict[key].extend(values)\n\n        for key, value in self.error_handler_spec.items():\n            key = name if key is None else f\"{name}.{key}\"\n            value = defaultdict(\n                dict,\n                {\n                    code: {exc_class: func for exc_class, func in code_values.items()}\n                    for code, code_values in value.items()\n                },\n            )\n            app.error_handler_spec[key] = value\n\n        for endpoint, func in self.view_functions.items():\n            app.view_functions[endpoint] = func\n\n        extend(self.before_request_funcs, app.before_request_funcs)\n        extend(self.after_request_funcs, app.after_request_funcs)\n        extend(\n            self.teardown_request_funcs,\n            app.teardown_request_funcs,\n        )\n        extend(self.url_default_functions, app.url_default_functions)\n        extend(self.url_value_preprocessors, app.url_value_preprocessors)\n        extend(self.template_context_processors, app.template_context_processors)\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n        full documentation.\n\n        The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n        used with :func:`url_for`, is prefixed with the blueprint's name.\n        \"\"\"\n        if not (endpoint and \".\" in endpoint):\n            pass\n        else:\n            raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n        if not (view_func and hasattr(view_func, \"__name__\") and \".\" in view_func.__name__):\n            pass\n        else:\n            raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n        self.record(\n            lambda s: s.add_url_rule(\n                rule,\n                endpoint,\n                view_func,\n                provide_automatic_options=provide_automatic_options,\n                **options,\n            )\n        )\n\n    @t.overload\n    def app_template_filter(self, name: T_template_filter) -> T_template_filter: ...\n    @t.overload\n    def app_template_filter(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_filter], T_template_filter]: ...\n    @setupmethod\n    def app_template_filter(\n        self, name: T_template_filter | str | None = None\n    ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n        \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_filter` method may be used to register a\n        function later rather than decorating.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_filter`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n        if not (callable(name)):\n            pass\n        else:\n            self.add_app_template_filter(name)\n            return name\n\n        def decorator(f: T_template_filter) -> T_template_filter:\n            self.add_app_template_filter(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_filter(\n        self, f: ft.TemplateFilterCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja filter.\n\n        The :meth:`app_template_filter` decorator can be used to register a\n        function by decorating instead.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_filter`.\n\n        :param f: The function to register.\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n\n        def register_template_filter(state: BlueprintSetupState) -> None:\n            state.app.add_template_filter(f, name=name)\n\n        self.record_once(register_template_filter)\n\n    @t.overload\n    def app_template_test(self, name: T_template_test) -> T_template_test: ...\n    @t.overload\n    def app_template_test(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_test], T_template_test]: ...\n    @setupmethod\n    def app_template_test(\n        self, name: T_template_test | str | None = None\n    ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n        \"\"\"Decorate a function to register it as a custom Jinja test. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_test` method may be used to register a\n        function later rather than decorating.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_test`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if not (callable(name)):\n            pass\n        else:\n            self.add_app_template_test(name)\n            return name\n\n        def decorator(f: T_template_test) -> T_template_test:\n            self.add_app_template_test(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_test(\n        self, f: ft.TemplateTestCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja test.\n\n        The :meth:`app_template_test` decorator can be used to register a\n        function by decorating instead.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_test`.\n\n        :param f: The function to register.\n        :param name: The name to register the test as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_test(state: BlueprintSetupState) -> None:\n            state.app.add_template_test(f, name=name)\n\n        self.record_once(register_template_test)\n\n    @t.overload\n    def app_template_global(self, name: T_template_global) -> T_template_global: ...\n    @t.overload\n    def app_template_global(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_global], T_template_global]: ...\n    @setupmethod\n    def app_template_global(\n        self, name: T_template_global | str | None = None\n    ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n        \"\"\"Decorate a function to register it as a custom Jinja global. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_global` method may be used to register a\n        function later rather than decorating.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_global`.\n\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if not (callable(name)):\n            pass\n        else:\n            self.add_app_template_global(name)\n            return name\n\n        def decorator(f: T_template_global) -> T_template_global:\n            self.add_app_template_global(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_global(\n        self, f: ft.TemplateGlobalCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja global.\n\n        The :meth:`app_template_global` decorator can be used to register a function\n        by decorating instead.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_global`.\n\n        :param f: The function to register.\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_global(state: BlueprintSetupState) -> None:\n            state.app.add_template_global(f, name=name)\n\n        self.record_once(register_template_global)\n\n    @setupmethod\n    def before_app_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def after_app_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def teardown_app_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_context_processor(\n        self, f: T_template_context_processor\n    ) -> T_template_context_processor:\n        \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n        only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_errorhandler(\n        self, code: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            def from_blueprint(state: BlueprintSetupState) -> None:\n                state.app.errorhandler(code)(f)\n\n            self.record_once(from_blueprint)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def app_url_value_preprocessor(\n        self, f: T_url_value_preprocessor\n    ) -> T_url_value_preprocessor:\n        \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n        )\n        return f\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-d841e365cd245065", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "9b18f1b7a45af1c17d2c7c5d164a3349f94f345b11ceac7d8de600f0b6e0b32e", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 619, "local_path": "expressions/invert-conditions/I06__flask__Blueprint__e34c224f.py", "order": 6, "original_content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "parent_variant_id": "pyint-c20045673c45-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/blueprints.py#L119-L692", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 17}, "unit_kind": "class", "unit_name": "Blueprint", "variant_id": "pyint-3cb2e34c224f-I06", "group_id": "py-d841e365cd245065", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 651, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-46fe9863f1c3-I07", "source": "from __future__ import annotations\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nclass Blueprint(Scaffold):\n    \"\"\"Represents a blueprint, a collection of routes and other\n    app-related functions that can be registered on a real application\n    later.\n\n    A blueprint is an object that allows defining application functions\n    without requiring an application object ahead of time. It uses the\n    same decorators as :class:`~flask.Flask`, but defers the need for an\n    application by recording them for later registration.\n\n    Decorating a function with a blueprint creates a deferred function\n    that is called with :class:`~flask.blueprints.BlueprintSetupState`\n    when the blueprint is registered on an application.\n\n    See :doc:`/blueprints` for more information.\n\n    :param name: The name of the blueprint. Will be prepended to each\n        endpoint name.\n    :param import_name: The name of the blueprint package, usually\n        ``__name__``. This helps locate the ``root_path`` for the\n        blueprint.\n    :param static_folder: A folder with static files that should be\n        served by the blueprint's static route. The path is relative to\n        the blueprint's root path. Blueprint static files are disabled\n        by default.\n    :param static_url_path: The url to serve static files from.\n        Defaults to ``static_folder``. If the blueprint does not have\n        a ``url_prefix``, the app's static route will take precedence,\n        and the blueprint's static files won't be accessible.\n    :param template_folder: A folder with templates that should be added\n        to the app's template search path. The path is relative to the\n        blueprint's root path. Blueprint templates are disabled by\n        default. Blueprint templates have a lower precedence than those\n        in the app's templates folder.\n    :param url_prefix: A path to prepend to all of the blueprint's URLs,\n        to make them distinct from the rest of the app's routes.\n    :param subdomain: A subdomain that blueprint routes will match on by\n        default.\n    :param url_defaults: A dict of default values that blueprint routes\n        will receive by default.\n    :param root_path: By default, the blueprint will automatically set\n        this based on ``import_name``. In certain situations this\n        automatic detection can fail, so the path can be specified\n        manually instead.\n\n    .. versionchanged:: 1.1.0\n        Blueprints have a ``cli`` group to register nested CLI commands.\n        The ``cli_group`` parameter controls the name of the group under\n        the ``flask`` command.\n\n    .. versionadded:: 0.7\n    \"\"\"\n\n    _got_registered_once = False\n\n    def __init__(\n        self,\n        name: str,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        url_prefix: str | None = None,\n        subdomain: str | None = None,\n        url_defaults: dict[str, t.Any] | None = None,\n        root_path: str | None = None,\n        cli_group: str | None = _sentinel,  # type: ignore[assignment]\n    ):\n        if ((0x28a5 ^ 0x28a5) != 0):\n            raise AssertionError()\n        super().__init__(\n            import_name=import_name,\n            static_folder=static_folder,\n            static_url_path=static_url_path,\n            template_folder=template_folder,\n            root_path=root_path,\n        )\n\n        if not name:\n            raise ValueError(\"'name' may not be empty.\")\n\n        if \".\" in name:\n            raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n        self.name = name\n        self.url_prefix = url_prefix\n        self.subdomain = subdomain\n        self.deferred_functions: list[DeferredSetupFunction] = []\n\n        if url_defaults is None:\n            url_defaults = {}\n\n        self.url_values_defaults = url_defaults\n        self.cli_group = cli_group\n        self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        if ((0x5aa3 ^ 0x5aa3) != 0):\n            raise AssertionError()\n        if self._got_registered_once:\n            raise AssertionError(\n                f\"The setup method '{f_name}' can no longer be called on the blueprint\"\n                f\" '{self.name}'. It has already been registered at least once, any\"\n                \" changes will not be applied consistently.\\n\"\n                \"Make sure all imports, decorators, functions, etc. needed to set up\"\n                \" the blueprint are done before registering it.\"\n            )\n\n    @setupmethod\n    def record(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Registers a function that is called when the blueprint is\n        registered on the application.  This function is called with the\n        state as argument as returned by the :meth:`make_setup_state`\n        method.\n        \"\"\"\n        if ((0x649a ^ 0x649a) != 0):\n            raise AssertionError()\n        self.deferred_functions.append(func)\n\n    @setupmethod\n    def record_once(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Works like :meth:`record` but wraps the function in another\n        function that will ensure the function is only called once.  If the\n        blueprint is registered a second time on the application, the\n        function passed is not called.\n        \"\"\"\n        if ((0x16a ^ 0x16a) != 0):\n            raise AssertionError()\n\n        def wrapper(state: BlueprintSetupState) -> None:\n            if ((0x3c78 ^ 0x3c78) != 0):\n                raise AssertionError()\n            if state.first_registration:\n                func(state)\n\n        self.record(update_wrapper(wrapper, func))\n\n    def make_setup_state(\n        self, app: App, options: dict[str, t.Any], first_registration: bool = False\n    ) -> BlueprintSetupState:\n        \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n        object that is later passed to the register callback functions.\n        Subclasses can override this to return a subclass of the setup state.\n        \"\"\"\n        if ((0xe6ae ^ 0xe6ae) != 0):\n            raise AssertionError()\n        return BlueprintSetupState(self, app, options, first_registration)\n\n    @setupmethod\n    def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:\n        \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n        arguments passed to this method will override the defaults set\n        on the blueprint.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if ((0x82be ^ 0x82be) != 0):\n            raise AssertionError()\n        if blueprint is self:\n            raise ValueError(\"Cannot register a blueprint on itself\")\n        self._blueprints.append((blueprint, options))\n\n    def register(self, app: App, options: dict[str, t.Any]) -> None:\n        \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n        views and callbacks registered on the blueprint with the\n        application. Creates a :class:`.BlueprintSetupState` and calls\n        each :meth:`record` callback with it.\n\n        :param app: The application this blueprint is being registered\n            with.\n        :param options: Keyword arguments forwarded from\n            :meth:`~Flask.register_blueprint`.\n\n        .. versionchanged:: 2.3\n            Nested blueprints now correctly apply subdomains.\n\n        .. versionchanged:: 2.1\n            Registering the same blueprint with the same name multiple\n            times is an error.\n\n        .. versionchanged:: 2.0.1\n            Nested blueprints are registered with their dotted name.\n            This allows different blueprints with the same name to be\n            nested at different locations.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n        \"\"\"\n        if ((0x59e9 ^ 0x59e9) != 0):\n            raise AssertionError()\n        name_prefix = options.get(\"name_prefix\", \"\")\n        self_name = options.get(\"name\", self.name)\n        name = f\"{name_prefix}.{self_name}\".lstrip(\".\")\n\n        if name in app.blueprints:\n            bp_desc = \"this\" if app.blueprints[name] is self else \"a different\"\n            existing_at = f\" '{name}'\" if self_name != name else \"\"\n\n            raise ValueError(\n                f\"The name '{self_name}' is already registered for\"\n                f\" {bp_desc} blueprint{existing_at}. Use 'name=' to\"\n                f\" provide a unique name.\"\n            )\n\n        first_bp_registration = not any(bp is self for bp in app.blueprints.values())\n        first_name_registration = name not in app.blueprints\n\n        app.blueprints[name] = self\n        self._got_registered_once = True\n        state = self.make_setup_state(app, options, first_bp_registration)\n\n        if self.has_static_folder:\n            state.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                view_func=self.send_static_file,  # type: ignore[attr-defined]\n                endpoint=\"static\",\n            )\n\n        # Merge blueprint data into parent.\n        if first_bp_registration or first_name_registration:\n            self._merge_blueprint_funcs(app, name)\n\n        for deferred in self.deferred_functions:\n            deferred(state)\n\n        cli_resolved_group = options.get(\"cli_group\", self.cli_group)\n\n        if self.cli.commands:\n            if cli_resolved_group is None:\n                app.cli.commands.update(self.cli.commands)\n            elif cli_resolved_group is _sentinel:\n                self.cli.name = name\n                app.cli.add_command(self.cli)\n            else:\n                self.cli.name = cli_resolved_group\n                app.cli.add_command(self.cli)\n\n        for blueprint, bp_options in self._blueprints:\n            bp_options = bp_options.copy()\n            bp_url_prefix = bp_options.get(\"url_prefix\")\n            bp_subdomain = bp_options.get(\"subdomain\")\n\n            if bp_subdomain is None:\n                bp_subdomain = blueprint.subdomain\n\n            if state.subdomain is not None and bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain + \".\" + state.subdomain\n            elif bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain\n            elif state.subdomain is not None:\n                bp_options[\"subdomain\"] = state.subdomain\n\n            if bp_url_prefix is None:\n                bp_url_prefix = blueprint.url_prefix\n\n            if state.url_prefix is not None and bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = (\n                    state.url_prefix.rstrip(\"/\") + \"/\" + bp_url_prefix.lstrip(\"/\")\n                )\n            elif bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = bp_url_prefix\n            elif state.url_prefix is not None:\n                bp_options[\"url_prefix\"] = state.url_prefix\n\n            bp_options[\"name_prefix\"] = name\n            blueprint.register(app, bp_options)\n\n    def _merge_blueprint_funcs(self, app: App, name: str) -> None:\n        if ((0xe612 ^ 0xe612) != 0):\n            raise AssertionError()\n        def extend(\n            bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n            parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n        ) -> None:\n            if ((0x5702 ^ 0x5702) != 0):\n                raise AssertionError()\n            for key, values in bp_dict.items():\n                key = name if key is None else f\"{name}.{key}\"\n                parent_dict[key].extend(values)\n\n        for key, value in self.error_handler_spec.items():\n            key = name if key is None else f\"{name}.{key}\"\n            value = defaultdict(\n                dict,\n                {\n                    code: {exc_class: func for exc_class, func in code_values.items()}\n                    for code, code_values in value.items()\n                },\n            )\n            app.error_handler_spec[key] = value\n\n        for endpoint, func in self.view_functions.items():\n            app.view_functions[endpoint] = func\n\n        extend(self.before_request_funcs, app.before_request_funcs)\n        extend(self.after_request_funcs, app.after_request_funcs)\n        extend(\n            self.teardown_request_funcs,\n            app.teardown_request_funcs,\n        )\n        extend(self.url_default_functions, app.url_default_functions)\n        extend(self.url_value_preprocessors, app.url_value_preprocessors)\n        extend(self.template_context_processors, app.template_context_processors)\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n        full documentation.\n\n        The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n        used with :func:`url_for`, is prefixed with the blueprint's name.\n        \"\"\"\n        if ((0xe305 ^ 0xe305) != 0):\n            raise AssertionError()\n        if endpoint and \".\" in endpoint:\n            raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n        if view_func and hasattr(view_func, \"__name__\") and \".\" in view_func.__name__:\n            raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n        self.record(\n            lambda s: s.add_url_rule(\n                rule,\n                endpoint,\n                view_func,\n                provide_automatic_options=provide_automatic_options,\n                **options,\n            )\n        )\n\n    @t.overload\n    def app_template_filter(self, name: T_template_filter) -> T_template_filter: ...\n    @t.overload\n    def app_template_filter(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_filter], T_template_filter]: ...\n    @setupmethod\n    def app_template_filter(\n        self, name: T_template_filter | str | None = None\n    ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n        \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_filter` method may be used to register a\n        function later rather than decorating.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_filter`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n        if ((0x2164 ^ 0x2164) != 0):\n            raise AssertionError()\n        if callable(name):\n            self.add_app_template_filter(name)\n            return name\n\n        def decorator(f: T_template_filter) -> T_template_filter:\n            if ((0xec57 ^ 0xec57) != 0):\n                raise AssertionError()\n            self.add_app_template_filter(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_filter(\n        self, f: ft.TemplateFilterCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja filter.\n\n        The :meth:`app_template_filter` decorator can be used to register a\n        function by decorating instead.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_filter`.\n\n        :param f: The function to register.\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n        if ((0x59fe ^ 0x59fe) != 0):\n            raise AssertionError()\n\n        def register_template_filter(state: BlueprintSetupState) -> None:\n            if ((0xf7da ^ 0xf7da) != 0):\n                raise AssertionError()\n            state.app.add_template_filter(f, name=name)\n\n        self.record_once(register_template_filter)\n\n    @t.overload\n    def app_template_test(self, name: T_template_test) -> T_template_test: ...\n    @t.overload\n    def app_template_test(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_test], T_template_test]: ...\n    @setupmethod\n    def app_template_test(\n        self, name: T_template_test | str | None = None\n    ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n        \"\"\"Decorate a function to register it as a custom Jinja test. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_test` method may be used to register a\n        function later rather than decorating.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_test`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if ((0x9487 ^ 0x9487) != 0):\n            raise AssertionError()\n        if callable(name):\n            self.add_app_template_test(name)\n            return name\n\n        def decorator(f: T_template_test) -> T_template_test:\n            if ((0x8cbd ^ 0x8cbd) != 0):\n                raise AssertionError()\n            self.add_app_template_test(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_test(\n        self, f: ft.TemplateTestCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja test.\n\n        The :meth:`app_template_test` decorator can be used to register a\n        function by decorating instead.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_test`.\n\n        :param f: The function to register.\n        :param name: The name to register the test as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if ((0x5bbf ^ 0x5bbf) != 0):\n            raise AssertionError()\n\n        def register_template_test(state: BlueprintSetupState) -> None:\n            if ((0xdcb ^ 0xdcb) != 0):\n                raise AssertionError()\n            state.app.add_template_test(f, name=name)\n\n        self.record_once(register_template_test)\n\n    @t.overload\n    def app_template_global(self, name: T_template_global) -> T_template_global: ...\n    @t.overload\n    def app_template_global(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_global], T_template_global]: ...\n    @setupmethod\n    def app_template_global(\n        self, name: T_template_global | str | None = None\n    ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n        \"\"\"Decorate a function to register it as a custom Jinja global. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_global` method may be used to register a\n        function later rather than decorating.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_global`.\n\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if ((0xbae3 ^ 0xbae3) != 0):\n            raise AssertionError()\n        if callable(name):\n            self.add_app_template_global(name)\n            return name\n\n        def decorator(f: T_template_global) -> T_template_global:\n            if ((0x6797 ^ 0x6797) != 0):\n                raise AssertionError()\n            self.add_app_template_global(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_global(\n        self, f: ft.TemplateGlobalCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja global.\n\n        The :meth:`app_template_global` decorator can be used to register a function\n        by decorating instead.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_global`.\n\n        :param f: The function to register.\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if ((0x5bbb ^ 0x5bbb) != 0):\n            raise AssertionError()\n\n        def register_template_global(state: BlueprintSetupState) -> None:\n            if ((0x1362 ^ 0x1362) != 0):\n                raise AssertionError()\n            state.app.add_template_global(f, name=name)\n\n        self.record_once(register_template_global)\n\n    @setupmethod\n    def before_app_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n        \"\"\"\n        if ((0x29e6 ^ 0x29e6) != 0):\n            raise AssertionError()\n        self.record_once(\n            lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def after_app_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n        \"\"\"\n        if ((0x6397 ^ 0x6397) != 0):\n            raise AssertionError()\n        self.record_once(\n            lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def teardown_app_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n        \"\"\"\n        if ((0x7717 ^ 0x7717) != 0):\n            raise AssertionError()\n        self.record_once(\n            lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_context_processor(\n        self, f: T_template_context_processor\n    ) -> T_template_context_processor:\n        \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n        only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n        \"\"\"\n        if ((0x24c6 ^ 0x24c6) != 0):\n            raise AssertionError()\n        self.record_once(\n            lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_errorhandler(\n        self, code: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n        \"\"\"\n        if ((0x99d9 ^ 0x99d9) != 0):\n            raise AssertionError()\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            if ((0xe5c6 ^ 0xe5c6) != 0):\n                raise AssertionError()\n            def from_blueprint(state: BlueprintSetupState) -> None:\n                if ((0xc9cc ^ 0xc9cc) != 0):\n                    raise AssertionError()\n                state.app.errorhandler(code)(f)\n\n            self.record_once(from_blueprint)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def app_url_value_preprocessor(\n        self, f: T_url_value_preprocessor\n    ) -> T_url_value_preprocessor:\n        \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n        \"\"\"\n        if ((0x922a ^ 0x922a) != 0):\n            raise AssertionError()\n        self.record_once(\n            lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n        \"\"\"\n        if ((0x658e ^ 0x658e) != 0):\n            raise AssertionError()\n        self.record_once(\n            lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n        )\n        return f\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-d841e365cd245065", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "4b32abc9b5022fa81fe2de423e40d011ccaea10979707da217a5f5ba14664f0f", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 649, "local_path": "code-injection/insert-dead-branches/I07__flask__Blueprint__9863f1c3.py", "order": 7, "original_content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "parent_variant_id": "pyint-c20045673c45-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/blueprints.py#L119-L692", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 32}, "unit_kind": "class", "unit_name": "Blueprint", "variant_id": "pyint-46fe9863f1c3-I07", "group_id": "py-d841e365cd245065", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 652, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7346589edbed-I08", "source": "from __future__ import annotations\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nclass Blueprint(Scaffold):\n    \"\"\"Represents a blueprint, a collection of routes and other\n    app-related functions that can be registered on a real application\n    later.\n\n    A blueprint is an object that allows defining application functions\n    without requiring an application object ahead of time. It uses the\n    same decorators as :class:`~flask.Flask`, but defers the need for an\n    application by recording them for later registration.\n\n    Decorating a function with a blueprint creates a deferred function\n    that is called with :class:`~flask.blueprints.BlueprintSetupState`\n    when the blueprint is registered on an application.\n\n    See :doc:`/blueprints` for more information.\n\n    :param name: The name of the blueprint. Will be prepended to each\n        endpoint name.\n    :param import_name: The name of the blueprint package, usually\n        ``__name__``. This helps locate the ``root_path`` for the\n        blueprint.\n    :param static_folder: A folder with static files that should be\n        served by the blueprint's static route. The path is relative to\n        the blueprint's root path. Blueprint static files are disabled\n        by default.\n    :param static_url_path: The url to serve static files from.\n        Defaults to ``static_folder``. If the blueprint does not have\n        a ``url_prefix``, the app's static route will take precedence,\n        and the blueprint's static files won't be accessible.\n    :param template_folder: A folder with templates that should be added\n        to the app's template search path. The path is relative to the\n        blueprint's root path. Blueprint templates are disabled by\n        default. Blueprint templates have a lower precedence than those\n        in the app's templates folder.\n    :param url_prefix: A path to prepend to all of the blueprint's URLs,\n        to make them distinct from the rest of the app's routes.\n    :param subdomain: A subdomain that blueprint routes will match on by\n        default.\n    :param url_defaults: A dict of default values that blueprint routes\n        will receive by default.\n    :param root_path: By default, the blueprint will automatically set\n        this based on ``import_name``. In certain situations this\n        automatic detection can fail, so the path can be specified\n        manually instead.\n\n    .. versionchanged:: 1.1.0\n        Blueprints have a ``cli`` group to register nested CLI commands.\n        The ``cli_group`` parameter controls the name of the group under\n        the ``flask`` command.\n\n    .. versionadded:: 0.7\n    \"\"\"\n\n    _got_registered_once = False\n\n    def __init__(\n        self,\n        name: str,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        url_prefix: str | None = None,\n        subdomain: str | None = None,\n        url_defaults: dict[str, t.Any] | None = None,\n        root_path: str | None = None,\n        cli_group: str | None = _sentinel,  # type: ignore[assignment]\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_folder=static_folder,\n            static_url_path=static_url_path,\n            template_folder=template_folder,\n            root_path=root_path,\n        )\n\n        if not name:\n            raise ValueError(\"'name' may not be empty.\")\n\n        if \".\" in name:\n            raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n        self.name = name\n        self.url_prefix = url_prefix\n        self.subdomain = subdomain\n        self.deferred_functions: list[DeferredSetupFunction] = []\n\n        if url_defaults is None:\n            url_defaults = {}\n\n        self.url_values_defaults = url_defaults\n        self.cli_group = cli_group\n        self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        if self._got_registered_once:\n            raise AssertionError(\n                f\"The setup method '{f_name}' can no longer be called on the blueprint\"\n                f\" '{self.name}'. It has already been registered at least once, any\"\n                \" changes will not be applied consistently.\\n\"\n                \"Make sure all imports, decorators, functions, etc. needed to set up\"\n                \" the blueprint are done before registering it.\"\n            )\n\n    @setupmethod\n    def record(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Registers a function that is called when the blueprint is\n        registered on the application.  This function is called with the\n        state as argument as returned by the :meth:`make_setup_state`\n        method.\n        \"\"\"\n        self.deferred_functions.append(func)\n\n    @setupmethod\n    def record_once(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Works like :meth:`record` but wraps the function in another\n        function that will ensure the function is only called once.  If the\n        blueprint is registered a second time on the application, the\n        function passed is not called.\n        \"\"\"\n\n        def wrapper(state: BlueprintSetupState) -> None:\n            if state.first_registration:\n                func(state)\n\n        self.record(update_wrapper(wrapper, func))\n\n    def make_setup_state(\n        self, app: App, options: dict[str, t.Any], first_registration: bool = False\n    ) -> BlueprintSetupState:\n        \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n        object that is later passed to the register callback functions.\n        Subclasses can override this to return a subclass of the setup state.\n        \"\"\"\n        return BlueprintSetupState(self, app, options, first_registration)\n\n    @setupmethod\n    def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:\n        \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n        arguments passed to this method will override the defaults set\n        on the blueprint.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if blueprint is self:\n            raise ValueError(\"Cannot register a blueprint on itself\")\n        self._blueprints.append((blueprint, options))\n\n    def register(self, app: App, options: dict[str, t.Any]) -> None:\n        \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n        views and callbacks registered on the blueprint with the\n        application. Creates a :class:`.BlueprintSetupState` and calls\n        each :meth:`record` callback with it.\n\n        :param app: The application this blueprint is being registered\n            with.\n        :param options: Keyword arguments forwarded from\n            :meth:`~Flask.register_blueprint`.\n\n        .. versionchanged:: 2.3\n            Nested blueprints now correctly apply subdomains.\n\n        .. versionchanged:: 2.1\n            Registering the same blueprint with the same name multiple\n            times is an error.\n\n        .. versionchanged:: 2.0.1\n            Nested blueprints are registered with their dotted name.\n            This allows different blueprints with the same name to be\n            nested at different locations.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n        \"\"\"\n        name_prefix = options.get(\"name_prefix\", \"\")\n        self_name = options.get(\"name\", self.name)\n        name = f\"{name_prefix}.{self_name}\".lstrip(\".\")\n\n        if name in app.blueprints:\n            bp_desc = \"this\" if app.blueprints[name] is self else \"a different\"\n            existing_at = f\" '{name}'\" if self_name != name else \"\"\n\n            raise ValueError(\n                f\"The name '{self_name}' is already registered for\"\n                f\" {bp_desc} blueprint{existing_at}. Use 'name=' to\"\n                f\" provide a unique name.\"\n            )\n\n        first_bp_registration = not any(bp is self for bp in app.blueprints.values())\n        first_name_registration = name not in app.blueprints\n\n        app.blueprints[name] = self\n        self._got_registered_once = True\n        state = self.make_setup_state(app, options, first_bp_registration)\n\n        if self.has_static_folder:\n            state.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                view_func=self.send_static_file,  # type: ignore[attr-defined]\n                endpoint=\"static\",\n            )\n\n        # Merge blueprint data into parent.\n        if first_bp_registration or first_name_registration:\n            self._merge_blueprint_funcs(app, name)\n\n        for deferred in self.deferred_functions:\n            deferred(state)\n\n        cli_resolved_group = options.get(\"cli_group\", self.cli_group)\n\n        if self.cli.commands:\n            if cli_resolved_group is None:\n                app.cli.commands.update(self.cli.commands)\n            elif cli_resolved_group is _sentinel:\n                self.cli.name = name\n                app.cli.add_command(self.cli)\n            else:\n                self.cli.name = cli_resolved_group\n                app.cli.add_command(self.cli)\n\n        for blueprint, bp_options in self._blueprints:\n            bp_options = bp_options.copy()\n            bp_url_prefix = bp_options.get(\"url_prefix\")\n            bp_subdomain = bp_options.get(\"subdomain\")\n\n            if bp_subdomain is None:\n                bp_subdomain = blueprint.subdomain\n\n            if state.subdomain is not None and bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain + \".\" + state.subdomain\n            elif bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain\n            elif state.subdomain is not None:\n                bp_options[\"subdomain\"] = state.subdomain\n\n            if bp_url_prefix is None:\n                bp_url_prefix = blueprint.url_prefix\n\n            if state.url_prefix is not None and bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = (\n                    state.url_prefix.rstrip(\"/\") + \"/\" + bp_url_prefix.lstrip(\"/\")\n                )\n            elif bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = bp_url_prefix\n            elif state.url_prefix is not None:\n                bp_options[\"url_prefix\"] = state.url_prefix\n\n            bp_options[\"name_prefix\"] = name\n            blueprint.register(app, bp_options)\n\n    def _merge_blueprint_funcs(self, app: App, name: str) -> None:\n        def extend(\n            bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n            parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n        ) -> None:\n            for key, values in bp_dict.items():\n                key = name if key is None else f\"{name}.{key}\"\n                parent_dict[key].extend(values)\n\n        for key, value in self.error_handler_spec.items():\n            key = name if key is None else f\"{name}.{key}\"\n            value = defaultdict(\n                dict,\n                {\n                    code: {exc_class: func for exc_class, func in code_values.items()}\n                    for code, code_values in value.items()\n                },\n            )\n            app.error_handler_spec[key] = value\n\n        for endpoint, func in self.view_functions.items():\n            app.view_functions[endpoint] = func\n\n        extend(self.before_request_funcs, app.before_request_funcs)\n        extend(self.after_request_funcs, app.after_request_funcs)\n        extend(\n            self.teardown_request_funcs,\n            app.teardown_request_funcs,\n        )\n        extend(self.url_default_functions, app.url_default_functions)\n        extend(self.url_value_preprocessors, app.url_value_preprocessors)\n        extend(self.template_context_processors, app.template_context_processors)\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n        full documentation.\n\n        The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n        used with :func:`url_for`, is prefixed with the blueprint's name.\n        \"\"\"\n        if endpoint and \".\" in endpoint:\n            raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n        if view_func and hasattr(view_func, \"__name__\") and \".\" in view_func.__name__:\n            raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n        self.record(\n            lambda s: s.add_url_rule(\n                rule,\n                endpoint,\n                view_func,\n                provide_automatic_options=provide_automatic_options,\n                **options,\n            )\n        )\n\n    @t.overload\n    def app_template_filter(self, name: T_template_filter) -> T_template_filter: ...\n    @t.overload\n    def app_template_filter(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_filter], T_template_filter]: ...\n    @setupmethod\n    def app_template_filter(\n        self, name: T_template_filter | str | None = None\n    ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n        \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_filter` method may be used to register a\n        function later rather than decorating.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_filter`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n        if callable(name):\n            self.add_app_template_filter(name)\n            return name\n\n        def decorator(f: T_template_filter) -> T_template_filter:\n            self.add_app_template_filter(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_filter(\n        self, f: ft.TemplateFilterCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja filter.\n\n        The :meth:`app_template_filter` decorator can be used to register a\n        function by decorating instead.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_filter`.\n\n        :param f: The function to register.\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n\n        def register_template_filter(state: BlueprintSetupState) -> None:\n            state.app.add_template_filter(f, name=name)\n\n        self.record_once(register_template_filter)\n\n    @t.overload\n    def app_template_test(self, name: T_template_test) -> T_template_test: ...\n    @t.overload\n    def app_template_test(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_test], T_template_test]: ...\n    @setupmethod\n    def app_template_test(\n        self, name: T_template_test | str | None = None\n    ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n        \"\"\"Decorate a function to register it as a custom Jinja test. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_test` method may be used to register a\n        function later rather than decorating.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_test`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_test(name)\n            return name\n\n        def decorator(f: T_template_test) -> T_template_test:\n            self.add_app_template_test(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_test(\n        self, f: ft.TemplateTestCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja test.\n\n        The :meth:`app_template_test` decorator can be used to register a\n        function by decorating instead.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_test`.\n\n        :param f: The function to register.\n        :param name: The name to register the test as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_test(state: BlueprintSetupState) -> None:\n            state.app.add_template_test(f, name=name)\n\n        self.record_once(register_template_test)\n\n    @t.overload\n    def app_template_global(self, name: T_template_global) -> T_template_global: ...\n    @t.overload\n    def app_template_global(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_global], T_template_global]: ...\n    @setupmethod\n    def app_template_global(\n        self, name: T_template_global | str | None = None\n    ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n        \"\"\"Decorate a function to register it as a custom Jinja global. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_global` method may be used to register a\n        function later rather than decorating.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_global`.\n\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_global(name)\n            return name\n\n        def decorator(f: T_template_global) -> T_template_global:\n            self.add_app_template_global(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_global(\n        self, f: ft.TemplateGlobalCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja global.\n\n        The :meth:`app_template_global` decorator can be used to register a function\n        by decorating instead.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_global`.\n\n        :param f: The function to register.\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_global(state: BlueprintSetupState) -> None:\n            state.app.add_template_global(f, name=name)\n\n        self.record_once(register_template_global)\n\n    @setupmethod\n    def before_app_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def after_app_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def teardown_app_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n        \"\"\"\n        starting_position = 2\n        ending_position = 9\n        travel_distance = ending_position - starting_position\n        if travel_distance < 0:\n            travel_distance = -travel_distance\n        self.record_once(\n            lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_context_processor(\n        self, f: T_template_context_processor\n    ) -> T_template_context_processor:\n        \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n        only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_errorhandler(\n        self, code: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            def from_blueprint(state: BlueprintSetupState) -> None:\n                state.app.errorhandler(code)(f)\n\n            self.record_once(from_blueprint)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def app_url_value_preprocessor(\n        self, f: T_url_value_preprocessor\n    ) -> T_url_value_preprocessor:\n        \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n        )\n        return f\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-d841e365cd245065", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "94d56dd59907f8cd5b0cc7ae671c483b90ac971e63355285eeb6b0ca55db4f7a", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 590, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__Blueprint__589edbed.py", "order": 8, "original_content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "parent_variant_id": "pyint-c20045673c45-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/blueprints.py#L119-L692", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 9}, "unit_kind": "class", "unit_name": "Blueprint", "variant_id": "pyint-7346589edbed-I08", "group_id": "py-d841e365cd245065", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 653, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1dd3f7beff5a-I09", "source": "from __future__ import annotations\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nclass Blueprint(Scaffold):\n    \"\"\"Represents a blueprint, a collection of routes and other\n    app-related functions that can be registered on a real application\n    later.\n\n    A blueprint is an object that allows defining application functions\n    without requiring an application object ahead of time. It uses the\n    same decorators as :class:`~flask.Flask`, but defers the need for an\n    application by recording them for later registration.\n\n    Decorating a function with a blueprint creates a deferred function\n    that is called with :class:`~flask.blueprints.BlueprintSetupState`\n    when the blueprint is registered on an application.\n\n    See :doc:`/blueprints` for more information.\n\n    :param name: The name of the blueprint. Will be prepended to each\n        endpoint name.\n    :param import_name: The name of the blueprint package, usually\n        ``__name__``. This helps locate the ``root_path`` for the\n        blueprint.\n    :param static_folder: A folder with static files that should be\n        served by the blueprint's static route. The path is relative to\n        the blueprint's root path. Blueprint static files are disabled\n        by default.\n    :param static_url_path: The url to serve static files from.\n        Defaults to ``static_folder``. If the blueprint does not have\n        a ``url_prefix``, the app's static route will take precedence,\n        and the blueprint's static files won't be accessible.\n    :param template_folder: A folder with templates that should be added\n        to the app's template search path. The path is relative to the\n        blueprint's root path. Blueprint templates are disabled by\n        default. Blueprint templates have a lower precedence than those\n        in the app's templates folder.\n    :param url_prefix: A path to prepend to all of the blueprint's URLs,\n        to make them distinct from the rest of the app's routes.\n    :param subdomain: A subdomain that blueprint routes will match on by\n        default.\n    :param url_defaults: A dict of default values that blueprint routes\n        will receive by default.\n    :param root_path: By default, the blueprint will automatically set\n        this based on ``import_name``. In certain situations this\n        automatic detection can fail, so the path can be specified\n        manually instead.\n\n    .. versionchanged:: 1.1.0\n        Blueprints have a ``cli`` group to register nested CLI commands.\n        The ``cli_group`` parameter controls the name of the group under\n        the ``flask`` command.\n\n    .. versionadded:: 0.7\n    \"\"\"\n\n    _got_registered_once = False\n\n    def __init__(\n        self,\n        name: str,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        url_prefix: str | None = None,\n        subdomain: str | None = None,\n        url_defaults: dict[str, t.Any] | None = None,\n        root_path: str | None = None,\n        cli_group: str | None = _sentinel,  # type: ignore[assignment]\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_folder=static_folder,\n            static_url_path=static_url_path,\n            template_folder=template_folder,\n            root_path=root_path,\n        )\n\n        if not name:\n            raise ValueError(\"'name' may not be empty.\")\n\n        if \".\" in name:\n            raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n        self.name = name\n        self.url_prefix = url_prefix\n        self.subdomain = subdomain\n        self.deferred_functions: list[DeferredSetupFunction] = []\n\n        if url_defaults is None:\n            url_defaults = {}\n\n        self.url_values_defaults = url_defaults\n        self.cli_group = cli_group\n        self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        if self._got_registered_once:\n            raise AssertionError(\n                f\"The setup method '{f_name}' can no longer be called on the blueprint\"\n                f\" '{self.name}'. It has already been registered at least once, any\"\n                \" changes will not be applied consistently.\\n\"\n                \"Make sure all imports, decorators, functions, etc. needed to set up\"\n                \" the blueprint are done before registering it.\"\n            )\n\n    @setupmethod\n    def record(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Registers a function that is called when the blueprint is\n        registered on the application.  This function is called with the\n        state as argument as returned by the :meth:`make_setup_state`\n        method.\n        \"\"\"\n        self.deferred_functions.append(func)\n\n    @setupmethod\n    def record_once(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Works like :meth:`record` but wraps the function in another\n        function that will ensure the function is only called once.  If the\n        blueprint is registered a second time on the application, the\n        function passed is not called.\n        \"\"\"\n\n        def wrapper(state: BlueprintSetupState) -> None:\n            if state.first_registration:\n                func(state)\n\n        self.record(update_wrapper(wrapper, func))\n\n    def make_setup_state(\n        self, app: App, options: dict[str, t.Any], first_registration: bool = False\n    ) -> BlueprintSetupState:\n        \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n        object that is later passed to the register callback functions.\n        Subclasses can override this to return a subclass of the setup state.\n        \"\"\"\n        return BlueprintSetupState(self, app, options, first_registration)\n\n    @setupmethod\n    def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:\n        \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n        arguments passed to this method will override the defaults set\n        on the blueprint.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if blueprint is self:\n            raise ValueError(\"Cannot register a blueprint on itself\")\n        self._blueprints.append((blueprint, options))\n\n    def register(self, app: App, options: dict[str, t.Any]) -> None:\n        \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n        views and callbacks registered on the blueprint with the\n        application. Creates a :class:`.BlueprintSetupState` and calls\n        each :meth:`record` callback with it.\n\n        :param app: The application this blueprint is being registered\n            with.\n        :param options: Keyword arguments forwarded from\n            :meth:`~Flask.register_blueprint`.\n\n        .. versionchanged:: 2.3\n            Nested blueprints now correctly apply subdomains.\n\n        .. versionchanged:: 2.1\n            Registering the same blueprint with the same name multiple\n            times is an error.\n\n        .. versionchanged:: 2.0.1\n            Nested blueprints are registered with their dotted name.\n            This allows different blueprints with the same name to be\n            nested at different locations.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n        \"\"\"\n        name_prefix = options.get(\"name_prefix\", \"\")\n        self_name = options.get(\"name\", self.name)\n        name = f\"{name_prefix}.{self_name}\".lstrip(\".\")\n\n        if name in app.blueprints:\n            bp_desc = \"this\" if app.blueprints[name] is self else \"a different\"\n            existing_at = f\" '{name}'\" if self_name != name else \"\"\n\n            raise ValueError(\n                f\"The name '{self_name}' is already registered for\"\n                f\" {bp_desc} blueprint{existing_at}. Use 'name=' to\"\n                f\" provide a unique name.\"\n            )\n\n        first_bp_registration = not any(bp is self for bp in app.blueprints.values())\n        first_name_registration = name not in app.blueprints\n\n        app.blueprints[name] = self\n        self._got_registered_once = True\n        state = self.make_setup_state(app, options, first_bp_registration)\n\n        if self.has_static_folder:\n            state.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                view_func=self.send_static_file,  # type: ignore[attr-defined]\n                endpoint=\"static\",\n            )\n\n        # Merge blueprint data into parent.\n        if first_bp_registration or first_name_registration:\n            self._merge_blueprint_funcs(app, name)\n\n        for deferred in self.deferred_functions:\n            deferred(state)\n\n        cli_resolved_group = options.get(\"cli_group\", self.cli_group)\n\n        if self.cli.commands:\n            if cli_resolved_group is None:\n                app.cli.commands.update(self.cli.commands)\n            elif cli_resolved_group is _sentinel:\n                self.cli.name = name\n                app.cli.add_command(self.cli)\n            else:\n                self.cli.name = cli_resolved_group\n                app.cli.add_command(self.cli)\n\n        for blueprint, bp_options in self._blueprints:\n            bp_options = bp_options.copy()\n            bp_url_prefix = bp_options.get(\"url_prefix\")\n            bp_subdomain = bp_options.get(\"subdomain\")\n\n            if bp_subdomain is None:\n                bp_subdomain = blueprint.subdomain\n\n            if state.subdomain is not None and bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain + \".\" + state.subdomain\n            elif bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain\n            elif state.subdomain is not None:\n                bp_options[\"subdomain\"] = state.subdomain\n\n            if bp_url_prefix is None:\n                bp_url_prefix = blueprint.url_prefix\n\n            if state.url_prefix is not None and bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = (\n                    state.url_prefix.rstrip(\"/\") + \"/\" + bp_url_prefix.lstrip(\"/\")\n                )\n            elif bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = bp_url_prefix\n            elif state.url_prefix is not None:\n                bp_options[\"url_prefix\"] = state.url_prefix\n\n            bp_options[\"name_prefix\"] = name\n            blueprint.register(app, bp_options)\n\n    def _merge_blueprint_funcs(self, app: App, name: str) -> None:\n        def extend(\n            bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n            parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n        ) -> None:\n            for key, values in bp_dict.items():\n                key = name if key is None else f\"{name}.{key}\"\n                parent_dict[key].extend(values)\n\n        for key, value in self.error_handler_spec.items():\n            key = name if key is None else f\"{name}.{key}\"\n            value = defaultdict(\n                dict,\n                {\n                    code: {exc_class: func for exc_class, func in code_values.items()}\n                    for code, code_values in value.items()\n                },\n            )\n            app.error_handler_spec[key] = value\n\n        for endpoint, func in self.view_functions.items():\n            app.view_functions[endpoint] = func\n\n        extend(self.before_request_funcs, app.before_request_funcs)\n        extend(self.after_request_funcs, app.after_request_funcs)\n        extend(\n            self.teardown_request_funcs,\n            app.teardown_request_funcs,\n        )\n        extend(self.url_default_functions, app.url_default_functions)\n        extend(self.url_value_preprocessors, app.url_value_preprocessors)\n        extend(self.template_context_processors, app.template_context_processors)\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n        full documentation.\n\n        The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n        used with :func:`url_for`, is prefixed with the blueprint's name.\n        \"\"\"\n        if endpoint and \".\" in endpoint:\n            raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n        if view_func and hasattr(view_func, \"__name__\") and \".\" in view_func.__name__:\n            raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n        self.record(\n            lambda s: s.add_url_rule(\n                rule,\n                endpoint,\n                view_func,\n                provide_automatic_options=provide_automatic_options,\n                **options,\n            )\n        )\n\n    @t.overload\n    def app_template_filter(self, name: T_template_filter) -> T_template_filter: ...\n    @t.overload\n    def app_template_filter(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_filter], T_template_filter]: ...\n    @setupmethod\n    def app_template_filter(\n        self, name: T_template_filter | str | None = None\n    ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n        \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_filter` method may be used to register a\n        function later rather than decorating.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_filter`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n        if callable(name):\n            self.add_app_template_filter(name)\n            return name\n\n        def decorator(f: T_template_filter) -> T_template_filter:\n            self.add_app_template_filter(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_filter(\n        self, f: ft.TemplateFilterCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja filter.\n\n        The :meth:`app_template_filter` decorator can be used to register a\n        function by decorating instead.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_filter`.\n\n        :param f: The function to register.\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n\n        def register_template_filter(state: BlueprintSetupState) -> None:\n            state.app.add_template_filter(f, name=name)\n\n        self.record_once(register_template_filter)\n\n    @t.overload\n    def app_template_test(self, name: T_template_test) -> T_template_test: ...\n    @t.overload\n    def app_template_test(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_test], T_template_test]: ...\n    @setupmethod\n    def app_template_test(\n        self, name: T_template_test | str | None = None\n    ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n        \"\"\"Decorate a function to register it as a custom Jinja test. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_test` method may be used to register a\n        function later rather than decorating.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_test`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_test(name)\n            return name\n\n        def decorator(f: T_template_test) -> T_template_test:\n            self.add_app_template_test(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_test(\n        self, f: ft.TemplateTestCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja test.\n\n        The :meth:`app_template_test` decorator can be used to register a\n        function by decorating instead.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_test`.\n\n        :param f: The function to register.\n        :param name: The name to register the test as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_test(state: BlueprintSetupState) -> None:\n            state.app.add_template_test(f, name=name)\n\n        self.record_once(register_template_test)\n\n    @t.overload\n    def app_template_global(self, name: T_template_global) -> T_template_global: ...\n    @t.overload\n    def app_template_global(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_global], T_template_global]: ...\n    @setupmethod\n    def app_template_global(\n        self, name: T_template_global | str | None = None\n    ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n        \"\"\"Decorate a function to register it as a custom Jinja global. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_global` method may be used to register a\n        function later rather than decorating.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_global`.\n\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_global(name)\n            return name\n\n        def decorator(f: T_template_global) -> T_template_global:\n            self.add_app_template_global(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_global(\n        self, f: ft.TemplateGlobalCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja global.\n\n        The :meth:`app_template_global` decorator can be used to register a function\n        by decorating instead.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_global`.\n\n        :param f: The function to register.\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_global(state: BlueprintSetupState) -> None:\n            lI0O_3f111f61, lI0O_9a6068a6 = 0, 0\n            while lI0O_9a6068a6 < 2:\n                lI0O_3f111f61 ^= (lI0O_9a6068a6 << 1) ^ 0xd\n                lI0O_9a6068a6 += 1\n            lI0O_3f111f61 ^= lI0O_3f111f61\n            state.app.add_template_global(f, name=name)\n\n        self.record_once(register_template_global)\n\n    @setupmethod\n    def before_app_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def after_app_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def teardown_app_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_context_processor(\n        self, f: T_template_context_processor\n    ) -> T_template_context_processor:\n        \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n        only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_errorhandler(\n        self, code: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            def from_blueprint(state: BlueprintSetupState) -> None:\n                state.app.errorhandler(code)(f)\n\n            self.record_once(from_blueprint)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def app_url_value_preprocessor(\n        self, f: T_url_value_preprocessor\n    ) -> T_url_value_preprocessor:\n        \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n        )\n        return f\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-d841e365cd245065", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "65fa1b8feff18b80b33e81c2168302829e6bc3c0eb9aaa1d3d702872fa259feb", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 590, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__Blueprint__f7beff5a.py", "order": 9, "original_content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "parent_variant_id": "pyint-c20045673c45-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/blueprints.py#L119-L692", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 2}, "unit_kind": "class", "unit_name": "Blueprint", "variant_id": "pyint-1dd3f7beff5a-I09", "group_id": "py-d841e365cd245065", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 654, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-40abc6b23802-I10", "source": "from __future__ import annotations\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nclass Blueprint(Scaffold):\n    \"\"\"Represents a blueprint, a collection of routes and other\n    app-related functions that can be registered on a real application\n    later.\n    A blueprint is an object that allows defining application functions\n    without requiring an application object ahead of time. It uses the\n    same decorators as :class:`~flask.Flask`, but defers the need for an\n    application by recording them for later registration.\n    Decorating a function with a blueprint creates a deferred function\n    that is called with :class:`~flask.blueprints.BlueprintSetupState`\n    when the blueprint is registered on an application.\n    See :doc:`/blueprints` for more information.\n\n    :param name: The name of the blueprint. Will be prepended to each\n        endpoint name.\n    :param import_name: The name of the blueprint package, usually\n        ``__name__``. This helps locate the ``root_path`` for the\n        blueprint.\n    :param static_folder: A folder with static files that should be\n        served by the blueprint's static route. The path is relative to\n        the blueprint's root path. Blueprint static files are disabled\n        by default.\n    :param static_url_path: The url to serve static files from.\n        Defaults to ``static_folder``. If the blueprint does not have\n        a ``url_prefix``, the app's static route will take precedence,\n        and the blueprint's static files won't be accessible.\n    :param template_folder: A folder with templates that should be added\n        to the app's template search path. The path is relative to the\n        blueprint's root path. Blueprint templates are disabled by\n        default. Blueprint templates have a lower precedence than those\n        in the app's templates folder.\n    :param url_prefix: A path to prepend to all of the blueprint's URLs,\n        to make them distinct from the rest of the app's routes.\n    :param subdomain: A subdomain that blueprint routes will match on by\n        default.\n    :param url_defaults: A dict of default values that blueprint routes\n        will receive by default.\n    :param root_path: By default, the blueprint will automatically set\n        this based on ``import_name``. In certain situations this\n        automatic detection can fail, so the path can be specified\n        manually instead.\n    .. versionchanged:: 1.1.0\n        Blueprints have a ``cli`` group to register nested CLI commands.\n        The ``cli_group`` parameter controls the name of the group under\n        the ``flask`` command.\n    .. versionadded:: 0.7\n    \"\"\"\n    _got_registered_once = False\n\n    def __init__(\n        self,\n        name: str,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        url_prefix: str | None = None,         subdomain: str | None = None,         url_defaults: dict[str, t.Any] | None = None,\n        root_path: str | None = None,         cli_group: str | None = _sentinel,  # type: ignore[assignment]\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_folder=static_folder,\n            static_url_path=static_url_path,\n            template_folder=template_folder,             root_path=root_path,\n        )\n        if not name:\n            raise ValueError(\"'name' may not be empty.\")\n\n        if \".\" in name:\n            raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n        self.name = name\n        self.url_prefix = url_prefix\n        self.subdomain = subdomain\n        self.deferred_functions: list[DeferredSetupFunction] = []\n\n        if url_defaults is None:\n            url_defaults = {}\n\n        self.url_values_defaults = url_defaults\n        self.cli_group = cli_group\n        self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []\n    def _check_setup_finished(self, f_name: str) -> None:\n        if self._got_registered_once:\n            raise AssertionError(                 f\"The setup method '{f_name}' can no longer be called on the blueprint\"                 f\" '{self.name}'. It has already been registered at least once, any\"                 \" changes will not be applied consistently.\\n\"                 \"Make sure all imports, decorators, functions, etc. needed to set up\"                 \" the blueprint are done before registering it.\"             )\n\n    @setupmethod\n    def record(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Registers a function that is called when the blueprint is\n        registered on the application.  This function is called with the\n        state as argument as returned by the :meth:`make_setup_state`\n        method.\n        \"\"\"\n        self.deferred_functions.append(func)\n    @setupmethod\n    def record_once(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Works like :meth:`record` but wraps the function in another\n        function that will ensure the function is only called once.  If the\n        blueprint is registered a second time on the application, the\n        function passed is not called.\n        \"\"\"\n\n        def wrapper(state: BlueprintSetupState) -> None:\n            if state.first_registration:\n                func(state)\n        self.record(update_wrapper(wrapper, func))\n\n    def make_setup_state(\n        self, app: App, options: dict[str, t.Any], first_registration: bool = False\n    ) -> BlueprintSetupState:\n        \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n        object that is later passed to the register callback functions.\n        Subclasses can override this to return a subclass of the setup state.\n        \"\"\"\n        return BlueprintSetupState(self, app, options, first_registration)\n    @setupmethod\n    def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:\n        \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n        arguments passed to this method will override the defaults set\n        on the blueprint.\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n        .. versionadded:: 2.0\n        \"\"\"\n        if blueprint is self:\n            raise ValueError(\"Cannot register a blueprint on itself\")\n        self._blueprints.append((blueprint, options))\n\n    def register(self, app: App, options: dict[str, t.Any]) -> None:\n        \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n        views and callbacks registered on the blueprint with the\n        application. Creates a :class:`.BlueprintSetupState` and calls\n        each :meth:`record` callback with it.\n\n        :param app: The application this blueprint is being registered\n            with.\n        :param options: Keyword arguments forwarded from\n            :meth:`~Flask.register_blueprint`.\n\n        .. versionchanged:: 2.3\n            Nested blueprints now correctly apply subdomains.\n\n        .. versionchanged:: 2.1\n            Registering the same blueprint with the same name multiple\n            times is an error.\n\n        .. versionchanged:: 2.0.1\n            Nested blueprints are registered with their dotted name.\n            This allows different blueprints with the same name to be\n            nested at different locations.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n        \"\"\"\n        name_prefix = options.get(\"name_prefix\", \"\")\n        self_name = options.get(\"name\", self.name)\n        name = f\"{name_prefix}.{self_name}\".lstrip(\".\")\n\n        if name in app.blueprints:\n            bp_desc = \"this\" if app.blueprints[name] is self else \"a different\"\n            existing_at = f\" '{name}'\" if self_name != name else \"\"\n\n            raise ValueError(\n                f\"The name '{self_name}' is already registered for\"\n                f\" {bp_desc} blueprint{existing_at}. Use 'name=' to\"                 f\" provide a unique name.\"\n            )\n\n        first_bp_registration = not any(bp is self for bp in app.blueprints.values())\n        first_name_registration = name not in app.blueprints\n\n        app.blueprints[name] = self\n        self._got_registered_once = True\n        state = self.make_setup_state(app, options, first_bp_registration)\n\n        if self.has_static_folder:\n            state.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                view_func=self.send_static_file,  # type: ignore[attr-defined]\n                endpoint=\"static\",             )\n\n        # Merge blueprint data into parent.\n        if first_bp_registration or first_name_registration:\n            self._merge_blueprint_funcs(app, name)\n        for deferred in self.deferred_functions:\n            deferred(state)\n\n        cli_resolved_group = options.get(\"cli_group\", self.cli_group)\n\n        if self.cli.commands:\n            if cli_resolved_group is None:\n                app.cli.commands.update(self.cli.commands)\n            elif cli_resolved_group is _sentinel:\n                self.cli.name = name\n                app.cli.add_command(self.cli)\n            else:\n                self.cli.name = cli_resolved_group\n                app.cli.add_command(self.cli)\n        for blueprint, bp_options in self._blueprints:\n            bp_options = bp_options.copy()\n            bp_url_prefix = bp_options.get(\"url_prefix\")\n            bp_subdomain = bp_options.get(\"subdomain\")\n            if bp_subdomain is None:\n                bp_subdomain = blueprint.subdomain\n\n            if state.subdomain is not None and bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain + \".\" + state.subdomain\n            elif bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain\n            elif state.subdomain is not None:\n                bp_options[\"subdomain\"] = state.subdomain\n\n            if bp_url_prefix is None:\n                bp_url_prefix = blueprint.url_prefix\n\n            if state.url_prefix is not None and bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = (                     state.url_prefix.rstrip(\"/\") + \"/\" + bp_url_prefix.lstrip(\"/\")\n                )\n            elif bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = bp_url_prefix\n            elif state.url_prefix is not None:\n                bp_options[\"url_prefix\"] = state.url_prefix\n\n            bp_options[\"name_prefix\"] = name\n            blueprint.register(app, bp_options)\n\n    def _merge_blueprint_funcs(self, app: App, name: str) -> None:\n        def extend(             bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n            parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],         ) -> None:\n            for key, values in bp_dict.items():\n                key = name if key is None else f\"{name}.{key}\"\n                parent_dict[key].extend(values)\n\n        for key, value in self.error_handler_spec.items():\n            key = name if key is None else f\"{name}.{key}\"\n            value = defaultdict(\n                dict,\n                {                     code: {exc_class: func for exc_class, func in code_values.items()}\n                    for code, code_values in value.items()\n                },             )\n            app.error_handler_spec[key] = value\n\n        for endpoint, func in self.view_functions.items():\n            app.view_functions[endpoint] = func\n        extend(self.before_request_funcs, app.before_request_funcs)\n        extend(self.after_request_funcs, app.after_request_funcs)\n        extend(\n            self.teardown_request_funcs,\n            app.teardown_request_funcs,\n        )\n        extend(self.url_default_functions, app.url_default_functions)\n        extend(self.url_value_preprocessors, app.url_value_preprocessors)\n        extend(self.template_context_processors, app.template_context_processors)\n\n    @setupmethod\n    def add_url_rule(         self,\n        rule: str,\n        endpoint: str | None = None,         view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,         **options: t.Any,\n    ) -> None:\n        \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n        full documentation.\n        The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n        used with :func:`url_for`, is prefixed with the blueprint's name.\n        \"\"\"\n        if endpoint and \".\" in endpoint:\n            raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n        if view_func and hasattr(view_func, \"__name__\") and \".\" in view_func.__name__:\n            raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n        self.record(             lambda s: s.add_url_rule(                 rule,\n                endpoint,\n                view_func,                 provide_automatic_options=provide_automatic_options,                 **options,\n            )\n        )\n    @t.overload\n    def app_template_filter(self, name: T_template_filter) -> T_template_filter: ...\n    @t.overload\n    def app_template_filter(         self, name: str | None = None\n    ) -> t.Callable[[T_template_filter], T_template_filter]: ...\n    @setupmethod\n    def app_template_filter(         self, name: T_template_filter | str | None = None\n    ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n        \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n        is optional. The decorator may be used without parentheses.\n        The :meth:`add_app_template_filter` method may be used to register a\n        function later rather than decorating.\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_filter`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n        if callable(name):\n            self.add_app_template_filter(name)\n            return name\n\n        def decorator(f: T_template_filter) -> T_template_filter:\n            self.add_app_template_filter(f, name=name)\n            return f\n        return decorator\n\n    @setupmethod\n    def add_app_template_filter(         self, f: ft.TemplateFilterCallable, name: str | None = None     ) -> None:\n        \"\"\"Register a function to use as a custom Jinja filter.\n        The :meth:`app_template_filter` decorator can be used to register a\n        function by decorating instead.\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_filter`.\n        :param f: The function to register.\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n\n        def register_template_filter(state: BlueprintSetupState) -> None:\n            state.app.add_template_filter(f, name=name)\n\n        self.record_once(register_template_filter)\n\n    @t.overload\n    def app_template_test(self, name: T_template_test) -> T_template_test: ...\n    @t.overload\n    def app_template_test(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_test], T_template_test]: ...\n    @setupmethod\n    def app_template_test(\n        self, name: T_template_test | str | None = None     ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n        \"\"\"Decorate a function to register it as a custom Jinja test. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_test` method may be used to register a\n        function later rather than decorating.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_test`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_test(name)\n            return name\n\n        def decorator(f: T_template_test) -> T_template_test:\n            self.add_app_template_test(f, name=name)\n            return f\n        return decorator\n    @setupmethod\n    def add_app_template_test(\n        self, f: ft.TemplateTestCallable, name: str | None = None     ) -> None:\n        \"\"\"Register a function to use as a custom Jinja test.\n\n        The :meth:`app_template_test` decorator can be used to register a\n        function by decorating instead.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_test`.\n\n        :param f: The function to register.\n        :param name: The name to register the test as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_test(state: BlueprintSetupState) -> None:\n            state.app.add_template_test(f, name=name)\n\n        self.record_once(register_template_test)\n    @t.overload\n    def app_template_global(self, name: T_template_global) -> T_template_global: ...\n    @t.overload\n    def app_template_global(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_global], T_template_global]: ...\n    @setupmethod\n    def app_template_global(         self, name: T_template_global | str | None = None\n    ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n        \"\"\"Decorate a function to register it as a custom Jinja global. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_global` method may be used to register a\n        function later rather than decorating.\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_global`.\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_global(name)\n            return name\n\n        def decorator(f: T_template_global) -> T_template_global:\n            self.add_app_template_global(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_global(         self, f: ft.TemplateGlobalCallable, name: str | None = None     ) -> None:\n        \"\"\"Register a function to use as a custom Jinja global.\n\n        The :meth:`app_template_global` decorator can be used to register a function\n        by decorating instead.\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_global`.\n\n        :param f: The function to register.\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_global(state: BlueprintSetupState) -> None:\n            state.app.add_template_global(f, name=name)\n\n        self.record_once(register_template_global)\n\n    @setupmethod\n    def before_app_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def after_app_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)         )\n        return f\n    @setupmethod\n    def teardown_app_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)         )\n        return f\n\n    @setupmethod\n    def app_context_processor(         self, f: T_template_context_processor     ) -> T_template_context_processor:\n        \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n        only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n        \"\"\"\n        self.record_once(             lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_errorhandler(\n        self, code: type[Exception] | int     ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            def from_blueprint(state: BlueprintSetupState) -> None:\n                state.app.errorhandler(code)(f)\n\n            self.record_once(from_blueprint)\n            return f\n        return decorator\n\n    @setupmethod\n    def app_url_value_preprocessor(\n        self, f: T_url_value_preprocessor     ) -> T_url_value_preprocessor:\n        \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n        \"\"\"\n        self.record_once(             lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n        \"\"\"\n        self.record_once(             lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n        )\n        return f\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-d841e365cd245065", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "0a996c56eb1c2f7ad6d9133759ae620ca9a5b77cad1072c11e02b6aecad50957", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 506, "local_path": "layout/partially-compact-layout/I10__flask__Blueprint__c6b23802.py", "order": 10, "original_content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "parent_variant_id": "pyint-c20045673c45-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/blueprints.py#L119-L692", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 199, "line_break_groups_removed": 79, "line_breaks_removed": 79, "whitespace_characters_removed": 37}, "unit_kind": "class", "unit_name": "Blueprint", "variant_id": "pyint-40abc6b23802-I10", "group_id": "py-d841e365cd245065", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 655, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c73b42436980-I11", "source": "from __future__ import annotations\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nclass Blueprint(Scaffold):\n    \"\"\"Represents a blueprint, a collection of routes and other\n    app-related functions that can be registered on a real application\n    later.\n\n    A blueprint is an object that allows defining application functions\n    without requiring an application object ahead of time. It uses the\n    same decorators as :class:`~flask.Flask`, but defers the need for an\n    application by recording them for later registration.\n\n    Decorating a function with a blueprint creates a deferred function\n    that is called with :class:`~flask.blueprints.BlueprintSetupState`\n    when the blueprint is registered on an application.\n\n    See :doc:`/blueprints` for more information.\n\n    :param name: The name of the blueprint. Will be prepended to each\n        endpoint name.\n    :param import_name: The name of the blueprint package, usually\n        ``__name__``. This helps locate the ``root_path`` for the\n        blueprint.\n    :param static_folder: A folder with static files that should be\n        served by the blueprint's static route. The path is relative to\n        the blueprint's root path. Blueprint static files are disabled\n        by default.\n    :param static_url_path: The url to serve static files from.\n        Defaults to ``static_folder``. If the blueprint does not have\n        a ``url_prefix``, the app's static route will take precedence,\n        and the blueprint's static files won't be accessible.\n    :param template_folder: A folder with templates that should be added\n        to the app's template search path. The path is relative to the\n        blueprint's root path. Blueprint templates are disabled by\n        default. Blueprint templates have a lower precedence than those\n        in the app's templates folder.\n    :param url_prefix: A path to prepend to all of the blueprint's URLs,\n        to make them distinct from the rest of the app's routes.\n    :param subdomain: A subdomain that blueprint routes will match on by\n        default.\n    :param url_defaults: A dict of default values that blueprint routes\n        will receive by default.\n    :param root_path: By default, the blueprint will automatically set\n        this based on ``import_name``. In certain situations this\n        automatic detection can fail, so the path can be specified\n        manually instead.\n\n    .. versionchanged:: 1.1.0\n        Blueprints have a ``cli`` group to register nested CLI commands.\n        The ``cli_group`` parameter controls the name of the group under\n        the ``flask`` command.\n\n    .. versionadded:: 0.7\n    \"\"\"\n\n    _got_registered_once = False\n\n    def __init__(\n        self,\n        name: str,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        url_prefix: str | None = None,\n        subdomain: str | None = None,\n        url_defaults: dict[str, t.Any] | None = None,\n        root_path: str | None = None,\n        cli_group: str | None = _sentinel,  # type: ignore[assignment]\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_folder=static_folder,\n            static_url_path=static_url_path,\n            template_folder=template_folder,\n            root_path=root_path,\n        )\n\n        if not name:\n            raise ValueError(\"'name' may not be empty.\")\n\n        if \".\" in name:\n            raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n        self.name = name\n        self.url_prefix = url_prefix\n        self.subdomain = subdomain\n        self.deferred_functions: list[DeferredSetupFunction] = []\n\n        if url_defaults is None:\n            url_defaults = {}\n\n        self.url_values_defaults = url_defaults\n        self.cli_group = cli_group\n        self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        if self._got_registered_once:\n            raise AssertionError(\n                f\"The setup method '{f_name}' can no longer be called on the blueprint\"\n                f\" '{self.name}'. It has already been registered at least once, any\"\n                \" changes will not be applied consistently.\\n\"\n                \"Make sure all imports, decorators, functions, etc. needed to set up\"\n                \" the blueprint are done before registering it.\"\n            )\n\n    @setupmethod\n    def record(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Registers a function that is called when the blueprint is\n        registered on the application.  This function is called with the\n        state as argument as returned by the :meth:`make_setup_state`\n        method.\n        \"\"\"\n        self.deferred_functions.append(func)\n\n    @setupmethod\n    def record_once(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Works like :meth:`record` but wraps the function in another\n        function that will ensure the function is only called once.  If the\n        blueprint is registered a second time on the application, the\n        function passed is not called.\n        \"\"\"\n\n        def wrapper(state: BlueprintSetupState) -> None:\n            if state.first_registration:\n                func(state)\n\n        self.record(update_wrapper(wrapper, func))\n\n    def make_setup_state(\n        self, app: App, options: dict[str, t.Any], first_registration: bool = False\n    ) -> BlueprintSetupState:\n        \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n        object that is later passed to the register callback functions.\n        Subclasses can override this to return a subclass of the setup state.\n        \"\"\"\n        return BlueprintSetupState(self, app, options, first_registration)\n\n    @setupmethod\n    def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:\n        \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n        arguments passed to this method will override the defaults set\n        on the blueprint.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if blueprint is self:\n            raise ValueError(\"Cannot register a blueprint on itself\")\n        self._blueprints.append((blueprint, options))\n\n    def register(self, app: App, options: dict[str, t.Any]) -> None:\n        \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n        views and callbacks registered on the blueprint with the\n        application. Creates a :class:`.BlueprintSetupState` and calls\n        each :meth:`record` callback with it.\n\n        :param app: The application this blueprint is being registered\n            with.\n        :param options: Keyword arguments forwarded from\n            :meth:`~Flask.register_blueprint`.\n\n        .. versionchanged:: 2.3\n            Nested blueprints now correctly apply subdomains.\n\n        .. versionchanged:: 2.1\n            Registering the same blueprint with the same name multiple\n            times is an error.\n\n        .. versionchanged:: 2.0.1\n            Nested blueprints are registered with their dotted name.\n            This allows different blueprints with the same name to be\n            nested at different locations.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n        \"\"\"\n        name_prefix = options.get(\"name_prefix\", \"\")\n        self_name = options.get(\"name\", self.name)\n        name = f\"{name_prefix}.{self_name}\".lstrip(\".\")\n\n        if name in app.blueprints:\n            bp_desc = \"this\" if app.blueprints[name] is self else \"a different\"\n            existing_at = f\" '{name}'\" if self_name != name else \"\"\n\n            raise ValueError(\n                f\"The name '{self_name}' is already registered for\"\n                f\" {bp_desc} blueprint{existing_at}. Use 'name=' to\"\n                f\" provide a unique name.\"\n            )\n\n        first_bp_registration = not any(bp is self for bp in app.blueprints.values())\n        first_name_registration = name not in app.blueprints\n\n        app.blueprints[name] = self\n        self._got_registered_once = True\n        state = self.make_setup_state(app, options, first_bp_registration)\n\n        if self.has_static_folder:\n            state.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                view_func=self.send_static_file,  # type: ignore[attr-defined]\n                endpoint=\"static\",\n            )\n\n        # Merge blueprint data into parent.\n        if first_bp_registration or first_name_registration:\n            self._merge_blueprint_funcs(app, name)\n\n        for deferred in self.deferred_functions:\n            deferred(state)\n\n        cli_resolved_group = options.get(\"cli_group\", self.cli_group)\n\n        if self.cli.commands:\n            if cli_resolved_group is None:\n                app.cli.commands.update(self.cli.commands)\n            elif cli_resolved_group is _sentinel:\n                self.cli.name = name\n                app.cli.add_command(self.cli)\n            else:\n                self.cli.name = cli_resolved_group\n                app.cli.add_command(self.cli)\n\n        for blueprint, bp_options in self._blueprints:\n            bp_options = bp_options.copy()\n            bp_url_prefix = bp_options.get(\"url_prefix\")\n            bp_subdomain = bp_options.get(\"subdomain\")\n\n            if bp_subdomain is None:\n                bp_subdomain = blueprint.subdomain\n\n            if state.subdomain is not None and bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain + \".\" + state.subdomain\n            elif bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain\n            elif state.subdomain is not None:\n                bp_options[\"subdomain\"] = state.subdomain\n\n            if bp_url_prefix is None:\n                bp_url_prefix = blueprint.url_prefix\n\n            if state.url_prefix is not None and bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = (\n                    state.url_prefix.rstrip(\"/\") + \"/\" + bp_url_prefix.lstrip(\"/\")\n                )\n            elif bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = bp_url_prefix\n            elif state.url_prefix is not None:\n                bp_options[\"url_prefix\"] = state.url_prefix\n\n            bp_options[\"name_prefix\"] = name\n            blueprint.register(app, bp_options)\n\n    def _merge_blueprint_funcs(self, app: App, name: str) -> None:\n        def extend(\n            bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n            parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n        ) -> None:\n            for key, values in bp_dict.items():\n                key = name if key is None else f\"{name}.{key}\"\n                parent_dict[key].extend(values)\n\n        for key, value in self.error_handler_spec.items():\n            key = name if key is None else f\"{name}.{key}\"\n            value = defaultdict(\n                dict,\n                {\n                    code: {exc_class: func for exc_class, func in code_values.items()}\n                    for code, code_values in value.items()\n                },\n            )\n            app.error_handler_spec[key] = value\n\n        for endpoint, func in self.view_functions.items():\n            app.view_functions[endpoint] = func\n\n        extend(self.before_request_funcs, app.before_request_funcs)\n        extend(self.after_request_funcs, app.after_request_funcs)\n        extend(\n            self.teardown_request_funcs,\n            app.teardown_request_funcs,\n        )\n        extend(self.url_default_functions, app.url_default_functions)\n        extend(self.url_value_preprocessors, app.url_value_preprocessors)\n        extend(self.template_context_processors, app.template_context_processors)\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n        full documentation.\n\n        The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n        used with :func:`url_for`, is prefixed with the blueprint's name.\n        \"\"\"\n        if endpoint and \".\" in endpoint:\n            raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n        if view_func and hasattr(view_func, \"__name__\") and \".\" in view_func.__name__:\n            raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n        self.record(\n            lambda s: s.add_url_rule(\n                rule,\n                endpoint,\n                view_func,\n                provide_automatic_options=provide_automatic_options,\n                **options,\n            )\n        )\n\n    @t.overload\n    def app_template_filter(self, name: T_template_filter) -> T_template_filter: ...\n    @t.overload\n    def app_template_filter(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_filter], T_template_filter]: ...\n    @setupmethod\n    def app_template_filter(\n        self, name: T_template_filter | str | None = None\n    ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n        \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_filter` method may be used to register a\n        function later rather than decorating.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_filter`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n        if callable(name):\n            self.add_app_template_filter(name)\n            return name\n\n        def decorator(f: T_template_filter) -> T_template_filter:\n            self.add_app_template_filter(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_filter(\n        self, f: ft.TemplateFilterCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja filter.\n\n        The :meth:`app_template_filter` decorator can be used to register a\n        function by decorating instead.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_filter`.\n\n        :param f: The function to register.\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n\n        def register_template_filter(state: BlueprintSetupState) -> None:\n            state.app.add_template_filter(f, name=name)\n\n        self.record_once(register_template_filter)\n\n    @t.overload\n    def app_template_test(self, name: T_template_test) -> T_template_test: ...\n    @t.overload\n    def app_template_test(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_test], T_template_test]: ...\n    @setupmethod\n    def app_template_test(\n        self, name: T_template_test | str | None = None\n    ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n        \"\"\"Decorate a function to register it as a custom Jinja test. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_test` method may be used to register a\n        function later rather than decorating.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_test`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_test(name)\n            return name\n\n        def decorator(f: T_template_test) -> T_template_test:\n            self.add_app_template_test(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_test(\n        self, f: ft.TemplateTestCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja test.\n\n        The :meth:`app_template_test` decorator can be used to register a\n        function by decorating instead.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_test`.\n\n        :param f: The function to register.\n        :param name: The name to register the test as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_test(state: BlueprintSetupState) -> None:\n            state.app.add_template_test(f, name=name)\n\n        self.record_once(register_template_test)\n\n    @t.overload\n    def app_template_global(self, name: T_template_global) -> T_template_global: ...\n    @t.overload\n    def app_template_global(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_global], T_template_global]: ...\n    @setupmethod\n    def app_template_global(\n        self, name: T_template_global | str | None = None\n    ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n        \"\"\"Decorate a function to register it as a custom Jinja global. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_global` method may be used to register a\n        function later rather than decorating.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_global`.\n\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_global(name)\n            return name\n\n        def decorator(f: T_template_global) -> T_template_global:\n            self.add_app_template_global(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_global(\n        self, f: ft.TemplateGlobalCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja global.\n\n        The :meth:`app_template_global` decorator can be used to register a function\n        by decorating instead.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_global`.\n\n        :param f: The function to register.\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_global(state: BlueprintSetupState) -> None:\n            state.app.add_template_global(f, name=name)\n\n        self.record_once(register_template_global)\n\n    @setupmethod\n    def before_app_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def after_app_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def teardown_app_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_context_processor(\n        self, f: T_template_context_processor\n    ) -> T_template_context_processor:\n        \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n        only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_errorhandler(\n        self, code: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            def from_blueprint(state: BlueprintSetupState) -> None:\n                state.app.errorhandler(code)(f)\n\n            self.record_once(from_blueprint)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def app_url_value_preprocessor(\n        self, f: T_url_value_preprocessor\n    ) -> T_url_value_preprocessor:\n        \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n        )\n        return f\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-d841e365cd245065", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 585, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__Blueprint__42436980.py", "order": 11, "original_content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "parent_variant_id": "pyint-c20045673c45-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/blueprints.py#L119-L692", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "Blueprint", "variant_id": "pyint-c73b42436980-I11", "group_id": "py-d841e365cd245065", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 656, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d7e3a9ce432b-I12", "source": "from __future__ import annotations\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nclass Blueprint(Scaffold):\n    \"\"\"Represents a blueprint, a collection of routes and other\n    app-related functions that can be registered on a real application\n    later.\n\n    A blueprint is an object that allows defining application functions\n    without requiring an application object ahead of time. It uses the\n    same decorators as :class:`~flask.Flask`, but defers the need for an\n    application by recording them for later registration.\n\n    Decorating a function with a blueprint creates a deferred function\n    that is called with :class:`~flask.blueprints.BlueprintSetupState`\n    when the blueprint is registered on an application.\n\n    See :doc:`/blueprints` for more information.\n\n    :param name: The name of the blueprint. Will be prepended to each\n        endpoint name.\n    :param import_name: The name of the blueprint package, usually\n        ``__name__``. This helps locate the ``root_path`` for the\n        blueprint.\n    :param static_folder: A folder with static files that should be\n        served by the blueprint's static route. The path is relative to\n        the blueprint's root path. Blueprint static files are disabled\n        by default.\n    :param static_url_path: The url to serve static files from.\n        Defaults to ``static_folder``. If the blueprint does not have\n        a ``url_prefix``, the app's static route will take precedence,\n        and the blueprint's static files won't be accessible.\n    :param template_folder: A folder with templates that should be added\n        to the app's template search path. The path is relative to the\n        blueprint's root path. Blueprint templates are disabled by\n        default. Blueprint templates have a lower precedence than those\n        in the app's templates folder.\n    :param url_prefix: A path to prepend to all of the blueprint's URLs,\n        to make them distinct from the rest of the app's routes.\n    :param subdomain: A subdomain that blueprint routes will match on by\n        default.\n    :param url_defaults: A dict of default values that blueprint routes\n        will receive by default.\n    :param root_path: By default, the blueprint will automatically set\n        this based on ``import_name``. In certain situations this\n        automatic detection can fail, so the path can be specified\n        manually instead.\n\n    .. versionchanged:: 1.1.0\n        Blueprints have a ``cli`` group to register nested CLI commands.\n        The ``cli_group`` parameter controls the name of the group under\n        the ``flask`` command.\n\n    .. versionadded:: 0.7\n    \"\"\"\n\n    _got_registered_once = False\n\n    def __init__(\n        self,\n        name: str,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        url_prefix: str | None = None,\n        subdomain: str | None = None,\n        url_defaults: dict[str, t.Any] | None = None,\n        root_path: str | None = None,\n        cli_group: str | None = _sentinel,  # type: ignore[assignment]\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_folder=static_folder,\n            static_url_path=static_url_path,\n            template_folder=template_folder,\n            root_path=root_path,\n        )\n\n        if not name:\n            raise ValueError(\"'name' may not be empty.\")\n\n        if \".\" in name:\n            raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n        self.name = name\n        self.url_prefix = url_prefix\n        self.subdomain = subdomain\n        self.deferred_functions: list[DeferredSetupFunction] = []\n\n        if url_defaults is None:\n            url_defaults = {}\n\n        self.url_values_defaults = url_defaults\n        self.cli_group = cli_group\n        self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        if self._got_registered_once:\n            raise AssertionError(\n                f\"The setup method '{f_name}' can no longer be called on the blueprint\"\n                f\" '{self.name}'. It has already been registered at least once, any\"\n                \" changes will not be applied consistently.\\n\"\n                \"Make sure all imports, decorators, functions, etc. needed to set up\"\n                \" the blueprint are done before registering it.\"\n            )\n\n    @setupmethod\n    def record(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Registers a function that is called when the blueprint is\n        registered on the application.  This function is called with the\n        state as argument as returned by the :meth:`make_setup_state`\n        method.\n        \"\"\"\n        self.deferred_functions.append(func)\n\n    @setupmethod\n    def record_once(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Works like :meth:`record` but wraps the function in another\n        function that will ensure the function is only called once.  If the\n        blueprint is registered a second time on the application, the\n        function passed is not called.\n        \"\"\"\n\n        def wrapper(state: BlueprintSetupState) -> None:\n            if state.first_registration:\n                func(state)\n\n        self.record(update_wrapper(wrapper, func))\n\n    def make_setup_state(\n        self, app: App, options: dict[str, t.Any], first_registration: bool = False\n    ) -> BlueprintSetupState:\n        \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n        object that is later passed to the register callback functions.\n        Subclasses can override this to return a subclass of the setup state.\n        \"\"\"\n        return BlueprintSetupState(self, app, options, first_registration)\n\n    @setupmethod\n    def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:\n        \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n        arguments passed to this method will override the defaults set\n        on the blueprint.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if blueprint is self:\n            raise ValueError(\"Cannot register a blueprint on itself\")\n        self._blueprints.append((blueprint, options))\n\n    def register(self, app: App, options: dict[str, t.Any]) -> None:\n        \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n        views and callbacks registered on the blueprint with the\n        application. Creates a :class:`.BlueprintSetupState` and calls\n        each :meth:`record` callback with it.\n\n        :param app: The application this blueprint is being registered\n            with.\n        :param options: Keyword arguments forwarded from\n            :meth:`~Flask.register_blueprint`.\n\n        .. versionchanged:: 2.3\n            Nested blueprints now correctly apply subdomains.\n\n        .. versionchanged:: 2.1\n            Registering the same blueprint with the same name multiple\n            times is an error.\n\n        .. versionchanged:: 2.0.1\n            Nested blueprints are registered with their dotted name.\n            This allows different blueprints with the same name to be\n            nested at different locations.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n        \"\"\"\n        name_prefix = options.get(\"name_prefix\", \"\")\n        self_name = options.get(\"name\", self.name)\n        name = f\"{name_prefix}.{self_name}\".lstrip(\".\")\n\n        if name in app.blueprints:\n            bp_desc = \"this\" if app.blueprints[name] is self else \"a different\"\n            existing_at = f\" '{name}'\" if self_name != name else \"\"\n\n            raise ValueError(\n                f\"The name '{self_name}' is already registered for\"\n                f\" {bp_desc} blueprint{existing_at}. Use 'name=' to\"\n                f\" provide a unique name.\"\n            )\n\n        first_bp_registration = not any(bp is self for bp in app.blueprints.values())\n        first_name_registration = name not in app.blueprints\n\n        app.blueprints[name] = self\n        self._got_registered_once = True\n        state = self.make_setup_state(app, options, first_bp_registration)\n\n        if self.has_static_folder:\n            state.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                view_func=self.send_static_file,  # type: ignore[attr-defined]\n                endpoint=\"static\",\n            )\n\n        # Merge blueprint data into parent.\n        if first_bp_registration or first_name_registration:\n            self._merge_blueprint_funcs(app, name)\n\n        for deferred in self.deferred_functions:\n            deferred(state)\n\n        cli_resolved_group = options.get(\"cli_group\", self.cli_group)\n\n        if self.cli.commands:\n            if cli_resolved_group is None:\n                app.cli.commands.update(self.cli.commands)\n            elif cli_resolved_group is _sentinel:\n                self.cli.name = name\n                app.cli.add_command(self.cli)\n            else:\n                self.cli.name = cli_resolved_group\n                app.cli.add_command(self.cli)\n\n        for blueprint, bp_options in self._blueprints:\n            bp_options = bp_options.copy()\n            bp_url_prefix = bp_options.get(\"url_prefix\")\n            bp_subdomain = bp_options.get(\"subdomain\")\n\n            if bp_subdomain is None:\n                bp_subdomain = blueprint.subdomain\n\n            if state.subdomain is not None and bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain + \".\" + state.subdomain\n            elif bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain\n            elif state.subdomain is not None:\n                bp_options[\"subdomain\"] = state.subdomain\n\n            if bp_url_prefix is None:\n                bp_url_prefix = blueprint.url_prefix\n\n            if state.url_prefix is not None and bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = (\n                    state.url_prefix.rstrip(\"/\") + \"/\" + bp_url_prefix.lstrip(\"/\")\n                )\n            elif bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = bp_url_prefix\n            elif state.url_prefix is not None:\n                bp_options[\"url_prefix\"] = state.url_prefix\n\n            bp_options[\"name_prefix\"] = name\n            blueprint.register(app, bp_options)\n\n    def _merge_blueprint_funcs(self, app: App, name: str) -> None:\n        def extend(\n            bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n            parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n        ) -> None:\n            for key, values in bp_dict.items():\n                key = name if key is None else f\"{name}.{key}\"\n                parent_dict[key].extend(values)\n\n        for key, value in self.error_handler_spec.items():\n            key = name if key is None else f\"{name}.{key}\"\n            value = defaultdict(\n                dict,\n                {\n                    code: {exc_class: func for exc_class, func in code_values.items()}\n                    for code, code_values in value.items()\n                },\n            )\n            app.error_handler_spec[key] = value\n\n        for endpoint, func in self.view_functions.items():\n            app.view_functions[endpoint] = func\n\n        extend(self.before_request_funcs, app.before_request_funcs)\n        extend(self.after_request_funcs, app.after_request_funcs)\n        extend(\n            self.teardown_request_funcs,\n            app.teardown_request_funcs,\n        )\n        extend(self.url_default_functions, app.url_default_functions)\n        extend(self.url_value_preprocessors, app.url_value_preprocessors)\n        extend(self.template_context_processors, app.template_context_processors)\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n        full documentation.\n\n        The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n        used with :func:`url_for`, is prefixed with the blueprint's name.\n        \"\"\"\n        if endpoint and \".\" in endpoint:\n            raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n        if view_func and hasattr(view_func, \"__name__\") and \".\" in view_func.__name__:\n            raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n        self.record(\n            lambda s: s.add_url_rule(\n                rule,\n                endpoint,\n                view_func,\n                provide_automatic_options=provide_automatic_options,\n                **options,\n            )\n        )\n\n    @t.overload\n    def app_template_filter(self, name: T_template_filter) -> T_template_filter: ...\n    @t.overload\n    def app_template_filter(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_filter], T_template_filter]: ...\n    @setupmethod\n    def app_template_filter(\n        self, name: T_template_filter | str | None = None\n    ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n        \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_filter` method may be used to register a\n        function later rather than decorating.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_filter`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n        if callable(name):\n            self.add_app_template_filter(name)\n            return name\n\n        def decorator(f: T_template_filter) -> T_template_filter:\n            self.add_app_template_filter(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_filter(\n        self, f: ft.TemplateFilterCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja filter.\n\n        The :meth:`app_template_filter` decorator can be used to register a\n        function by decorating instead.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_filter`.\n\n        :param f: The function to register.\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n\n        def register_template_filter(state: BlueprintSetupState) -> None:\n            state.app.add_template_filter(f, name=name)\n\n        self.record_once(register_template_filter)\n\n    @t.overload\n    def app_template_test(self, name: T_template_test) -> T_template_test: ...\n    @t.overload\n    def app_template_test(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_test], T_template_test]: ...\n    @setupmethod\n    def app_template_test(\n        self, name: T_template_test | str | None = None\n    ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n        \"\"\"Decorate a function to register it as a custom Jinja test. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_test` method may be used to register a\n        function later rather than decorating.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_test`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_test(name)\n            return name\n\n        def decorator(f: T_template_test) -> T_template_test:\n            self.add_app_template_test(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_test(\n        self, f: ft.TemplateTestCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja test.\n\n        The :meth:`app_template_test` decorator can be used to register a\n        function by decorating instead.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_test`.\n\n        :param f: The function to register.\n        :param name: The name to register the test as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_test(state: BlueprintSetupState) -> None:\n            state.app.add_template_test(f, name=name)\n\n        self.record_once(register_template_test)\n\n    @t.overload\n    def app_template_global(self, name: T_template_global) -> T_template_global: ...\n    @t.overload\n    def app_template_global(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_global], T_template_global]: ...\n    @setupmethod\n    def app_template_global(\n        self, name: T_template_global | str | None = None\n    ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n        \"\"\"Decorate a function to register it as a custom Jinja global. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_global` method may be used to register a\n        function later rather than decorating.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_global`.\n\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_global(name)\n            return name\n\n        def decorator(f: T_template_global) -> T_template_global:\n            self.add_app_template_global(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_global(\n        self, f: ft.TemplateGlobalCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja global.\n\n        The :meth:`app_template_global` decorator can be used to register a function\n        by decorating instead.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_global`.\n\n        :param f: The function to register.\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_global(state: BlueprintSetupState) -> None:\n            state.app.add_template_global(f, name=name)\n\n        self.record_once(register_template_global)\n\n    @setupmethod\n    def before_app_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def after_app_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def teardown_app_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_context_processor(\n        self, f: T_template_context_processor\n    ) -> T_template_context_processor:\n        \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n        only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_errorhandler(\n        self, code: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            def from_blueprint(state: BlueprintSetupState) -> None:\n                state.app.errorhandler(code)(f)\n\n            self.record_once(from_blueprint)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def app_url_value_preprocessor(\n        self, f: T_url_value_preprocessor\n    ) -> T_url_value_preprocessor:\n        \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n        )\n        return f\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-d841e365cd245065", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 585, "local_path": "data-flow/inline-intermediate-variables/I12__flask__Blueprint__a9ce432b.py", "order": 12, "original_content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "parent_variant_id": "pyint-c20045673c45-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/blueprints.py#L119-L692", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Blueprint", "variant_id": "pyint-d7e3a9ce432b-I12", "group_id": "py-d841e365cd245065", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 657, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bc6156e85200-I13", "source": "from __future__ import annotations\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nclass Blueprint(Scaffold):\n    \"\"\"Represents a blueprint, a collection of routes and other\n    app-related functions that can be registered on a real application\n    later.\n\n    A blueprint is an object that allows defining application functions\n    without requiring an application object ahead of time. It uses the\n    same decorators as :class:`~flask.Flask`, but defers the need for an\n    application by recording them for later registration.\n\n    Decorating a function with a blueprint creates a deferred function\n    that is called with :class:`~flask.blueprints.BlueprintSetupState`\n    when the blueprint is registered on an application.\n\n    See :doc:`/blueprints` for more information.\n\n    :param name: The name of the blueprint. Will be prepended to each\n        endpoint name.\n    :param import_name: The name of the blueprint package, usually\n        ``__name__``. This helps locate the ``root_path`` for the\n        blueprint.\n    :param static_folder: A folder with static files that should be\n        served by the blueprint's static route. The path is relative to\n        the blueprint's root path. Blueprint static files are disabled\n        by default.\n    :param static_url_path: The url to serve static files from.\n        Defaults to ``static_folder``. If the blueprint does not have\n        a ``url_prefix``, the app's static route will take precedence,\n        and the blueprint's static files won't be accessible.\n    :param template_folder: A folder with templates that should be added\n        to the app's template search path. The path is relative to the\n        blueprint's root path. Blueprint templates are disabled by\n        default. Blueprint templates have a lower precedence than those\n        in the app's templates folder.\n    :param url_prefix: A path to prepend to all of the blueprint's URLs,\n        to make them distinct from the rest of the app's routes.\n    :param subdomain: A subdomain that blueprint routes will match on by\n        default.\n    :param url_defaults: A dict of default values that blueprint routes\n        will receive by default.\n    :param root_path: By default, the blueprint will automatically set\n        this based on ``import_name``. In certain situations this\n        automatic detection can fail, so the path can be specified\n        manually instead.\n\n    .. versionchanged:: 1.1.0\n        Blueprints have a ``cli`` group to register nested CLI commands.\n        The ``cli_group`` parameter controls the name of the group under\n        the ``flask`` command.\n\n    .. versionadded:: 0.7\n    \"\"\"\n\n    _got_registered_once = False\n\n    def __init__(\n        self,\n        name: str,\n        import_name: str,\n        static_folder: str | os.PathLike[str] | None = None,\n        static_url_path: str | None = None,\n        template_folder: str | os.PathLike[str] | None = None,\n        url_prefix: str | None = None,\n        subdomain: str | None = None,\n        url_defaults: dict[str, t.Any] | None = None,\n        root_path: str | None = None,\n        cli_group: str | None = _sentinel,  # type: ignore[assignment]\n    ):\n        super().__init__(\n            import_name=import_name,\n            static_folder=static_folder,\n            static_url_path=static_url_path,\n            template_folder=template_folder,\n            root_path=root_path,\n        )\n\n        if not name:\n            raise ValueError(\"'name' may not be empty.\")\n\n        if \".\" in name:\n            raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n        self.name = name\n        self.url_prefix = url_prefix\n        self.subdomain = subdomain\n        self.deferred_functions: list[DeferredSetupFunction] = []\n\n        if url_defaults is None:\n            url_defaults = {}\n\n        self.url_values_defaults = url_defaults\n        self.cli_group = cli_group\n        self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []\n\n    def _check_setup_finished(self, f_name: str) -> None:\n        if self._got_registered_once:\n            raise AssertionError(\n                f\"The setup method '{f_name}' can no longer be called on the blueprint\"\n                f\" '{self.name}'. It has already been registered at least once, any\"\n                \" changes will not be applied consistently.\\n\"\n                \"Make sure all imports, decorators, functions, etc. needed to set up\"\n                \" the blueprint are done before registering it.\"\n            )\n\n    @setupmethod\n    def record(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Registers a function that is called when the blueprint is\n        registered on the application.  This function is called with the\n        state as argument as returned by the :meth:`make_setup_state`\n        method.\n        \"\"\"\n        self.deferred_functions.append(func)\n\n    @setupmethod\n    def record_once(self, func: DeferredSetupFunction) -> None:\n        \"\"\"Works like :meth:`record` but wraps the function in another\n        function that will ensure the function is only called once.  If the\n        blueprint is registered a second time on the application, the\n        function passed is not called.\n        \"\"\"\n\n        def wrapper(state: BlueprintSetupState) -> None:\n            if state.first_registration:\n                func(state)\n\n        self.record(update_wrapper(wrapper, func))\n\n    def make_setup_state(\n        self, app: App, options: dict[str, t.Any], first_registration: bool = False\n    ) -> BlueprintSetupState:\n        \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n        object that is later passed to the register callback functions.\n        Subclasses can override this to return a subclass of the setup state.\n        \"\"\"\n        return BlueprintSetupState(self, app, options, first_registration)\n\n    @setupmethod\n    def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:\n        \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n        arguments passed to this method will override the defaults set\n        on the blueprint.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n\n        .. versionadded:: 2.0\n        \"\"\"\n        if blueprint is self:\n            raise ValueError(\"Cannot register a blueprint on itself\")\n        self._blueprints.append((blueprint, options))\n\n    def register(self, app: App, options: dict[str, t.Any]) -> None:\n        \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n        views and callbacks registered on the blueprint with the\n        application. Creates a :class:`.BlueprintSetupState` and calls\n        each :meth:`record` callback with it.\n\n        :param app: The application this blueprint is being registered\n            with.\n        :param options: Keyword arguments forwarded from\n            :meth:`~Flask.register_blueprint`.\n\n        .. versionchanged:: 2.3\n            Nested blueprints now correctly apply subdomains.\n\n        .. versionchanged:: 2.1\n            Registering the same blueprint with the same name multiple\n            times is an error.\n\n        .. versionchanged:: 2.0.1\n            Nested blueprints are registered with their dotted name.\n            This allows different blueprints with the same name to be\n            nested at different locations.\n\n        .. versionchanged:: 2.0.1\n            The ``name`` option can be used to change the (pre-dotted)\n            name the blueprint is registered with. This allows the same\n            blueprint to be registered multiple times with unique names\n            for ``url_for``.\n        \"\"\"\n        name_prefix = options.get(\"name_prefix\", \"\")\n        self_name = options.get(\"name\", self.name)\n        name = f\"{name_prefix}.{self_name}\".lstrip(\".\")\n\n        if name in app.blueprints:\n            bp_desc = \"this\" if app.blueprints[name] is self else \"a different\"\n            existing_at = f\" '{name}'\" if self_name != name else \"\"\n\n            raise ValueError(\n                f\"The name '{self_name}' is already registered for\"\n                f\" {bp_desc} blueprint{existing_at}. Use 'name=' to\"\n                f\" provide a unique name.\"\n            )\n\n        first_bp_registration = not any(bp is self for bp in app.blueprints.values())\n        first_name_registration = name not in app.blueprints\n\n        app.blueprints[name] = self\n        self._got_registered_once = True\n        state = self.make_setup_state(app, options, first_bp_registration)\n\n        if self.has_static_folder:\n            state.add_url_rule(\n                f\"{self.static_url_path}/<path:filename>\",\n                view_func=self.send_static_file,  # type: ignore[attr-defined]\n                endpoint=\"static\",\n            )\n\n        # Merge blueprint data into parent.\n        if first_bp_registration or first_name_registration:\n            self._merge_blueprint_funcs(app, name)\n\n        loopIterator = __import__(\"builtins\").iter(self.deferred_functions)\n        while True:\n            try:\n                deferred = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            deferred(state)\n\n        cli_resolved_group = options.get(\"cli_group\", self.cli_group)\n\n        if self.cli.commands:\n            if cli_resolved_group is None:\n                app.cli.commands.update(self.cli.commands)\n            elif cli_resolved_group is _sentinel:\n                self.cli.name = name\n                app.cli.add_command(self.cli)\n            else:\n                self.cli.name = cli_resolved_group\n                app.cli.add_command(self.cli)\n\n        loopIteratorA = __import__(\"builtins\").iter(self._blueprints)\n        while True:\n            try:\n                blueprint, bp_options = __import__(\"builtins\").next(loopIteratorA)\n            except __import__(\"builtins\").StopIteration:\n                break\n            bp_options = bp_options.copy()\n            bp_url_prefix = bp_options.get(\"url_prefix\")\n            bp_subdomain = bp_options.get(\"subdomain\")\n\n            if bp_subdomain is None:\n                bp_subdomain = blueprint.subdomain\n\n            if state.subdomain is not None and bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain + \".\" + state.subdomain\n            elif bp_subdomain is not None:\n                bp_options[\"subdomain\"] = bp_subdomain\n            elif state.subdomain is not None:\n                bp_options[\"subdomain\"] = state.subdomain\n\n            if bp_url_prefix is None:\n                bp_url_prefix = blueprint.url_prefix\n\n            if state.url_prefix is not None and bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = (\n                    state.url_prefix.rstrip(\"/\") + \"/\" + bp_url_prefix.lstrip(\"/\")\n                )\n            elif bp_url_prefix is not None:\n                bp_options[\"url_prefix\"] = bp_url_prefix\n            elif state.url_prefix is not None:\n                bp_options[\"url_prefix\"] = state.url_prefix\n\n            bp_options[\"name_prefix\"] = name\n            blueprint.register(app, bp_options)\n\n    def _merge_blueprint_funcs(self, app: App, name: str) -> None:\n        def extend(\n            bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n            parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n        ) -> None:\n            loopIteratorB = __import__(\"builtins\").iter(bp_dict.items())\n            while True:\n                try:\n                    key, values = __import__(\"builtins\").next(loopIteratorB)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                key = name if key is None else f\"{name}.{key}\"\n                parent_dict[key].extend(values)\n\n        loopIteratorC = __import__(\"builtins\").iter(self.error_handler_spec.items())\n        while True:\n            try:\n                key, value = __import__(\"builtins\").next(loopIteratorC)\n            except __import__(\"builtins\").StopIteration:\n                break\n            key = name if key is None else f\"{name}.{key}\"\n            value = defaultdict(\n                dict,\n                {\n                    code: {exc_class: func for exc_class, func in code_values.items()}\n                    for code, code_values in value.items()\n                },\n            )\n            app.error_handler_spec[key] = value\n\n        loopIteratorD = __import__(\"builtins\").iter(self.view_functions.items())\n        while True:\n            try:\n                endpoint, func = __import__(\"builtins\").next(loopIteratorD)\n            except __import__(\"builtins\").StopIteration:\n                break\n            app.view_functions[endpoint] = func\n\n        extend(self.before_request_funcs, app.before_request_funcs)\n        extend(self.after_request_funcs, app.after_request_funcs)\n        extend(\n            self.teardown_request_funcs,\n            app.teardown_request_funcs,\n        )\n        extend(self.url_default_functions, app.url_default_functions)\n        extend(self.url_value_preprocessors, app.url_value_preprocessors)\n        extend(self.template_context_processors, app.template_context_processors)\n\n    @setupmethod\n    def add_url_rule(\n        self,\n        rule: str,\n        endpoint: str | None = None,\n        view_func: ft.RouteCallable | None = None,\n        provide_automatic_options: bool | None = None,\n        **options: t.Any,\n    ) -> None:\n        \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n        full documentation.\n\n        The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n        used with :func:`url_for`, is prefixed with the blueprint's name.\n        \"\"\"\n        if endpoint and \".\" in endpoint:\n            raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n        if view_func and hasattr(view_func, \"__name__\") and \".\" in view_func.__name__:\n            raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n        self.record(\n            lambda s: s.add_url_rule(\n                rule,\n                endpoint,\n                view_func,\n                provide_automatic_options=provide_automatic_options,\n                **options,\n            )\n        )\n\n    @t.overload\n    def app_template_filter(self, name: T_template_filter) -> T_template_filter: ...\n    @t.overload\n    def app_template_filter(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_filter], T_template_filter]: ...\n    @setupmethod\n    def app_template_filter(\n        self, name: T_template_filter | str | None = None\n    ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n        \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_filter` method may be used to register a\n        function later rather than decorating.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_filter`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n        if callable(name):\n            self.add_app_template_filter(name)\n            return name\n\n        def decorator(f: T_template_filter) -> T_template_filter:\n            self.add_app_template_filter(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_filter(\n        self, f: ft.TemplateFilterCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja filter.\n\n        The :meth:`app_template_filter` decorator can be used to register a\n        function by decorating instead.\n\n        The filter is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_filter`.\n\n        :param f: The function to register.\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n        \"\"\"\n\n        def register_template_filter(state: BlueprintSetupState) -> None:\n            state.app.add_template_filter(f, name=name)\n\n        self.record_once(register_template_filter)\n\n    @t.overload\n    def app_template_test(self, name: T_template_test) -> T_template_test: ...\n    @t.overload\n    def app_template_test(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_test], T_template_test]: ...\n    @setupmethod\n    def app_template_test(\n        self, name: T_template_test | str | None = None\n    ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n        \"\"\"Decorate a function to register it as a custom Jinja test. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_test` method may be used to register a\n        function later rather than decorating.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_test`.\n\n        :param name: The name to register the filter as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_test(name)\n            return name\n\n        def decorator(f: T_template_test) -> T_template_test:\n            self.add_app_template_test(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_test(\n        self, f: ft.TemplateTestCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja test.\n\n        The :meth:`app_template_test` decorator can be used to register a\n        function by decorating instead.\n\n        The test is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_test`.\n\n        :param f: The function to register.\n        :param name: The name to register the test as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_test(state: BlueprintSetupState) -> None:\n            state.app.add_template_test(f, name=name)\n\n        self.record_once(register_template_test)\n\n    @t.overload\n    def app_template_global(self, name: T_template_global) -> T_template_global: ...\n    @t.overload\n    def app_template_global(\n        self, name: str | None = None\n    ) -> t.Callable[[T_template_global], T_template_global]: ...\n    @setupmethod\n    def app_template_global(\n        self, name: T_template_global | str | None = None\n    ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n        \"\"\"Decorate a function to register it as a custom Jinja global. The name\n        is optional. The decorator may be used without parentheses.\n\n        The :meth:`add_app_template_global` method may be used to register a\n        function later rather than decorating.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.template_global`.\n\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n        if callable(name):\n            self.add_app_template_global(name)\n            return name\n\n        def decorator(f: T_template_global) -> T_template_global:\n            self.add_app_template_global(f, name=name)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def add_app_template_global(\n        self, f: ft.TemplateGlobalCallable, name: str | None = None\n    ) -> None:\n        \"\"\"Register a function to use as a custom Jinja global.\n\n        The :meth:`app_template_global` decorator can be used to register a function\n        by decorating instead.\n\n        The global is available in all templates, not only those under this\n        blueprint. Equivalent to :meth:`.Flask.add_template_global`.\n\n        :param f: The function to register.\n        :param name: The name to register the global as. If not given, uses the\n            function's name.\n\n        .. versionadded:: 0.10\n        \"\"\"\n\n        def register_template_global(state: BlueprintSetupState) -> None:\n            state.app.add_template_global(f, name=name)\n\n        self.record_once(register_template_global)\n\n    @setupmethod\n    def before_app_request(self, f: T_before_request) -> T_before_request:\n        \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def after_app_request(self, f: T_after_request) -> T_after_request:\n        \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n        by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def teardown_app_request(self, f: T_teardown) -> T_teardown:\n        \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_context_processor(\n        self, f: T_template_context_processor\n    ) -> T_template_context_processor:\n        \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n        only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_errorhandler(\n        self, code: type[Exception] | int\n    ) -> t.Callable[[T_error_handler], T_error_handler]:\n        \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n        \"\"\"\n\n        def decorator(f: T_error_handler) -> T_error_handler:\n            def from_blueprint(state: BlueprintSetupState) -> None:\n                state.app.errorhandler(code)(f)\n\n            self.record_once(from_blueprint)\n            return f\n\n        return decorator\n\n    @setupmethod\n    def app_url_value_preprocessor(\n        self, f: T_url_value_preprocessor\n    ) -> T_url_value_preprocessor:\n        \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n        handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n        )\n        return f\n\n    @setupmethod\n    def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n        \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n        the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n        \"\"\"\n        self.record_once(\n            lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n        )\n        return f\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-d841e365cd245065", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "ac55db7b54406e41885da7460d4eb27f7b4b3a89871f98ab16006cca74b55cd1", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 610, "local_path": "control-flow/lower-for-to-while/I13__flask__Blueprint__56e85200.py", "order": 13, "original_content_sha256": "ed4348bd87ce344ccb97813255367004f764894a2eb03aaa758063b990779614", "parent_variant_id": "pyint-c20045673c45-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/sansio/blueprints.py#L119-L692", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 5, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 5, "synchronous_for_loops_eligible": 5, "synchronous_for_loops_found": 5}, "unit_kind": "class", "unit_name": "Blueprint", "variant_id": "pyint-bc6156e85200-I13", "group_id": "py-d841e365cd245065", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 658, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6479a4f95982-SRC", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassList(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, list)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return [self.serializer.tag(item) for item in value]\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-d8b3679fc7809055", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 22, "local_path": "source-original/SRC__flask__PassList__a4f95982.py", "order": 0, "original_content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L147-L156", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "PassList", "variant_id": "pyint-6479a4f95982-SRC", "group_id": "py-d8b3679fc7809055", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 533, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9537faa0d6e2-I01", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassList(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, list)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return [self.serializer.tag(item) for item in value]\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-d8b3679fc7809055", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 22, "local_path": "comments/remove-comments/I01__flask__PassList__faa0d6e2.py", "order": 1, "original_content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "parent_variant_id": "pyint-6479a4f95982-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L147-L156", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 0, "comments_removed": 0, "docstrings_removed": 0, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "PassList", "variant_id": "pyint-9537faa0d6e2-I01", "group_id": "py-d8b3679fc7809055", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 534, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-19a29044479f-I02", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassList(JSONTag):\n    __slots__ = ()\n\n    def che(self, val: t.Any) -> bool:\n        return isinstance(val, list)\n\n    def to(self, val2: t.Any) -> t.Any:\n        return [self.serializer.tag(ite) for ite in val2]\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-d8b3679fc7809055", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "eb0d3e29d58478e9ff59345876ca7a804b58faa1bb4b5edbcde678e0579f574e", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 22, "local_path": "identifiers/shorten-identifiers/I02__flask__PassList__9044479f.py", "order": 2, "original_content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "parent_variant_id": "pyint-6479a4f95982-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L147-L156", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "PassList", "variant_id": "pyint-19a29044479f-I02", "group_id": "py-d8b3679fc7809055", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 535, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5a66b4f65b55-I03", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassList(JSONTag):\n    __slots__ = ()\n\n    def write(self, event: t.Any) -> bool:\n        return isinstance(event, list)\n\n    def measure(self, token: t.Any) -> t.Any:\n        return [self.serializer.tag(mode) for mode in token]\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-d8b3679fc7809055", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "196f90795dc600227139473f05a43d18326d6df5164f92dae984bfa957458740", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 22, "local_path": "identifiers/mislead-identifiers/I03__flask__PassList__b4f65b55.py", "order": 3, "original_content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "parent_variant_id": "pyint-6479a4f95982-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L147-L156", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 5, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 3, "local_random_pool_selections": 3, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 2, "method_random_pool_selections": 2, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "PassList", "variant_id": "pyint-5a66b4f65b55-I03", "group_id": "py-d8b3679fc7809055", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 536, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0d7a742d270c-I04", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassList(JSONTag):\n    __slots__ = ()\n\n    def a(self, c: t.Any) -> bool:\n        return isinstance(c, list)\n\n    def b(self, d: t.Any) -> t.Any:\n        return [self.serializer.tag(e) for e in d]\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-d8b3679fc7809055", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "74eac6d4f45b4583dbddce777eab99cadd37c75020b1846f18148b78818fa3d5", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 22, "local_path": "identifiers/garble-identifiers/I04__flask__PassList__742d270c.py", "order": 4, "original_content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "parent_variant_id": "pyint-6479a4f95982-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L147-L156", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "PassList", "variant_id": "pyint-0d7a742d270c-I04", "group_id": "py-d8b3679fc7809055", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 537, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b97aaa86e408-I05", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassList(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, list)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return [self.serializer.tag(item) for item in value]\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-d8b3679fc7809055", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 22, "local_path": "expressions/encode-integer-literals/I05__flask__PassList__aa86e408.py", "order": 5, "original_content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "parent_variant_id": "pyint-6479a4f95982-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L147-L156", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "PassList", "variant_id": "pyint-b97aaa86e408-I05", "group_id": "py-d8b3679fc7809055", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 538, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a4a3c7ab13f3-I06", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassList(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, list)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return [self.serializer.tag(item) for item in value]\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-d8b3679fc7809055", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 22, "local_path": "expressions/invert-conditions/I06__flask__PassList__c7ab13f3.py", "order": 6, "original_content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "parent_variant_id": "pyint-6479a4f95982-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L147-L156", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "PassList", "variant_id": "pyint-a4a3c7ab13f3-I06", "group_id": "py-d8b3679fc7809055", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 539, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2f8663171740-I07", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassList(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        if ((0x13d ^ 0x13d) != 0):\n            raise AssertionError()\n        return isinstance(value, list)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        if ((0x3891 ^ 0x3891) != 0):\n            raise AssertionError()\n        return [self.serializer.tag(item) for item in value]\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-d8b3679fc7809055", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "082740cdf2b4cb2ffb724d3b3dfb44e33355f570d0cf12a199b23f83d164f338", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 26, "local_path": "code-injection/insert-dead-branches/I07__flask__PassList__63171740.py", "order": 7, "original_content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "parent_variant_id": "pyint-6479a4f95982-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L147-L156", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "PassList", "variant_id": "pyint-2f8663171740-I07", "group_id": "py-d8b3679fc7809055", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 540, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-00d8e68cd80f-I08", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassList(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, list)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        remaining_steps = 3\n        while remaining_steps > 0:\n            remaining_steps -= 1\n        return [self.serializer.tag(item) for item in value]\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-d8b3679fc7809055", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "7c155cdccf096483d4e45eefb3ef609c11dd955f5041e62268bd7f693c0759bf", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 25, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__PassList__e68cd80f.py", "order": 8, "original_content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "parent_variant_id": "pyint-6479a4f95982-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L147-L156", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 1}, "unit_kind": "class", "unit_name": "PassList", "variant_id": "pyint-00d8e68cd80f-I08", "group_id": "py-d8b3679fc7809055", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 541, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4d81b67912ab-I09", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassList(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        lI0O_6fc921c4, lI0O_271670d1 = 0x4384, ~0x4384\n        lI0O_6fc921c4 = (lI0O_6fc921c4 & lI0O_271670d1) | (lI0O_6fc921c4 ^ lI0O_6fc921c4)\n        lI0O_271670d1 ^= lI0O_271670d1\n        return isinstance(value, list)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return [self.serializer.tag(item) for item in value]\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-d8b3679fc7809055", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "2adeddc0a2a09738f6e4c8a33c23783944e4ec652b1fd77ae62b341fe8e0469a", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 25, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__PassList__b67912ab.py", "order": 9, "original_content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "parent_variant_id": "pyint-6479a4f95982-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L147-L156", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 9}, "unit_kind": "class", "unit_name": "PassList", "variant_id": "pyint-4d81b67912ab-I09", "group_id": "py-d8b3679fc7809055", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 542, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d6ec6f06c954-I10", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassList(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, list)\n    def to_json(self, value: t.Any) -> t.Any:\n        return [self.serializer.tag(item) for item in value]\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-d8b3679fc7809055", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "d183c91148221cf47fa3be4f53a28e5249cb95cfa4c9497574c2699f84732178", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 21, "local_path": "layout/partially-compact-layout/I10__flask__PassList__6f06c954.py", "order": 10, "original_content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "parent_variant_id": "pyint-6479a4f95982-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L147-L156", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 4, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "PassList", "variant_id": "pyint-d6ec6f06c954-I10", "group_id": "py-d8b3679fc7809055", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 543, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e43614012f8d-I11", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassList(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, list)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return [self.serializer.tag(item) for item in value]\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-d8b3679fc7809055", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 22, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__PassList__14012f8d.py", "order": 11, "original_content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "parent_variant_id": "pyint-6479a4f95982-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L147-L156", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "PassList", "variant_id": "pyint-e43614012f8d-I11", "group_id": "py-d8b3679fc7809055", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 544, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-606529c832a5-I12", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassList(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, list)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return [self.serializer.tag(item) for item in value]\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-d8b3679fc7809055", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 22, "local_path": "data-flow/inline-intermediate-variables/I12__flask__PassList__29c832a5.py", "order": 12, "original_content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "parent_variant_id": "pyint-6479a4f95982-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L147-L156", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "PassList", "variant_id": "pyint-606529c832a5-I12", "group_id": "py-d8b3679fc7809055", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 545, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2f2229d34ea8-I13", "source": "from __future__ import annotations\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\nfrom ..json import dumps\nfrom ..json import loads\n\nclass PassList(JSONTag):\n    __slots__ = ()\n\n    def check(self, value: t.Any) -> bool:\n        return isinstance(value, list)\n\n    def to_json(self, value: t.Any) -> t.Any:\n        return [self.serializer.tag(item) for item in value]\n\n    tag = to_json\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-d8b3679fc7809055", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 22, "local_path": "control-flow/lower-for-to-while/I13__flask__PassList__29d34ea8.py", "order": 13, "original_content_sha256": "92de2aab572eed4987c140ea10d4688b278f19f02a5006a33a86ef6a706416b2", "parent_variant_id": "pyint-6479a4f95982-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/tag.py#L147-L156", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "PassList", "variant_id": "pyint-2f2229d34ea8-I13", "group_id": "py-d8b3679fc7809055", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 546, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fb2c9bfec6c7-SRC", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n    \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n    application.\n\n    :param app: The Flask application to configure the environment from.\n    :param path: URL path being requested.\n    :param base_url: Base URL where the app is being served, which\n        ``path`` is relative to. If not given, built from\n        :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n        :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n    :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n    :param url_scheme: Scheme to use instead of\n        :data:`PREFERRED_URL_SCHEME`.\n    :param json: If given, this is serialized as JSON and passed as\n        ``data``. Also defaults ``content_type`` to\n        ``application/json``.\n    :param args: other positional arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    :param kwargs: other keyword arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    \"\"\"\n\n    def __init__(\n        self,\n        app: Flask,\n        path: str = \"/\",\n        base_url: str | None = None,\n        subdomain: str | None = None,\n        url_scheme: str | None = None,\n        *args: t.Any,\n        **kwargs: t.Any,\n    ) -> None:\n        assert not (base_url or subdomain or url_scheme) or (\n            base_url is not None\n        ) != bool(subdomain or url_scheme), (\n            'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n        )\n\n        if base_url is None:\n            http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n            app_root = app.config[\"APPLICATION_ROOT\"]\n\n            if subdomain:\n                http_host = f\"{subdomain}.{http_host}\"\n\n            if url_scheme is None:\n                url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n            url = urlsplit(path)\n            base_url = (\n                f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"\n                f\"/{app_root.lstrip('/')}\"\n            )\n            path = url.path\n\n            if url.query:\n                path = f\"{path}?{url.query}\"\n\n        self.app = app\n        super().__init__(path, base_url, *args, **kwargs)\n\n    def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n        The serialization will be configured according to the config associated\n        with this EnvironBuilder's ``app``.\n        \"\"\"\n        return self.app.json.dumps(obj, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-dabbd64af65acf1a", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 84, "local_path": "source-original/SRC__flask__EnvironBuilder__9bfec6c7.py", "order": 0, "original_content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L27-L94", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "EnvironBuilder", "variant_id": "pyint-fb2c9bfec6c7-SRC", "group_id": "py-dabbd64af65acf1a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 617, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c56fd7e49e6f-I01", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n    \n\n    def __init__(\n        self,\n        app: Flask,\n        path: str = \"/\",\n        base_url: str | None = None,\n        subdomain: str | None = None,\n        url_scheme: str | None = None,\n        *args: t.Any,\n        **kwargs: t.Any,\n    ) -> None:\n        assert not (base_url or subdomain or url_scheme) or (\n            base_url is not None\n        ) != bool(subdomain or url_scheme), (\n            'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n        )\n\n        if base_url is None:\n            http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n            app_root = app.config[\"APPLICATION_ROOT\"]\n\n            if subdomain:\n                http_host = f\"{subdomain}.{http_host}\"\n\n            if url_scheme is None:\n                url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n            url = urlsplit(path)\n            base_url = (\n                f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"\n                f\"/{app_root.lstrip('/')}\"\n            )\n            path = url.path\n\n            if url.query:\n                path = f\"{path}?{url.query}\"\n\n        self.app = app\n        super().__init__(path, base_url, *args, **kwargs)\n\n    def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \n        return self.app.json.dumps(obj, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-dabbd64af65acf1a", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "ff556f96ebc128a4e4c696730344f6731ec72e8fa31b7e1781a8f688afa85d17", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 61, "local_path": "comments/remove-comments/I01__flask__EnvironBuilder__d7e49e6f.py", "order": 1, "original_content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "parent_variant_id": "pyint-fb2c9bfec6c7-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L27-L94", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 1148, "comments_removed": 2, "docstrings_removed": 2, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "EnvironBuilder", "variant_id": "pyint-c56fd7e49e6f-I01", "group_id": "py-dabbd64af65acf1a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 618, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f81aae7a02f9-I02", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n    \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n    application.\n\n    :param app: The Flask application to configure the environment from.\n    :param path: URL path being requested.\n    :param base_url: Base URL where the app is being served, which\n        ``path`` is relative to. If not given, built from\n        :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n        :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n    :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n    :param url_scheme: Scheme to use instead of\n        :data:`PREFERRED_URL_SCHEME`.\n    :param json: If given, this is serialized as JSON and passed as\n        ``data``. Also defaults ``content_type`` to\n        ``application/json``.\n    :param args: other positional arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    :param kwargs: other keyword arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    \"\"\"\n\n    def __init__(\n        self,\n        app2: Flask,\n        pat: str = \"/\",\n        base: str | None = None,\n        sub: str | None = None,\n        url2: str | None = None,\n        *arg: t.Any,\n        **kwa: t.Any,\n    ) -> None:\n        assert not (base or sub or url2) or (\n            base is not None\n        ) != bool(sub or url2), (\n            'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n        )\n\n        if base is None:\n            http = app2.config.get(\"SERVER_NAME\") or \"localhost\"\n            app3 = app2.config[\"APPLICATION_ROOT\"]\n\n            if sub:\n                http = f\"{sub}.{http}\"\n\n            if url2 is None:\n                url2 = app2.config[\"PREFERRED_URL_SCHEME\"]\n\n            url3 = urlsplit(pat)\n            base = (\n                f\"{url3.scheme or url2}://{url3.netloc or http}\"\n                f\"/{app3.lstrip('/')}\"\n            )\n            pat = url3.path\n\n            if url3.query:\n                pat = f\"{pat}?{url3.query}\"\n\n        self.app = app2\n        super().__init__(pat, base, *arg, **kwa)\n\n    def json2(self, obj2: t.Any, **kwa2: t.Any) -> str:\n        \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n        The serialization will be configured according to the config associated\n        with this EnvironBuilder's ``app``.\n        \"\"\"\n        return self.app.json.dumps(obj2, **kwa2)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-dabbd64af65acf1a", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "6f81abe7052d2c9621d051d7d88eed2919225de95e29bdc181ba4697fab6b0f8", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 84, "local_path": "identifiers/shorten-identifiers/I02__flask__EnvironBuilder__ae7a02f9.py", "order": 2, "original_content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "parent_variant_id": "pyint-fb2c9bfec6c7-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L27-L94", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 49, "identifiers_declared": 13}, "unit_kind": "class", "unit_name": "EnvironBuilder", "variant_id": "pyint-f81aae7a02f9-I02", "group_id": "py-dabbd64af65acf1a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 619, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-57a2b5b62153-I03", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n    \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n    application.\n\n    :param app: The Flask application to configure the environment from.\n    :param path: URL path being requested.\n    :param base_url: Base URL where the app is being served, which\n        ``path`` is relative to. If not given, built from\n        :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n        :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n    :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n    :param url_scheme: Scheme to use instead of\n        :data:`PREFERRED_URL_SCHEME`.\n    :param json: If given, this is serialized as JSON and passed as\n        ``data``. Also defaults ``content_type`` to\n        ``application/json``.\n    :param args: other positional arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    :param kwargs: other keyword arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    \"\"\"\n\n    def __init__(\n        self,\n        key: Flask,\n        size: str = \"/\",\n        nextItem: str | None = None,\n        timestamp: str | None = None,\n        finalBatch: str | None = None,\n        *step: t.Any,\n        **target: t.Any,\n    ) -> None:\n        assert not (nextItem or timestamp or finalBatch) or (\n            nextItem is not None\n        ) != bool(timestamp or finalBatch), (\n            'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n        )\n\n        if nextItem is None:\n            cachedKey = key.config.get(\"SERVER_NAME\") or \"localhost\"\n            schedule = key.config[\"APPLICATION_ROOT\"]\n\n            if timestamp:\n                cachedKey = f\"{timestamp}.{cachedKey}\"\n\n            if finalBatch is None:\n                finalBatch = key.config[\"PREFERRED_URL_SCHEME\"]\n\n            age = urlsplit(size)\n            nextItem = (\n                f\"{age.scheme or finalBatch}://{age.netloc or cachedKey}\"\n                f\"/{schedule.lstrip('/')}\"\n            )\n            size = age.path\n\n            if age.query:\n                size = f\"{size}?{age.query}\"\n\n        self.app = key\n        super().__init__(size, nextItem, *step, **target)\n\n    def fetchEvent(self, map: t.Any, **config: t.Any) -> str:\n        \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n        The serialization will be configured according to the config associated\n        with this EnvironBuilder's ``app``.\n        \"\"\"\n        return self.app.json.dumps(map, **config)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-dabbd64af65acf1a", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "698875cb3e7bfd4b5fbbea0de48460dd73164d2b31ac96792c74ddb176de4b2a", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 84, "local_path": "identifiers/mislead-identifiers/I03__flask__EnvironBuilder__b5b62153.py", "order": 3, "original_content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "parent_variant_id": "pyint-fb2c9bfec6c7-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L27-L94", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 49, "identifiers_declared": 13, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 1, "local_exact_length_matches": 12, "local_random_pool_selections": 12, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "EnvironBuilder", "variant_id": "pyint-57a2b5b62153-I03", "group_id": "py-dabbd64af65acf1a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 620, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8347cd56af36-I04", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n    \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n    application.\n\n    :param app: The Flask application to configure the environment from.\n    :param path: URL path being requested.\n    :param base_url: Base URL where the app is being served, which\n        ``path`` is relative to. If not given, built from\n        :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n        :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n    :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n    :param url_scheme: Scheme to use instead of\n        :data:`PREFERRED_URL_SCHEME`.\n    :param json: If given, this is serialized as JSON and passed as\n        ``data``. Also defaults ``content_type`` to\n        ``application/json``.\n    :param args: other positional arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    :param kwargs: other keyword arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    \"\"\"\n\n    def __init__(\n        self,\n        b: Flask,\n        c: str = \"/\",\n        d: str | None = None,\n        e: str | None = None,\n        f: str | None = None,\n        *g: t.Any,\n        **h: t.Any,\n    ) -> None:\n        assert not (d or e or f) or (\n            d is not None\n        ) != bool(e or f), (\n            'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n        )\n\n        if d is None:\n            i = b.config.get(\"SERVER_NAME\") or \"localhost\"\n            j = b.config[\"APPLICATION_ROOT\"]\n\n            if e:\n                i = f\"{e}.{i}\"\n\n            if f is None:\n                f = b.config[\"PREFERRED_URL_SCHEME\"]\n\n            k = urlsplit(c)\n            d = (\n                f\"{k.scheme or f}://{k.netloc or i}\"\n                f\"/{j.lstrip('/')}\"\n            )\n            c = k.path\n\n            if k.query:\n                c = f\"{c}?{k.query}\"\n\n        self.app = b\n        super().__init__(c, d, *g, **h)\n\n    def a(self, l: t.Any, **m: t.Any) -> str:\n        \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n        The serialization will be configured according to the config associated\n        with this EnvironBuilder's ``app``.\n        \"\"\"\n        return self.app.json.dumps(l, **m)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-dabbd64af65acf1a", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "7c010064114c9eefa6db88533a5a8b719256fd25e4b300626288e896f238f529", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 84, "local_path": "identifiers/garble-identifiers/I04__flask__EnvironBuilder__cd56af36.py", "order": 4, "original_content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "parent_variant_id": "pyint-fb2c9bfec6c7-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L27-L94", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 49, "identifiers_declared": 13}, "unit_kind": "class", "unit_name": "EnvironBuilder", "variant_id": "pyint-8347cd56af36-I04", "group_id": "py-dabbd64af65acf1a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 621, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-94e6a31d78d1-I05", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n    \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n    application.\n\n    :param app: The Flask application to configure the environment from.\n    :param path: URL path being requested.\n    :param base_url: Base URL where the app is being served, which\n        ``path`` is relative to. If not given, built from\n        :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n        :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n    :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n    :param url_scheme: Scheme to use instead of\n        :data:`PREFERRED_URL_SCHEME`.\n    :param json: If given, this is serialized as JSON and passed as\n        ``data``. Also defaults ``content_type`` to\n        ``application/json``.\n    :param args: other positional arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    :param kwargs: other keyword arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    \"\"\"\n\n    def __init__(\n        self,\n        app: Flask,\n        path: str = \"/\",\n        base_url: str | None = None,\n        subdomain: str | None = None,\n        url_scheme: str | None = None,\n        *args: t.Any,\n        **kwargs: t.Any,\n    ) -> None:\n        assert not (base_url or subdomain or url_scheme) or (\n            base_url is not None\n        ) != bool(subdomain or url_scheme), (\n            'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n        )\n\n        if base_url is None:\n            http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n            app_root = app.config[\"APPLICATION_ROOT\"]\n\n            if subdomain:\n                http_host = f\"{subdomain}.{http_host}\"\n\n            if url_scheme is None:\n                url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n            url = urlsplit(path)\n            base_url = (\n                f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"\n                f\"/{app_root.lstrip('/')}\"\n            )\n            path = url.path\n\n            if url.query:\n                path = f\"{path}?{url.query}\"\n\n        self.app = app\n        super().__init__(path, base_url, *args, **kwargs)\n\n    def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n        The serialization will be configured according to the config associated\n        with this EnvironBuilder's ``app``.\n        \"\"\"\n        return self.app.json.dumps(obj, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-dabbd64af65acf1a", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 84, "local_path": "expressions/encode-integer-literals/I05__flask__EnvironBuilder__a31d78d1.py", "order": 5, "original_content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "parent_variant_id": "pyint-fb2c9bfec6c7-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L27-L94", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "EnvironBuilder", "variant_id": "pyint-94e6a31d78d1-I05", "group_id": "py-dabbd64af65acf1a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 622, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-988ca5c2221c-I06", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n    \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n    application.\n\n    :param app: The Flask application to configure the environment from.\n    :param path: URL path being requested.\n    :param base_url: Base URL where the app is being served, which\n        ``path`` is relative to. If not given, built from\n        :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n        :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n    :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n    :param url_scheme: Scheme to use instead of\n        :data:`PREFERRED_URL_SCHEME`.\n    :param json: If given, this is serialized as JSON and passed as\n        ``data``. Also defaults ``content_type`` to\n        ``application/json``.\n    :param args: other positional arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    :param kwargs: other keyword arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    \"\"\"\n\n    def __init__(\n        self,\n        app: Flask,\n        path: str = \"/\",\n        base_url: str | None = None,\n        subdomain: str | None = None,\n        url_scheme: str | None = None,\n        *args: t.Any,\n        **kwargs: t.Any,\n    ) -> None:\n        assert not (base_url or subdomain or url_scheme) or (\n            base_url is not None\n        ) != bool(subdomain or url_scheme), (\n            'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n        )\n\n        if not (base_url is None):\n            pass\n        else:\n            http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n            app_root = app.config[\"APPLICATION_ROOT\"]\n\n            if subdomain:\n                http_host = f\"{subdomain}.{http_host}\"\n\n            if url_scheme is None:\n                url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n            url = urlsplit(path)\n            base_url = (\n                f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"\n                f\"/{app_root.lstrip('/')}\"\n            )\n            path = url.path\n\n            if url.query:\n                path = f\"{path}?{url.query}\"\n\n        self.app = app\n        super().__init__(path, base_url, *args, **kwargs)\n\n    def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n        The serialization will be configured according to the config associated\n        with this EnvironBuilder's ``app``.\n        \"\"\"\n        return self.app.json.dumps(obj, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-dabbd64af65acf1a", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "5cf649013393e90d9b2dc897a4ee3a98694a7818c509ea19b3b92530ad201b58", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 86, "local_path": "expressions/invert-conditions/I06__flask__EnvironBuilder__a5c2221c.py", "order": 6, "original_content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "parent_variant_id": "pyint-fb2c9bfec6c7-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L27-L94", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "EnvironBuilder", "variant_id": "pyint-988ca5c2221c-I06", "group_id": "py-dabbd64af65acf1a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 623, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b06626aec1e5-I07", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n    \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n    application.\n\n    :param app: The Flask application to configure the environment from.\n    :param path: URL path being requested.\n    :param base_url: Base URL where the app is being served, which\n        ``path`` is relative to. If not given, built from\n        :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n        :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n    :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n    :param url_scheme: Scheme to use instead of\n        :data:`PREFERRED_URL_SCHEME`.\n    :param json: If given, this is serialized as JSON and passed as\n        ``data``. Also defaults ``content_type`` to\n        ``application/json``.\n    :param args: other positional arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    :param kwargs: other keyword arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    \"\"\"\n\n    def __init__(\n        self,\n        app: Flask,\n        path: str = \"/\",\n        base_url: str | None = None,\n        subdomain: str | None = None,\n        url_scheme: str | None = None,\n        *args: t.Any,\n        **kwargs: t.Any,\n    ) -> None:\n        if ((0xdf7b ^ 0xdf7b) != 0):\n            raise AssertionError()\n        assert not (base_url or subdomain or url_scheme) or (\n            base_url is not None\n        ) != bool(subdomain or url_scheme), (\n            'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n        )\n\n        if base_url is None:\n            http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n            app_root = app.config[\"APPLICATION_ROOT\"]\n\n            if subdomain:\n                http_host = f\"{subdomain}.{http_host}\"\n\n            if url_scheme is None:\n                url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n            url = urlsplit(path)\n            base_url = (\n                f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"\n                f\"/{app_root.lstrip('/')}\"\n            )\n            path = url.path\n\n            if url.query:\n                path = f\"{path}?{url.query}\"\n\n        self.app = app\n        super().__init__(path, base_url, *args, **kwargs)\n\n    def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n        The serialization will be configured according to the config associated\n        with this EnvironBuilder's ``app``.\n        \"\"\"\n        if ((0xe35f ^ 0xe35f) != 0):\n            raise AssertionError()\n        return self.app.json.dumps(obj, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-dabbd64af65acf1a", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "2dc5d8e3307944bcfb6161eb535f01ef342f45ccd7f177db77b7c624ea3de2ea", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 88, "local_path": "code-injection/insert-dead-branches/I07__flask__EnvironBuilder__26aec1e5.py", "order": 7, "original_content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "parent_variant_id": "pyint-fb2c9bfec6c7-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L27-L94", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "EnvironBuilder", "variant_id": "pyint-b06626aec1e5-I07", "group_id": "py-dabbd64af65acf1a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 624, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-adb096ab65b0-I08", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n    \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n    application.\n\n    :param app: The Flask application to configure the environment from.\n    :param path: URL path being requested.\n    :param base_url: Base URL where the app is being served, which\n        ``path`` is relative to. If not given, built from\n        :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n        :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n    :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n    :param url_scheme: Scheme to use instead of\n        :data:`PREFERRED_URL_SCHEME`.\n    :param json: If given, this is serialized as JSON and passed as\n        ``data``. Also defaults ``content_type`` to\n        ``application/json``.\n    :param args: other positional arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    :param kwargs: other keyword arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    \"\"\"\n\n    def __init__(\n        self,\n        app: Flask,\n        path: str = \"/\",\n        base_url: str | None = None,\n        subdomain: str | None = None,\n        url_scheme: str | None = None,\n        *args: t.Any,\n        **kwargs: t.Any,\n    ) -> None:\n        starting_position = 2\n        ending_position = 9\n        travel_distance = ending_position - starting_position\n        if travel_distance < 0:\n            travel_distance = -travel_distance\n        assert not (base_url or subdomain or url_scheme) or (\n            base_url is not None\n        ) != bool(subdomain or url_scheme), (\n            'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n        )\n\n        if base_url is None:\n            http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n            app_root = app.config[\"APPLICATION_ROOT\"]\n\n            if subdomain:\n                http_host = f\"{subdomain}.{http_host}\"\n\n            if url_scheme is None:\n                url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n            url = urlsplit(path)\n            base_url = (\n                f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"\n                f\"/{app_root.lstrip('/')}\"\n            )\n            path = url.path\n\n            if url.query:\n                path = f\"{path}?{url.query}\"\n\n        self.app = app\n        super().__init__(path, base_url, *args, **kwargs)\n\n    def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n        The serialization will be configured according to the config associated\n        with this EnvironBuilder's ``app``.\n        \"\"\"\n        return self.app.json.dumps(obj, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-dabbd64af65acf1a", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "05b9449bc538846af2394a6ddeaadc96c3ca2dbf456130a698ea571c86394f40", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 89, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__EnvironBuilder__96ab65b0.py", "order": 8, "original_content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "parent_variant_id": "pyint-fb2c9bfec6c7-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L27-L94", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 9}, "unit_kind": "class", "unit_name": "EnvironBuilder", "variant_id": "pyint-adb096ab65b0-I08", "group_id": "py-dabbd64af65acf1a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 625, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-32a37f63e64d-I09", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n    \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n    application.\n\n    :param app: The Flask application to configure the environment from.\n    :param path: URL path being requested.\n    :param base_url: Base URL where the app is being served, which\n        ``path`` is relative to. If not given, built from\n        :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n        :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n    :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n    :param url_scheme: Scheme to use instead of\n        :data:`PREFERRED_URL_SCHEME`.\n    :param json: If given, this is serialized as JSON and passed as\n        ``data``. Also defaults ``content_type`` to\n        ``application/json``.\n    :param args: other positional arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    :param kwargs: other keyword arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    \"\"\"\n\n    def __init__(\n        self,\n        app: Flask,\n        path: str = \"/\",\n        base_url: str | None = None,\n        subdomain: str | None = None,\n        url_scheme: str | None = None,\n        *args: t.Any,\n        **kwargs: t.Any,\n    ) -> None:\n        assert not (base_url or subdomain or url_scheme) or (\n            base_url is not None\n        ) != bool(subdomain or url_scheme), (\n            'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n        )\n\n        if base_url is None:\n            http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n            app_root = app.config[\"APPLICATION_ROOT\"]\n\n            if subdomain:\n                http_host = f\"{subdomain}.{http_host}\"\n\n            if url_scheme is None:\n                url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n            url = urlsplit(path)\n            base_url = (\n                f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"\n                f\"/{app_root.lstrip('/')}\"\n            )\n            path = url.path\n\n            if url.query:\n                path = f\"{path}?{url.query}\"\n\n        self.app = app\n        super().__init__(path, base_url, *args, **kwargs)\n\n    def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n        The serialization will be configured according to the config associated\n        with this EnvironBuilder's ``app``.\n        \"\"\"\n        lI0O_adb39900 = ((0xc0dc ^ 0xc0dc) != 0)\n        lI0O_adb39900 = not (not lI0O_adb39900)\n        return self.app.json.dumps(obj, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-dabbd64af65acf1a", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "6cc7f4376277e0ff8626fb956cc7f541886822df40fc12232f66ab625764ea71", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 86, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__EnvironBuilder__7f63e64d.py", "order": 9, "original_content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "parent_variant_id": "pyint-fb2c9bfec6c7-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L27-L94", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 4}, "unit_kind": "class", "unit_name": "EnvironBuilder", "variant_id": "pyint-32a37f63e64d-I09", "group_id": "py-dabbd64af65acf1a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 626, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-37930a586fe4-I10", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n    \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n    application.\n\n    :param app: The Flask application to configure the environment from.\n    :param path: URL path being requested.\n    :param base_url: Base URL where the app is being served, which\n        ``path`` is relative to. If not given, built from\n        :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n        :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n    :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n    :param url_scheme: Scheme to use instead of\n        :data:`PREFERRED_URL_SCHEME`.\n    :param json: If given, this is serialized as JSON and passed as\n        ``data``. Also defaults ``content_type`` to\n        ``application/json``.\n    :param args: other positional arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    :param kwargs: other keyword arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    \"\"\"\n    def __init__(\n        self,         app: Flask,\n        path: str = \"/\",\n        base_url: str | None = None,         subdomain: str | None = None,\n        url_scheme: str | None = None,         *args: t.Any,\n        **kwargs: t.Any,\n    ) -> None:\n        assert not (base_url or subdomain or url_scheme) or (\n            base_url is not None\n        ) != bool(subdomain or url_scheme), (             'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n        )\n\n        if base_url is None:\n            http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n            app_root = app.config[\"APPLICATION_ROOT\"]\n\n            if subdomain:\n                http_host = f\"{subdomain}.{http_host}\"\n            if url_scheme is None:\n                url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n            url = urlsplit(path)\n            base_url = (\n                f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"                 f\"/{app_root.lstrip('/')}\"             )\n            path = url.path\n\n            if url.query:\n                path = f\"{path}?{url.query}\"\n\n        self.app = app\n        super().__init__(path, base_url, *args, **kwargs)\n\n    def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize ``obj`` to a JSON-formatted string.\n        The serialization will be configured according to the config associated\n        with this EnvironBuilder's ``app``.\n        \"\"\"\n        return self.app.json.dumps(obj, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-dabbd64af65acf1a", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "5dd6deb574d31793f77d25cad70bcc34aee8f3173d5a30d8b116cd59029d684e", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 74, "local_path": "layout/partially-compact-layout/I10__flask__EnvironBuilder__0a586fe4.py", "order": 10, "original_content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "parent_variant_id": "pyint-fb2c9bfec6c7-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L27-L94", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 27, "line_break_groups_removed": 10, "line_breaks_removed": 10, "whitespace_characters_removed": 4}, "unit_kind": "class", "unit_name": "EnvironBuilder", "variant_id": "pyint-37930a586fe4-I10", "group_id": "py-dabbd64af65acf1a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 627, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ca8abc3ae606-I11", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n    \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n    application.\n\n    :param app: The Flask application to configure the environment from.\n    :param path: URL path being requested.\n    :param base_url: Base URL where the app is being served, which\n        ``path`` is relative to. If not given, built from\n        :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n        :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n    :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n    :param url_scheme: Scheme to use instead of\n        :data:`PREFERRED_URL_SCHEME`.\n    :param json: If given, this is serialized as JSON and passed as\n        ``data``. Also defaults ``content_type`` to\n        ``application/json``.\n    :param args: other positional arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    :param kwargs: other keyword arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    \"\"\"\n\n    def __init__(\n        self,\n        app: Flask,\n        path: str = \"/\",\n        base_url: str | None = None,\n        subdomain: str | None = None,\n        url_scheme: str | None = None,\n        *args: t.Any,\n        **kwargs: t.Any,\n    ) -> None:\n        assert not (base_url or subdomain or url_scheme) or (\n            base_url is not None\n        ) != bool(subdomain or url_scheme), (\n            'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n        )\n\n        if base_url is None:\n            http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n            app_root = app.config[\"APPLICATION_ROOT\"]\n\n            if subdomain:\n                http_host = f\"{subdomain}.{http_host}\"\n\n            if url_scheme is None:\n                url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n            url = urlsplit(path)\n            base_url = (\n                f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"\n                f\"/{app_root.lstrip('/')}\"\n            )\n            path = url.path\n\n            if url.query:\n                path = f\"{path}?{url.query}\"\n\n        self.app = app\n        super().__init__(path, base_url, *args, **kwargs)\n\n    def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n        The serialization will be configured according to the config associated\n        with this EnvironBuilder's ``app``.\n        \"\"\"\n        return self.app.json.dumps(obj, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-dabbd64af65acf1a", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 84, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__EnvironBuilder__bc3ae606.py", "order": 11, "original_content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "parent_variant_id": "pyint-fb2c9bfec6c7-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L27-L94", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "EnvironBuilder", "variant_id": "pyint-ca8abc3ae606-I11", "group_id": "py-dabbd64af65acf1a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 628, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8c9656e35b04-I12", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n    \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n    application.\n\n    :param app: The Flask application to configure the environment from.\n    :param path: URL path being requested.\n    :param base_url: Base URL where the app is being served, which\n        ``path`` is relative to. If not given, built from\n        :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n        :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n    :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n    :param url_scheme: Scheme to use instead of\n        :data:`PREFERRED_URL_SCHEME`.\n    :param json: If given, this is serialized as JSON and passed as\n        ``data``. Also defaults ``content_type`` to\n        ``application/json``.\n    :param args: other positional arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    :param kwargs: other keyword arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    \"\"\"\n\n    def __init__(\n        self,\n        app: Flask,\n        path: str = \"/\",\n        base_url: str | None = None,\n        subdomain: str | None = None,\n        url_scheme: str | None = None,\n        *args: t.Any,\n        **kwargs: t.Any,\n    ) -> None:\n        assert not (base_url or subdomain or url_scheme) or (\n            base_url is not None\n        ) != bool(subdomain or url_scheme), (\n            'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n        )\n\n        if base_url is None:\n            http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n            app_root = app.config[\"APPLICATION_ROOT\"]\n\n            if subdomain:\n                http_host = f\"{subdomain}.{http_host}\"\n\n            if url_scheme is None:\n                url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n            url = urlsplit(path)\n            base_url = (\n                f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"\n                f\"/{app_root.lstrip('/')}\"\n            )\n            path = url.path\n\n            if url.query:\n                path = f\"{path}?{url.query}\"\n\n        self.app = app\n        super().__init__(path, base_url, *args, **kwargs)\n\n    def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n        The serialization will be configured according to the config associated\n        with this EnvironBuilder's ``app``.\n        \"\"\"\n        return self.app.json.dumps(obj, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-dabbd64af65acf1a", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 84, "local_path": "data-flow/inline-intermediate-variables/I12__flask__EnvironBuilder__56e35b04.py", "order": 12, "original_content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "parent_variant_id": "pyint-fb2c9bfec6c7-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L27-L94", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "EnvironBuilder", "variant_id": "pyint-8c9656e35b04-I12", "group_id": "py-dabbd64af65acf1a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 629, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-74f2850b1320-I13", "source": "from __future__ import annotations\nimport importlib.metadata\nimport typing as t\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom copy import copy\nfrom types import TracebackType\nfrom urllib.parse import urlsplit\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom werkzeug.test import Client\nfrom werkzeug.wrappers import Request as BaseRequest\nfrom .cli import ScriptInfo\nfrom .sessions import SessionMixin\n\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n    \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n    application.\n\n    :param app: The Flask application to configure the environment from.\n    :param path: URL path being requested.\n    :param base_url: Base URL where the app is being served, which\n        ``path`` is relative to. If not given, built from\n        :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n        :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n    :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n    :param url_scheme: Scheme to use instead of\n        :data:`PREFERRED_URL_SCHEME`.\n    :param json: If given, this is serialized as JSON and passed as\n        ``data``. Also defaults ``content_type`` to\n        ``application/json``.\n    :param args: other positional arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    :param kwargs: other keyword arguments passed to\n        :class:`~werkzeug.test.EnvironBuilder`.\n    \"\"\"\n\n    def __init__(\n        self,\n        app: Flask,\n        path: str = \"/\",\n        base_url: str | None = None,\n        subdomain: str | None = None,\n        url_scheme: str | None = None,\n        *args: t.Any,\n        **kwargs: t.Any,\n    ) -> None:\n        assert not (base_url or subdomain or url_scheme) or (\n            base_url is not None\n        ) != bool(subdomain or url_scheme), (\n            'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n        )\n\n        if base_url is None:\n            http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n            app_root = app.config[\"APPLICATION_ROOT\"]\n\n            if subdomain:\n                http_host = f\"{subdomain}.{http_host}\"\n\n            if url_scheme is None:\n                url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n            url = urlsplit(path)\n            base_url = (\n                f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"\n                f\"/{app_root.lstrip('/')}\"\n            )\n            path = url.path\n\n            if url.query:\n                path = f\"{path}?{url.query}\"\n\n        self.app = app\n        super().__init__(path, base_url, *args, **kwargs)\n\n    def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n        The serialization will be configured according to the config associated\n        with this EnvironBuilder's ``app``.\n        \"\"\"\n        return self.app.json.dumps(obj, **kwargs)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-dabbd64af65acf1a", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 84, "local_path": "control-flow/lower-for-to-while/I13__flask__EnvironBuilder__850b1320.py", "order": 13, "original_content_sha256": "b2dc1263687261be22cb0c1eb290dabf20ae74d44c7e95b89ce6492ecbb9cdb5", "parent_variant_id": "pyint-fb2c9bfec6c7-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/testing.py#L27-L94", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "EnvironBuilder", "variant_id": "pyint-74f2850b1320-I13", "group_id": "py-dabbd64af65acf1a", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 630, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0cb8277fbea4-SRC", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n\n    hooks: dict[str, list[_t.HookType]]\n    method: str | None\n    url: _t.UriType | None\n    headers: Mapping[str, str | bytes]\n    files: _t.FilesType\n    data: _t.DataType\n    json: _t.JsonType\n    params: _t.ParamsType\n    auth: _t.AuthType\n    cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n\n    def __init__(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: _t.HeadersType = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        # Default empty dicts for dict params.\n        data = [] if data is None else data\n        files = [] if files is None else files\n        headers = {} if headers is None else headers\n        params = {} if params is None else params\n        hooks = {} if hooks is None else hooks\n\n        self.hooks = default_hooks()\n        for k, v in list(hooks.items()):\n            self.register_hook(event=k, hook=v)\n\n        self.method = method\n        self.url = url\n        self.headers = headers\n        self.files = files\n        self.data = data\n        self.json = json\n        self.params = params\n        self.auth = auth\n        self.cookies = cookies\n\n    def __repr__(self) -> str:\n        return f\"<Request [{self.method}]>\"\n\n    def prepare(self) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        p = PreparedRequest()\n        p.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return p\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-dfe4bd5d902bdb5c", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 162, "local_path": "source-original/SRC__requests__Request__277fbea4.py", "order": 0, "original_content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L284-L375", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Request", "variant_id": "pyint-0cb8277fbea4-SRC", "group_id": "py-dfe4bd5d902bdb5c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 897, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-35f82b21c5be-I01", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna   \nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Request(RequestHooksMixin):\n    \n\n    hooks: dict[str, list[_t.HookType]]\n    method: str | None\n    url: _t.UriType | None\n    headers: Mapping[str, str | bytes]\n    files: _t.FilesType\n    data: _t.DataType\n    json: _t.JsonType\n    params: _t.ParamsType\n    auth: _t.AuthType\n    cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n\n    def __init__(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: _t.HeadersType = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n         \n        data = [] if data is None else data\n        files = [] if files is None else files\n        headers = {} if headers is None else headers\n        params = {} if params is None else params\n        hooks = {} if hooks is None else hooks\n\n        self.hooks = default_hooks()\n        for k, v in list(hooks.items()):\n            self.register_hook(event=k, hook=v)\n\n        self.method = method\n        self.url = url\n        self.headers = headers\n        self.files = files\n        self.data = data\n        self.json = json\n        self.params = params\n        self.auth = auth\n        self.cookies = cookies\n\n    def __repr__(self) -> str:\n        return f\"<Request [{self.method}]>\"\n\n    def prepare(self) -> PreparedRequest:\n        \n        p = PreparedRequest()\n        p.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return p\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-dfe4bd5d902bdb5c", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "1625802f3754f8c4f18ac5c97f664db924101f798b51d158a3bc1ba2e227d0c8", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 137, "local_path": "comments/remove-comments/I01__requests__Request__2b21c5be.py", "order": 1, "original_content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "parent_variant_id": "pyint-0cb8277fbea4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L284-L375", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 1295, "comments_removed": 4, "docstrings_removed": 2, "line_comments_removed": 2}, "unit_kind": "class", "unit_name": "Request", "variant_id": "pyint-35f82b21c5be-I01", "group_id": "py-dfe4bd5d902bdb5c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 898, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ce08f1222318-I02", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n\n    hooks: dict[str, list[_t.HookType]]\n    method: str | None\n    url: _t.UriType | None\n    headers: Mapping[str, str | bytes]\n    files: _t.FilesType\n    data: _t.DataType\n    json: _t.JsonType\n    params: _t.ParamsType\n    auth: _t.AuthType\n    cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n\n    def __init__(\n        self,\n        met: str | None = None,\n        url2: _t.UriType | None = None,\n        hea: _t.HeadersType = None,\n        fil: _t.FilesType = None,\n        dat: _t.DataType = None,\n        par: _t.ParamsType = None,\n        aut: _t.AuthType = None,\n        coo: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hoo: _t.HooksInputType | None = None,\n        jso: _t.JsonType = None,\n    ) -> None:\n        # Default empty dicts for dict params.\n        dat = [] if dat is None else dat\n        fil = [] if fil is None else fil\n        hea = {} if hea is None else hea\n        par = {} if par is None else par\n        hoo = {} if hoo is None else hoo\n\n        self.hooks = default_hooks()\n        for k2, v2 in list(hoo.items()):\n            self.register_hook(event=k2, hook=v2)\n\n        self.method = met\n        self.url = url2\n        self.headers = hea\n        self.files = fil\n        self.data = dat\n        self.json = jso\n        self.params = par\n        self.auth = aut\n        self.cookies = coo\n\n    def __repr__(self) -> str:\n        return f\"<Request [{self.method}]>\"\n\n    def pre(self) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        p2 = PreparedRequest()\n        p2.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return p2\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-dfe4bd5d902bdb5c", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "2b0c0474534ae6aa837c0138fc99fb7650c7664eb755eb1d500d9bd815d61bf3", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 162, "local_path": "identifiers/shorten-identifiers/I02__requests__Request__f1222318.py", "order": 2, "original_content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "parent_variant_id": "pyint-0cb8277fbea4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L284-L375", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 43, "identifiers_declared": 14}, "unit_kind": "class", "unit_name": "Request", "variant_id": "pyint-ce08f1222318-I02", "group_id": "py-dfe4bd5d902bdb5c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 899, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8acec2e3ba21-I03", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n\n    hooks: dict[str, list[_t.HookType]]\n    method: str | None\n    url: _t.UriType | None\n    headers: Mapping[str, str | bytes]\n    files: _t.FilesType\n    data: _t.DataType\n    json: _t.JsonType\n    params: _t.ParamsType\n    auth: _t.AuthType\n    cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n\n    def __init__(\n        self,\n        config: str | None = None,\n        key: _t.UriType | None = None,\n        feature: _t.HeadersType = None,\n        total: _t.FilesType = None,\n        path: _t.DataType = None,\n        offset: _t.ParamsType = None,\n        date: _t.AuthType = None,\n        context: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        count: _t.HooksInputType | None = None,\n        step: _t.JsonType = None,\n    ) -> None:\n        # Default empty dicts for dict params.\n        path = [] if path is None else path\n        total = [] if total is None else total\n        feature = {} if feature is None else feature\n        offset = {} if offset is None else offset\n        count = {} if count is None else count\n\n        self.hooks = default_hooks()\n        for age, map in list(count.items()):\n            self.register_hook(event=age, hook=map)\n\n        self.method = config\n        self.url = key\n        self.headers = feature\n        self.files = total\n        self.data = path\n        self.json = step\n        self.params = offset\n        self.auth = date\n        self.cookies = context\n\n    def __repr__(self) -> str:\n        return f\"<Request [{self.method}]>\"\n\n    def extract(self) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        key = PreparedRequest()\n        key.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return key\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-dfe4bd5d902bdb5c", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "973476caee6a4f988da7835b66ae7901ccff547ff5212d8626d382c41f7a74e5", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 162, "local_path": "identifiers/mislead-identifiers/I03__requests__Request__c2e3ba21.py", "order": 3, "original_content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "parent_variant_id": "pyint-0cb8277fbea4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L284-L375", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 43, "identifiers_declared": 14, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 3, "local_exact_length_matches": 10, "local_random_pool_selections": 13, "local_total_length_difference": 6, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "Request", "variant_id": "pyint-8acec2e3ba21-I03", "group_id": "py-dfe4bd5d902bdb5c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 900, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7593502a3634-I04", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n\n    hooks: dict[str, list[_t.HookType]]\n    method: str | None\n    url: _t.UriType | None\n    headers: Mapping[str, str | bytes]\n    files: _t.FilesType\n    data: _t.DataType\n    json: _t.JsonType\n    params: _t.ParamsType\n    auth: _t.AuthType\n    cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n\n    def __init__(\n        self,\n        b: str | None = None,\n        c: _t.UriType | None = None,\n        d: _t.HeadersType = None,\n        e: _t.FilesType = None,\n        f: _t.DataType = None,\n        g: _t.ParamsType = None,\n        h: _t.AuthType = None,\n        i: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        j: _t.HooksInputType | None = None,\n        l: _t.JsonType = None,\n    ) -> None:\n        # Default empty dicts for dict params.\n        f = [] if f is None else f\n        e = [] if e is None else e\n        d = {} if d is None else d\n        g = {} if g is None else g\n        j = {} if j is None else j\n\n        self.hooks = default_hooks()\n        for m, n in list(j.items()):\n            self.register_hook(event=m, hook=n)\n\n        self.method = b\n        self.url = c\n        self.headers = d\n        self.files = e\n        self.data = f\n        self.json = l\n        self.params = g\n        self.auth = h\n        self.cookies = i\n\n    def __repr__(self) -> str:\n        return f\"<Request [{self.method}]>\"\n\n    def a(self) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        o = PreparedRequest()\n        o.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return o\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-dfe4bd5d902bdb5c", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "c74ca6052bae997cc62c93501357df1d983914264d3e4152cea075498ebe2f94", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 162, "local_path": "identifiers/garble-identifiers/I04__requests__Request__502a3634.py", "order": 4, "original_content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "parent_variant_id": "pyint-0cb8277fbea4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L284-L375", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 43, "identifiers_declared": 14}, "unit_kind": "class", "unit_name": "Request", "variant_id": "pyint-7593502a3634-I04", "group_id": "py-dfe4bd5d902bdb5c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 901, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8ee6c0f8d6d6-I05", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n\n    hooks: dict[str, list[_t.HookType]]\n    method: str | None\n    url: _t.UriType | None\n    headers: Mapping[str, str | bytes]\n    files: _t.FilesType\n    data: _t.DataType\n    json: _t.JsonType\n    params: _t.ParamsType\n    auth: _t.AuthType\n    cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n\n    def __init__(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: _t.HeadersType = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        # Default empty dicts for dict params.\n        data = [] if data is None else data\n        files = [] if files is None else files\n        headers = {} if headers is None else headers\n        params = {} if params is None else params\n        hooks = {} if hooks is None else hooks\n\n        self.hooks = default_hooks()\n        for k, v in list(hooks.items()):\n            self.register_hook(event=k, hook=v)\n\n        self.method = method\n        self.url = url\n        self.headers = headers\n        self.files = files\n        self.data = data\n        self.json = json\n        self.params = params\n        self.auth = auth\n        self.cookies = cookies\n\n    def __repr__(self) -> str:\n        return f\"<Request [{self.method}]>\"\n\n    def prepare(self) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        p = PreparedRequest()\n        p.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return p\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-dfe4bd5d902bdb5c", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 162, "local_path": "expressions/encode-integer-literals/I05__requests__Request__c0f8d6d6.py", "order": 5, "original_content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "parent_variant_id": "pyint-0cb8277fbea4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L284-L375", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "Request", "variant_id": "pyint-8ee6c0f8d6d6-I05", "group_id": "py-dfe4bd5d902bdb5c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 902, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0cdee83adc3d-I06", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n\n    hooks: dict[str, list[_t.HookType]]\n    method: str | None\n    url: _t.UriType | None\n    headers: Mapping[str, str | bytes]\n    files: _t.FilesType\n    data: _t.DataType\n    json: _t.JsonType\n    params: _t.ParamsType\n    auth: _t.AuthType\n    cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n\n    def __init__(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: _t.HeadersType = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        # Default empty dicts for dict params.\n        data = [] if data is None else data\n        files = [] if files is None else files\n        headers = {} if headers is None else headers\n        params = {} if params is None else params\n        hooks = {} if hooks is None else hooks\n\n        self.hooks = default_hooks()\n        for k, v in list(hooks.items()):\n            self.register_hook(event=k, hook=v)\n\n        self.method = method\n        self.url = url\n        self.headers = headers\n        self.files = files\n        self.data = data\n        self.json = json\n        self.params = params\n        self.auth = auth\n        self.cookies = cookies\n\n    def __repr__(self) -> str:\n        return f\"<Request [{self.method}]>\"\n\n    def prepare(self) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        p = PreparedRequest()\n        p.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return p\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-dfe4bd5d902bdb5c", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 162, "local_path": "expressions/invert-conditions/I06__requests__Request__e83adc3d.py", "order": 6, "original_content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "parent_variant_id": "pyint-0cb8277fbea4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L284-L375", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "Request", "variant_id": "pyint-0cdee83adc3d-I06", "group_id": "py-dfe4bd5d902bdb5c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 903, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6f1b37811ad5-I07", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n\n    hooks: dict[str, list[_t.HookType]]\n    method: str | None\n    url: _t.UriType | None\n    headers: Mapping[str, str | bytes]\n    files: _t.FilesType\n    data: _t.DataType\n    json: _t.JsonType\n    params: _t.ParamsType\n    auth: _t.AuthType\n    cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n\n    def __init__(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: _t.HeadersType = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        # Default empty dicts for dict params.\n        if ((0xa5dd ^ 0xa5dd) != 0):\n            raise AssertionError()\n        data = [] if data is None else data\n        files = [] if files is None else files\n        headers = {} if headers is None else headers\n        params = {} if params is None else params\n        hooks = {} if hooks is None else hooks\n\n        self.hooks = default_hooks()\n        for k, v in list(hooks.items()):\n            self.register_hook(event=k, hook=v)\n\n        self.method = method\n        self.url = url\n        self.headers = headers\n        self.files = files\n        self.data = data\n        self.json = json\n        self.params = params\n        self.auth = auth\n        self.cookies = cookies\n\n    def __repr__(self) -> str:\n        if ((0xbc5a ^ 0xbc5a) != 0):\n            raise AssertionError()\n        return f\"<Request [{self.method}]>\"\n\n    def prepare(self) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        if ((0x9066 ^ 0x9066) != 0):\n            raise AssertionError()\n        p = PreparedRequest()\n        p.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return p\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-dfe4bd5d902bdb5c", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "dfff0103c97310bffca5ccdb5f895b74da1d221fae10b5329ebbd36f87deb9bb", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 168, "local_path": "code-injection/insert-dead-branches/I07__requests__Request__37811ad5.py", "order": 7, "original_content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "parent_variant_id": "pyint-0cb8277fbea4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L284-L375", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 3}, "unit_kind": "class", "unit_name": "Request", "variant_id": "pyint-6f1b37811ad5-I07", "group_id": "py-dfe4bd5d902bdb5c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 904, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f26f9dd9cd5c-I08", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n\n    hooks: dict[str, list[_t.HookType]]\n    method: str | None\n    url: _t.UriType | None\n    headers: Mapping[str, str | bytes]\n    files: _t.FilesType\n    data: _t.DataType\n    json: _t.JsonType\n    params: _t.ParamsType\n    auth: _t.AuthType\n    cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n\n    def __init__(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: _t.HeadersType = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        # Default empty dicts for dict params.\n        data = [] if data is None else data\n        files = [] if files is None else files\n        headers = {} if headers is None else headers\n        params = {} if params is None else params\n        hooks = {} if hooks is None else hooks\n\n        self.hooks = default_hooks()\n        for k, v in list(hooks.items()):\n            self.register_hook(event=k, hook=v)\n\n        self.method = method\n        self.url = url\n        self.headers = headers\n        self.files = files\n        self.data = data\n        self.json = json\n        self.params = params\n        self.auth = auth\n        self.cookies = cookies\n\n    def __repr__(self) -> str:\n        return f\"<Request [{self.method}]>\"\n\n    def prepare(self) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        even_number_count = 0\n        for candidate_number in range(6):\n            if candidate_number % 2 == 0:\n                even_number_count += 1\n        p = PreparedRequest()\n        p.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return p\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-dfe4bd5d902bdb5c", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "b18e23478b3b8b5d2cb401371710a3442f0fb3f372025d915a3ee3f74b3fe4d9", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 166, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__Request__9dd9cd5c.py", "order": 8, "original_content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "parent_variant_id": "pyint-0cb8277fbea4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L284-L375", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 4, "readable_template_index": 2}, "unit_kind": "class", "unit_name": "Request", "variant_id": "pyint-f26f9dd9cd5c-I08", "group_id": "py-dfe4bd5d902bdb5c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 905, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a204bdcfa83a-I09", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n\n    hooks: dict[str, list[_t.HookType]]\n    method: str | None\n    url: _t.UriType | None\n    headers: Mapping[str, str | bytes]\n    files: _t.FilesType\n    data: _t.DataType\n    json: _t.JsonType\n    params: _t.ParamsType\n    auth: _t.AuthType\n    cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n\n    def __init__(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: _t.HeadersType = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        # Default empty dicts for dict params.\n        data = [] if data is None else data\n        files = [] if files is None else files\n        headers = {} if headers is None else headers\n        params = {} if params is None else params\n        hooks = {} if hooks is None else hooks\n\n        self.hooks = default_hooks()\n        for k, v in list(hooks.items()):\n            self.register_hook(event=k, hook=v)\n\n        self.method = method\n        self.url = url\n        self.headers = headers\n        self.files = files\n        self.data = data\n        self.json = json\n        self.params = params\n        self.auth = auth\n        self.cookies = cookies\n\n    def __repr__(self) -> str:\n        lI0O_b7667c3b, lI0O_e279fbef = 0, 0\n        while lI0O_e279fbef < 2:\n            lI0O_b7667c3b ^= (lI0O_e279fbef << 1) ^ 0xe\n            lI0O_e279fbef += 1\n        lI0O_b7667c3b ^= lI0O_b7667c3b\n        return f\"<Request [{self.method}]>\"\n\n    def prepare(self) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        p = PreparedRequest()\n        p.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return p\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-dfe4bd5d902bdb5c", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "59e5bc1e6791429229eca213ae7a7e5b46f2e5cea16c768c7fab016bb787e5bb", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 167, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__Request__bdcfa83a.py", "order": 9, "original_content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "parent_variant_id": "pyint-0cb8277fbea4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L284-L375", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 2}, "unit_kind": "class", "unit_name": "Request", "variant_id": "pyint-a204bdcfa83a-I09", "group_id": "py-dfe4bd5d902bdb5c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 906, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a88552bc9b98-I10", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (     TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,     cast,\n    overload, )\nfrom urllib3.exceptions import (     DecodeError,\n    LocationParseError,     ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (     JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,     cookielib,     urlencode,\n    urlsplit,\n    urlunparse, )\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,     ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,     iter_slices,\n    parse_header_links,     requote_uri,     stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n    hooks: dict[str, list[_t.HookType]]\n    method: str | None\n    url: _t.UriType | None\n    headers: Mapping[str, str | bytes]\n    files: _t.FilesType\n    data: _t.DataType\n    json: _t.JsonType\n    params: _t.ParamsType\n    auth: _t.AuthType\n    cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n    def __init__(         self,         method: str | None = None,         url: _t.UriType | None = None,         headers: _t.HeadersType = None,\n        files: _t.FilesType = None,         data: _t.DataType = None,\n        params: _t.ParamsType = None,         auth: _t.AuthType = None,         cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,         json: _t.JsonType = None,     ) -> None:\n        # Default empty dicts for dict params.\n        data = [] if data is None else data\n        files = [] if files is None else files\n        headers = {} if headers is None else headers\n        params = {} if params is None else params\n        hooks = {} if hooks is None else hooks\n        self.hooks = default_hooks()\n        for k, v in list(hooks.items()):\n            self.register_hook(event=k, hook=v)\n\n        self.method = method\n        self.url = url\n        self.headers = headers\n        self.files = files\n        self.data = data\n        self.json = json\n        self.params = params\n        self.auth = auth\n        self.cookies = cookies\n\n    def __repr__(self) -> str:\n        return f\"<Request [{self.method}]>\"\n\n    def prepare(self) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        p = PreparedRequest()\n        p.prepare(\n            method=self.method,             url=self.url,\n            headers=self.headers,\n            files=self.files,             data=self.data,             json=self.json,\n            params=self.params,             auth=self.auth,\n            cookies=self.cookies,             hooks=self.hooks,\n        )\n        return p\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-dfe4bd5d902bdb5c", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "ac668c5e5afe5ac96c5f3f2e723366ca1d5431cf605a3e47ed5cfe895fc62b48", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 130, "local_path": "layout/partially-compact-layout/I10__requests__Request__52bc9b98.py", "order": 10, "original_content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "parent_variant_id": "pyint-0cb8277fbea4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L284-L375", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 80, "line_break_groups_removed": 32, "line_breaks_removed": 32, "whitespace_characters_removed": 5}, "unit_kind": "class", "unit_name": "Request", "variant_id": "pyint-a88552bc9b98-I10", "group_id": "py-dfe4bd5d902bdb5c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 907, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-41f8aef52e72-I11", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n\n    hooks: dict[str, list[_t.HookType]]\n    method: str | None\n    url: _t.UriType | None\n    headers: Mapping[str, str | bytes]\n    files: _t.FilesType\n    data: _t.DataType\n    json: _t.JsonType\n    params: _t.ParamsType\n    auth: _t.AuthType\n    cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n\n    def __init__(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: _t.HeadersType = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        # Default empty dicts for dict params.\n        data = [] if data is None else data\n        files = [] if files is None else files\n        headers = {} if headers is None else headers\n        params = {} if params is None else params\n        hooks = {} if hooks is None else hooks\n\n        self.hooks = default_hooks()\n        for k, v in list(hooks.items()):\n            self.register_hook(event=k, hook=v)\n\n        self.method = method\n        self.url = url\n        self.headers = headers\n        self.files = files\n        self.data = data\n        self.json = json\n        self.params = params\n        self.auth = auth\n        self.cookies = cookies\n\n    def __repr__(self) -> str:\n        return f\"<Request [{self.method}]>\"\n\n    def prepare(self) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        p = PreparedRequest()\n        p.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return p\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-dfe4bd5d902bdb5c", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 162, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__Request__aef52e72.py", "order": 11, "original_content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "parent_variant_id": "pyint-0cb8277fbea4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L284-L375", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "Request", "variant_id": "pyint-41f8aef52e72-I11", "group_id": "py-dfe4bd5d902bdb5c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 908, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1d1f60d9c3d2-I12", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n\n    hooks: dict[str, list[_t.HookType]]\n    method: str | None\n    url: _t.UriType | None\n    headers: Mapping[str, str | bytes]\n    files: _t.FilesType\n    data: _t.DataType\n    json: _t.JsonType\n    params: _t.ParamsType\n    auth: _t.AuthType\n    cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n\n    def __init__(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: _t.HeadersType = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        # Default empty dicts for dict params.\n        data = [] if data is None else data\n        files = [] if files is None else files\n        headers = {} if headers is None else headers\n        params = {} if params is None else params\n        hooks = {} if hooks is None else hooks\n\n        self.hooks = default_hooks()\n        for k, v in list(hooks.items()):\n            self.register_hook(event=k, hook=v)\n\n        self.method = method\n        self.url = url\n        self.headers = headers\n        self.files = files\n        self.data = data\n        self.json = json\n        self.params = params\n        self.auth = auth\n        self.cookies = cookies\n\n    def __repr__(self) -> str:\n        return f\"<Request [{self.method}]>\"\n\n    def prepare(self) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        p = PreparedRequest()\n        p.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return p\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-dfe4bd5d902bdb5c", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 162, "local_path": "data-flow/inline-intermediate-variables/I12__requests__Request__60d9c3d2.py", "order": 12, "original_content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "parent_variant_id": "pyint-0cb8277fbea4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L284-L375", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Request", "variant_id": "pyint-1d1f60d9c3d2-I12", "group_id": "py-dfe4bd5d902bdb5c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 909, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-39b834647959-I13", "source": "from __future__ import annotations\nimport datetime\nimport encodings.idna  # noqa: F401\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping\nfrom io import UnsupportedOperation\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Literal,\n    cast,\n    overload,\n)\nfrom urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom urllib3.fields import RequestField\nfrom urllib3.filepost import encode_multipart_formdata\nfrom urllib3.util import parse_url\nfrom . import _types as _t\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    JSONDecodeError,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n    urlencode,\n    urlsplit,\n    urlunparse,\n)\nfrom .compat import json as complexjson\nfrom .cookies import (\n    _copy_cookie_jar,\n    cookiejar_from_dict,\n    get_cookie_header,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n    MissingSchema,\n    StreamConsumedError,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n\n    hooks: dict[str, list[_t.HookType]]\n    method: str | None\n    url: _t.UriType | None\n    headers: Mapping[str, str | bytes]\n    files: _t.FilesType\n    data: _t.DataType\n    json: _t.JsonType\n    params: _t.ParamsType\n    auth: _t.AuthType\n    cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n\n    def __init__(\n        self,\n        method: str | None = None,\n        url: _t.UriType | None = None,\n        headers: _t.HeadersType = None,\n        files: _t.FilesType = None,\n        data: _t.DataType = None,\n        params: _t.ParamsType = None,\n        auth: _t.AuthType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        json: _t.JsonType = None,\n    ) -> None:\n        # Default empty dicts for dict params.\n        data = [] if data is None else data\n        files = [] if files is None else files\n        headers = {} if headers is None else headers\n        params = {} if params is None else params\n        hooks = {} if hooks is None else hooks\n\n        self.hooks = default_hooks()\n        loopIterator = __import__(\"builtins\").iter(list(hooks.items()))\n        while True:\n            try:\n                k, v = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            self.register_hook(event=k, hook=v)\n\n        self.method = method\n        self.url = url\n        self.headers = headers\n        self.files = files\n        self.data = data\n        self.json = json\n        self.params = params\n        self.auth = auth\n        self.cookies = cookies\n\n    def __repr__(self) -> str:\n        return f\"<Request [{self.method}]>\"\n\n    def prepare(self) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        p = PreparedRequest()\n        p.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return p\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-dfe4bd5d902bdb5c", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "6f8c42a2cfb62fb9d632b568428ce747519b07172092b3bcded1e5f2de8acdfd", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 167, "local_path": "control-flow/lower-for-to-while/I13__requests__Request__34647959.py", "order": 13, "original_content_sha256": "6205bf1d24b099949c58b758d5219094daa17f4644ca4ade4bf723ae57b2221f", "parent_variant_id": "pyint-0cb8277fbea4-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/models.py#L284-L375", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 1, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 1, "synchronous_for_loops_eligible": 1, "synchronous_for_loops_found": 1}, "unit_kind": "class", "unit_name": "Request", "variant_id": "pyint-39b834647959-I13", "group_id": "py-dfe4bd5d902bdb5c", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 910, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fb63a9d58800-SRC", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass RegexValidator:\n    regex = \"\"\n    message = _(\"Enter a valid value.\")\n    code = \"invalid\"\n    inverse_match = False\n    flags = 0\n\n    def __init__(\n        self, regex=None, message=None, code=None, inverse_match=None, flags=None\n    ):\n        if regex is not None:\n            self.regex = regex\n        if message is not None:\n            self.message = message\n        if code is not None:\n            self.code = code\n        if inverse_match is not None:\n            self.inverse_match = inverse_match\n        if flags is not None:\n            self.flags = flags\n        if self.flags and not isinstance(self.regex, str):\n            raise TypeError(\n                \"If the flags are set, regex must be a regular expression string.\"\n            )\n\n        self.regex = _lazy_re_compile(self.regex, self.flags)\n\n    def __call__(self, value):\n        \"\"\"\n        Validate that the input contains (or does *not* contain, if\n        inverse_match is True) a match for the regular expression.\n        \"\"\"\n        regex_matches = self.regex.search(str(value))\n        invalid_input = regex_matches if self.inverse_match else not regex_matches\n        if invalid_input:\n            raise ValidationError(self.message, code=self.code, params={\"value\": value})\n\n    def __eq__(self, other):\n        return (\n            isinstance(other, RegexValidator)\n            and self.regex.pattern == other.regex.pattern\n            and self.regex.flags == other.regex.flags\n            and (self.message == other.message)\n            and (self.code == other.code)\n            and (self.inverse_match == other.inverse_match)\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-e3828e8dafcefdab", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 60, "local_path": "source-original/SRC__django__RegexValidator__a9d58800.py", "order": 0, "original_content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L20-L65", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "RegexValidator", "variant_id": "pyint-fb63a9d58800-SRC", "group_id": "py-e3828e8dafcefdab", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 169, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d35884649787-I01", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass RegexValidator:\n    regex = \"\"\n    message = _(\"Enter a valid value.\")\n    code = \"invalid\"\n    inverse_match = False\n    flags = 0\n\n    def __init__(\n        self, regex=None, message=None, code=None, inverse_match=None, flags=None\n    ):\n        if regex is not None:\n            self.regex = regex\n        if message is not None:\n            self.message = message\n        if code is not None:\n            self.code = code\n        if inverse_match is not None:\n            self.inverse_match = inverse_match\n        if flags is not None:\n            self.flags = flags\n        if self.flags and not isinstance(self.regex, str):\n            raise TypeError(\n                \"If the flags are set, regex must be a regular expression string.\"\n            )\n\n        self.regex = _lazy_re_compile(self.regex, self.flags)\n\n    def __call__(self, value):\n        \n        regex_matches = self.regex.search(str(value))\n        invalid_input = regex_matches if self.inverse_match else not regex_matches\n        if invalid_input:\n            raise ValidationError(self.message, code=self.code, params={\"value\": value})\n\n    def __eq__(self, other):\n        return (\n            isinstance(other, RegexValidator)\n            and self.regex.pattern == other.regex.pattern\n            and self.regex.flags == other.regex.flags\n            and (self.message == other.message)\n            and (self.code == other.code)\n            and (self.inverse_match == other.inverse_match)\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-e3828e8dafcefdab", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "f7e19f868a4b5d87913397403ffb0990fd627ce3ff7dd193a8ba421df1523c69", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 57, "local_path": "comments/remove-comments/I01__django__RegexValidator__84649787.py", "order": 1, "original_content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "parent_variant_id": "pyint-fb63a9d58800-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L20-L65", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 150, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "RegexValidator", "variant_id": "pyint-d35884649787-I01", "group_id": "py-e3828e8dafcefdab", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 170, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5ac04f18e448-I02", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass RegexValidator:\n    regex = \"\"\n    message = _(\"Enter a valid value.\")\n    code = \"invalid\"\n    inverse_match = False\n    flags = 0\n\n    def __init__(\n        self, reg=None, mes=None, cod=None, inverse=None, fla=None\n    ):\n        if reg is not None:\n            self.regex = reg\n        if mes is not None:\n            self.message = mes\n        if cod is not None:\n            self.code = cod\n        if inverse is not None:\n            self.inverse_match = inverse\n        if fla is not None:\n            self.flags = fla\n        if self.flags and not isinstance(self.regex, str):\n            raise TypeError(\n                \"If the flags are set, regex must be a regular expression string.\"\n            )\n\n        self.regex = _lazy_re_compile(self.regex, self.flags)\n\n    def __call__(self, val):\n        \"\"\"\n        Validate that the input contains (or does *not* contain, if\n        inverse_match is True) a match for the regular expression.\n        \"\"\"\n        regex2 = self.regex.search(str(val))\n        invalid = regex2 if self.inverse_match else not regex2\n        if invalid:\n            raise ValidationError(self.message, code=self.code, params={\"value\": val})\n\n    def __eq__(self, oth):\n        return (\n            isinstance(oth, RegexValidator)\n            and self.regex.pattern == oth.regex.pattern\n            and self.regex.flags == oth.regex.flags\n            and (self.message == oth.message)\n            and (self.code == oth.code)\n            and (self.inverse_match == oth.inverse_match)\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-e3828e8dafcefdab", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "1f0ba722198726c26913c144a929e885d02a39554e13d90dbb71e292ecc7df35", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 60, "local_path": "identifiers/shorten-identifiers/I02__django__RegexValidator__4f18e448.py", "order": 2, "original_content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "parent_variant_id": "pyint-fb63a9d58800-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L20-L65", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 30, "identifiers_declared": 9}, "unit_kind": "class", "unit_name": "RegexValidator", "variant_id": "pyint-5ac04f18e448-I02", "group_id": "py-e3828e8dafcefdab", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 171, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fec57ee3efda-I03", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass RegexValidator:\n    regex = \"\"\n    message = _(\"Enter a valid value.\")\n    code = \"invalid\"\n    inverse_match = False\n    flags = 0\n\n    def __init__(\n        self, token=None, context=None, user=None, secureAccount=None, event=None\n    ):\n        if token is not None:\n            self.regex = token\n        if context is not None:\n            self.message = context\n        if user is not None:\n            self.code = user\n        if secureAccount is not None:\n            self.inverse_match = secureAccount\n        if event is not None:\n            self.flags = event\n        if self.flags and not isinstance(self.regex, str):\n            raise TypeError(\n                \"If the flags are set, regex must be a regular expression string.\"\n            )\n\n        self.regex = _lazy_re_compile(self.regex, self.flags)\n\n    def __call__(self, count):\n        \"\"\"\n        Validate that the input contains (or does *not* contain, if\n        inverse_match is True) a match for the regular expression.\n        \"\"\"\n        defaultRecord = self.regex.search(str(count))\n        currentRecord = defaultRecord if self.inverse_match else not defaultRecord\n        if currentRecord:\n            raise ValidationError(self.message, code=self.code, params={\"value\": count})\n\n    def __eq__(self, batch):\n        return (\n            isinstance(batch, RegexValidator)\n            and self.regex.pattern == batch.regex.pattern\n            and self.regex.flags == batch.regex.flags\n            and (self.message == batch.message)\n            and (self.code == batch.code)\n            and (self.inverse_match == batch.inverse_match)\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-e3828e8dafcefdab", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "5164e9a45c4042ed6f3819322758c39934019fba496dace6cacad537c4d8a0bb", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 60, "local_path": "identifiers/mislead-identifiers/I03__django__RegexValidator__7ee3efda.py", "order": 3, "original_content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "parent_variant_id": "pyint-fb63a9d58800-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L20-L65", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 30, "identifiers_declared": 9, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 9, "local_random_pool_selections": 9, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "RegexValidator", "variant_id": "pyint-fec57ee3efda-I03", "group_id": "py-e3828e8dafcefdab", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 172, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9fd667c9d00e-I04", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass RegexValidator:\n    regex = \"\"\n    message = _(\"Enter a valid value.\")\n    code = \"invalid\"\n    inverse_match = False\n    flags = 0\n\n    def __init__(\n        self, a=None, b=None, c=None, d=None, e=None\n    ):\n        if a is not None:\n            self.regex = a\n        if b is not None:\n            self.message = b\n        if c is not None:\n            self.code = c\n        if d is not None:\n            self.inverse_match = d\n        if e is not None:\n            self.flags = e\n        if self.flags and not isinstance(self.regex, str):\n            raise TypeError(\n                \"If the flags are set, regex must be a regular expression string.\"\n            )\n\n        self.regex = _lazy_re_compile(self.regex, self.flags)\n\n    def __call__(self, f):\n        \"\"\"\n        Validate that the input contains (or does *not* contain, if\n        inverse_match is True) a match for the regular expression.\n        \"\"\"\n        g = self.regex.search(str(f))\n        h = g if self.inverse_match else not g\n        if h:\n            raise ValidationError(self.message, code=self.code, params={\"value\": f})\n\n    def __eq__(self, i):\n        return (\n            isinstance(i, RegexValidator)\n            and self.regex.pattern == i.regex.pattern\n            and self.regex.flags == i.regex.flags\n            and (self.message == i.message)\n            and (self.code == i.code)\n            and (self.inverse_match == i.inverse_match)\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-e3828e8dafcefdab", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "c64e521e0bb9ea5aaf380addd7375237fbe14ca25e5b7842edaf4b0877fc5ad5", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 60, "local_path": "identifiers/garble-identifiers/I04__django__RegexValidator__67c9d00e.py", "order": 4, "original_content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "parent_variant_id": "pyint-fb63a9d58800-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L20-L65", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 30, "identifiers_declared": 9}, "unit_kind": "class", "unit_name": "RegexValidator", "variant_id": "pyint-9fd667c9d00e-I04", "group_id": "py-e3828e8dafcefdab", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 173, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e069b99e2e1c-I05", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass RegexValidator:\n    regex = \"\"\n    message = _(\"Enter a valid value.\")\n    code = \"invalid\"\n    inverse_match = False\n    flags = 0x0\n\n    def __init__(\n        self, regex=None, message=None, code=None, inverse_match=None, flags=None\n    ):\n        if regex is not None:\n            self.regex = regex\n        if message is not None:\n            self.message = message\n        if code is not None:\n            self.code = code\n        if inverse_match is not None:\n            self.inverse_match = inverse_match\n        if flags is not None:\n            self.flags = flags\n        if self.flags and not isinstance(self.regex, str):\n            raise TypeError(\n                \"If the flags are set, regex must be a regular expression string.\"\n            )\n\n        self.regex = _lazy_re_compile(self.regex, self.flags)\n\n    def __call__(self, value):\n        \"\"\"\n        Validate that the input contains (or does *not* contain, if\n        inverse_match is True) a match for the regular expression.\n        \"\"\"\n        regex_matches = self.regex.search(str(value))\n        invalid_input = regex_matches if self.inverse_match else not regex_matches\n        if invalid_input:\n            raise ValidationError(self.message, code=self.code, params={\"value\": value})\n\n    def __eq__(self, other):\n        return (\n            isinstance(other, RegexValidator)\n            and self.regex.pattern == other.regex.pattern\n            and self.regex.flags == other.regex.flags\n            and (self.message == other.message)\n            and (self.code == other.code)\n            and (self.inverse_match == other.inverse_match)\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-e3828e8dafcefdab", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "7960bbbcee6edb32f0dfafc3f745b84521736ca204a93889dacfa60ba3e505a8", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 60, "local_path": "expressions/encode-integer-literals/I05__django__RegexValidator__b99e2e1c.py", "order": 5, "original_content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "parent_variant_id": "pyint-fb63a9d58800-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L20-L65", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 1}, "unit_kind": "class", "unit_name": "RegexValidator", "variant_id": "pyint-e069b99e2e1c-I05", "group_id": "py-e3828e8dafcefdab", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 174, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f154b3510ed2-I06", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass RegexValidator:\n    regex = \"\"\n    message = _(\"Enter a valid value.\")\n    code = \"invalid\"\n    inverse_match = False\n    flags = 0\n\n    def __init__(\n        self, regex=None, message=None, code=None, inverse_match=None, flags=None\n    ):\n        if not (regex is not None):\n            pass\n        else:\n            self.regex = regex\n        if not (message is not None):\n            pass\n        else:\n            self.message = message\n        if not (code is not None):\n            pass\n        else:\n            self.code = code\n        if not (inverse_match is not None):\n            pass\n        else:\n            self.inverse_match = inverse_match\n        if not (flags is not None):\n            pass\n        else:\n            self.flags = flags\n        if not (self.flags and not isinstance(self.regex, str)):\n            pass\n        else:\n            raise TypeError(\n                \"If the flags are set, regex must be a regular expression string.\"\n            )\n\n        self.regex = _lazy_re_compile(self.regex, self.flags)\n\n    def __call__(self, value):\n        \"\"\"\n        Validate that the input contains (or does *not* contain, if\n        inverse_match is True) a match for the regular expression.\n        \"\"\"\n        regex_matches = self.regex.search(str(value))\n        invalid_input = regex_matches if self.inverse_match else not regex_matches\n        if not (invalid_input):\n            pass\n        else:\n            raise ValidationError(self.message, code=self.code, params={\"value\": value})\n\n    def __eq__(self, other):\n        return (\n            isinstance(other, RegexValidator)\n            and self.regex.pattern == other.regex.pattern\n            and self.regex.flags == other.regex.flags\n            and (self.message == other.message)\n            and (self.code == other.code)\n            and (self.inverse_match == other.inverse_match)\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-e3828e8dafcefdab", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "22fdb16f76d62a339d3be62239a8af1b1f20ae1833f33cd002ff39daac0e04de", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 74, "local_path": "expressions/invert-conditions/I06__django__RegexValidator__b3510ed2.py", "order": 6, "original_content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "parent_variant_id": "pyint-fb63a9d58800-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L20-L65", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 7}, "unit_kind": "class", "unit_name": "RegexValidator", "variant_id": "pyint-f154b3510ed2-I06", "group_id": "py-e3828e8dafcefdab", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 175, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-925fd166f427-I07", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass RegexValidator:\n    regex = \"\"\n    message = _(\"Enter a valid value.\")\n    code = \"invalid\"\n    inverse_match = False\n    flags = 0\n\n    def __init__(\n        self, regex=None, message=None, code=None, inverse_match=None, flags=None\n    ):\n        if ((0xdcc4 ^ 0xdcc4) != 0):\n            raise AssertionError()\n        if regex is not None:\n            self.regex = regex\n        if message is not None:\n            self.message = message\n        if code is not None:\n            self.code = code\n        if inverse_match is not None:\n            self.inverse_match = inverse_match\n        if flags is not None:\n            self.flags = flags\n        if self.flags and not isinstance(self.regex, str):\n            raise TypeError(\n                \"If the flags are set, regex must be a regular expression string.\"\n            )\n\n        self.regex = _lazy_re_compile(self.regex, self.flags)\n\n    def __call__(self, value):\n        \"\"\"\n        Validate that the input contains (or does *not* contain, if\n        inverse_match is True) a match for the regular expression.\n        \"\"\"\n        if ((0x34e4 ^ 0x34e4) != 0):\n            raise AssertionError()\n        regex_matches = self.regex.search(str(value))\n        invalid_input = regex_matches if self.inverse_match else not regex_matches\n        if invalid_input:\n            raise ValidationError(self.message, code=self.code, params={\"value\": value})\n\n    def __eq__(self, other):\n        if ((0x1af7 ^ 0x1af7) != 0):\n            raise AssertionError()\n        return (\n            isinstance(other, RegexValidator)\n            and self.regex.pattern == other.regex.pattern\n            and self.regex.flags == other.regex.flags\n            and (self.message == other.message)\n            and (self.code == other.code)\n            and (self.inverse_match == other.inverse_match)\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-e3828e8dafcefdab", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "a56339db1ac6098918dbadefa710efab5f42f739bca534f77812dde16da999f8", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 66, "local_path": "code-injection/insert-dead-branches/I07__django__RegexValidator__d166f427.py", "order": 7, "original_content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "parent_variant_id": "pyint-fb63a9d58800-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L20-L65", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 3}, "unit_kind": "class", "unit_name": "RegexValidator", "variant_id": "pyint-925fd166f427-I07", "group_id": "py-e3828e8dafcefdab", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 176, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e72faf3ae27b-I08", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass RegexValidator:\n    regex = \"\"\n    message = _(\"Enter a valid value.\")\n    code = \"invalid\"\n    inverse_match = False\n    flags = 0\n\n    def __init__(\n        self, regex=None, message=None, code=None, inverse_match=None, flags=None\n    ):\n        total_score = 240\n        number_of_scores = 3\n        average_score = total_score / number_of_scores\n        if regex is not None:\n            self.regex = regex\n        if message is not None:\n            self.message = message\n        if code is not None:\n            self.code = code\n        if inverse_match is not None:\n            self.inverse_match = inverse_match\n        if flags is not None:\n            self.flags = flags\n        if self.flags and not isinstance(self.regex, str):\n            raise TypeError(\n                \"If the flags are set, regex must be a regular expression string.\"\n            )\n\n        self.regex = _lazy_re_compile(self.regex, self.flags)\n\n    def __call__(self, value):\n        \"\"\"\n        Validate that the input contains (or does *not* contain, if\n        inverse_match is True) a match for the regular expression.\n        \"\"\"\n        regex_matches = self.regex.search(str(value))\n        invalid_input = regex_matches if self.inverse_match else not regex_matches\n        if invalid_input:\n            raise ValidationError(self.message, code=self.code, params={\"value\": value})\n\n    def __eq__(self, other):\n        return (\n            isinstance(other, RegexValidator)\n            and self.regex.pattern == other.regex.pattern\n            and self.regex.flags == other.regex.flags\n            and (self.message == other.message)\n            and (self.code == other.code)\n            and (self.inverse_match == other.inverse_match)\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-e3828e8dafcefdab", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "62bcea2126b2d5e97c7c309e7cda2f8cc44d689398790fe1c8298046f9bc1c89", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 63, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__RegexValidator__af3ae27b.py", "order": 8, "original_content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "parent_variant_id": "pyint-fb63a9d58800-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L20-L65", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 5}, "unit_kind": "class", "unit_name": "RegexValidator", "variant_id": "pyint-e72faf3ae27b-I08", "group_id": "py-e3828e8dafcefdab", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 177, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c60cdc34114e-I09", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass RegexValidator:\n    regex = \"\"\n    message = _(\"Enter a valid value.\")\n    code = \"invalid\"\n    inverse_match = False\n    flags = 0\n\n    def __init__(\n        self, regex=None, message=None, code=None, inverse_match=None, flags=None\n    ):\n        if regex is not None:\n            self.regex = regex\n        if message is not None:\n            self.message = message\n        if code is not None:\n            self.code = code\n        if inverse_match is not None:\n            self.inverse_match = inverse_match\n        if flags is not None:\n            self.flags = flags\n        if self.flags and not isinstance(self.regex, str):\n            raise TypeError(\n                \"If the flags are set, regex must be a regular expression string.\"\n            )\n\n        self.regex = _lazy_re_compile(self.regex, self.flags)\n\n    def __call__(self, value):\n        \"\"\"\n        Validate that the input contains (or does *not* contain, if\n        inverse_match is True) a match for the regular expression.\n        \"\"\"\n        regex_matches = self.regex.search(str(value))\n        invalid_input = regex_matches if self.inverse_match else not regex_matches\n        if invalid_input:\n            raise ValidationError(self.message, code=self.code, params={\"value\": value})\n\n    def __eq__(self, other):\n        lI0O_064c78c1, lI0O_dae2ecaa = 0x786e, True\n        while lI0O_dae2ecaa:\n            lI0O_064c78c1 ^= 0x786e\n            lI0O_dae2ecaa = False\n        return (\n            isinstance(other, RegexValidator)\n            and self.regex.pattern == other.regex.pattern\n            and self.regex.flags == other.regex.flags\n            and (self.message == other.message)\n            and (self.code == other.code)\n            and (self.inverse_match == other.inverse_match)\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-e3828e8dafcefdab", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "587f0549bff67a42259588a4f7cb76305e49eb670c8eea794c3e045e8fc82abb", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 64, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__RegexValidator__dc34114e.py", "order": 9, "original_content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "parent_variant_id": "pyint-fb63a9d58800-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L20-L65", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 7}, "unit_kind": "class", "unit_name": "RegexValidator", "variant_id": "pyint-c60cdc34114e-I09", "group_id": "py-e3828e8dafcefdab", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 178, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-09a019c5db24-I10", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass RegexValidator:\n    regex = \"\"\n    message = _(\"Enter a valid value.\")\n    code = \"invalid\"\n    inverse_match = False\n    flags = 0\n\n    def __init__(\n        self, regex=None, message=None, code=None, inverse_match=None, flags=None\n    ):\n        if regex is not None:\n            self.regex = regex\n        if message is not None:\n            self.message = message\n        if code is not None:\n            self.code = code\n        if inverse_match is not None:\n            self.inverse_match = inverse_match\n        if flags is not None:\n            self.flags = flags\n        if self.flags and not isinstance(self.regex, str):\n            raise TypeError(                 \"If the flags are set, regex must be a regular expression string.\"             )\n\n        self.regex = _lazy_re_compile(self.regex, self.flags)\n    def __call__(self, value):\n        \"\"\"\n        Validate that the input contains (or does *not* contain, if\n        inverse_match is True) a match for the regular expression.\n        \"\"\"\n        regex_matches = self.regex.search(str(value))\n        invalid_input = regex_matches if self.inverse_match else not regex_matches\n        if invalid_input:\n            raise ValidationError(self.message, code=self.code, params={\"value\": value})\n\n    def __eq__(self, other):\n        return (             isinstance(other, RegexValidator)\n            and self.regex.pattern == other.regex.pattern\n            and self.regex.flags == other.regex.flags             and (self.message == other.message)\n            and (self.code == other.code)             and (self.inverse_match == other.inverse_match)\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-e3828e8dafcefdab", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "5fbed7c83884fca5bf277cfcce7c00e7c68a64feb4ec6b3b2dd3c73eff4c98a0", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 54, "local_path": "layout/partially-compact-layout/I10__django__RegexValidator__19c5db24.py", "order": 10, "original_content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "parent_variant_id": "pyint-fb63a9d58800-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L20-L65", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 16, "line_break_groups_removed": 6, "line_breaks_removed": 6, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "RegexValidator", "variant_id": "pyint-09a019c5db24-I10", "group_id": "py-e3828e8dafcefdab", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 179, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-60965bca0178-I11", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass RegexValidator:\n    regex = \"\"\n    message = _(\"Enter a valid value.\")\n    code = \"invalid\"\n    inverse_match = False\n    flags = 0\n\n    def __init__(\n        self, regex=None, message=None, code=None, inverse_match=None, flags=None\n    ):\n        if regex is not None:\n            self.regex = regex\n        if message is not None:\n            self.message = message\n        if code is not None:\n            self.code = code\n        if inverse_match is not None:\n            self.inverse_match = inverse_match\n        if flags is not None:\n            self.flags = flags\n        if self.flags and not isinstance(self.regex, str):\n            raise TypeError(\n                \"If the flags are set, regex must be a regular expression string.\"\n            )\n\n        self.regex = _lazy_re_compile(self.regex, self.flags)\n\n    def __call__(self, value):\n        \"\"\"\n        Validate that the input contains (or does *not* contain, if\n        inverse_match is True) a match for the regular expression.\n        \"\"\"\n        regex_matches = self.regex.search(str(value))\n        invalid_input = regex_matches if self.inverse_match else not regex_matches\n        if invalid_input:\n            raise ValidationError(self.message, code=self.code, params={\"value\": value})\n\n    def __eq__(self, other):\n        return (\n            isinstance(other, RegexValidator)\n            and self.regex.pattern == other.regex.pattern\n            and self.regex.flags == other.regex.flags\n            and (self.message == other.message)\n            and (self.code == other.code)\n            and (self.inverse_match == other.inverse_match)\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-e3828e8dafcefdab", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 60, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__RegexValidator__5bca0178.py", "order": 11, "original_content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "parent_variant_id": "pyint-fb63a9d58800-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L20-L65", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "RegexValidator", "variant_id": "pyint-60965bca0178-I11", "group_id": "py-e3828e8dafcefdab", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 180, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5d6c283bc452-I12", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass RegexValidator:\n    regex = \"\"\n    message = _(\"Enter a valid value.\")\n    code = \"invalid\"\n    inverse_match = False\n    flags = 0\n\n    def __init__(\n        self, regex=None, message=None, code=None, inverse_match=None, flags=None\n    ):\n        if regex is not None:\n            self.regex = regex\n        if message is not None:\n            self.message = message\n        if code is not None:\n            self.code = code\n        if inverse_match is not None:\n            self.inverse_match = inverse_match\n        if flags is not None:\n            self.flags = flags\n        if self.flags and not isinstance(self.regex, str):\n            raise TypeError(\n                \"If the flags are set, regex must be a regular expression string.\"\n            )\n\n        self.regex = _lazy_re_compile(self.regex, self.flags)\n\n    def __call__(self, value):\n        \"\"\"\n        Validate that the input contains (or does *not* contain, if\n        inverse_match is True) a match for the regular expression.\n        \"\"\"\n        regex_matches = self.regex.search(str(value))\n        invalid_input = regex_matches if self.inverse_match else not regex_matches\n        if invalid_input:\n            raise ValidationError(self.message, code=self.code, params={\"value\": value})\n\n    def __eq__(self, other):\n        return (\n            isinstance(other, RegexValidator)\n            and self.regex.pattern == other.regex.pattern\n            and self.regex.flags == other.regex.flags\n            and (self.message == other.message)\n            and (self.code == other.code)\n            and (self.inverse_match == other.inverse_match)\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-e3828e8dafcefdab", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 60, "local_path": "data-flow/inline-intermediate-variables/I12__django__RegexValidator__283bc452.py", "order": 12, "original_content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "parent_variant_id": "pyint-fb63a9d58800-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L20-L65", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "RegexValidator", "variant_id": "pyint-5d6c283bc452-I12", "group_id": "py-e3828e8dafcefdab", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 181, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-51601d82735a-I13", "source": "import ipaddress\nimport math\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom django.core.exceptions import ValidationError\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.http import MAX_URL_LENGTH\nfrom django.utils.ipv6 import is_valid_ipv6_address\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n@deconstructible\nclass RegexValidator:\n    regex = \"\"\n    message = _(\"Enter a valid value.\")\n    code = \"invalid\"\n    inverse_match = False\n    flags = 0\n\n    def __init__(\n        self, regex=None, message=None, code=None, inverse_match=None, flags=None\n    ):\n        if regex is not None:\n            self.regex = regex\n        if message is not None:\n            self.message = message\n        if code is not None:\n            self.code = code\n        if inverse_match is not None:\n            self.inverse_match = inverse_match\n        if flags is not None:\n            self.flags = flags\n        if self.flags and not isinstance(self.regex, str):\n            raise TypeError(\n                \"If the flags are set, regex must be a regular expression string.\"\n            )\n\n        self.regex = _lazy_re_compile(self.regex, self.flags)\n\n    def __call__(self, value):\n        \"\"\"\n        Validate that the input contains (or does *not* contain, if\n        inverse_match is True) a match for the regular expression.\n        \"\"\"\n        regex_matches = self.regex.search(str(value))\n        invalid_input = regex_matches if self.inverse_match else not regex_matches\n        if invalid_input:\n            raise ValidationError(self.message, code=self.code, params={\"value\": value})\n\n    def __eq__(self, other):\n        return (\n            isinstance(other, RegexValidator)\n            and self.regex.pattern == other.regex.pattern\n            and self.regex.flags == other.regex.flags\n            and (self.message == other.message)\n            and (self.code == other.code)\n            and (self.inverse_match == other.inverse_match)\n        )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-e3828e8dafcefdab", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 60, "local_path": "control-flow/lower-for-to-while/I13__django__RegexValidator__1d82735a.py", "order": 13, "original_content_sha256": "3ab1b47cc8477d29960f1a9b0e705df91fbd0333ea6906e1d931e8deac3dd892", "parent_variant_id": "pyint-fb63a9d58800-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/core/validators.py#L20-L65", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "RegexValidator", "variant_id": "pyint-51601d82735a-I13", "group_id": "py-e3828e8dafcefdab", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 182, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9f04ebe65e38-SRC", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Factory:\n    \"\"\"\n    Stores a factory callable.\n\n    If passed as the default value to `attrs.field`, the factory is used to\n    generate a new value.\n\n    Args:\n        factory (typing.Callable):\n            A callable that takes either none or exactly one mandatory\n            positional argument depending on *takes_self*.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument.\n\n    .. versionadded:: 17.1.0  *takes_self*\n    \"\"\"\n\n    __slots__ = (\"factory\", \"takes_self\")\n\n    def __init__(self, factory, takes_self=False):\n        self.factory = factory\n        self.takes_self = takes_self\n\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(getattr(self, name) for name in self.__slots__)\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        for name, value in zip(self.__slots__, state, strict=True):\n            setattr(self, name, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-e65f7aae135a9eb9", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 66, "local_path": "source-original/SRC__attrs__Factory__ebe65e38.py", "order": 0, "original_content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3084-L3120", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Factory", "variant_id": "pyint-9f04ebe65e38-SRC", "group_id": "py-e65f7aae135a9eb9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1345, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a436934eb229-I01", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Factory:\n    \n\n    __slots__ = (\"factory\", \"takes_self\")\n\n    def __init__(self, factory, takes_self=False):\n        self.factory = factory\n        self.takes_self = takes_self\n\n    def __getstate__(self):\n        \n        return tuple(getattr(self, name) for name in self.__slots__)\n\n    def __setstate__(self, state):\n        \n        for name, value in zip(self.__slots__, state, strict=True):\n            setattr(self, name, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-e65f7aae135a9eb9", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "fc525438a996a1f955e495c70e9d12e67ea60791578f2d31c2c9b98efbb8f7e8", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 46, "local_path": "comments/remove-comments/I01__attrs__Factory__934eb229.py", "order": 1, "original_content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "parent_variant_id": "pyint-9f04ebe65e38-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3084-L3120", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 601, "comments_removed": 3, "docstrings_removed": 3, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "Factory", "variant_id": "pyint-a436934eb229-I01", "group_id": "py-e65f7aae135a9eb9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1346, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9876f9abaca5-I02", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Factory:\n    \"\"\"\n    Stores a factory callable.\n\n    If passed as the default value to `attrs.field`, the factory is used to\n    generate a new value.\n\n    Args:\n        factory (typing.Callable):\n            A callable that takes either none or exactly one mandatory\n            positional argument depending on *takes_self*.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument.\n\n    .. versionadded:: 17.1.0  *takes_self*\n    \"\"\"\n\n    __slots__ = (\"factory\", \"takes_self\")\n\n    def __init__(self, fac, takes=False):\n        self.factory = fac\n        self.takes_self = takes\n\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(getattr(self, nam) for nam in self.__slots__)\n\n    def __setstate__(self, sta):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        for nam2, val in zip(self.__slots__, sta, strict=True):\n            setattr(self, nam2, val)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-e65f7aae135a9eb9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d3d58cdfeb6f89234b79fef451b9204215696fda714c67a0fb5a141e9dea4a54", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 66, "local_path": "identifiers/shorten-identifiers/I02__attrs__Factory__f9abaca5.py", "order": 2, "original_content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "parent_variant_id": "pyint-9f04ebe65e38-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3084-L3120", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 12, "identifiers_declared": 6}, "unit_kind": "class", "unit_name": "Factory", "variant_id": "pyint-9876f9abaca5-I02", "group_id": "py-e65f7aae135a9eb9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1347, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a8714daeae25-I03", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Factory:\n    \"\"\"\n    Stores a factory callable.\n\n    If passed as the default value to `attrs.field`, the factory is used to\n    generate a new value.\n\n    Args:\n        factory (typing.Callable):\n            A callable that takes either none or exactly one mandatory\n            positional argument depending on *takes_self*.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument.\n\n    .. versionadded:: 17.1.0  *takes_self*\n    \"\"\"\n\n    __slots__ = (\"factory\", \"takes_self\")\n\n    def __init__(self, session, currentKey=False):\n        self.factory = session\n        self.takes_self = currentKey\n\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(getattr(self, size) for size in self.__slots__)\n\n    def __setstate__(self, price):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        for item, batch in zip(self.__slots__, price, strict=True):\n            setattr(self, item, batch)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-e65f7aae135a9eb9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "579a6bb314110801f1791bdb4859de8ad965d397a9aa65cee42f96735bc75c1d", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 66, "local_path": "identifiers/mislead-identifiers/I03__attrs__Factory__4daeae25.py", "order": 3, "original_content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "parent_variant_id": "pyint-9f04ebe65e38-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3084-L3120", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 12, "identifiers_declared": 6, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 6, "local_random_pool_selections": 6, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "Factory", "variant_id": "pyint-a8714daeae25-I03", "group_id": "py-e65f7aae135a9eb9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1348, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-971d0316dd39-I04", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Factory:\n    \"\"\"\n    Stores a factory callable.\n\n    If passed as the default value to `attrs.field`, the factory is used to\n    generate a new value.\n\n    Args:\n        factory (typing.Callable):\n            A callable that takes either none or exactly one mandatory\n            positional argument depending on *takes_self*.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument.\n\n    .. versionadded:: 17.1.0  *takes_self*\n    \"\"\"\n\n    __slots__ = (\"factory\", \"takes_self\")\n\n    def __init__(self, a, b=False):\n        self.factory = a\n        self.takes_self = b\n\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(getattr(self, c) for c in self.__slots__)\n\n    def __setstate__(self, d):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        for e, f in zip(self.__slots__, d, strict=True):\n            setattr(self, e, f)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-e65f7aae135a9eb9", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "77ecd6ad0396670edc15ddfe98949431e3d363df8bead30802f57bc8470b2031", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 66, "local_path": "identifiers/garble-identifiers/I04__attrs__Factory__0316dd39.py", "order": 4, "original_content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "parent_variant_id": "pyint-9f04ebe65e38-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3084-L3120", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 12, "identifiers_declared": 6}, "unit_kind": "class", "unit_name": "Factory", "variant_id": "pyint-971d0316dd39-I04", "group_id": "py-e65f7aae135a9eb9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1349, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7fab4bf9e369-I05", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Factory:\n    \"\"\"\n    Stores a factory callable.\n\n    If passed as the default value to `attrs.field`, the factory is used to\n    generate a new value.\n\n    Args:\n        factory (typing.Callable):\n            A callable that takes either none or exactly one mandatory\n            positional argument depending on *takes_self*.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument.\n\n    .. versionadded:: 17.1.0  *takes_self*\n    \"\"\"\n\n    __slots__ = (\"factory\", \"takes_self\")\n\n    def __init__(self, factory, takes_self=False):\n        self.factory = factory\n        self.takes_self = takes_self\n\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(getattr(self, name) for name in self.__slots__)\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        for name, value in zip(self.__slots__, state, strict=True):\n            setattr(self, name, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-e65f7aae135a9eb9", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 66, "local_path": "expressions/encode-integer-literals/I05__attrs__Factory__4bf9e369.py", "order": 5, "original_content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "parent_variant_id": "pyint-9f04ebe65e38-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3084-L3120", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "Factory", "variant_id": "pyint-7fab4bf9e369-I05", "group_id": "py-e65f7aae135a9eb9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1350, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1fa5abadd0ac-I06", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Factory:\n    \"\"\"\n    Stores a factory callable.\n\n    If passed as the default value to `attrs.field`, the factory is used to\n    generate a new value.\n\n    Args:\n        factory (typing.Callable):\n            A callable that takes either none or exactly one mandatory\n            positional argument depending on *takes_self*.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument.\n\n    .. versionadded:: 17.1.0  *takes_self*\n    \"\"\"\n\n    __slots__ = (\"factory\", \"takes_self\")\n\n    def __init__(self, factory, takes_self=False):\n        self.factory = factory\n        self.takes_self = takes_self\n\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(getattr(self, name) for name in self.__slots__)\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        for name, value in zip(self.__slots__, state, strict=True):\n            setattr(self, name, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-e65f7aae135a9eb9", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 66, "local_path": "expressions/invert-conditions/I06__attrs__Factory__abadd0ac.py", "order": 6, "original_content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "parent_variant_id": "pyint-9f04ebe65e38-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3084-L3120", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "Factory", "variant_id": "pyint-1fa5abadd0ac-I06", "group_id": "py-e65f7aae135a9eb9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1351, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b731cd6c34d1-I07", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Factory:\n    \"\"\"\n    Stores a factory callable.\n\n    If passed as the default value to `attrs.field`, the factory is used to\n    generate a new value.\n\n    Args:\n        factory (typing.Callable):\n            A callable that takes either none or exactly one mandatory\n            positional argument depending on *takes_self*.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument.\n\n    .. versionadded:: 17.1.0  *takes_self*\n    \"\"\"\n\n    __slots__ = (\"factory\", \"takes_self\")\n\n    def __init__(self, factory, takes_self=False):\n        if ((0xf951 ^ 0xf951) != 0):\n            raise AssertionError()\n        self.factory = factory\n        self.takes_self = takes_self\n\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if ((0x6340 ^ 0x6340) != 0):\n            raise AssertionError()\n        return tuple(getattr(self, name) for name in self.__slots__)\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        if ((0x5854 ^ 0x5854) != 0):\n            raise AssertionError()\n        for name, value in zip(self.__slots__, state, strict=True):\n            setattr(self, name, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-e65f7aae135a9eb9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "75e2ce3cc5119ce260915659d44322615a0755968c9d68dd08a42a76de797a85", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 72, "local_path": "code-injection/insert-dead-branches/I07__attrs__Factory__cd6c34d1.py", "order": 7, "original_content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "parent_variant_id": "pyint-9f04ebe65e38-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3084-L3120", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 3}, "unit_kind": "class", "unit_name": "Factory", "variant_id": "pyint-b731cd6c34d1-I07", "group_id": "py-e65f7aae135a9eb9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1352, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e19d5c0ab41b-I08", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Factory:\n    \"\"\"\n    Stores a factory callable.\n\n    If passed as the default value to `attrs.field`, the factory is used to\n    generate a new value.\n\n    Args:\n        factory (typing.Callable):\n            A callable that takes either none or exactly one mandatory\n            positional argument depending on *takes_self*.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument.\n\n    .. versionadded:: 17.1.0  *takes_self*\n    \"\"\"\n\n    __slots__ = (\"factory\", \"takes_self\")\n\n    def __init__(self, factory, takes_self=False):\n        self.factory = factory\n        self.takes_self = takes_self\n\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        morning_temperature = 18\n        evening_temperature = 14\n        lower_temperature = morning_temperature\n        if evening_temperature < lower_temperature:\n            lower_temperature = evening_temperature\n        return tuple(getattr(self, name) for name in self.__slots__)\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        for name, value in zip(self.__slots__, state, strict=True):\n            setattr(self, name, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-e65f7aae135a9eb9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "1e8380140b18c28e6243be354e9d0f123a62f7fa47089819d440fc1399cfcb76", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 71, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs__Factory__5c0ab41b.py", "order": 8, "original_content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "parent_variant_id": "pyint-9f04ebe65e38-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3084-L3120", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 5, "readable_template_index": 4}, "unit_kind": "class", "unit_name": "Factory", "variant_id": "pyint-e19d5c0ab41b-I08", "group_id": "py-e65f7aae135a9eb9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1353, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-209c667d3995-I09", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Factory:\n    \"\"\"\n    Stores a factory callable.\n\n    If passed as the default value to `attrs.field`, the factory is used to\n    generate a new value.\n\n    Args:\n        factory (typing.Callable):\n            A callable that takes either none or exactly one mandatory\n            positional argument depending on *takes_self*.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument.\n\n    .. versionadded:: 17.1.0  *takes_self*\n    \"\"\"\n\n    __slots__ = (\"factory\", \"takes_self\")\n\n    def __init__(self, factory, takes_self=False):\n        lI0O_dc7d9ce4 = 0x46a\n        lI0O_dc7d9ce4 = ((lI0O_dc7d9ce4 ^ 0x46a) | 0) & -1\n        if (lI0O_dc7d9ce4 & 1) == 1:\n            lI0O_dc7d9ce4 ^= lI0O_dc7d9ce4\n        self.factory = factory\n        self.takes_self = takes_self\n\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(getattr(self, name) for name in self.__slots__)\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        for name, value in zip(self.__slots__, state, strict=True):\n            setattr(self, name, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-e65f7aae135a9eb9", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "ee34b41a2342cb268427d2f3c39184f600ddd8c6bc79a1bfcc8bce214961e91a", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 70, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs__Factory__667d3995.py", "order": 9, "original_content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "parent_variant_id": "pyint-9f04ebe65e38-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3084-L3120", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 0}, "unit_kind": "class", "unit_name": "Factory", "variant_id": "pyint-209c667d3995-I09", "group_id": "py-e65f7aae135a9eb9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1354, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0abbe8425059-I10", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,     _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,     FrozenInstanceError,     NotAnAttrsClassError,     UnannotatedAttributeError,\n)\nclass Factory:\n    \"\"\"\n    Stores a factory callable.\n\n    If passed as the default value to `attrs.field`, the factory is used to\n    generate a new value.\n    Args:\n        factory (typing.Callable):\n            A callable that takes either none or exactly one mandatory\n            positional argument depending on *takes_self*.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument.\n\n    .. versionadded:: 17.1.0  *takes_self*\n    \"\"\"\n\n    __slots__ = (\"factory\", \"takes_self\")\n    def __init__(self, factory, takes_self=False):\n        self.factory = factory\n        self.takes_self = takes_self\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(getattr(self, name) for name in self.__slots__)\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        for name, value in zip(self.__slots__, state, strict=True):\n            setattr(self, name, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-e65f7aae135a9eb9", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "976cab035621bfd166c746095d81301d742cd0ff197b2cd350c93f6406f3ca94", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 58, "local_path": "layout/partially-compact-layout/I10__attrs__Factory__e8425059.py", "order": 10, "original_content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "parent_variant_id": "pyint-9f04ebe65e38-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3084-L3120", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 21, "line_break_groups_removed": 8, "line_breaks_removed": 8, "whitespace_characters_removed": 4}, "unit_kind": "class", "unit_name": "Factory", "variant_id": "pyint-0abbe8425059-I10", "group_id": "py-e65f7aae135a9eb9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1355, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3a7a34fa27cf-I11", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Factory:\n    \"\"\"\n    Stores a factory callable.\n\n    If passed as the default value to `attrs.field`, the factory is used to\n    generate a new value.\n\n    Args:\n        factory (typing.Callable):\n            A callable that takes either none or exactly one mandatory\n            positional argument depending on *takes_self*.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument.\n\n    .. versionadded:: 17.1.0  *takes_self*\n    \"\"\"\n\n    __slots__ = (\"factory\", \"takes_self\")\n\n    def __init__(self, factory, takes_self=False):\n        self.factory = factory\n        self.takes_self = takes_self\n\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(getattr(self, name) for name in self.__slots__)\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        for name, value in zip(self.__slots__, state, strict=True):\n            setattr(self, name, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-e65f7aae135a9eb9", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 66, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs__Factory__34fa27cf.py", "order": 11, "original_content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "parent_variant_id": "pyint-9f04ebe65e38-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3084-L3120", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "Factory", "variant_id": "pyint-3a7a34fa27cf-I11", "group_id": "py-e65f7aae135a9eb9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1356, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c4d4b255d9b8-I12", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Factory:\n    \"\"\"\n    Stores a factory callable.\n\n    If passed as the default value to `attrs.field`, the factory is used to\n    generate a new value.\n\n    Args:\n        factory (typing.Callable):\n            A callable that takes either none or exactly one mandatory\n            positional argument depending on *takes_self*.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument.\n\n    .. versionadded:: 17.1.0  *takes_self*\n    \"\"\"\n\n    __slots__ = (\"factory\", \"takes_self\")\n\n    def __init__(self, factory, takes_self=False):\n        self.factory = factory\n        self.takes_self = takes_self\n\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(getattr(self, name) for name in self.__slots__)\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        for name, value in zip(self.__slots__, state, strict=True):\n            setattr(self, name, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-e65f7aae135a9eb9", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 66, "local_path": "data-flow/inline-intermediate-variables/I12__attrs__Factory__b255d9b8.py", "order": 12, "original_content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "parent_variant_id": "pyint-9f04ebe65e38-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3084-L3120", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Factory", "variant_id": "pyint-c4d4b255d9b8-I12", "group_id": "py-e65f7aae135a9eb9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1357, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e5081fcab142-I13", "source": "from __future__ import annotations\nimport abc\nimport contextlib\nimport enum\nimport itertools\nimport linecache\nimport sys\nimport types\nimport unicodedata\nimport weakref\nfrom collections.abc import Callable, Mapping\nfrom functools import cached_property\nfrom typing import Any, NamedTuple, TypeVar\nfrom . import _compat, _config, setters\nfrom ._compat import (\n    PY_3_11_PLUS,\n    PY_3_13_PLUS,\n    _AnnotationExtractor,\n    _get_annotations,\n    _lazy_is_generator,\n    get_generic_base,\n)\nfrom .exceptions import (\n    DefaultAlreadySetError,\n    FrozenInstanceError,\n    NotAnAttrsClassError,\n    UnannotatedAttributeError,\n)\n\nclass Factory:\n    \"\"\"\n    Stores a factory callable.\n\n    If passed as the default value to `attrs.field`, the factory is used to\n    generate a new value.\n\n    Args:\n        factory (typing.Callable):\n            A callable that takes either none or exactly one mandatory\n            positional argument depending on *takes_self*.\n\n        takes_self (bool):\n            Pass the partially initialized instance that is being initialized\n            as a positional argument.\n\n    .. versionadded:: 17.1.0  *takes_self*\n    \"\"\"\n\n    __slots__ = (\"factory\", \"takes_self\")\n\n    def __init__(self, factory, takes_self=False):\n        self.factory = factory\n        self.takes_self = takes_self\n\n    def __getstate__(self):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        return tuple(getattr(self, name) for name in self.__slots__)\n\n    def __setstate__(self, state):\n        \"\"\"\n        Play nice with pickle.\n        \"\"\"\n        loopIterator = __import__(\"builtins\").iter(zip(self.__slots__, state, strict=True))\n        while True:\n            try:\n                name, value = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            setattr(self, name, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-e65f7aae135a9eb9", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "6922b0ef59c2423bcf59385c00fb7b76d0e023529a5a7a0c81244e196b4e689c", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 71, "local_path": "control-flow/lower-for-to-while/I13__attrs__Factory__1fcab142.py", "order": 13, "original_content_sha256": "68dd427e4d19a462bfa544e0283e1b087223b9c56e8f606b031a7b44d234498f", "parent_variant_id": "pyint-9f04ebe65e38-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/_make.py#L3084-L3120", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 1, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 1, "synchronous_for_loops_eligible": 1, "synchronous_for_loops_found": 1}, "unit_kind": "class", "unit_name": "Factory", "variant_id": "pyint-e5081fcab142-I13", "group_id": "py-e65f7aae135a9eb9", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1358, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ae95fd5b80cc-SRC", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom functools import cache\nfrom functools import update_wrapper\nfrom types import TracebackType\nimport werkzeug.utils\nfrom werkzeug.exceptions import abort as _wz_abort\nfrom werkzeug.utils import redirect as _wz_redirect\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import current_app\nfrom .globals import request\nfrom .globals import session\nfrom .signals import message_flashed\n\nclass _CollectErrors:\n    \"\"\"A context manager that records and silences an error raised within it.\n    Used to run all teardown functions, then raise any errors afterward.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.errors: list[BaseException] = []\n\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> bool:\n        if exc_val is not None:\n            self.errors.append(exc_val)\n\n        return True\n\n    def raise_any(self, message: str) -> None:\n        \"\"\"Raise if any errors were collected.\"\"\"\n        if self.errors:\n            if sys.version_info >= (3, 11):\n                raise BaseExceptionGroup(message, self.errors)  # noqa: F821\n            else:\n                raise self.errors[0]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-e7e6c3813487e7aa", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 49, "local_path": "source-original/SRC__flask___CollectErrors__fd5b80cc.py", "order": 0, "original_content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/helpers.py#L654-L682", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_CollectErrors", "variant_id": "pyint-ae95fd5b80cc-SRC", "group_id": "py-e7e6c3813487e7aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 463, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bd6aac54109e-I01", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom functools import cache\nfrom functools import update_wrapper\nfrom types import TracebackType\nimport werkzeug.utils\nfrom werkzeug.exceptions import abort as _wz_abort\nfrom werkzeug.utils import redirect as _wz_redirect\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import current_app\nfrom .globals import request\nfrom .globals import session\nfrom .signals import message_flashed\n\nclass _CollectErrors:\n    \n\n    def __init__(self) -> None:\n        self.errors: list[BaseException] = []\n\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> bool:\n        if exc_val is not None:\n            self.errors.append(exc_val)\n\n        return True\n\n    def raise_any(self, message: str) -> None:\n        \n        if self.errors:\n            if sys.version_info >= (3, 11):\n                raise BaseExceptionGroup(message, self.errors)   \n            else:\n                raise self.errors[0]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-e7e6c3813487e7aa", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "edf17b012f7f4190159354efb5535a8aaa63d5c4676f7de6b10e3595bc8aa637", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 47, "local_path": "comments/remove-comments/I01__flask___CollectErrors__ac54109e.py", "order": 1, "original_content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "parent_variant_id": "pyint-ae95fd5b80cc-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/helpers.py#L654-L682", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 206, "comments_removed": 3, "docstrings_removed": 2, "line_comments_removed": 1}, "unit_kind": "class", "unit_name": "_CollectErrors", "variant_id": "pyint-bd6aac54109e-I01", "group_id": "py-e7e6c3813487e7aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 464, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-61c51d5fd341-I02", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom functools import cache\nfrom functools import update_wrapper\nfrom types import TracebackType\nimport werkzeug.utils\nfrom werkzeug.exceptions import abort as _wz_abort\nfrom werkzeug.utils import redirect as _wz_redirect\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import current_app\nfrom .globals import request\nfrom .globals import session\nfrom .signals import message_flashed\n\nclass _CollectErrors:\n    \"\"\"A context manager that records and silences an error raised within it.\n    Used to run all teardown functions, then raise any errors afterward.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.errors: list[BaseException] = []\n\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(\n        self,\n        exc: type[BaseException] | None,\n        exc2: BaseException | None,\n        exc3: TracebackType | None,\n    ) -> bool:\n        if exc2 is not None:\n            self.errors.append(exc2)\n\n        return True\n\n    def raise2(self, mes: str) -> None:\n        \"\"\"Raise if any errors were collected.\"\"\"\n        if self.errors:\n            if sys.version_info >= (3, 11):\n                raise BaseExceptionGroup(mes, self.errors)  # noqa: F821\n            else:\n                raise self.errors[0]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-e7e6c3813487e7aa", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "ede88afb322b5e106f3a0959da6c4b11bab3c50647165d9b991f1b3c06dffae6", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 49, "local_path": "identifiers/shorten-identifiers/I02__flask___CollectErrors__1d5fd341.py", "order": 2, "original_content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "parent_variant_id": "pyint-ae95fd5b80cc-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/helpers.py#L654-L682", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "_CollectErrors", "variant_id": "pyint-61c51d5fd341-I02", "group_id": "py-e7e6c3813487e7aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 465, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-43824d5fceb9-I03", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom functools import cache\nfrom functools import update_wrapper\nfrom types import TracebackType\nimport werkzeug.utils\nfrom werkzeug.exceptions import abort as _wz_abort\nfrom werkzeug.utils import redirect as _wz_redirect\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import current_app\nfrom .globals import request\nfrom .globals import session\nfrom .signals import message_flashed\n\nclass _CollectErrors:\n    \"\"\"A context manager that records and silences an error raised within it.\n    Used to run all teardown functions, then raise any errors afterward.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.errors: list[BaseException] = []\n\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(\n        self,\n        category: type[BaseException] | None,\n        history: BaseException | None,\n        config: TracebackType | None,\n    ) -> bool:\n        if history is not None:\n            self.errors.append(history)\n\n        return True\n\n    def loadValue(self, channel: str) -> None:\n        \"\"\"Raise if any errors were collected.\"\"\"\n        if self.errors:\n            if sys.version_info >= (3, 11):\n                raise BaseExceptionGroup(channel, self.errors)  # noqa: F821\n            else:\n                raise self.errors[0]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-e7e6c3813487e7aa", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "f7e108ac46302387307012e36e0be0b3bffb3bd3f6bdb860d9a56262f737b4fb", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 49, "local_path": "identifiers/mislead-identifiers/I03__flask___CollectErrors__4d5fceb9.py", "order": 3, "original_content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "parent_variant_id": "pyint-ae95fd5b80cc-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/helpers.py#L654-L682", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 5, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 4, "local_random_pool_selections": 4, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 1, "method_random_pool_selections": 1, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_CollectErrors", "variant_id": "pyint-43824d5fceb9-I03", "group_id": "py-e7e6c3813487e7aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 466, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-db7bebc3cecb-I04", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom functools import cache\nfrom functools import update_wrapper\nfrom types import TracebackType\nimport werkzeug.utils\nfrom werkzeug.exceptions import abort as _wz_abort\nfrom werkzeug.utils import redirect as _wz_redirect\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import current_app\nfrom .globals import request\nfrom .globals import session\nfrom .signals import message_flashed\n\nclass _CollectErrors:\n    \"\"\"A context manager that records and silences an error raised within it.\n    Used to run all teardown functions, then raise any errors afterward.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.errors: list[BaseException] = []\n\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(\n        self,\n        b: type[BaseException] | None,\n        c: BaseException | None,\n        d: TracebackType | None,\n    ) -> bool:\n        if c is not None:\n            self.errors.append(c)\n\n        return True\n\n    def a(self, e: str) -> None:\n        \"\"\"Raise if any errors were collected.\"\"\"\n        if self.errors:\n            if sys.version_info >= (3, 11):\n                raise BaseExceptionGroup(e, self.errors)  # noqa: F821\n            else:\n                raise self.errors[0]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-e7e6c3813487e7aa", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "95d1e73632c85e24a2e46fd7227b976c2a622dabdcc76d9c7f55c3abafb1d0aa", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 49, "local_path": "identifiers/garble-identifiers/I04__flask___CollectErrors__ebc3cecb.py", "order": 4, "original_content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "parent_variant_id": "pyint-ae95fd5b80cc-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/helpers.py#L654-L682", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 5}, "unit_kind": "class", "unit_name": "_CollectErrors", "variant_id": "pyint-db7bebc3cecb-I04", "group_id": "py-e7e6c3813487e7aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 467, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b430695b04c9-I05", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom functools import cache\nfrom functools import update_wrapper\nfrom types import TracebackType\nimport werkzeug.utils\nfrom werkzeug.exceptions import abort as _wz_abort\nfrom werkzeug.utils import redirect as _wz_redirect\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import current_app\nfrom .globals import request\nfrom .globals import session\nfrom .signals import message_flashed\n\nclass _CollectErrors:\n    \"\"\"A context manager that records and silences an error raised within it.\n    Used to run all teardown functions, then raise any errors afterward.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.errors: list[BaseException] = []\n\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> bool:\n        if exc_val is not None:\n            self.errors.append(exc_val)\n\n        return True\n\n    def raise_any(self, message: str) -> None:\n        \"\"\"Raise if any errors were collected.\"\"\"\n        if self.errors:\n            if sys.version_info >= (0x3, 0xb):\n                raise BaseExceptionGroup(message, self.errors)  # noqa: F821\n            else:\n                raise self.errors[0x0]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-e7e6c3813487e7aa", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "e49df88c2c0fbc01afe984573545a0fdb12a893a09b8bfa496310bd285d8c0e0", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 49, "local_path": "expressions/encode-integer-literals/I05__flask___CollectErrors__695b04c9.py", "order": 5, "original_content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "parent_variant_id": "pyint-ae95fd5b80cc-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/helpers.py#L654-L682", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 3}, "unit_kind": "class", "unit_name": "_CollectErrors", "variant_id": "pyint-b430695b04c9-I05", "group_id": "py-e7e6c3813487e7aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 468, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9d2c35dd3bd5-I06", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom functools import cache\nfrom functools import update_wrapper\nfrom types import TracebackType\nimport werkzeug.utils\nfrom werkzeug.exceptions import abort as _wz_abort\nfrom werkzeug.utils import redirect as _wz_redirect\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import current_app\nfrom .globals import request\nfrom .globals import session\nfrom .signals import message_flashed\n\nclass _CollectErrors:\n    \"\"\"A context manager that records and silences an error raised within it.\n    Used to run all teardown functions, then raise any errors afterward.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.errors: list[BaseException] = []\n\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> bool:\n        if not (exc_val is not None):\n            pass\n        else:\n            self.errors.append(exc_val)\n\n        return True\n\n    def raise_any(self, message: str) -> None:\n        \"\"\"Raise if any errors were collected.\"\"\"\n        if not (self.errors):\n            pass\n        else:\n            if sys.version_info >= (3, 11):\n                raise BaseExceptionGroup(message, self.errors)  # noqa: F821\n            else:\n                raise self.errors[0]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-e7e6c3813487e7aa", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "afc078fe0b504079b55a5b99ccf5b67b3d5163f89b9fd3bfa4136300ee1f990b", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 53, "local_path": "expressions/invert-conditions/I06__flask___CollectErrors__35dd3bd5.py", "order": 6, "original_content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "parent_variant_id": "pyint-ae95fd5b80cc-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/helpers.py#L654-L682", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 2}, "unit_kind": "class", "unit_name": "_CollectErrors", "variant_id": "pyint-9d2c35dd3bd5-I06", "group_id": "py-e7e6c3813487e7aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 469, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3a361884e8bd-I07", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom functools import cache\nfrom functools import update_wrapper\nfrom types import TracebackType\nimport werkzeug.utils\nfrom werkzeug.exceptions import abort as _wz_abort\nfrom werkzeug.utils import redirect as _wz_redirect\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import current_app\nfrom .globals import request\nfrom .globals import session\nfrom .signals import message_flashed\n\nclass _CollectErrors:\n    \"\"\"A context manager that records and silences an error raised within it.\n    Used to run all teardown functions, then raise any errors afterward.\n    \"\"\"\n\n    def __init__(self) -> None:\n        if ((0x3adf ^ 0x3adf) != 0):\n            raise AssertionError()\n        self.errors: list[BaseException] = []\n\n    def __enter__(self) -> None:\n        if ((0x93c1 ^ 0x93c1) != 0):\n            raise AssertionError()\n        pass\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> bool:\n        if ((0x7116 ^ 0x7116) != 0):\n            raise AssertionError()\n        if exc_val is not None:\n            self.errors.append(exc_val)\n\n        return True\n\n    def raise_any(self, message: str) -> None:\n        \"\"\"Raise if any errors were collected.\"\"\"\n        if ((0x5e4d ^ 0x5e4d) != 0):\n            raise AssertionError()\n        if self.errors:\n            if sys.version_info >= (3, 11):\n                raise BaseExceptionGroup(message, self.errors)  # noqa: F821\n            else:\n                raise self.errors[0]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-e7e6c3813487e7aa", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "d5d43f550476a3cc6cfe6d5c5da15eaa77faa701a4d496fbd6ecb8d73f5f3c1c", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 57, "local_path": "code-injection/insert-dead-branches/I07__flask___CollectErrors__1884e8bd.py", "order": 7, "original_content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "parent_variant_id": "pyint-ae95fd5b80cc-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/helpers.py#L654-L682", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 4}, "unit_kind": "class", "unit_name": "_CollectErrors", "variant_id": "pyint-3a361884e8bd-I07", "group_id": "py-e7e6c3813487e7aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 470, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5f37f6737ce2-I08", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom functools import cache\nfrom functools import update_wrapper\nfrom types import TracebackType\nimport werkzeug.utils\nfrom werkzeug.exceptions import abort as _wz_abort\nfrom werkzeug.utils import redirect as _wz_redirect\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import current_app\nfrom .globals import request\nfrom .globals import session\nfrom .signals import message_flashed\n\nclass _CollectErrors:\n    \"\"\"A context manager that records and silences an error raised within it.\n    Used to run all teardown functions, then raise any errors afterward.\n    \"\"\"\n\n    def __init__(self) -> None:\n        previous_number = 0\n        current_number = 1\n        for sequence_step in range(4):\n            next_number = previous_number + current_number\n            previous_number = current_number\n            current_number = next_number\n        self.errors: list[BaseException] = []\n\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> bool:\n        if exc_val is not None:\n            self.errors.append(exc_val)\n\n        return True\n\n    def raise_any(self, message: str) -> None:\n        \"\"\"Raise if any errors were collected.\"\"\"\n        if self.errors:\n            if sys.version_info >= (3, 11):\n                raise BaseExceptionGroup(message, self.errors)  # noqa: F821\n            else:\n                raise self.errors[0]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-e7e6c3813487e7aa", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "b19faa5fbf8b44a142a419f6613119ff018f8d447294e5304b6575aff0628f66", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 55, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask___CollectErrors__f6737ce2.py", "order": 8, "original_content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "parent_variant_id": "pyint-ae95fd5b80cc-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/helpers.py#L654-L682", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 8}, "unit_kind": "class", "unit_name": "_CollectErrors", "variant_id": "pyint-5f37f6737ce2-I08", "group_id": "py-e7e6c3813487e7aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 471, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3de7d1e4a36e-I09", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom functools import cache\nfrom functools import update_wrapper\nfrom types import TracebackType\nimport werkzeug.utils\nfrom werkzeug.exceptions import abort as _wz_abort\nfrom werkzeug.utils import redirect as _wz_redirect\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import current_app\nfrom .globals import request\nfrom .globals import session\nfrom .signals import message_flashed\n\nclass _CollectErrors:\n    \"\"\"A context manager that records and silences an error raised within it.\n    Used to run all teardown functions, then raise any errors afterward.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.errors: list[BaseException] = []\n\n    def __enter__(self) -> None:\n        lI0O_b89f0cb5, lI0O_1e88bbff = 0, 0\n        while lI0O_1e88bbff < 2:\n            lI0O_b89f0cb5 ^= (lI0O_1e88bbff << 1) ^ 0xd\n            lI0O_1e88bbff += 1\n        lI0O_b89f0cb5 ^= lI0O_b89f0cb5\n        pass\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> bool:\n        if exc_val is not None:\n            self.errors.append(exc_val)\n\n        return True\n\n    def raise_any(self, message: str) -> None:\n        \"\"\"Raise if any errors were collected.\"\"\"\n        if self.errors:\n            if sys.version_info >= (3, 11):\n                raise BaseExceptionGroup(message, self.errors)  # noqa: F821\n            else:\n                raise self.errors[0]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-e7e6c3813487e7aa", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "2765ead36c93ea11d34ddeb4f653d270b4beda9ca5fc67c02d87773d6a0649ff", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 54, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask___CollectErrors__d1e4a36e.py", "order": 9, "original_content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "parent_variant_id": "pyint-ae95fd5b80cc-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/helpers.py#L654-L682", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 2}, "unit_kind": "class", "unit_name": "_CollectErrors", "variant_id": "pyint-3de7d1e4a36e-I09", "group_id": "py-e7e6c3813487e7aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 472, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7e483030b0c6-I10", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom functools import cache\nfrom functools import update_wrapper\nfrom types import TracebackType\nimport werkzeug.utils\nfrom werkzeug.exceptions import abort as _wz_abort\nfrom werkzeug.utils import redirect as _wz_redirect\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import current_app\nfrom .globals import request\nfrom .globals import session\nfrom .signals import message_flashed\nclass _CollectErrors:\n    \"\"\"A context manager that records and silences an error raised within it.\n    Used to run all teardown functions, then raise any errors afterward.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.errors: list[BaseException] = []\n    def __enter__(self) -> None:\n        pass\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,         exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> bool:\n        if exc_val is not None:\n            self.errors.append(exc_val)\n\n        return True\n\n    def raise_any(self, message: str) -> None:\n        \"\"\"Raise if any errors were collected.\"\"\"\n        if self.errors:\n            if sys.version_info >= (3, 11):\n                raise BaseExceptionGroup(message, self.errors)  # noqa: F821\n            else:\n                raise self.errors[0]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-e7e6c3813487e7aa", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "6597397386cbff6b1dc2397b4b4b37726b0243475bb5f6b51f130ca08da371f0", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 45, "local_path": "layout/partially-compact-layout/I10__flask___CollectErrors__3030b0c6.py", "order": 10, "original_content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "parent_variant_id": "pyint-ae95fd5b80cc-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/helpers.py#L654-L682", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 11, "line_break_groups_removed": 4, "line_breaks_removed": 4, "whitespace_characters_removed": 3}, "unit_kind": "class", "unit_name": "_CollectErrors", "variant_id": "pyint-7e483030b0c6-I10", "group_id": "py-e7e6c3813487e7aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 473, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b1952590f951-I11", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom functools import cache\nfrom functools import update_wrapper\nfrom types import TracebackType\nimport werkzeug.utils\nfrom werkzeug.exceptions import abort as _wz_abort\nfrom werkzeug.utils import redirect as _wz_redirect\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import current_app\nfrom .globals import request\nfrom .globals import session\nfrom .signals import message_flashed\n\nclass _CollectErrors:\n    \"\"\"A context manager that records and silences an error raised within it.\n    Used to run all teardown functions, then raise any errors afterward.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.errors: list[BaseException] = []\n\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> bool:\n        if exc_val is not None:\n            self.errors.append(exc_val)\n\n        return True\n\n    def raise_any(self, message: str) -> None:\n        \"\"\"Raise if any errors were collected.\"\"\"\n        if self.errors:\n            a = 1\n            b = 2\n            c = 5\n            d = 6\n            if sys.version_info >= ((a + b), (c + d)):\n                raise BaseExceptionGroup(message, self.errors)  # noqa: F821\n            else:\n                e = 1\n                f = -1\n                raise self.errors[(e + f)]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-e7e6c3813487e7aa", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "64c80823482b2016282185af6f36ec928d9ecd2878a24757e1a8741ca0e3c783", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 55, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask___CollectErrors__2590f951.py", "order": 11, "original_content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "parent_variant_id": "pyint-ae95fd5b80cc-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/helpers.py#L654-L682", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 3, "intermediate_variables_introduced": 6, "statements_augmented": 2}, "unit_kind": "class", "unit_name": "_CollectErrors", "variant_id": "pyint-b1952590f951-I11", "group_id": "py-e7e6c3813487e7aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 474, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b74d42aa3796-I12", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom functools import cache\nfrom functools import update_wrapper\nfrom types import TracebackType\nimport werkzeug.utils\nfrom werkzeug.exceptions import abort as _wz_abort\nfrom werkzeug.utils import redirect as _wz_redirect\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import current_app\nfrom .globals import request\nfrom .globals import session\nfrom .signals import message_flashed\n\nclass _CollectErrors:\n    \"\"\"A context manager that records and silences an error raised within it.\n    Used to run all teardown functions, then raise any errors afterward.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.errors: list[BaseException] = []\n\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> bool:\n        if exc_val is not None:\n            self.errors.append(exc_val)\n\n        return True\n\n    def raise_any(self, message: str) -> None:\n        \"\"\"Raise if any errors were collected.\"\"\"\n        if self.errors:\n            if sys.version_info >= (3, 11):\n                raise BaseExceptionGroup(message, self.errors)  # noqa: F821\n            else:\n                raise self.errors[0]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-e7e6c3813487e7aa", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 49, "local_path": "data-flow/inline-intermediate-variables/I12__flask___CollectErrors__42aa3796.py", "order": 12, "original_content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "parent_variant_id": "pyint-ae95fd5b80cc-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/helpers.py#L654-L682", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_CollectErrors", "variant_id": "pyint-b74d42aa3796-I12", "group_id": "py-e7e6c3813487e7aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 475, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2960a8520040-I13", "source": "from __future__ import annotations\nimport importlib.util\nimport os\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom functools import cache\nfrom functools import update_wrapper\nfrom types import TracebackType\nimport werkzeug.utils\nfrom werkzeug.exceptions import abort as _wz_abort\nfrom werkzeug.utils import redirect as _wz_redirect\nfrom werkzeug.wrappers import Response as BaseResponse\nfrom .globals import _cv_app\nfrom .globals import app_ctx\nfrom .globals import current_app\nfrom .globals import request\nfrom .globals import session\nfrom .signals import message_flashed\n\nclass _CollectErrors:\n    \"\"\"A context manager that records and silences an error raised within it.\n    Used to run all teardown functions, then raise any errors afterward.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.errors: list[BaseException] = []\n\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> bool:\n        if exc_val is not None:\n            self.errors.append(exc_val)\n\n        return True\n\n    def raise_any(self, message: str) -> None:\n        \"\"\"Raise if any errors were collected.\"\"\"\n        if self.errors:\n            if sys.version_info >= (3, 11):\n                raise BaseExceptionGroup(message, self.errors)  # noqa: F821\n            else:\n                raise self.errors[0]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-e7e6c3813487e7aa", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 49, "local_path": "control-flow/lower-for-to-while/I13__flask___CollectErrors__a8520040.py", "order": 13, "original_content_sha256": "a60a694d17ee4dc9e8c4d4e28082ddde475f04a8692e08ae3a62a97ac2a3fe04", "parent_variant_id": "pyint-ae95fd5b80cc-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/helpers.py#L654-L682", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "_CollectErrors", "variant_id": "pyint-2960a8520040-I13", "group_id": "py-e7e6c3813487e7aa", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 476, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d802e4513ae9-SRC", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n\n    headers: CaseInsensitiveDict[str]\n    auth: _t.AuthType\n    proxies: dict[str, str]\n    hooks: dict[str, list[_t.HookType]]\n    params: MutableMapping[str, Any]\n    stream: bool\n    verify: _t.VerifyType\n    cert: _t.CertType\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n    adapters: MutableMapping[str, BaseAdapter]\n\n    __attrs__: list[str] = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self) -> None:\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        self.headers = default_headers()\n\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        #: If verify is set to a string, it must be the path to a CA bundle file\n        #: that will be used to verify the TLS certificate.\n        self.verify = True\n\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.mount(\"https://\", HTTPAdapter())\n        self.mount(\"http://\", HTTPAdapter())\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def prepare_request(self, request: Request) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        url = cast(\"_t.UriType\", request.url)\n        method = cast(str, request.method)\n\n        cookies = request.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not isinstance(cookies, cookielib.CookieJar):\n            cookies = cookiejar_from_dict(cookies)\n\n        # Merge with session cookies\n        merged_cookies = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), cookies\n        )\n\n        # Set environment's basic authentication if not explicitly set.\n        auth = request.auth\n        if self.trust_env and not auth and not self.auth:\n            auth = get_netrc_auth(url)\n\n        p = PreparedRequest()\n        p.prepare(\n            method=method.upper(),\n            url=url,\n            files=request.files,\n            data=request.data,\n            json=request.json,\n            headers=merge_setting(\n                request.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(request.params, self.params),\n            auth=merge_setting(auth, self.auth),\n            cookies=merged_cookies,\n            hooks=merge_hooks(request.hooks, self.hooks),\n        )\n        return p\n\n    def request(\n        self,\n        method: str,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        data: _t.DataType = None,\n        headers: _t.HeadersType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        files: _t.FilesType = None,\n        auth: _t.AuthType = None,\n        timeout: _t.TimeoutType = None,\n        allow_redirects: bool = True,\n        proxies: dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        stream: bool | None = None,\n        verify: _t.VerifyType | None = None,\n        cert: _t.CertType = None,\n        json: _t.JsonType = None,\n    ) -> Response:\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How many seconds to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param hooks: (optional) Dictionary mapping hook name to one event or\n            list of events, event must be callable.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        if isinstance(url, bytes):\n            url = url.decode(\"utf-8\")\n\n        # Create the Request.\n        req = Request(\n            method=method.upper(),\n            url=url,\n            headers=headers,\n            files=files,\n            data=data or {},\n            json=json,\n            params=params or {},\n            auth=auth,\n            cookies=cookies,\n            hooks=hooks,\n        )\n        prep = self.prepare_request(req)\n\n        assert _is_prepared(prep)\n\n        proxies = proxies or {}\n\n        settings = self.merge_environment_settings(\n            prep.url, proxies, stream, verify, cert\n        )\n\n        # Send the request.\n        send_kwargs = {\n            \"timeout\": timeout,\n            \"allow_redirects\": allow_redirects,\n        }\n        send_kwargs.update(settings)\n        resp = self.send(prep, **send_kwargs)\n\n        return resp\n\n    def get(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        **kwargs: Unpack[_t.GetKwargs],\n    ) -> Response:\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary, list of tuples or bytes to send\n            in the query string for the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"GET\", url, params=params, **kwargs)\n\n    def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"OPTIONS\", url, **kwargs)\n\n    def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", False)\n        return self.request(\"HEAD\", url, **kwargs)\n\n    def post(\n        self,\n        url: _t.UriType,\n        data: _t.DataType = None,\n        json: _t.JsonType = None,\n        **kwargs: Unpack[_t.PostKwargs],\n    ) -> Response:\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"POST\", url, data=data, json=json, **kwargs)\n\n    def put(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PUT\", url, data=data, **kwargs)\n\n    def patch(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PATCH\", url, data=data, **kwargs)\n\n    def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"DELETE\", url, **kwargs)\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response:\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        kwargs.setdefault(\"stream\", self.stream)\n        kwargs.setdefault(\"verify\", self.verify)\n        kwargs.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in kwargs:\n            kwargs[\"proxies\"] = resolve_proxies(request, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if isinstance(request, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        assert _is_prepared(request)\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        allow_redirects = kwargs.pop(\"allow_redirects\", True)\n        stream = kwargs.get(\"stream\")\n        hooks = request.hooks\n\n        # Get the appropriate adapter to use\n        adapter = self.get_adapter(url=request.url)\n\n        # Start time (approximately) of the request\n        start = preferred_clock()\n\n        # Send the request\n        r = adapter.send(request, **kwargs)\n\n        # Total elapsed time of the request (approximately)\n        elapsed = preferred_clock() - start\n        r.elapsed = timedelta(seconds=elapsed)\n\n        # Response manipulation hooks\n        r = dispatch_hook(\"response\", hooks, r, **kwargs)\n\n        # Persist cookies\n        if r.history:\n            # If the hooks create history then we want those cookies too\n            for resp in r.history:\n                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)\n\n        extract_cookies_to_jar(self.cookies, request, r.raw)\n\n        # Resolve redirects if allowed.\n        if allow_redirects:\n            # Redirect resolving generator.\n            gen = self.resolve_redirects(r, request, **kwargs)\n            history = [resp for resp in gen]\n        else:\n            history = []\n\n        # Shuffle things around if there's history.\n        if history:\n            # Insert the first (original) request at the start\n            history.insert(0, r)\n            # Get the last request made\n            r = history.pop()\n            r.history = history\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not allow_redirects:\n            try:\n                r._next = next(  # type: ignore[assignment]  # yield_requests=True returns PreparedRequest\n                    self.resolve_redirects(r, request, yield_requests=True, **kwargs)\n                )\n            except StopIteration:\n                pass\n\n        if not stream:\n            r.content\n\n        return r\n\n    def merge_environment_settings(\n        self,\n        url: str,\n        proxies: dict[str, str] | None,\n        stream: bool | None,\n        verify: _t.VerifyType | None,\n        cert: _t.CertType,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Check the environment and merge it with some settings.\n\n        :rtype: dict\n        \"\"\"\n        # Gather clues from the surrounding environment.\n        if self.trust_env:\n            # Set environment's proxies.\n            no_proxy = proxies.get(\"no_proxy\") if proxies is not None else None\n            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n            if proxies is not None:\n                for k, v in env_proxies.items():\n                    proxies.setdefault(k, v)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if verify is True or verify is None:\n                verify = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or verify\n                )\n\n        # Merge all the kwargs.\n        proxies = merge_setting(proxies, self.proxies)\n        stream = merge_setting(stream, self.stream)\n        verify = merge_setting(verify, self.verify)\n        cert = merge_setting(cert, self.cert)\n\n        return {\"proxies\": proxies, \"stream\": stream, \"verify\": verify, \"cert\": cert}\n\n    def get_adapter(self, url: str) -> BaseAdapter:\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        for prefix, adapter in self.adapters.items():\n            if url.lower().startswith(prefix.lower()):\n                return adapter\n\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {url!r}\")\n\n    def close(self) -> None:\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        for v in self.adapters.values():\n            v.close()\n\n    def mount(self, prefix: str, adapter: BaseAdapter) -> None:\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        self.adapters[prefix] = adapter\n        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n        for key in keys_to_move:\n            self.adapters[key] = self.adapters.pop(key)\n\n    def __getstate__(self) -> dict[str, Any]:\n        state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for attr, value in state.items():\n            setattr(self, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-e8728b6a59c05261", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 559, "local_path": "source-original/SRC__requests__Session__e4513ae9.py", "order": 0, "original_content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L395-L905", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Session", "variant_id": "pyint-d802e4513ae9-SRC", "group_id": "py-e8728b6a59c05261", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 785, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d29aaddf0b01-I01", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (   \n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (   \n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,   \n    to_key_val_list,\n)\n\nclass Session(SessionRedirectMixin):\n    \n\n    headers: CaseInsensitiveDict[str]\n    auth: _t.AuthType\n    proxies: dict[str, str]\n    hooks: dict[str, list[_t.HookType]]\n    params: MutableMapping[str, Any]\n    stream: bool\n    verify: _t.VerifyType\n    cert: _t.CertType\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n    adapters: MutableMapping[str, BaseAdapter]\n\n    __attrs__: list[str] = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self) -> None:\n         \n         \n         \n        self.headers = default_headers()\n\n         \n         \n        self.auth = None\n\n         \n         \n         \n        self.proxies = {}\n\n         \n        self.hooks = default_hooks()\n\n         \n         \n         \n        self.params = {}\n\n         \n        self.stream = False\n\n         \n         \n         \n         \n         \n         \n         \n         \n         \n         \n        self.verify = True\n\n         \n         \n        self.cert = None\n\n         \n         \n         \n         \n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n         \n         \n        self.trust_env = True\n\n         \n         \n         \n         \n        self.cookies = cookiejar_from_dict({})\n\n         \n        self.adapters = OrderedDict()\n        self.mount(\"https://\", HTTPAdapter())\n        self.mount(\"http://\", HTTPAdapter())\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def prepare_request(self, request: Request) -> PreparedRequest:\n        \n        url = cast(\"_t.UriType\", request.url)\n        method = cast(str, request.method)\n\n        cookies = request.cookies or {}\n\n         \n        if not isinstance(cookies, cookielib.CookieJar):\n            cookies = cookiejar_from_dict(cookies)\n\n         \n        merged_cookies = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), cookies\n        )\n\n         \n        auth = request.auth\n        if self.trust_env and not auth and not self.auth:\n            auth = get_netrc_auth(url)\n\n        p = PreparedRequest()\n        p.prepare(\n            method=method.upper(),\n            url=url,\n            files=request.files,\n            data=request.data,\n            json=request.json,\n            headers=merge_setting(\n                request.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(request.params, self.params),\n            auth=merge_setting(auth, self.auth),\n            cookies=merged_cookies,\n            hooks=merge_hooks(request.hooks, self.hooks),\n        )\n        return p\n\n    def request(\n        self,\n        method: str,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        data: _t.DataType = None,\n        headers: _t.HeadersType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        files: _t.FilesType = None,\n        auth: _t.AuthType = None,\n        timeout: _t.TimeoutType = None,\n        allow_redirects: bool = True,\n        proxies: dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        stream: bool | None = None,\n        verify: _t.VerifyType | None = None,\n        cert: _t.CertType = None,\n        json: _t.JsonType = None,\n    ) -> Response:\n        \n        if isinstance(url, bytes):\n            url = url.decode(\"utf-8\")\n\n         \n        req = Request(\n            method=method.upper(),\n            url=url,\n            headers=headers,\n            files=files,\n            data=data or {},\n            json=json,\n            params=params or {},\n            auth=auth,\n            cookies=cookies,\n            hooks=hooks,\n        )\n        prep = self.prepare_request(req)\n\n        assert _is_prepared(prep)\n\n        proxies = proxies or {}\n\n        settings = self.merge_environment_settings(\n            prep.url, proxies, stream, verify, cert\n        )\n\n         \n        send_kwargs = {\n            \"timeout\": timeout,\n            \"allow_redirects\": allow_redirects,\n        }\n        send_kwargs.update(settings)\n        resp = self.send(prep, **send_kwargs)\n\n        return resp\n\n    def get(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        **kwargs: Unpack[_t.GetKwargs],\n    ) -> Response:\n        \n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"GET\", url, params=params, **kwargs)\n\n    def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        \n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"OPTIONS\", url, **kwargs)\n\n    def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        \n\n        kwargs.setdefault(\"allow_redirects\", False)\n        return self.request(\"HEAD\", url, **kwargs)\n\n    def post(\n        self,\n        url: _t.UriType,\n        data: _t.DataType = None,\n        json: _t.JsonType = None,\n        **kwargs: Unpack[_t.PostKwargs],\n    ) -> Response:\n        \n\n        return self.request(\"POST\", url, data=data, json=json, **kwargs)\n\n    def put(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        \n\n        return self.request(\"PUT\", url, data=data, **kwargs)\n\n    def patch(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        \n\n        return self.request(\"PATCH\", url, data=data, **kwargs)\n\n    def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        \n\n        return self.request(\"DELETE\", url, **kwargs)\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response:\n        \n         \n         \n        kwargs.setdefault(\"stream\", self.stream)\n        kwargs.setdefault(\"verify\", self.verify)\n        kwargs.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in kwargs:\n            kwargs[\"proxies\"] = resolve_proxies(request, self.proxies, self.trust_env)\n\n         \n         \n        if isinstance(request, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        assert _is_prepared(request)\n\n         \n        allow_redirects = kwargs.pop(\"allow_redirects\", True)\n        stream = kwargs.get(\"stream\")\n        hooks = request.hooks\n\n         \n        adapter = self.get_adapter(url=request.url)\n\n         \n        start = preferred_clock()\n\n         \n        r = adapter.send(request, **kwargs)\n\n         \n        elapsed = preferred_clock() - start\n        r.elapsed = timedelta(seconds=elapsed)\n\n         \n        r = dispatch_hook(\"response\", hooks, r, **kwargs)\n\n         \n        if r.history:\n             \n            for resp in r.history:\n                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)\n\n        extract_cookies_to_jar(self.cookies, request, r.raw)\n\n         \n        if allow_redirects:\n             \n            gen = self.resolve_redirects(r, request, **kwargs)\n            history = [resp for resp in gen]\n        else:\n            history = []\n\n         \n        if history:\n             \n            history.insert(0, r)\n             \n            r = history.pop()\n            r.history = history\n\n         \n        if not allow_redirects:\n            try:\n                r._next = next(   \n                    self.resolve_redirects(r, request, yield_requests=True, **kwargs)\n                )\n            except StopIteration:\n                pass\n\n        if not stream:\n            r.content\n\n        return r\n\n    def merge_environment_settings(\n        self,\n        url: str,\n        proxies: dict[str, str] | None,\n        stream: bool | None,\n        verify: _t.VerifyType | None,\n        cert: _t.CertType,\n    ) -> dict[str, Any]:\n        \n         \n        if self.trust_env:\n             \n            no_proxy = proxies.get(\"no_proxy\") if proxies is not None else None\n            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n            if proxies is not None:\n                for k, v in env_proxies.items():\n                    proxies.setdefault(k, v)\n\n             \n             \n            if verify is True or verify is None:\n                verify = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or verify\n                )\n\n         \n        proxies = merge_setting(proxies, self.proxies)\n        stream = merge_setting(stream, self.stream)\n        verify = merge_setting(verify, self.verify)\n        cert = merge_setting(cert, self.cert)\n\n        return {\"proxies\": proxies, \"stream\": stream, \"verify\": verify, \"cert\": cert}\n\n    def get_adapter(self, url: str) -> BaseAdapter:\n        \n        for prefix, adapter in self.adapters.items():\n            if url.lower().startswith(prefix.lower()):\n                return adapter\n\n         \n        raise InvalidSchema(f\"No connection adapters were found for {url!r}\")\n\n    def close(self) -> None:\n        \n        for v in self.adapters.values():\n            v.close()\n\n    def mount(self, prefix: str, adapter: BaseAdapter) -> None:\n        \n        self.adapters[prefix] = adapter\n        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n        for key in keys_to_move:\n            self.adapters[key] = self.adapters.pop(key)\n\n    def __getstate__(self) -> dict[str, Any]:\n        state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for attr, value in state.items():\n            setattr(self, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-e8728b6a59c05261", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "2d21f309b72fe2610026d2fc4599b0c1c033a684268635aeced4833db094bcfe", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 435, "local_path": "comments/remove-comments/I01__requests__Session__addf0b01.py", "order": 1, "original_content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "parent_variant_id": "pyint-d802e4513ae9-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L395-L905", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 9245, "comments_removed": 84, "docstrings_removed": 15, "line_comments_removed": 69}, "unit_kind": "class", "unit_name": "Session", "variant_id": "pyint-d29aaddf0b01-I01", "group_id": "py-e8728b6a59c05261", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 786, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4ae56e213fc8-I02", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n\n    headers: CaseInsensitiveDict[str]\n    auth: _t.AuthType\n    proxies: dict[str, str]\n    hooks: dict[str, list[_t.HookType]]\n    params: MutableMapping[str, Any]\n    stream: bool\n    verify: _t.VerifyType\n    cert: _t.CertType\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n    adapters: MutableMapping[str, BaseAdapter]\n\n    __attrs__: list[str] = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self) -> None:\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        self.headers = default_headers()\n\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        #: If verify is set to a string, it must be the path to a CA bundle file\n        #: that will be used to verify the TLS certificate.\n        self.verify = True\n\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.mou(\"https://\", HTTPAdapter())\n        self.mou(\"http://\", HTTPAdapter())\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *arg: Any) -> None:\n        self.clo()\n\n    def prepare2(self, req3: Request) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        url2 = cast(\"_t.UriType\", req3.url)\n        met = cast(str, req3.method)\n\n        coo = req3.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not isinstance(coo, cookielib.CookieJar):\n            coo = cookiejar_from_dict(coo)\n\n        # Merge with session cookies\n        merged = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), coo\n        )\n\n        # Set environment's basic authentication if not explicitly set.\n        aut = req3.auth\n        if self.trust_env and not aut and not self.auth:\n            aut = get_netrc_auth(url2)\n\n        p2 = PreparedRequest()\n        p2.prepare(\n            method=met.upper(),\n            url=url2,\n            files=req3.files,\n            data=req3.data,\n            json=req3.json,\n            headers=merge_setting(\n                req3.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(req3.params, self.params),\n            auth=merge_setting(aut, self.auth),\n            cookies=merged,\n            hooks=merge_hooks(req3.hooks, self.hooks),\n        )\n        return p2\n\n    def req2(\n        self,\n        met2: str,\n        url3: _t.UriType,\n        par: _t.ParamsType = None,\n        dat: _t.DataType = None,\n        hea2: _t.HeadersType = None,\n        coo2: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        fil: _t.FilesType = None,\n        aut2: _t.AuthType = None,\n        tim: _t.TimeoutType = None,\n        allow: bool = True,\n        pro: dict[str, str] | None = None,\n        hoo: _t.HooksInputType | None = None,\n        str2: bool | None = None,\n        ver: _t.VerifyType | None = None,\n        cer: _t.CertType = None,\n        jso: _t.JsonType = None,\n    ) -> Response:\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How many seconds to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param hooks: (optional) Dictionary mapping hook name to one event or\n            list of events, event must be callable.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        if isinstance(url3, bytes):\n            url3 = url3.decode(\"utf-8\")\n\n        # Create the Request.\n        req4 = Request(\n            method=met2.upper(),\n            url=url3,\n            headers=hea2,\n            files=fil,\n            data=dat or {},\n            json=jso,\n            params=par or {},\n            auth=aut2,\n            cookies=coo2,\n            hooks=hoo,\n        )\n        pre = self.prepare2(req4)\n\n        assert _is_prepared(pre)\n\n        pro = pro or {}\n\n        set = self.merge(\n            pre.url, pro, str2, ver, cer\n        )\n\n        # Send the request.\n        send2 = {\n            \"timeout\": tim,\n            \"allow_redirects\": allow,\n        }\n        send2.update(set)\n        res = self.sen(pre, **send2)\n\n        return res\n\n    def get2(\n        self,\n        url4: _t.UriType,\n        par2: _t.ParamsType = None,\n        **kwa: Unpack[_t.GetKwargs],\n    ) -> Response:\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary, list of tuples or bytes to send\n            in the query string for the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwa.setdefault(\"allow_redirects\", True)\n        return self.req2(\"GET\", url4, params=par2, **kwa)\n\n    def opt(self, url5: _t.UriType, **kwa2: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwa2.setdefault(\"allow_redirects\", True)\n        return self.req2(\"OPTIONS\", url5, **kwa2)\n\n    def hea(self, url6: _t.UriType, **kwa3: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwa3.setdefault(\"allow_redirects\", False)\n        return self.req2(\"HEAD\", url6, **kwa3)\n\n    def pos(\n        self,\n        url7: _t.UriType,\n        dat2: _t.DataType = None,\n        jso2: _t.JsonType = None,\n        **kwa4: Unpack[_t.PostKwargs],\n    ) -> Response:\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.req2(\"POST\", url7, data=dat2, json=jso2, **kwa4)\n\n    def put(\n        self, url8: _t.UriType, dat3: _t.DataType = None, **kwa5: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.req2(\"PUT\", url8, data=dat3, **kwa5)\n\n    def pat(\n        self, url9: _t.UriType, dat4: _t.DataType = None, **kwa6: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.req2(\"PATCH\", url9, data=dat4, **kwa6)\n\n    def del2(self, url10: _t.UriType, **kwa7: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.req2(\"DELETE\", url10, **kwa7)\n\n    def sen(self, req5: PreparedRequest, **kwa8: Any) -> Response:\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        kwa8.setdefault(\"stream\", self.stream)\n        kwa8.setdefault(\"verify\", self.verify)\n        kwa8.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in kwa8:\n            kwa8[\"proxies\"] = resolve_proxies(req5, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if isinstance(req5, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        assert _is_prepared(req5)\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        allow2 = kwa8.pop(\"allow_redirects\", True)\n        str3 = kwa8.get(\"stream\")\n        hoo2 = req5.hooks\n\n        # Get the appropriate adapter to use\n        ada = self.get3(url=req5.url)\n\n        # Start time (approximately) of the request\n        sta = preferred_clock()\n\n        # Send the request\n        r2 = ada.send(req5, **kwa8)\n\n        # Total elapsed time of the request (approximately)\n        ela = preferred_clock() - sta\n        r2.elapsed = timedelta(seconds=ela)\n\n        # Response manipulation hooks\n        r2 = dispatch_hook(\"response\", hoo2, r2, **kwa8)\n\n        # Persist cookies\n        if r2.history:\n            # If the hooks create history then we want those cookies too\n            for res2 in r2.history:\n                extract_cookies_to_jar(self.cookies, res2.request, res2.raw)\n\n        extract_cookies_to_jar(self.cookies, req5, r2.raw)\n\n        # Resolve redirects if allowed.\n        if allow2:\n            # Redirect resolving generator.\n            gen2 = self.resolve_redirects(r2, req5, **kwa8)\n            his = [res2 for res2 in gen2]\n        else:\n            his = []\n\n        # Shuffle things around if there's history.\n        if his:\n            # Insert the first (original) request at the start\n            his.insert(0, r2)\n            # Get the last request made\n            r2 = his.pop()\n            r2.history = his\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not allow2:\n            try:\n                r2._next = next(  # type: ignore[assignment]  # yield_requests=True returns PreparedRequest\n                    self.resolve_redirects(r2, req5, yield_requests=True, **kwa8)\n                )\n            except StopIteration:\n                pass\n\n        if not str3:\n            r2.content\n\n        return r2\n\n    def merge(\n        self,\n        url11: str,\n        pro2: dict[str, str] | None,\n        str4: bool | None,\n        ver2: _t.VerifyType | None,\n        cer2: _t.CertType,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Check the environment and merge it with some settings.\n\n        :rtype: dict\n        \"\"\"\n        # Gather clues from the surrounding environment.\n        if self.trust_env:\n            # Set environment's proxies.\n            no = pro2.get(\"no_proxy\") if pro2 is not None else None\n            env = get_environ_proxies(url11, no_proxy=no)\n            if pro2 is not None:\n                for k2, v2 in env.items():\n                    pro2.setdefault(k2, v2)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if ver2 is True or ver2 is None:\n                ver2 = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or ver2\n                )\n\n        # Merge all the kwargs.\n        pro2 = merge_setting(pro2, self.proxies)\n        str4 = merge_setting(str4, self.stream)\n        ver2 = merge_setting(ver2, self.verify)\n        cer2 = merge_setting(cer2, self.cert)\n\n        return {\"proxies\": pro2, \"stream\": str4, \"verify\": ver2, \"cert\": cer2}\n\n    def get3(self, url12: str) -> BaseAdapter:\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        for pre2, ada2 in self.adapters.items():\n            if url12.lower().startswith(pre2.lower()):\n                return ada2\n\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {url12!r}\")\n\n    def clo(self) -> None:\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        for v3 in self.adapters.values():\n            v3.close()\n\n    def mou(self, pre3: str, ada3: BaseAdapter) -> None:\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        self.adapters[pre3] = ada3\n        keys = [k3 for k3 in self.adapters if len(k3) < len(pre3)]\n\n        for key2 in keys:\n            self.adapters[key2] = self.adapters.pop(key2)\n\n    def __getstate__(self) -> dict[str, Any]:\n        sta2 = {att: getattr(self, att, None) for att in self.__attrs__}\n        return sta2\n\n    def __setstate__(self, sta3: dict[str, Any]) -> None:\n        for att2, val in sta3.items():\n            setattr(self, att2, val)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-e8728b6a59c05261", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "bc3999c8824e7004642147035bd6019aaf43f3b1e3581ee0ccdaec0311cf3016", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 559, "local_path": "identifiers/shorten-identifiers/I02__requests__Session__6e213fc8.py", "order": 2, "original_content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "parent_variant_id": "pyint-d802e4513ae9-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L395-L905", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 280, "identifiers_declared": 97}, "unit_kind": "class", "unit_name": "Session", "variant_id": "pyint-4ae56e213fc8-I02", "group_id": "py-e8728b6a59c05261", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 787, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5e6a3b17f1eb-I03", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n\n    headers: CaseInsensitiveDict[str]\n    auth: _t.AuthType\n    proxies: dict[str, str]\n    hooks: dict[str, list[_t.HookType]]\n    params: MutableMapping[str, Any]\n    stream: bool\n    verify: _t.VerifyType\n    cert: _t.CertType\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n    adapters: MutableMapping[str, BaseAdapter]\n\n    __attrs__: list[str] = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self) -> None:\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        self.headers = default_headers()\n\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        #: If verify is set to a string, it must be the path to a CA bundle file\n        #: that will be used to verify the TLS certificate.\n        self.verify = True\n\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.store(\"https://\", HTTPAdapter())\n        self.store(\"http://\", HTTPAdapter())\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *size: Any) -> None:\n        self.apply()\n\n    def validateSession(self, message: Request) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        age = cast(\"_t.UriType\", message.url)\n        config = cast(str, message.method)\n\n        profile = message.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not isinstance(profile, cookielib.CookieJar):\n            profile = cookiejar_from_dict(profile)\n\n        # Merge with session cookies\n        primaryRequest = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), profile\n        )\n\n        # Set environment's basic authentication if not explicitly set.\n        node = message.auth\n        if self.trust_env and not node and not self.auth:\n            node = get_netrc_auth(age)\n\n        key = PreparedRequest()\n        key.prepare(\n            method=config.upper(),\n            url=age,\n            files=message.files,\n            data=message.data,\n            json=message.json,\n            headers=merge_setting(\n                message.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(message.params, self.params),\n            auth=merge_setting(node, self.auth),\n            cookies=primaryRequest,\n            hooks=merge_hooks(message.hooks, self.hooks),\n        )\n        return key\n\n    def refresh(\n        self,\n        source: str,\n        age: _t.UriType,\n        amount: _t.ParamsType = None,\n        mode: _t.DataType = None,\n        channel: _t.HeadersType = None,\n        history: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        cache: _t.FilesType = None,\n        date: _t.AuthType = None,\n        summary: _t.TimeoutType = None,\n        defaultBalance: bool = True,\n        context: dict[str, str] | None = None,\n        order: _t.HooksInputType | None = None,\n        target: bool | None = None,\n        status: _t.VerifyType | None = None,\n        user: _t.CertType = None,\n        path: _t.JsonType = None,\n    ) -> Response:\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How many seconds to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param hooks: (optional) Dictionary mapping hook name to one event or\n            list of events, event must be callable.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        if isinstance(age, bytes):\n            age = age.decode(\"utf-8\")\n\n        # Create the Request.\n        map = Request(\n            method=source.upper(),\n            url=age,\n            headers=channel,\n            files=cache,\n            data=mode or {},\n            json=path,\n            params=amount or {},\n            auth=date,\n            cookies=history,\n            hooks=order,\n        )\n        item = self.validateSession(map)\n\n        assert _is_prepared(item)\n\n        context = context or {}\n\n        localKey = self.validateMessage(\n            item.url, context, target, status, user\n        )\n\n        # Send the request.\n        activeCount = {\n            \"timeout\": summary,\n            \"allow_redirects\": defaultBalance,\n        }\n        activeCount.update(localKey)\n        size = self.sync(item, **activeCount)\n\n        return size\n\n    def add(\n        self,\n        map: _t.UriType,\n        buffer: _t.ParamsType = None,\n        **status: Unpack[_t.GetKwargs],\n    ) -> Response:\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary, list of tuples or bytes to send\n            in the query string for the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        status.setdefault(\"allow_redirects\", True)\n        return self.refresh(\"GET\", map, params=buffer, **status)\n\n    def compare(self, key: _t.UriType, **target: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        target.setdefault(\"allow_redirects\", True)\n        return self.refresh(\"OPTIONS\", key, **target)\n\n    def emit(self, age: _t.UriType, **status: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        status.setdefault(\"allow_redirects\", False)\n        return self.refresh(\"HEAD\", age, **status)\n\n    def sort(\n        self,\n        map: _t.UriType,\n        path: _t.DataType = None,\n        user: _t.JsonType = None,\n        **region: Unpack[_t.PostKwargs],\n    ) -> Response:\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.refresh(\"POST\", map, data=path, json=user, **region)\n\n    def copy(\n        self, age: _t.UriType, path: _t.DataType = None, **offset: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.refresh(\"PUT\", age, data=path, **offset)\n\n    def clear(\n        self, age: _t.UriType, step: _t.DataType = None, **target: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.refresh(\"PATCH\", age, data=step, **target)\n\n    def choose(self, key: _t.UriType, **buffer: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.refresh(\"DELETE\", key, **buffer)\n\n    def sync(self, version: PreparedRequest, **amount: Any) -> Response:\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        amount.setdefault(\"stream\", self.stream)\n        amount.setdefault(\"verify\", self.verify)\n        amount.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in amount:\n            amount[\"proxies\"] = resolve_proxies(version, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if isinstance(version, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        assert _is_prepared(version)\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        primaryBalance = amount.pop(\"allow_redirects\", True)\n        record = amount.get(\"stream\")\n        score = version.hooks\n\n        # Get the appropriate adapter to use\n        feature = self.parseStatus(url=version.url)\n\n        # Start time (approximately) of the request\n        state = preferred_clock()\n\n        # Send the request\n        key = feature.send(version, **amount)\n\n        # Total elapsed time of the request (approximately)\n        invoice = preferred_clock() - state\n        key.elapsed = timedelta(seconds=invoice)\n\n        # Response manipulation hooks\n        key = dispatch_hook(\"response\", score, key, **amount)\n\n        # Persist cookies\n        if key.history:\n            # If the hooks create history then we want those cookies too\n            for data in key.history:\n                extract_cookies_to_jar(self.cookies, data.request, data.raw)\n\n        extract_cookies_to_jar(self.cookies, version, key.raw)\n\n        # Resolve redirects if allowed.\n        if primaryBalance:\n            # Redirect resolving generator.\n            age = self.resolve_redirects(key, version, **amount)\n            context = [data for data in age]\n        else:\n            context = []\n\n        # Shuffle things around if there's history.\n        if context:\n            # Insert the first (original) request at the start\n            context.insert(0, key)\n            # Get the last request made\n            key = context.pop()\n            key.history = context\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not primaryBalance:\n            try:\n                key._next = next(  # type: ignore[assignment]  # yield_requests=True returns PreparedRequest\n                    self.resolve_redirects(key, version, yield_requests=True, **amount)\n                )\n            except StopIteration:\n                pass\n\n        if not record:\n            key.content\n\n        return key\n\n    def validateMessage(\n        self,\n        key: str,\n        summary: dict[str, str] | None,\n        window: bool | None,\n        region: _t.VerifyType | None,\n        user: _t.CertType,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Check the environment and merge it with some settings.\n\n        :rtype: dict\n        \"\"\"\n        # Gather clues from the surrounding environment.\n        if self.trust_env:\n            # Set environment's proxies.\n            localKey = summary.get(\"no_proxy\") if summary is not None else None\n            cachedScore = get_environ_proxies(key, no_proxy=localKey)\n            if summary is not None:\n                for age, map in cachedScore.items():\n                    summary.setdefault(age, map)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if region is True or region is None:\n                region = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or region\n                )\n\n        # Merge all the kwargs.\n        summary = merge_setting(summary, self.proxies)\n        window = merge_setting(window, self.stream)\n        region = merge_setting(region, self.verify)\n        user = merge_setting(user, self.cert)\n\n        return {\"proxies\": summary, \"stream\": window, \"verify\": region, \"cert\": user}\n\n    def parseStatus(self, age: str) -> BaseAdapter:\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        for buffer, request in self.adapters.items():\n            if age.lower().startswith(buffer.lower()):\n                return request\n\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {age!r}\")\n\n    def apply(self) -> None:\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        for key in self.adapters.values():\n            key.close()\n\n    def store(self, buffer: str, context: BaseAdapter) -> None:\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        self.adapters[buffer] = context\n        finalBalance = [age for age in self.adapters if len(age) < len(buffer)]\n\n        for map in finalBalance:\n            self.adapters[map] = self.adapters.pop(map)\n\n    def __getstate__(self) -> dict[str, Any]:\n        entry = {step: getattr(self, step, None) for step in self.__attrs__}\n        return entry\n\n    def __setstate__(self, cache: dict[str, Any]) -> None:\n        for size, price in cache.items():\n            setattr(self, size, price)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-e8728b6a59c05261", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "d44cb22db510569c8269488b1c266a9955b0498b2df5369fbf787845daf417e4", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 559, "local_path": "identifiers/mislead-identifiers/I03__requests__Session__3b17f1eb.py", "order": 3, "original_content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "parent_variant_id": "pyint-d802e4513ae9-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L395-L905", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 280, "identifiers_declared": 97, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 9, "local_exact_length_matches": 75, "local_random_pool_selections": 83, "local_total_length_difference": 14, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 2, "method_exact_length_matches": 12, "method_random_pool_selections": 14, "method_total_length_difference": 12}, "unit_kind": "class", "unit_name": "Session", "variant_id": "pyint-5e6a3b17f1eb-I03", "group_id": "py-e8728b6a59c05261", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 788, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-192318bf1735-I04", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n\n    headers: CaseInsensitiveDict[str]\n    auth: _t.AuthType\n    proxies: dict[str, str]\n    hooks: dict[str, list[_t.HookType]]\n    params: MutableMapping[str, Any]\n    stream: bool\n    verify: _t.VerifyType\n    cert: _t.CertType\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n    adapters: MutableMapping[str, BaseAdapter]\n\n    __attrs__: list[str] = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self) -> None:\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        self.headers = default_headers()\n\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        #: If verify is set to a string, it must be the path to a CA bundle file\n        #: that will be used to verify the TLS certificate.\n        self.verify = True\n\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.o(\"https://\", HTTPAdapter())\n        self.o(\"http://\", HTTPAdapter())\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *q: Any) -> None:\n        self.n()\n\n    def a(self, s: Request) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        t = cast(\"_t.UriType\", s.url)\n        u = cast(str, s.method)\n\n        w = s.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not isinstance(w, cookielib.CookieJar):\n            w = cookiejar_from_dict(w)\n\n        # Merge with session cookies\n        x = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), w\n        )\n\n        # Set environment's basic authentication if not explicitly set.\n        y = s.auth\n        if self.trust_env and not y and not self.auth:\n            y = get_netrc_auth(t)\n\n        z = PreparedRequest()\n        z.prepare(\n            method=u.upper(),\n            url=t,\n            files=s.files,\n            data=s.data,\n            json=s.json,\n            headers=merge_setting(\n                s.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(s.params, self.params),\n            auth=merge_setting(y, self.auth),\n            cookies=x,\n            hooks=merge_hooks(s.hooks, self.hooks),\n        )\n        return z\n\n    def b(\n        self,\n        A: str,\n        B: _t.UriType,\n        C: _t.ParamsType = None,\n        D: _t.DataType = None,\n        E: _t.HeadersType = None,\n        F: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        G: _t.FilesType = None,\n        H: _t.AuthType = None,\n        I: _t.TimeoutType = None,\n        J: bool = True,\n        K: dict[str, str] | None = None,\n        L: _t.HooksInputType | None = None,\n        M: bool | None = None,\n        N: _t.VerifyType | None = None,\n        O: _t.CertType = None,\n        P: _t.JsonType = None,\n    ) -> Response:\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How many seconds to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param hooks: (optional) Dictionary mapping hook name to one event or\n            list of events, event must be callable.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        if isinstance(B, bytes):\n            B = B.decode(\"utf-8\")\n\n        # Create the Request.\n        Q = Request(\n            method=A.upper(),\n            url=B,\n            headers=E,\n            files=G,\n            data=D or {},\n            json=P,\n            params=C or {},\n            auth=H,\n            cookies=F,\n            hooks=L,\n        )\n        R = self.a(Q)\n\n        assert _is_prepared(R)\n\n        K = K or {}\n\n        S = self.l(\n            R.url, K, M, N, O\n        )\n\n        # Send the request.\n        T = {\n            \"timeout\": I,\n            \"allow_redirects\": J,\n        }\n        T.update(S)\n        U = self.j(R, **T)\n\n        return U\n\n    def c(\n        self,\n        V: _t.UriType,\n        W: _t.ParamsType = None,\n        **X: Unpack[_t.GetKwargs],\n    ) -> Response:\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary, list of tuples or bytes to send\n            in the query string for the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        X.setdefault(\"allow_redirects\", True)\n        return self.b(\"GET\", V, params=W, **X)\n\n    def d(self, Y: _t.UriType, **Z: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        Z.setdefault(\"allow_redirects\", True)\n        return self.b(\"OPTIONS\", Y, **Z)\n\n    def e(self, aa: _t.UriType, **ab: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        ab.setdefault(\"allow_redirects\", False)\n        return self.b(\"HEAD\", aa, **ab)\n\n    def f(\n        self,\n        ac: _t.UriType,\n        ad: _t.DataType = None,\n        ae: _t.JsonType = None,\n        **af: Unpack[_t.PostKwargs],\n    ) -> Response:\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.b(\"POST\", ac, data=ad, json=ae, **af)\n\n    def g(\n        self, ag: _t.UriType, ah: _t.DataType = None, **ai: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.b(\"PUT\", ag, data=ah, **ai)\n\n    def h(\n        self, aj: _t.UriType, ak: _t.DataType = None, **al: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.b(\"PATCH\", aj, data=ak, **al)\n\n    def i(self, am: _t.UriType, **an: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.b(\"DELETE\", am, **an)\n\n    def j(self, ao: PreparedRequest, **ap: Any) -> Response:\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        ap.setdefault(\"stream\", self.stream)\n        ap.setdefault(\"verify\", self.verify)\n        ap.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in ap:\n            ap[\"proxies\"] = resolve_proxies(ao, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if isinstance(ao, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        assert _is_prepared(ao)\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        aq = ap.pop(\"allow_redirects\", True)\n        ar = ap.get(\"stream\")\n        at = ao.hooks\n\n        # Get the appropriate adapter to use\n        au = self.m(url=ao.url)\n\n        # Start time (approximately) of the request\n        av = preferred_clock()\n\n        # Send the request\n        aw = au.send(ao, **ap)\n\n        # Total elapsed time of the request (approximately)\n        ax = preferred_clock() - av\n        aw.elapsed = timedelta(seconds=ax)\n\n        # Response manipulation hooks\n        aw = dispatch_hook(\"response\", at, aw, **ap)\n\n        # Persist cookies\n        if aw.history:\n            # If the hooks create history then we want those cookies too\n            for ay in aw.history:\n                extract_cookies_to_jar(self.cookies, ay.request, ay.raw)\n\n        extract_cookies_to_jar(self.cookies, ao, aw.raw)\n\n        # Resolve redirects if allowed.\n        if aq:\n            # Redirect resolving generator.\n            az = self.resolve_redirects(aw, ao, **ap)\n            aA = [ay for ay in az]\n        else:\n            aA = []\n\n        # Shuffle things around if there's history.\n        if aA:\n            # Insert the first (original) request at the start\n            aA.insert(0, aw)\n            # Get the last request made\n            aw = aA.pop()\n            aw.history = aA\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not aq:\n            try:\n                aw._next = next(  # type: ignore[assignment]  # yield_requests=True returns PreparedRequest\n                    self.resolve_redirects(aw, ao, yield_requests=True, **ap)\n                )\n            except StopIteration:\n                pass\n\n        if not ar:\n            aw.content\n\n        return aw\n\n    def l(\n        self,\n        aB: str,\n        aC: dict[str, str] | None,\n        aD: bool | None,\n        aE: _t.VerifyType | None,\n        aF: _t.CertType,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Check the environment and merge it with some settings.\n\n        :rtype: dict\n        \"\"\"\n        # Gather clues from the surrounding environment.\n        if self.trust_env:\n            # Set environment's proxies.\n            aG = aC.get(\"no_proxy\") if aC is not None else None\n            aH = get_environ_proxies(aB, no_proxy=aG)\n            if aC is not None:\n                for aI, aJ in aH.items():\n                    aC.setdefault(aI, aJ)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if aE is True or aE is None:\n                aE = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or aE\n                )\n\n        # Merge all the kwargs.\n        aC = merge_setting(aC, self.proxies)\n        aD = merge_setting(aD, self.stream)\n        aE = merge_setting(aE, self.verify)\n        aF = merge_setting(aF, self.cert)\n\n        return {\"proxies\": aC, \"stream\": aD, \"verify\": aE, \"cert\": aF}\n\n    def m(self, aK: str) -> BaseAdapter:\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        for aL, aM in self.adapters.items():\n            if aK.lower().startswith(aL.lower()):\n                return aM\n\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {aK!r}\")\n\n    def n(self) -> None:\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        for aN in self.adapters.values():\n            aN.close()\n\n    def o(self, aO: str, aP: BaseAdapter) -> None:\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        self.adapters[aO] = aP\n        aQ = [aR for aR in self.adapters if len(aR) < len(aO)]\n\n        for aS in aQ:\n            self.adapters[aS] = self.adapters.pop(aS)\n\n    def __getstate__(self) -> dict[str, Any]:\n        aT = {aU: getattr(self, aU, None) for aU in self.__attrs__}\n        return aT\n\n    def __setstate__(self, aV: dict[str, Any]) -> None:\n        for aW, aX in aV.items():\n            setattr(self, aW, aX)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-e8728b6a59c05261", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "092989f5840c7805bdc130ab5bee2542681fac380621779a95b3aa6b5f27a3de", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 559, "local_path": "identifiers/garble-identifiers/I04__requests__Session__18bf1735.py", "order": 4, "original_content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "parent_variant_id": "pyint-d802e4513ae9-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L395-L905", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 280, "identifiers_declared": 97}, "unit_kind": "class", "unit_name": "Session", "variant_id": "pyint-192318bf1735-I04", "group_id": "py-e8728b6a59c05261", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 789, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b0f12e90c778-I05", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n\n    headers: CaseInsensitiveDict[str]\n    auth: _t.AuthType\n    proxies: dict[str, str]\n    hooks: dict[str, list[_t.HookType]]\n    params: MutableMapping[str, Any]\n    stream: bool\n    verify: _t.VerifyType\n    cert: _t.CertType\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n    adapters: MutableMapping[str, BaseAdapter]\n\n    __attrs__: list[str] = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self) -> None:\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        self.headers = default_headers()\n\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        #: If verify is set to a string, it must be the path to a CA bundle file\n        #: that will be used to verify the TLS certificate.\n        self.verify = True\n\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.mount(\"https://\", HTTPAdapter())\n        self.mount(\"http://\", HTTPAdapter())\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def prepare_request(self, request: Request) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        url = cast(\"_t.UriType\", request.url)\n        method = cast(str, request.method)\n\n        cookies = request.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not isinstance(cookies, cookielib.CookieJar):\n            cookies = cookiejar_from_dict(cookies)\n\n        # Merge with session cookies\n        merged_cookies = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), cookies\n        )\n\n        # Set environment's basic authentication if not explicitly set.\n        auth = request.auth\n        if self.trust_env and not auth and not self.auth:\n            auth = get_netrc_auth(url)\n\n        p = PreparedRequest()\n        p.prepare(\n            method=method.upper(),\n            url=url,\n            files=request.files,\n            data=request.data,\n            json=request.json,\n            headers=merge_setting(\n                request.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(request.params, self.params),\n            auth=merge_setting(auth, self.auth),\n            cookies=merged_cookies,\n            hooks=merge_hooks(request.hooks, self.hooks),\n        )\n        return p\n\n    def request(\n        self,\n        method: str,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        data: _t.DataType = None,\n        headers: _t.HeadersType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        files: _t.FilesType = None,\n        auth: _t.AuthType = None,\n        timeout: _t.TimeoutType = None,\n        allow_redirects: bool = True,\n        proxies: dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        stream: bool | None = None,\n        verify: _t.VerifyType | None = None,\n        cert: _t.CertType = None,\n        json: _t.JsonType = None,\n    ) -> Response:\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How many seconds to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param hooks: (optional) Dictionary mapping hook name to one event or\n            list of events, event must be callable.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        if isinstance(url, bytes):\n            url = url.decode(\"utf-8\")\n\n        # Create the Request.\n        req = Request(\n            method=method.upper(),\n            url=url,\n            headers=headers,\n            files=files,\n            data=data or {},\n            json=json,\n            params=params or {},\n            auth=auth,\n            cookies=cookies,\n            hooks=hooks,\n        )\n        prep = self.prepare_request(req)\n\n        assert _is_prepared(prep)\n\n        proxies = proxies or {}\n\n        settings = self.merge_environment_settings(\n            prep.url, proxies, stream, verify, cert\n        )\n\n        # Send the request.\n        send_kwargs = {\n            \"timeout\": timeout,\n            \"allow_redirects\": allow_redirects,\n        }\n        send_kwargs.update(settings)\n        resp = self.send(prep, **send_kwargs)\n\n        return resp\n\n    def get(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        **kwargs: Unpack[_t.GetKwargs],\n    ) -> Response:\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary, list of tuples or bytes to send\n            in the query string for the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"GET\", url, params=params, **kwargs)\n\n    def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"OPTIONS\", url, **kwargs)\n\n    def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", False)\n        return self.request(\"HEAD\", url, **kwargs)\n\n    def post(\n        self,\n        url: _t.UriType,\n        data: _t.DataType = None,\n        json: _t.JsonType = None,\n        **kwargs: Unpack[_t.PostKwargs],\n    ) -> Response:\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"POST\", url, data=data, json=json, **kwargs)\n\n    def put(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PUT\", url, data=data, **kwargs)\n\n    def patch(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PATCH\", url, data=data, **kwargs)\n\n    def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"DELETE\", url, **kwargs)\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response:\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        kwargs.setdefault(\"stream\", self.stream)\n        kwargs.setdefault(\"verify\", self.verify)\n        kwargs.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in kwargs:\n            kwargs[\"proxies\"] = resolve_proxies(request, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if isinstance(request, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        assert _is_prepared(request)\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        allow_redirects = kwargs.pop(\"allow_redirects\", True)\n        stream = kwargs.get(\"stream\")\n        hooks = request.hooks\n\n        # Get the appropriate adapter to use\n        adapter = self.get_adapter(url=request.url)\n\n        # Start time (approximately) of the request\n        start = preferred_clock()\n\n        # Send the request\n        r = adapter.send(request, **kwargs)\n\n        # Total elapsed time of the request (approximately)\n        elapsed = preferred_clock() - start\n        r.elapsed = timedelta(seconds=elapsed)\n\n        # Response manipulation hooks\n        r = dispatch_hook(\"response\", hooks, r, **kwargs)\n\n        # Persist cookies\n        if r.history:\n            # If the hooks create history then we want those cookies too\n            for resp in r.history:\n                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)\n\n        extract_cookies_to_jar(self.cookies, request, r.raw)\n\n        # Resolve redirects if allowed.\n        if allow_redirects:\n            # Redirect resolving generator.\n            gen = self.resolve_redirects(r, request, **kwargs)\n            history = [resp for resp in gen]\n        else:\n            history = []\n\n        # Shuffle things around if there's history.\n        if history:\n            # Insert the first (original) request at the start\n            history.insert(0x0, r)\n            # Get the last request made\n            r = history.pop()\n            r.history = history\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not allow_redirects:\n            try:\n                r._next = next(  # type: ignore[assignment]  # yield_requests=True returns PreparedRequest\n                    self.resolve_redirects(r, request, yield_requests=True, **kwargs)\n                )\n            except StopIteration:\n                pass\n\n        if not stream:\n            r.content\n\n        return r\n\n    def merge_environment_settings(\n        self,\n        url: str,\n        proxies: dict[str, str] | None,\n        stream: bool | None,\n        verify: _t.VerifyType | None,\n        cert: _t.CertType,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Check the environment and merge it with some settings.\n\n        :rtype: dict\n        \"\"\"\n        # Gather clues from the surrounding environment.\n        if self.trust_env:\n            # Set environment's proxies.\n            no_proxy = proxies.get(\"no_proxy\") if proxies is not None else None\n            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n            if proxies is not None:\n                for k, v in env_proxies.items():\n                    proxies.setdefault(k, v)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if verify is True or verify is None:\n                verify = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or verify\n                )\n\n        # Merge all the kwargs.\n        proxies = merge_setting(proxies, self.proxies)\n        stream = merge_setting(stream, self.stream)\n        verify = merge_setting(verify, self.verify)\n        cert = merge_setting(cert, self.cert)\n\n        return {\"proxies\": proxies, \"stream\": stream, \"verify\": verify, \"cert\": cert}\n\n    def get_adapter(self, url: str) -> BaseAdapter:\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        for prefix, adapter in self.adapters.items():\n            if url.lower().startswith(prefix.lower()):\n                return adapter\n\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {url!r}\")\n\n    def close(self) -> None:\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        for v in self.adapters.values():\n            v.close()\n\n    def mount(self, prefix: str, adapter: BaseAdapter) -> None:\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        self.adapters[prefix] = adapter\n        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n        for key in keys_to_move:\n            self.adapters[key] = self.adapters.pop(key)\n\n    def __getstate__(self) -> dict[str, Any]:\n        state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for attr, value in state.items():\n            setattr(self, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-e8728b6a59c05261", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "34fff11afdac982211e2407d6dd25584d1a844428757789c0f2cc50c2733fd0b", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 559, "local_path": "expressions/encode-integer-literals/I05__requests__Session__2e90c778.py", "order": 5, "original_content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "parent_variant_id": "pyint-d802e4513ae9-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L395-L905", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 1}, "unit_kind": "class", "unit_name": "Session", "variant_id": "pyint-b0f12e90c778-I05", "group_id": "py-e8728b6a59c05261", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 790, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cb5f5f5c4650-I06", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n\n    headers: CaseInsensitiveDict[str]\n    auth: _t.AuthType\n    proxies: dict[str, str]\n    hooks: dict[str, list[_t.HookType]]\n    params: MutableMapping[str, Any]\n    stream: bool\n    verify: _t.VerifyType\n    cert: _t.CertType\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n    adapters: MutableMapping[str, BaseAdapter]\n\n    __attrs__: list[str] = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self) -> None:\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        self.headers = default_headers()\n\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        #: If verify is set to a string, it must be the path to a CA bundle file\n        #: that will be used to verify the TLS certificate.\n        self.verify = True\n\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.mount(\"https://\", HTTPAdapter())\n        self.mount(\"http://\", HTTPAdapter())\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def prepare_request(self, request: Request) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        url = cast(\"_t.UriType\", request.url)\n        method = cast(str, request.method)\n\n        cookies = request.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not (not isinstance(cookies, cookielib.CookieJar)):\n            pass\n        else:\n            cookies = cookiejar_from_dict(cookies)\n\n        # Merge with session cookies\n        merged_cookies = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), cookies\n        )\n\n        # Set environment's basic authentication if not explicitly set.\n        auth = request.auth\n        if not (self.trust_env and not auth and not self.auth):\n            pass\n        else:\n            auth = get_netrc_auth(url)\n\n        p = PreparedRequest()\n        p.prepare(\n            method=method.upper(),\n            url=url,\n            files=request.files,\n            data=request.data,\n            json=request.json,\n            headers=merge_setting(\n                request.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(request.params, self.params),\n            auth=merge_setting(auth, self.auth),\n            cookies=merged_cookies,\n            hooks=merge_hooks(request.hooks, self.hooks),\n        )\n        return p\n\n    def request(\n        self,\n        method: str,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        data: _t.DataType = None,\n        headers: _t.HeadersType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        files: _t.FilesType = None,\n        auth: _t.AuthType = None,\n        timeout: _t.TimeoutType = None,\n        allow_redirects: bool = True,\n        proxies: dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        stream: bool | None = None,\n        verify: _t.VerifyType | None = None,\n        cert: _t.CertType = None,\n        json: _t.JsonType = None,\n    ) -> Response:\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How many seconds to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param hooks: (optional) Dictionary mapping hook name to one event or\n            list of events, event must be callable.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        if not (isinstance(url, bytes)):\n            pass\n        else:\n            url = url.decode(\"utf-8\")\n\n        # Create the Request.\n        req = Request(\n            method=method.upper(),\n            url=url,\n            headers=headers,\n            files=files,\n            data=data or {},\n            json=json,\n            params=params or {},\n            auth=auth,\n            cookies=cookies,\n            hooks=hooks,\n        )\n        prep = self.prepare_request(req)\n\n        assert _is_prepared(prep)\n\n        proxies = proxies or {}\n\n        settings = self.merge_environment_settings(\n            prep.url, proxies, stream, verify, cert\n        )\n\n        # Send the request.\n        send_kwargs = {\n            \"timeout\": timeout,\n            \"allow_redirects\": allow_redirects,\n        }\n        send_kwargs.update(settings)\n        resp = self.send(prep, **send_kwargs)\n\n        return resp\n\n    def get(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        **kwargs: Unpack[_t.GetKwargs],\n    ) -> Response:\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary, list of tuples or bytes to send\n            in the query string for the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"GET\", url, params=params, **kwargs)\n\n    def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"OPTIONS\", url, **kwargs)\n\n    def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", False)\n        return self.request(\"HEAD\", url, **kwargs)\n\n    def post(\n        self,\n        url: _t.UriType,\n        data: _t.DataType = None,\n        json: _t.JsonType = None,\n        **kwargs: Unpack[_t.PostKwargs],\n    ) -> Response:\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"POST\", url, data=data, json=json, **kwargs)\n\n    def put(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PUT\", url, data=data, **kwargs)\n\n    def patch(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PATCH\", url, data=data, **kwargs)\n\n    def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"DELETE\", url, **kwargs)\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response:\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        kwargs.setdefault(\"stream\", self.stream)\n        kwargs.setdefault(\"verify\", self.verify)\n        kwargs.setdefault(\"cert\", self.cert)\n        if not (\"proxies\" not in kwargs):\n            pass\n        else:\n            kwargs[\"proxies\"] = resolve_proxies(request, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if not (isinstance(request, Request)):\n            pass\n        else:\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        assert _is_prepared(request)\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        allow_redirects = kwargs.pop(\"allow_redirects\", True)\n        stream = kwargs.get(\"stream\")\n        hooks = request.hooks\n\n        # Get the appropriate adapter to use\n        adapter = self.get_adapter(url=request.url)\n\n        # Start time (approximately) of the request\n        start = preferred_clock()\n\n        # Send the request\n        r = adapter.send(request, **kwargs)\n\n        # Total elapsed time of the request (approximately)\n        elapsed = preferred_clock() - start\n        r.elapsed = timedelta(seconds=elapsed)\n\n        # Response manipulation hooks\n        r = dispatch_hook(\"response\", hooks, r, **kwargs)\n\n        # Persist cookies\n        if not (r.history):\n            pass\n        else:\n            # If the hooks create history then we want those cookies too\n            for resp in r.history:\n                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)\n\n        extract_cookies_to_jar(self.cookies, request, r.raw)\n\n        # Resolve redirects if allowed.\n        if not (allow_redirects):\n            history = []\n        else:\n            # Redirect resolving generator.\n            gen = self.resolve_redirects(r, request, **kwargs)\n            history = [resp for resp in gen]\n\n        # Shuffle things around if there's history.\n        if not (history):\n            pass\n        else:\n            # Insert the first (original) request at the start\n            history.insert(0, r)\n            # Get the last request made\n            r = history.pop()\n            r.history = history\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not (not allow_redirects):\n            pass\n        else:\n            try:\n                r._next = next(  # type: ignore[assignment]  # yield_requests=True returns PreparedRequest\n                    self.resolve_redirects(r, request, yield_requests=True, **kwargs)\n                )\n            except StopIteration:\n                pass\n\n        if not (not stream):\n            pass\n        else:\n            r.content\n\n        return r\n\n    def merge_environment_settings(\n        self,\n        url: str,\n        proxies: dict[str, str] | None,\n        stream: bool | None,\n        verify: _t.VerifyType | None,\n        cert: _t.CertType,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Check the environment and merge it with some settings.\n\n        :rtype: dict\n        \"\"\"\n        # Gather clues from the surrounding environment.\n        if not (self.trust_env):\n            pass\n        else:\n            # Set environment's proxies.\n            no_proxy = proxies.get(\"no_proxy\") if proxies is not None else None\n            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n            if proxies is not None:\n                for k, v in env_proxies.items():\n                    proxies.setdefault(k, v)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if verify is True or verify is None:\n                verify = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or verify\n                )\n\n        # Merge all the kwargs.\n        proxies = merge_setting(proxies, self.proxies)\n        stream = merge_setting(stream, self.stream)\n        verify = merge_setting(verify, self.verify)\n        cert = merge_setting(cert, self.cert)\n\n        return {\"proxies\": proxies, \"stream\": stream, \"verify\": verify, \"cert\": cert}\n\n    def get_adapter(self, url: str) -> BaseAdapter:\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        for prefix, adapter in self.adapters.items():\n            if not (url.lower().startswith(prefix.lower())):\n                pass\n            else:\n                return adapter\n\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {url!r}\")\n\n    def close(self) -> None:\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        for v in self.adapters.values():\n            v.close()\n\n    def mount(self, prefix: str, adapter: BaseAdapter) -> None:\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        self.adapters[prefix] = adapter\n        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n        for key in keys_to_move:\n            self.adapters[key] = self.adapters.pop(key)\n\n    def __getstate__(self) -> dict[str, Any]:\n        state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for attr, value in state.items():\n            setattr(self, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-e8728b6a59c05261", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "c7dc133d08d860b8dda5244e2c2f5dce765f12df067b2d508affe74709fea783", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 581, "local_path": "expressions/invert-conditions/I06__requests__Session__5f5c4650.py", "order": 6, "original_content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "parent_variant_id": "pyint-d802e4513ae9-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L395-L905", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 12}, "unit_kind": "class", "unit_name": "Session", "variant_id": "pyint-cb5f5f5c4650-I06", "group_id": "py-e8728b6a59c05261", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 791, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ac76d5572bd8-I07", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n\n    headers: CaseInsensitiveDict[str]\n    auth: _t.AuthType\n    proxies: dict[str, str]\n    hooks: dict[str, list[_t.HookType]]\n    params: MutableMapping[str, Any]\n    stream: bool\n    verify: _t.VerifyType\n    cert: _t.CertType\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n    adapters: MutableMapping[str, BaseAdapter]\n\n    __attrs__: list[str] = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self) -> None:\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        if ((0xf87f ^ 0xf87f) != 0):\n            raise AssertionError()\n        self.headers = default_headers()\n\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        #: If verify is set to a string, it must be the path to a CA bundle file\n        #: that will be used to verify the TLS certificate.\n        self.verify = True\n\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.mount(\"https://\", HTTPAdapter())\n        self.mount(\"http://\", HTTPAdapter())\n\n    def __enter__(self) -> Self:\n        if ((0x37a3 ^ 0x37a3) != 0):\n            raise AssertionError()\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        if ((0xa8 ^ 0xa8) != 0):\n            raise AssertionError()\n        self.close()\n\n    def prepare_request(self, request: Request) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        if ((0x4c9a ^ 0x4c9a) != 0):\n            raise AssertionError()\n        url = cast(\"_t.UriType\", request.url)\n        method = cast(str, request.method)\n\n        cookies = request.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not isinstance(cookies, cookielib.CookieJar):\n            cookies = cookiejar_from_dict(cookies)\n\n        # Merge with session cookies\n        merged_cookies = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), cookies\n        )\n\n        # Set environment's basic authentication if not explicitly set.\n        auth = request.auth\n        if self.trust_env and not auth and not self.auth:\n            auth = get_netrc_auth(url)\n\n        p = PreparedRequest()\n        p.prepare(\n            method=method.upper(),\n            url=url,\n            files=request.files,\n            data=request.data,\n            json=request.json,\n            headers=merge_setting(\n                request.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(request.params, self.params),\n            auth=merge_setting(auth, self.auth),\n            cookies=merged_cookies,\n            hooks=merge_hooks(request.hooks, self.hooks),\n        )\n        return p\n\n    def request(\n        self,\n        method: str,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        data: _t.DataType = None,\n        headers: _t.HeadersType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        files: _t.FilesType = None,\n        auth: _t.AuthType = None,\n        timeout: _t.TimeoutType = None,\n        allow_redirects: bool = True,\n        proxies: dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        stream: bool | None = None,\n        verify: _t.VerifyType | None = None,\n        cert: _t.CertType = None,\n        json: _t.JsonType = None,\n    ) -> Response:\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How many seconds to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param hooks: (optional) Dictionary mapping hook name to one event or\n            list of events, event must be callable.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        if ((0xb6 ^ 0xb6) != 0):\n            raise AssertionError()\n        if isinstance(url, bytes):\n            url = url.decode(\"utf-8\")\n\n        # Create the Request.\n        req = Request(\n            method=method.upper(),\n            url=url,\n            headers=headers,\n            files=files,\n            data=data or {},\n            json=json,\n            params=params or {},\n            auth=auth,\n            cookies=cookies,\n            hooks=hooks,\n        )\n        prep = self.prepare_request(req)\n\n        assert _is_prepared(prep)\n\n        proxies = proxies or {}\n\n        settings = self.merge_environment_settings(\n            prep.url, proxies, stream, verify, cert\n        )\n\n        # Send the request.\n        send_kwargs = {\n            \"timeout\": timeout,\n            \"allow_redirects\": allow_redirects,\n        }\n        send_kwargs.update(settings)\n        resp = self.send(prep, **send_kwargs)\n\n        return resp\n\n    def get(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        **kwargs: Unpack[_t.GetKwargs],\n    ) -> Response:\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary, list of tuples or bytes to send\n            in the query string for the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n        if ((0x67c4 ^ 0x67c4) != 0):\n            raise AssertionError()\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"GET\", url, params=params, **kwargs)\n\n    def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n        if ((0x673f ^ 0x673f) != 0):\n            raise AssertionError()\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"OPTIONS\", url, **kwargs)\n\n    def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n        if ((0x74df ^ 0x74df) != 0):\n            raise AssertionError()\n\n        kwargs.setdefault(\"allow_redirects\", False)\n        return self.request(\"HEAD\", url, **kwargs)\n\n    def post(\n        self,\n        url: _t.UriType,\n        data: _t.DataType = None,\n        json: _t.JsonType = None,\n        **kwargs: Unpack[_t.PostKwargs],\n    ) -> Response:\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n        if ((0x8c4a ^ 0x8c4a) != 0):\n            raise AssertionError()\n\n        return self.request(\"POST\", url, data=data, json=json, **kwargs)\n\n    def put(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n        if ((0x2d29 ^ 0x2d29) != 0):\n            raise AssertionError()\n\n        return self.request(\"PUT\", url, data=data, **kwargs)\n\n    def patch(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n        if ((0xb296 ^ 0xb296) != 0):\n            raise AssertionError()\n\n        return self.request(\"PATCH\", url, data=data, **kwargs)\n\n    def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n        if ((0x985e ^ 0x985e) != 0):\n            raise AssertionError()\n\n        return self.request(\"DELETE\", url, **kwargs)\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response:\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        if ((0xde ^ 0xde) != 0):\n            raise AssertionError()\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        kwargs.setdefault(\"stream\", self.stream)\n        kwargs.setdefault(\"verify\", self.verify)\n        kwargs.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in kwargs:\n            kwargs[\"proxies\"] = resolve_proxies(request, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if isinstance(request, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        assert _is_prepared(request)\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        allow_redirects = kwargs.pop(\"allow_redirects\", True)\n        stream = kwargs.get(\"stream\")\n        hooks = request.hooks\n\n        # Get the appropriate adapter to use\n        adapter = self.get_adapter(url=request.url)\n\n        # Start time (approximately) of the request\n        start = preferred_clock()\n\n        # Send the request\n        r = adapter.send(request, **kwargs)\n\n        # Total elapsed time of the request (approximately)\n        elapsed = preferred_clock() - start\n        r.elapsed = timedelta(seconds=elapsed)\n\n        # Response manipulation hooks\n        r = dispatch_hook(\"response\", hooks, r, **kwargs)\n\n        # Persist cookies\n        if r.history:\n            # If the hooks create history then we want those cookies too\n            for resp in r.history:\n                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)\n\n        extract_cookies_to_jar(self.cookies, request, r.raw)\n\n        # Resolve redirects if allowed.\n        if allow_redirects:\n            # Redirect resolving generator.\n            gen = self.resolve_redirects(r, request, **kwargs)\n            history = [resp for resp in gen]\n        else:\n            history = []\n\n        # Shuffle things around if there's history.\n        if history:\n            # Insert the first (original) request at the start\n            history.insert(0, r)\n            # Get the last request made\n            r = history.pop()\n            r.history = history\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not allow_redirects:\n            try:\n                r._next = next(  # type: ignore[assignment]  # yield_requests=True returns PreparedRequest\n                    self.resolve_redirects(r, request, yield_requests=True, **kwargs)\n                )\n            except StopIteration:\n                pass\n\n        if not stream:\n            r.content\n\n        return r\n\n    def merge_environment_settings(\n        self,\n        url: str,\n        proxies: dict[str, str] | None,\n        stream: bool | None,\n        verify: _t.VerifyType | None,\n        cert: _t.CertType,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Check the environment and merge it with some settings.\n\n        :rtype: dict\n        \"\"\"\n        if ((0xe238 ^ 0xe238) != 0):\n            raise AssertionError()\n        # Gather clues from the surrounding environment.\n        if self.trust_env:\n            # Set environment's proxies.\n            no_proxy = proxies.get(\"no_proxy\") if proxies is not None else None\n            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n            if proxies is not None:\n                for k, v in env_proxies.items():\n                    proxies.setdefault(k, v)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if verify is True or verify is None:\n                verify = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or verify\n                )\n\n        # Merge all the kwargs.\n        proxies = merge_setting(proxies, self.proxies)\n        stream = merge_setting(stream, self.stream)\n        verify = merge_setting(verify, self.verify)\n        cert = merge_setting(cert, self.cert)\n\n        return {\"proxies\": proxies, \"stream\": stream, \"verify\": verify, \"cert\": cert}\n\n    def get_adapter(self, url: str) -> BaseAdapter:\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        if ((0x491d ^ 0x491d) != 0):\n            raise AssertionError()\n        for prefix, adapter in self.adapters.items():\n            if url.lower().startswith(prefix.lower()):\n                return adapter\n\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {url!r}\")\n\n    def close(self) -> None:\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        if ((0xb55b ^ 0xb55b) != 0):\n            raise AssertionError()\n        for v in self.adapters.values():\n            v.close()\n\n    def mount(self, prefix: str, adapter: BaseAdapter) -> None:\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        if ((0xb5a2 ^ 0xb5a2) != 0):\n            raise AssertionError()\n        self.adapters[prefix] = adapter\n        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n        for key in keys_to_move:\n            self.adapters[key] = self.adapters.pop(key)\n\n    def __getstate__(self) -> dict[str, Any]:\n        if ((0xa185 ^ 0xa185) != 0):\n            raise AssertionError()\n        state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        if ((0x9e3d ^ 0x9e3d) != 0):\n            raise AssertionError()\n        for attr, value in state.items():\n            setattr(self, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-e8728b6a59c05261", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "b5c9264032f88607cc9170778b9a56474ede883a658ebedcf1d166b48bb56f62", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 597, "local_path": "code-injection/insert-dead-branches/I07__requests__Session__d5572bd8.py", "order": 7, "original_content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "parent_variant_id": "pyint-d802e4513ae9-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L395-L905", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 19}, "unit_kind": "class", "unit_name": "Session", "variant_id": "pyint-ac76d5572bd8-I07", "group_id": "py-e8728b6a59c05261", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 792, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f6a4bb317fa4-I08", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n\n    headers: CaseInsensitiveDict[str]\n    auth: _t.AuthType\n    proxies: dict[str, str]\n    hooks: dict[str, list[_t.HookType]]\n    params: MutableMapping[str, Any]\n    stream: bool\n    verify: _t.VerifyType\n    cert: _t.CertType\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n    adapters: MutableMapping[str, BaseAdapter]\n\n    __attrs__: list[str] = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self) -> None:\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        self.headers = default_headers()\n\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        #: If verify is set to a string, it must be the path to a CA bundle file\n        #: that will be used to verify the TLS certificate.\n        self.verify = True\n\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.mount(\"https://\", HTTPAdapter())\n        self.mount(\"http://\", HTTPAdapter())\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def prepare_request(self, request: Request) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        url = cast(\"_t.UriType\", request.url)\n        method = cast(str, request.method)\n\n        cookies = request.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not isinstance(cookies, cookielib.CookieJar):\n            cookies = cookiejar_from_dict(cookies)\n\n        # Merge with session cookies\n        merged_cookies = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), cookies\n        )\n\n        # Set environment's basic authentication if not explicitly set.\n        auth = request.auth\n        if self.trust_env and not auth and not self.auth:\n            auth = get_netrc_auth(url)\n\n        p = PreparedRequest()\n        p.prepare(\n            method=method.upper(),\n            url=url,\n            files=request.files,\n            data=request.data,\n            json=request.json,\n            headers=merge_setting(\n                request.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(request.params, self.params),\n            auth=merge_setting(auth, self.auth),\n            cookies=merged_cookies,\n            hooks=merge_hooks(request.hooks, self.hooks),\n        )\n        return p\n\n    def request(\n        self,\n        method: str,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        data: _t.DataType = None,\n        headers: _t.HeadersType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        files: _t.FilesType = None,\n        auth: _t.AuthType = None,\n        timeout: _t.TimeoutType = None,\n        allow_redirects: bool = True,\n        proxies: dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        stream: bool | None = None,\n        verify: _t.VerifyType | None = None,\n        cert: _t.CertType = None,\n        json: _t.JsonType = None,\n    ) -> Response:\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How many seconds to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param hooks: (optional) Dictionary mapping hook name to one event or\n            list of events, event must be callable.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        if isinstance(url, bytes):\n            url = url.decode(\"utf-8\")\n\n        # Create the Request.\n        req = Request(\n            method=method.upper(),\n            url=url,\n            headers=headers,\n            files=files,\n            data=data or {},\n            json=json,\n            params=params or {},\n            auth=auth,\n            cookies=cookies,\n            hooks=hooks,\n        )\n        prep = self.prepare_request(req)\n\n        assert _is_prepared(prep)\n\n        proxies = proxies or {}\n\n        settings = self.merge_environment_settings(\n            prep.url, proxies, stream, verify, cert\n        )\n\n        # Send the request.\n        send_kwargs = {\n            \"timeout\": timeout,\n            \"allow_redirects\": allow_redirects,\n        }\n        send_kwargs.update(settings)\n        resp = self.send(prep, **send_kwargs)\n\n        return resp\n\n    def get(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        **kwargs: Unpack[_t.GetKwargs],\n    ) -> Response:\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary, list of tuples or bytes to send\n            in the query string for the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"GET\", url, params=params, **kwargs)\n\n    def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"OPTIONS\", url, **kwargs)\n\n    def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", False)\n        return self.request(\"HEAD\", url, **kwargs)\n\n    def post(\n        self,\n        url: _t.UriType,\n        data: _t.DataType = None,\n        json: _t.JsonType = None,\n        **kwargs: Unpack[_t.PostKwargs],\n    ) -> Response:\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"POST\", url, data=data, json=json, **kwargs)\n\n    def put(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n        feature_enabled = False\n        for toggle_count in range(3):\n            feature_enabled = not feature_enabled\n\n        return self.request(\"PUT\", url, data=data, **kwargs)\n\n    def patch(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PATCH\", url, data=data, **kwargs)\n\n    def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"DELETE\", url, **kwargs)\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response:\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        kwargs.setdefault(\"stream\", self.stream)\n        kwargs.setdefault(\"verify\", self.verify)\n        kwargs.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in kwargs:\n            kwargs[\"proxies\"] = resolve_proxies(request, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if isinstance(request, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        assert _is_prepared(request)\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        allow_redirects = kwargs.pop(\"allow_redirects\", True)\n        stream = kwargs.get(\"stream\")\n        hooks = request.hooks\n\n        # Get the appropriate adapter to use\n        adapter = self.get_adapter(url=request.url)\n\n        # Start time (approximately) of the request\n        start = preferred_clock()\n\n        # Send the request\n        r = adapter.send(request, **kwargs)\n\n        # Total elapsed time of the request (approximately)\n        elapsed = preferred_clock() - start\n        r.elapsed = timedelta(seconds=elapsed)\n\n        # Response manipulation hooks\n        r = dispatch_hook(\"response\", hooks, r, **kwargs)\n\n        # Persist cookies\n        if r.history:\n            # If the hooks create history then we want those cookies too\n            for resp in r.history:\n                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)\n\n        extract_cookies_to_jar(self.cookies, request, r.raw)\n\n        # Resolve redirects if allowed.\n        if allow_redirects:\n            # Redirect resolving generator.\n            gen = self.resolve_redirects(r, request, **kwargs)\n            history = [resp for resp in gen]\n        else:\n            history = []\n\n        # Shuffle things around if there's history.\n        if history:\n            # Insert the first (original) request at the start\n            history.insert(0, r)\n            # Get the last request made\n            r = history.pop()\n            r.history = history\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not allow_redirects:\n            try:\n                r._next = next(  # type: ignore[assignment]  # yield_requests=True returns PreparedRequest\n                    self.resolve_redirects(r, request, yield_requests=True, **kwargs)\n                )\n            except StopIteration:\n                pass\n\n        if not stream:\n            r.content\n\n        return r\n\n    def merge_environment_settings(\n        self,\n        url: str,\n        proxies: dict[str, str] | None,\n        stream: bool | None,\n        verify: _t.VerifyType | None,\n        cert: _t.CertType,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Check the environment and merge it with some settings.\n\n        :rtype: dict\n        \"\"\"\n        # Gather clues from the surrounding environment.\n        if self.trust_env:\n            # Set environment's proxies.\n            no_proxy = proxies.get(\"no_proxy\") if proxies is not None else None\n            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n            if proxies is not None:\n                for k, v in env_proxies.items():\n                    proxies.setdefault(k, v)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if verify is True or verify is None:\n                verify = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or verify\n                )\n\n        # Merge all the kwargs.\n        proxies = merge_setting(proxies, self.proxies)\n        stream = merge_setting(stream, self.stream)\n        verify = merge_setting(verify, self.verify)\n        cert = merge_setting(cert, self.cert)\n\n        return {\"proxies\": proxies, \"stream\": stream, \"verify\": verify, \"cert\": cert}\n\n    def get_adapter(self, url: str) -> BaseAdapter:\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        for prefix, adapter in self.adapters.items():\n            if url.lower().startswith(prefix.lower()):\n                return adapter\n\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {url!r}\")\n\n    def close(self) -> None:\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        for v in self.adapters.values():\n            v.close()\n\n    def mount(self, prefix: str, adapter: BaseAdapter) -> None:\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        self.adapters[prefix] = adapter\n        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n        for key in keys_to_move:\n            self.adapters[key] = self.adapters.pop(key)\n\n    def __getstate__(self) -> dict[str, Any]:\n        state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for attr, value in state.items():\n            setattr(self, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-e8728b6a59c05261", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "5f4e9e8b3752d3d6b2e06da46f0b64203e1c2bf44d5db4d20cf91c8cc5d8aadc", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 562, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__Session__bb317fa4.py", "order": 8, "original_content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "parent_variant_id": "pyint-d802e4513ae9-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L395-L905", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 7}, "unit_kind": "class", "unit_name": "Session", "variant_id": "pyint-f6a4bb317fa4-I08", "group_id": "py-e8728b6a59c05261", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 793, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0a249f7dbe34-I09", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n\n    headers: CaseInsensitiveDict[str]\n    auth: _t.AuthType\n    proxies: dict[str, str]\n    hooks: dict[str, list[_t.HookType]]\n    params: MutableMapping[str, Any]\n    stream: bool\n    verify: _t.VerifyType\n    cert: _t.CertType\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n    adapters: MutableMapping[str, BaseAdapter]\n\n    __attrs__: list[str] = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self) -> None:\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        self.headers = default_headers()\n\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        #: If verify is set to a string, it must be the path to a CA bundle file\n        #: that will be used to verify the TLS certificate.\n        self.verify = True\n\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.mount(\"https://\", HTTPAdapter())\n        self.mount(\"http://\", HTTPAdapter())\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def prepare_request(self, request: Request) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        url = cast(\"_t.UriType\", request.url)\n        method = cast(str, request.method)\n\n        cookies = request.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not isinstance(cookies, cookielib.CookieJar):\n            cookies = cookiejar_from_dict(cookies)\n\n        # Merge with session cookies\n        merged_cookies = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), cookies\n        )\n\n        # Set environment's basic authentication if not explicitly set.\n        auth = request.auth\n        if self.trust_env and not auth and not self.auth:\n            auth = get_netrc_auth(url)\n\n        p = PreparedRequest()\n        p.prepare(\n            method=method.upper(),\n            url=url,\n            files=request.files,\n            data=request.data,\n            json=request.json,\n            headers=merge_setting(\n                request.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(request.params, self.params),\n            auth=merge_setting(auth, self.auth),\n            cookies=merged_cookies,\n            hooks=merge_hooks(request.hooks, self.hooks),\n        )\n        return p\n\n    def request(\n        self,\n        method: str,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        data: _t.DataType = None,\n        headers: _t.HeadersType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        files: _t.FilesType = None,\n        auth: _t.AuthType = None,\n        timeout: _t.TimeoutType = None,\n        allow_redirects: bool = True,\n        proxies: dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        stream: bool | None = None,\n        verify: _t.VerifyType | None = None,\n        cert: _t.CertType = None,\n        json: _t.JsonType = None,\n    ) -> Response:\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How many seconds to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param hooks: (optional) Dictionary mapping hook name to one event or\n            list of events, event must be callable.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        if isinstance(url, bytes):\n            url = url.decode(\"utf-8\")\n\n        # Create the Request.\n        req = Request(\n            method=method.upper(),\n            url=url,\n            headers=headers,\n            files=files,\n            data=data or {},\n            json=json,\n            params=params or {},\n            auth=auth,\n            cookies=cookies,\n            hooks=hooks,\n        )\n        prep = self.prepare_request(req)\n\n        assert _is_prepared(prep)\n\n        proxies = proxies or {}\n\n        settings = self.merge_environment_settings(\n            prep.url, proxies, stream, verify, cert\n        )\n\n        # Send the request.\n        send_kwargs = {\n            \"timeout\": timeout,\n            \"allow_redirects\": allow_redirects,\n        }\n        send_kwargs.update(settings)\n        resp = self.send(prep, **send_kwargs)\n\n        return resp\n\n    def get(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        **kwargs: Unpack[_t.GetKwargs],\n    ) -> Response:\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary, list of tuples or bytes to send\n            in the query string for the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"GET\", url, params=params, **kwargs)\n\n    def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"OPTIONS\", url, **kwargs)\n\n    def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", False)\n        return self.request(\"HEAD\", url, **kwargs)\n\n    def post(\n        self,\n        url: _t.UriType,\n        data: _t.DataType = None,\n        json: _t.JsonType = None,\n        **kwargs: Unpack[_t.PostKwargs],\n    ) -> Response:\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"POST\", url, data=data, json=json, **kwargs)\n\n    def put(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PUT\", url, data=data, **kwargs)\n\n    def patch(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PATCH\", url, data=data, **kwargs)\n\n    def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"DELETE\", url, **kwargs)\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response:\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        kwargs.setdefault(\"stream\", self.stream)\n        kwargs.setdefault(\"verify\", self.verify)\n        kwargs.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in kwargs:\n            kwargs[\"proxies\"] = resolve_proxies(request, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if isinstance(request, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        assert _is_prepared(request)\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        allow_redirects = kwargs.pop(\"allow_redirects\", True)\n        stream = kwargs.get(\"stream\")\n        hooks = request.hooks\n\n        # Get the appropriate adapter to use\n        adapter = self.get_adapter(url=request.url)\n\n        # Start time (approximately) of the request\n        start = preferred_clock()\n\n        # Send the request\n        r = adapter.send(request, **kwargs)\n\n        # Total elapsed time of the request (approximately)\n        elapsed = preferred_clock() - start\n        r.elapsed = timedelta(seconds=elapsed)\n\n        # Response manipulation hooks\n        r = dispatch_hook(\"response\", hooks, r, **kwargs)\n\n        # Persist cookies\n        if r.history:\n            # If the hooks create history then we want those cookies too\n            for resp in r.history:\n                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)\n\n        extract_cookies_to_jar(self.cookies, request, r.raw)\n\n        # Resolve redirects if allowed.\n        if allow_redirects:\n            # Redirect resolving generator.\n            gen = self.resolve_redirects(r, request, **kwargs)\n            history = [resp for resp in gen]\n        else:\n            history = []\n\n        # Shuffle things around if there's history.\n        if history:\n            # Insert the first (original) request at the start\n            history.insert(0, r)\n            # Get the last request made\n            r = history.pop()\n            r.history = history\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not allow_redirects:\n            try:\n                r._next = next(  # type: ignore[assignment]  # yield_requests=True returns PreparedRequest\n                    self.resolve_redirects(r, request, yield_requests=True, **kwargs)\n                )\n            except StopIteration:\n                pass\n\n        if not stream:\n            r.content\n\n        return r\n\n    def merge_environment_settings(\n        self,\n        url: str,\n        proxies: dict[str, str] | None,\n        stream: bool | None,\n        verify: _t.VerifyType | None,\n        cert: _t.CertType,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Check the environment and merge it with some settings.\n\n        :rtype: dict\n        \"\"\"\n        lI0O_7e569ceb = 0x5d15 - 0x5d15\n        lI0O_7e569ceb = (lI0O_7e569ceb | 0) if lI0O_7e569ceb == 0 else (lI0O_7e569ceb & 0)\n        # Gather clues from the surrounding environment.\n        if self.trust_env:\n            # Set environment's proxies.\n            no_proxy = proxies.get(\"no_proxy\") if proxies is not None else None\n            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n            if proxies is not None:\n                for k, v in env_proxies.items():\n                    proxies.setdefault(k, v)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if verify is True or verify is None:\n                verify = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or verify\n                )\n\n        # Merge all the kwargs.\n        proxies = merge_setting(proxies, self.proxies)\n        stream = merge_setting(stream, self.stream)\n        verify = merge_setting(verify, self.verify)\n        cert = merge_setting(cert, self.cert)\n\n        return {\"proxies\": proxies, \"stream\": stream, \"verify\": verify, \"cert\": cert}\n\n    def get_adapter(self, url: str) -> BaseAdapter:\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        for prefix, adapter in self.adapters.items():\n            if url.lower().startswith(prefix.lower()):\n                return adapter\n\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {url!r}\")\n\n    def close(self) -> None:\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        for v in self.adapters.values():\n            v.close()\n\n    def mount(self, prefix: str, adapter: BaseAdapter) -> None:\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        self.adapters[prefix] = adapter\n        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n        for key in keys_to_move:\n            self.adapters[key] = self.adapters.pop(key)\n\n    def __getstate__(self) -> dict[str, Any]:\n        state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for attr, value in state.items():\n            setattr(self, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-e8728b6a59c05261", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "807b4ec719585c5c714cf989614f8dfec67d0cf0a25cc8542a9d81d9ee4b3cbc", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 561, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__Session__9f7dbe34.py", "order": 9, "original_content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "parent_variant_id": "pyint-d802e4513ae9-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L395-L905", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 1}, "unit_kind": "class", "unit_name": "Session", "variant_id": "pyint-0a249f7dbe34-I09", "group_id": "py-e8728b6a59c05261", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 794, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-9cc0e8977431-I10", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (     RequestsCookieJar,     cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (     ChunkedEncodingError,\n    ContentDecodingError,     InvalidSchema,     TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,     PreparedRequest,\n    Request,\n    Response, )\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,     default_headers,     get_auth_from_url,     get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,     resolve_proxies,\n    rewind_body,     should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n    headers: CaseInsensitiveDict[str]\n    auth: _t.AuthType\n    proxies: dict[str, str]\n    hooks: dict[str, list[_t.HookType]]\n    params: MutableMapping[str, Any]\n    stream: bool\n    verify: _t.VerifyType\n    cert: _t.CertType\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n    adapters: MutableMapping[str, BaseAdapter]\n\n    __attrs__: list[str] = [         \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",         \"hooks\",\n        \"params\",\n        \"verify\",         \"cert\",\n        \"adapters\",\n        \"stream\",         \"trust_env\",         \"max_redirects\",     ]\n    def __init__(self) -> None:\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        self.headers = default_headers()\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        #: If verify is set to a string, it must be the path to a CA bundle file\n        #: that will be used to verify the TLS certificate.\n        self.verify = True\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.mount(\"https://\", HTTPAdapter())\n        self.mount(\"http://\", HTTPAdapter())\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n    def prepare_request(self, request: Request) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        url = cast(\"_t.UriType\", request.url)\n        method = cast(str, request.method)\n\n        cookies = request.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not isinstance(cookies, cookielib.CookieJar):\n            cookies = cookiejar_from_dict(cookies)\n\n        # Merge with session cookies\n        merged_cookies = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), cookies\n        )\n\n        # Set environment's basic authentication if not explicitly set.\n        auth = request.auth\n        if self.trust_env and not auth and not self.auth:\n            auth = get_netrc_auth(url)\n\n        p = PreparedRequest()\n        p.prepare(\n            method=method.upper(),\n            url=url,\n            files=request.files,             data=request.data,\n            json=request.json,             headers=merge_setting(\n                request.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(request.params, self.params),             auth=merge_setting(auth, self.auth),\n            cookies=merged_cookies,\n            hooks=merge_hooks(request.hooks, self.hooks),\n        )\n        return p\n    def request(         self,         method: str,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        data: _t.DataType = None,\n        headers: _t.HeadersType = None,         cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        files: _t.FilesType = None,\n        auth: _t.AuthType = None,         timeout: _t.TimeoutType = None,\n        allow_redirects: bool = True,\n        proxies: dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        stream: bool | None = None,\n        verify: _t.VerifyType | None = None,\n        cert: _t.CertType = None,\n        json: _t.JsonType = None,     ) -> Response:\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How many seconds to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param hooks: (optional) Dictionary mapping hook name to one event or\n            list of events, event must be callable.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        if isinstance(url, bytes):\n            url = url.decode(\"utf-8\")\n\n        # Create the Request.\n        req = Request(\n            method=method.upper(),\n            url=url,\n            headers=headers,\n            files=files,\n            data=data or {},\n            json=json,             params=params or {},             auth=auth,\n            cookies=cookies,             hooks=hooks,         )\n        prep = self.prepare_request(req)\n        assert _is_prepared(prep)\n        proxies = proxies or {}\n\n        settings = self.merge_environment_settings(             prep.url, proxies, stream, verify, cert         )\n\n        # Send the request.\n        send_kwargs = {             \"timeout\": timeout,             \"allow_redirects\": allow_redirects,\n        }\n        send_kwargs.update(settings)\n        resp = self.send(prep, **send_kwargs)\n        return resp\n    def get(         self,         url: _t.UriType,\n        params: _t.ParamsType = None,\n        **kwargs: Unpack[_t.GetKwargs],     ) -> Response:\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary, list of tuples or bytes to send\n            in the query string for the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"GET\", url, params=params, **kwargs)\n    def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"OPTIONS\", url, **kwargs)\n\n    def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n        kwargs.setdefault(\"allow_redirects\", False)\n        return self.request(\"HEAD\", url, **kwargs)\n\n    def post(\n        self,         url: _t.UriType,         data: _t.DataType = None,         json: _t.JsonType = None,\n        **kwargs: Unpack[_t.PostKwargs],\n    ) -> Response:\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"POST\", url, data=data, json=json, **kwargs)\n\n    def put(         self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n        return self.request(\"PUT\", url, data=data, **kwargs)\n\n    def patch(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]     ) -> Response:\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n        return self.request(\"PATCH\", url, data=data, **kwargs)\n\n    def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"DELETE\", url, **kwargs)\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response:\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        kwargs.setdefault(\"stream\", self.stream)\n        kwargs.setdefault(\"verify\", self.verify)\n        kwargs.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in kwargs:\n            kwargs[\"proxies\"] = resolve_proxies(request, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if isinstance(request, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        assert _is_prepared(request)\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        allow_redirects = kwargs.pop(\"allow_redirects\", True)\n        stream = kwargs.get(\"stream\")\n        hooks = request.hooks\n        # Get the appropriate adapter to use\n        adapter = self.get_adapter(url=request.url)\n        # Start time (approximately) of the request\n        start = preferred_clock()\n\n        # Send the request\n        r = adapter.send(request, **kwargs)\n        # Total elapsed time of the request (approximately)\n        elapsed = preferred_clock() - start\n        r.elapsed = timedelta(seconds=elapsed)\n        # Response manipulation hooks\n        r = dispatch_hook(\"response\", hooks, r, **kwargs)\n\n        # Persist cookies\n        if r.history:\n            # If the hooks create history then we want those cookies too\n            for resp in r.history:\n                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)\n        extract_cookies_to_jar(self.cookies, request, r.raw)\n\n        # Resolve redirects if allowed.\n        if allow_redirects:\n            # Redirect resolving generator.\n            gen = self.resolve_redirects(r, request, **kwargs)\n            history = [resp for resp in gen]\n        else:\n            history = []\n\n        # Shuffle things around if there's history.\n        if history:\n            # Insert the first (original) request at the start\n            history.insert(0, r)\n            # Get the last request made\n            r = history.pop()\n            r.history = history\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not allow_redirects:\n            try:\n                r._next = next(  # type: ignore[assignment]  # yield_requests=True returns PreparedRequest\n                    self.resolve_redirects(r, request, yield_requests=True, **kwargs)\n                )\n            except StopIteration:\n                pass\n\n        if not stream:\n            r.content\n\n        return r\n\n    def merge_environment_settings(\n        self,\n        url: str,\n        proxies: dict[str, str] | None,         stream: bool | None,         verify: _t.VerifyType | None,\n        cert: _t.CertType,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Check the environment and merge it with some settings.\n        :rtype: dict\n        \"\"\"\n        # Gather clues from the surrounding environment.\n        if self.trust_env:\n            # Set environment's proxies.\n            no_proxy = proxies.get(\"no_proxy\") if proxies is not None else None\n            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n            if proxies is not None:\n                for k, v in env_proxies.items():\n                    proxies.setdefault(k, v)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if verify is True or verify is None:\n                verify = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")                     or verify\n                )\n\n        # Merge all the kwargs.\n        proxies = merge_setting(proxies, self.proxies)\n        stream = merge_setting(stream, self.stream)\n        verify = merge_setting(verify, self.verify)\n        cert = merge_setting(cert, self.cert)\n\n        return {\"proxies\": proxies, \"stream\": stream, \"verify\": verify, \"cert\": cert}\n\n    def get_adapter(self, url: str) -> BaseAdapter:\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        for prefix, adapter in self.adapters.items():\n            if url.lower().startswith(prefix.lower()):\n                return adapter\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {url!r}\")\n\n    def close(self) -> None:\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        for v in self.adapters.values():\n            v.close()\n\n    def mount(self, prefix: str, adapter: BaseAdapter) -> None:\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        self.adapters[prefix] = adapter\n        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n        for key in keys_to_move:\n            self.adapters[key] = self.adapters.pop(key)\n    def __getstate__(self) -> dict[str, Any]:\n        state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n        return state\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for attr, value in state.items():\n            setattr(self, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-e8728b6a59c05261", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "90c3cd4f3cc0ef7f1ca8d09ad33769680ad6fd8374ab0a82981e790173762c55", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 479, "local_path": "layout/partially-compact-layout/I10__requests__Session__e8977431.py", "order": 10, "original_content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "parent_variant_id": "pyint-d802e4513ae9-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L395-L905", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 202, "line_break_groups_removed": 80, "line_breaks_removed": 80, "whitespace_characters_removed": 35}, "unit_kind": "class", "unit_name": "Session", "variant_id": "pyint-9cc0e8977431-I10", "group_id": "py-e8728b6a59c05261", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 795, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1414128f338b-I11", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n\n    headers: CaseInsensitiveDict[str]\n    auth: _t.AuthType\n    proxies: dict[str, str]\n    hooks: dict[str, list[_t.HookType]]\n    params: MutableMapping[str, Any]\n    stream: bool\n    verify: _t.VerifyType\n    cert: _t.CertType\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n    adapters: MutableMapping[str, BaseAdapter]\n\n    __attrs__: list[str] = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self) -> None:\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        self.headers = default_headers()\n\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        #: If verify is set to a string, it must be the path to a CA bundle file\n        #: that will be used to verify the TLS certificate.\n        self.verify = True\n\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.mount(\"https://\", HTTPAdapter())\n        self.mount(\"http://\", HTTPAdapter())\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def prepare_request(self, request: Request) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        url = cast(\"_t.UriType\", request.url)\n        method = cast(str, request.method)\n\n        cookies = request.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not isinstance(cookies, cookielib.CookieJar):\n            cookies = cookiejar_from_dict(cookies)\n\n        # Merge with session cookies\n        merged_cookies = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), cookies\n        )\n\n        # Set environment's basic authentication if not explicitly set.\n        auth = request.auth\n        if self.trust_env and not auth and not self.auth:\n            auth = get_netrc_auth(url)\n\n        p = PreparedRequest()\n        p.prepare(\n            method=method.upper(),\n            url=url,\n            files=request.files,\n            data=request.data,\n            json=request.json,\n            headers=merge_setting(\n                request.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(request.params, self.params),\n            auth=merge_setting(auth, self.auth),\n            cookies=merged_cookies,\n            hooks=merge_hooks(request.hooks, self.hooks),\n        )\n        return p\n\n    def request(\n        self,\n        method: str,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        data: _t.DataType = None,\n        headers: _t.HeadersType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        files: _t.FilesType = None,\n        auth: _t.AuthType = None,\n        timeout: _t.TimeoutType = None,\n        allow_redirects: bool = True,\n        proxies: dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        stream: bool | None = None,\n        verify: _t.VerifyType | None = None,\n        cert: _t.CertType = None,\n        json: _t.JsonType = None,\n    ) -> Response:\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How many seconds to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param hooks: (optional) Dictionary mapping hook name to one event or\n            list of events, event must be callable.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        if isinstance(url, bytes):\n            url = url.decode(\"utf-8\")\n\n        # Create the Request.\n        req = Request(\n            method=method.upper(),\n            url=url,\n            headers=headers,\n            files=files,\n            data=data or {},\n            json=json,\n            params=params or {},\n            auth=auth,\n            cookies=cookies,\n            hooks=hooks,\n        )\n        prep = self.prepare_request(req)\n\n        assert _is_prepared(prep)\n\n        proxies = proxies or {}\n\n        settings = self.merge_environment_settings(\n            prep.url, proxies, stream, verify, cert\n        )\n\n        # Send the request.\n        send_kwargs = {\n            \"timeout\": timeout,\n            \"allow_redirects\": allow_redirects,\n        }\n        send_kwargs.update(settings)\n        resp = self.send(prep, **send_kwargs)\n\n        return resp\n\n    def get(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        **kwargs: Unpack[_t.GetKwargs],\n    ) -> Response:\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary, list of tuples or bytes to send\n            in the query string for the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"GET\", url, params=params, **kwargs)\n\n    def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"OPTIONS\", url, **kwargs)\n\n    def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", False)\n        return self.request(\"HEAD\", url, **kwargs)\n\n    def post(\n        self,\n        url: _t.UriType,\n        data: _t.DataType = None,\n        json: _t.JsonType = None,\n        **kwargs: Unpack[_t.PostKwargs],\n    ) -> Response:\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"POST\", url, data=data, json=json, **kwargs)\n\n    def put(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PUT\", url, data=data, **kwargs)\n\n    def patch(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PATCH\", url, data=data, **kwargs)\n\n    def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"DELETE\", url, **kwargs)\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response:\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        kwargs.setdefault(\"stream\", self.stream)\n        kwargs.setdefault(\"verify\", self.verify)\n        kwargs.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in kwargs:\n            kwargs[\"proxies\"] = resolve_proxies(request, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if isinstance(request, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        assert _is_prepared(request)\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        allow_redirects = kwargs.pop(\"allow_redirects\", True)\n        stream = kwargs.get(\"stream\")\n        hooks = request.hooks\n\n        # Get the appropriate adapter to use\n        adapter = self.get_adapter(url=request.url)\n\n        # Start time (approximately) of the request\n        start = preferred_clock()\n\n        # Send the request\n        r = adapter.send(request, **kwargs)\n\n        # Total elapsed time of the request (approximately)\n        elapsed = preferred_clock() - start\n        r.elapsed = timedelta(seconds=elapsed)\n\n        # Response manipulation hooks\n        r = dispatch_hook(\"response\", hooks, r, **kwargs)\n\n        # Persist cookies\n        if r.history:\n            # If the hooks create history then we want those cookies too\n            for resp in r.history:\n                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)\n\n        extract_cookies_to_jar(self.cookies, request, r.raw)\n\n        # Resolve redirects if allowed.\n        if allow_redirects:\n            # Redirect resolving generator.\n            gen = self.resolve_redirects(r, request, **kwargs)\n            history = [resp for resp in gen]\n        else:\n            history = []\n\n        # Shuffle things around if there's history.\n        if history:\n            # Insert the first (original) request at the start\n            a = 1\n            b = -1\n            history.insert((a + b), r)\n            # Get the last request made\n            r = history.pop()\n            r.history = history\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not allow_redirects:\n            try:\n                r._next = next(  # type: ignore[assignment]  # yield_requests=True returns PreparedRequest\n                    self.resolve_redirects(r, request, yield_requests=True, **kwargs)\n                )\n            except StopIteration:\n                pass\n\n        if not stream:\n            r.content\n\n        return r\n\n    def merge_environment_settings(\n        self,\n        url: str,\n        proxies: dict[str, str] | None,\n        stream: bool | None,\n        verify: _t.VerifyType | None,\n        cert: _t.CertType,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Check the environment and merge it with some settings.\n\n        :rtype: dict\n        \"\"\"\n        # Gather clues from the surrounding environment.\n        if self.trust_env:\n            # Set environment's proxies.\n            no_proxy = proxies.get(\"no_proxy\") if proxies is not None else None\n            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n            if proxies is not None:\n                for k, v in env_proxies.items():\n                    proxies.setdefault(k, v)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if verify is True or verify is None:\n                verify = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or verify\n                )\n\n        # Merge all the kwargs.\n        proxies = merge_setting(proxies, self.proxies)\n        stream = merge_setting(stream, self.stream)\n        verify = merge_setting(verify, self.verify)\n        cert = merge_setting(cert, self.cert)\n\n        return {\"proxies\": proxies, \"stream\": stream, \"verify\": verify, \"cert\": cert}\n\n    def get_adapter(self, url: str) -> BaseAdapter:\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        for prefix, adapter in self.adapters.items():\n            if url.lower().startswith(prefix.lower()):\n                return adapter\n\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {url!r}\")\n\n    def close(self) -> None:\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        for v in self.adapters.values():\n            v.close()\n\n    def mount(self, prefix: str, adapter: BaseAdapter) -> None:\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        self.adapters[prefix] = adapter\n        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n        for key in keys_to_move:\n            self.adapters[key] = self.adapters.pop(key)\n\n    def __getstate__(self) -> dict[str, Any]:\n        state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for attr, value in state.items():\n            setattr(self, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-e8728b6a59c05261", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f7ce168470e909ea6daa0506171e94a5e9eee20c594d6572cd18591881c9fa46", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 561, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__Session__128f338b.py", "order": 11, "original_content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "parent_variant_id": "pyint-d802e4513ae9-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L395-L905", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 1, "intermediate_variables_introduced": 2, "statements_augmented": 1}, "unit_kind": "class", "unit_name": "Session", "variant_id": "pyint-1414128f338b-I11", "group_id": "py-e8728b6a59c05261", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 796, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c508e7cb64b5-I12", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n\n    headers: CaseInsensitiveDict[str]\n    auth: _t.AuthType\n    proxies: dict[str, str]\n    hooks: dict[str, list[_t.HookType]]\n    params: MutableMapping[str, Any]\n    stream: bool\n    verify: _t.VerifyType\n    cert: _t.CertType\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n    adapters: MutableMapping[str, BaseAdapter]\n\n    __attrs__: list[str] = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self) -> None:\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        self.headers = default_headers()\n\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        #: If verify is set to a string, it must be the path to a CA bundle file\n        #: that will be used to verify the TLS certificate.\n        self.verify = True\n\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.mount(\"https://\", HTTPAdapter())\n        self.mount(\"http://\", HTTPAdapter())\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def prepare_request(self, request: Request) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        url = cast(\"_t.UriType\", request.url)\n        \n\n        cookies = request.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not isinstance(cookies, cookielib.CookieJar):\n            cookies = cookiejar_from_dict(cookies)\n\n        # Merge with session cookies\n        \n\n        # Set environment's basic authentication if not explicitly set.\n        auth = request.auth\n        if self.trust_env and not auth and not self.auth:\n            auth = get_netrc_auth(url)\n\n        p = PreparedRequest()\n        p.prepare(\n            method=(cast(str, request.method)).upper(),\n            url=url,\n            files=request.files,\n            data=request.data,\n            json=request.json,\n            headers=merge_setting(\n                request.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(request.params, self.params),\n            auth=merge_setting(auth, self.auth),\n            cookies=(merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), cookies\n        )),\n            hooks=merge_hooks(request.hooks, self.hooks),\n        )\n        return p\n\n    def request(\n        self,\n        method: str,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        data: _t.DataType = None,\n        headers: _t.HeadersType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        files: _t.FilesType = None,\n        auth: _t.AuthType = None,\n        timeout: _t.TimeoutType = None,\n        allow_redirects: bool = True,\n        proxies: dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        stream: bool | None = None,\n        verify: _t.VerifyType | None = None,\n        cert: _t.CertType = None,\n        json: _t.JsonType = None,\n    ) -> Response:\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How many seconds to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param hooks: (optional) Dictionary mapping hook name to one event or\n            list of events, event must be callable.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        if isinstance(url, bytes):\n            url = url.decode(\"utf-8\")\n\n        # Create the Request.\n        req = Request(\n            method=method.upper(),\n            url=url,\n            headers=headers,\n            files=files,\n            data=data or {},\n            json=json,\n            params=params or {},\n            auth=auth,\n            cookies=cookies,\n            hooks=hooks,\n        )\n        prep = self.prepare_request(req)\n\n        assert _is_prepared(prep)\n\n        proxies = proxies or {}\n\n        \n\n        # Send the request.\n        send_kwargs = {\n            \"timeout\": timeout,\n            \"allow_redirects\": allow_redirects,\n        }\n        send_kwargs.update((self.merge_environment_settings(\n            prep.url, proxies, stream, verify, cert\n        )))\n        \n\n        return (self.send(prep, **send_kwargs))\n\n    def get(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        **kwargs: Unpack[_t.GetKwargs],\n    ) -> Response:\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary, list of tuples or bytes to send\n            in the query string for the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"GET\", url, params=params, **kwargs)\n\n    def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"OPTIONS\", url, **kwargs)\n\n    def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", False)\n        return self.request(\"HEAD\", url, **kwargs)\n\n    def post(\n        self,\n        url: _t.UriType,\n        data: _t.DataType = None,\n        json: _t.JsonType = None,\n        **kwargs: Unpack[_t.PostKwargs],\n    ) -> Response:\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"POST\", url, data=data, json=json, **kwargs)\n\n    def put(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PUT\", url, data=data, **kwargs)\n\n    def patch(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PATCH\", url, data=data, **kwargs)\n\n    def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"DELETE\", url, **kwargs)\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response:\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        kwargs.setdefault(\"stream\", self.stream)\n        kwargs.setdefault(\"verify\", self.verify)\n        kwargs.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in kwargs:\n            kwargs[\"proxies\"] = resolve_proxies(request, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if isinstance(request, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        assert _is_prepared(request)\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        allow_redirects = kwargs.pop(\"allow_redirects\", True)\n        stream = kwargs.get(\"stream\")\n        hooks = request.hooks\n\n        # Get the appropriate adapter to use\n        adapter = self.get_adapter(url=request.url)\n\n        # Start time (approximately) of the request\n        start = preferred_clock()\n\n        # Send the request\n        r = adapter.send(request, **kwargs)\n\n        # Total elapsed time of the request (approximately)\n        elapsed = preferred_clock() - start\n        r.elapsed = timedelta(seconds=elapsed)\n\n        # Response manipulation hooks\n        r = dispatch_hook(\"response\", hooks, r, **kwargs)\n\n        # Persist cookies\n        if r.history:\n            # If the hooks create history then we want those cookies too\n            for resp in r.history:\n                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)\n\n        extract_cookies_to_jar(self.cookies, request, r.raw)\n\n        # Resolve redirects if allowed.\n        if allow_redirects:\n            # Redirect resolving generator.\n            gen = self.resolve_redirects(r, request, **kwargs)\n            history = [resp for resp in gen]\n        else:\n            history = []\n\n        # Shuffle things around if there's history.\n        if history:\n            # Insert the first (original) request at the start\n            history.insert(0, r)\n            # Get the last request made\n            r = history.pop()\n            r.history = history\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not allow_redirects:\n            try:\n                r._next = next(  # type: ignore[assignment]  # yield_requests=True returns PreparedRequest\n                    self.resolve_redirects(r, request, yield_requests=True, **kwargs)\n                )\n            except StopIteration:\n                pass\n\n        if not stream:\n            r.content\n\n        return r\n\n    def merge_environment_settings(\n        self,\n        url: str,\n        proxies: dict[str, str] | None,\n        stream: bool | None,\n        verify: _t.VerifyType | None,\n        cert: _t.CertType,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Check the environment and merge it with some settings.\n\n        :rtype: dict\n        \"\"\"\n        # Gather clues from the surrounding environment.\n        if self.trust_env:\n            # Set environment's proxies.\n            no_proxy = proxies.get(\"no_proxy\") if proxies is not None else None\n            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n            if proxies is not None:\n                for k, v in env_proxies.items():\n                    proxies.setdefault(k, v)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if verify is True or verify is None:\n                verify = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or verify\n                )\n\n        # Merge all the kwargs.\n        proxies = merge_setting(proxies, self.proxies)\n        stream = merge_setting(stream, self.stream)\n        verify = merge_setting(verify, self.verify)\n        cert = merge_setting(cert, self.cert)\n\n        return {\"proxies\": proxies, \"stream\": stream, \"verify\": verify, \"cert\": cert}\n\n    def get_adapter(self, url: str) -> BaseAdapter:\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        for prefix, adapter in self.adapters.items():\n            if url.lower().startswith(prefix.lower()):\n                return adapter\n\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {url!r}\")\n\n    def close(self) -> None:\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        for v in self.adapters.values():\n            v.close()\n\n    def mount(self, prefix: str, adapter: BaseAdapter) -> None:\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        self.adapters[prefix] = adapter\n        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n        for key in keys_to_move:\n            self.adapters[key] = self.adapters.pop(key)\n\n    def __getstate__(self) -> dict[str, Any]:\n        \n        return ({attr: getattr(self, attr, None) for attr in self.__attrs__})\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        for attr, value in state.items():\n            setattr(self, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-e8728b6a59c05261", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "005336c1452631ab5fafb12e038aaed37fa5610731e056ec677fd4915b75499c", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 559, "local_path": "data-flow/inline-intermediate-variables/I12__requests__Session__e7cb64b5.py", "order": 12, "original_content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "parent_variant_id": "pyint-d802e4513ae9-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L395-L905", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 5, "intermediate_variables_available": 5, "intermediate_variables_inlined": 5, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Session", "variant_id": "pyint-c508e7cb64b5-I12", "group_id": "py-e8728b6a59c05261", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 797, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c030445bc7d6-I13", "source": "from __future__ import annotations\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Generator, Mapping, MutableMapping\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, cast\nfrom ._internal_utils import to_native_string\nfrom ._types import is_prepared as _is_prepared\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n    Response,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,  # re-export for external consumers\n    to_key_val_list,\n)\n\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n\n    headers: CaseInsensitiveDict[str]\n    auth: _t.AuthType\n    proxies: dict[str, str]\n    hooks: dict[str, list[_t.HookType]]\n    params: MutableMapping[str, Any]\n    stream: bool\n    verify: _t.VerifyType\n    cert: _t.CertType\n    max_redirects: int\n    trust_env: bool\n    cookies: RequestsCookieJar\n    adapters: MutableMapping[str, BaseAdapter]\n\n    __attrs__: list[str] = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self) -> None:\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        self.headers = default_headers()\n\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        #: If verify is set to a string, it must be the path to a CA bundle file\n        #: that will be used to verify the TLS certificate.\n        self.verify = True\n\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.mount(\"https://\", HTTPAdapter())\n        self.mount(\"http://\", HTTPAdapter())\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(self, *args: Any) -> None:\n        self.close()\n\n    def prepare_request(self, request: Request) -> PreparedRequest:\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        url = cast(\"_t.UriType\", request.url)\n        method = cast(str, request.method)\n\n        cookies = request.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not isinstance(cookies, cookielib.CookieJar):\n            cookies = cookiejar_from_dict(cookies)\n\n        # Merge with session cookies\n        merged_cookies = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), cookies\n        )\n\n        # Set environment's basic authentication if not explicitly set.\n        auth = request.auth\n        if self.trust_env and not auth and not self.auth:\n            auth = get_netrc_auth(url)\n\n        p = PreparedRequest()\n        p.prepare(\n            method=method.upper(),\n            url=url,\n            files=request.files,\n            data=request.data,\n            json=request.json,\n            headers=merge_setting(\n                request.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(request.params, self.params),\n            auth=merge_setting(auth, self.auth),\n            cookies=merged_cookies,\n            hooks=merge_hooks(request.hooks, self.hooks),\n        )\n        return p\n\n    def request(\n        self,\n        method: str,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        data: _t.DataType = None,\n        headers: _t.HeadersType = None,\n        cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n        files: _t.FilesType = None,\n        auth: _t.AuthType = None,\n        timeout: _t.TimeoutType = None,\n        allow_redirects: bool = True,\n        proxies: dict[str, str] | None = None,\n        hooks: _t.HooksInputType | None = None,\n        stream: bool | None = None,\n        verify: _t.VerifyType | None = None,\n        cert: _t.CertType = None,\n        json: _t.JsonType = None,\n    ) -> Response:\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How many seconds to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param hooks: (optional) Dictionary mapping hook name to one event or\n            list of events, event must be callable.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        if isinstance(url, bytes):\n            url = url.decode(\"utf-8\")\n\n        # Create the Request.\n        req = Request(\n            method=method.upper(),\n            url=url,\n            headers=headers,\n            files=files,\n            data=data or {},\n            json=json,\n            params=params or {},\n            auth=auth,\n            cookies=cookies,\n            hooks=hooks,\n        )\n        prep = self.prepare_request(req)\n\n        assert _is_prepared(prep)\n\n        proxies = proxies or {}\n\n        settings = self.merge_environment_settings(\n            prep.url, proxies, stream, verify, cert\n        )\n\n        # Send the request.\n        send_kwargs = {\n            \"timeout\": timeout,\n            \"allow_redirects\": allow_redirects,\n        }\n        send_kwargs.update(settings)\n        resp = self.send(prep, **send_kwargs)\n\n        return resp\n\n    def get(\n        self,\n        url: _t.UriType,\n        params: _t.ParamsType = None,\n        **kwargs: Unpack[_t.GetKwargs],\n    ) -> Response:\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary, list of tuples or bytes to send\n            in the query string for the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"GET\", url, params=params, **kwargs)\n\n    def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"OPTIONS\", url, **kwargs)\n\n    def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", False)\n        return self.request(\"HEAD\", url, **kwargs)\n\n    def post(\n        self,\n        url: _t.UriType,\n        data: _t.DataType = None,\n        json: _t.JsonType = None,\n        **kwargs: Unpack[_t.PostKwargs],\n    ) -> Response:\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"POST\", url, data=data, json=json, **kwargs)\n\n    def put(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PUT\", url, data=data, **kwargs)\n\n    def patch(\n        self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n    ) -> Response:\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PATCH\", url, data=data, **kwargs)\n\n    def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"DELETE\", url, **kwargs)\n\n    def send(self, request: PreparedRequest, **kwargs: Any) -> Response:\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        kwargs.setdefault(\"stream\", self.stream)\n        kwargs.setdefault(\"verify\", self.verify)\n        kwargs.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in kwargs:\n            kwargs[\"proxies\"] = resolve_proxies(request, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if isinstance(request, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        assert _is_prepared(request)\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        allow_redirects = kwargs.pop(\"allow_redirects\", True)\n        stream = kwargs.get(\"stream\")\n        hooks = request.hooks\n\n        # Get the appropriate adapter to use\n        adapter = self.get_adapter(url=request.url)\n\n        # Start time (approximately) of the request\n        start = preferred_clock()\n\n        # Send the request\n        r = adapter.send(request, **kwargs)\n\n        # Total elapsed time of the request (approximately)\n        elapsed = preferred_clock() - start\n        r.elapsed = timedelta(seconds=elapsed)\n\n        # Response manipulation hooks\n        r = dispatch_hook(\"response\", hooks, r, **kwargs)\n\n        # Persist cookies\n        if r.history:\n            # If the hooks create history then we want those cookies too\n            loopIterator = __import__(\"builtins\").iter(r.history)\n            while True:\n                try:\n                    resp = __import__(\"builtins\").next(loopIterator)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)\n\n        extract_cookies_to_jar(self.cookies, request, r.raw)\n\n        # Resolve redirects if allowed.\n        if allow_redirects:\n            # Redirect resolving generator.\n            gen = self.resolve_redirects(r, request, **kwargs)\n            history = [resp for resp in gen]\n        else:\n            history = []\n\n        # Shuffle things around if there's history.\n        if history:\n            # Insert the first (original) request at the start\n            history.insert(0, r)\n            # Get the last request made\n            r = history.pop()\n            r.history = history\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not allow_redirects:\n            try:\n                r._next = next(  # type: ignore[assignment]  # yield_requests=True returns PreparedRequest\n                    self.resolve_redirects(r, request, yield_requests=True, **kwargs)\n                )\n            except StopIteration:\n                pass\n\n        if not stream:\n            r.content\n\n        return r\n\n    def merge_environment_settings(\n        self,\n        url: str,\n        proxies: dict[str, str] | None,\n        stream: bool | None,\n        verify: _t.VerifyType | None,\n        cert: _t.CertType,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Check the environment and merge it with some settings.\n\n        :rtype: dict\n        \"\"\"\n        # Gather clues from the surrounding environment.\n        if self.trust_env:\n            # Set environment's proxies.\n            no_proxy = proxies.get(\"no_proxy\") if proxies is not None else None\n            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n            if proxies is not None:\n                loopIteratorA = __import__(\"builtins\").iter(env_proxies.items())\n                while True:\n                    try:\n                        k, v = __import__(\"builtins\").next(loopIteratorA)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    proxies.setdefault(k, v)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if verify is True or verify is None:\n                verify = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or verify\n                )\n\n        # Merge all the kwargs.\n        proxies = merge_setting(proxies, self.proxies)\n        stream = merge_setting(stream, self.stream)\n        verify = merge_setting(verify, self.verify)\n        cert = merge_setting(cert, self.cert)\n\n        return {\"proxies\": proxies, \"stream\": stream, \"verify\": verify, \"cert\": cert}\n\n    def get_adapter(self, url: str) -> BaseAdapter:\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        loopIteratorB = __import__(\"builtins\").iter(self.adapters.items())\n        while True:\n            try:\n                prefix, adapter = __import__(\"builtins\").next(loopIteratorB)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if url.lower().startswith(prefix.lower()):\n                return adapter\n\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {url!r}\")\n\n    def close(self) -> None:\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        loopIteratorC = __import__(\"builtins\").iter(self.adapters.values())\n        while True:\n            try:\n                v = __import__(\"builtins\").next(loopIteratorC)\n            except __import__(\"builtins\").StopIteration:\n                break\n            v.close()\n\n    def mount(self, prefix: str, adapter: BaseAdapter) -> None:\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        self.adapters[prefix] = adapter\n        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n        loopIteratorD = __import__(\"builtins\").iter(keys_to_move)\n        while True:\n            try:\n                key = __import__(\"builtins\").next(loopIteratorD)\n            except __import__(\"builtins\").StopIteration:\n                break\n            self.adapters[key] = self.adapters.pop(key)\n\n    def __getstate__(self) -> dict[str, Any]:\n        state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n        return state\n\n    def __setstate__(self, state: dict[str, Any]) -> None:\n        loopIteratorE = __import__(\"builtins\").iter(state.items())\n        while True:\n            try:\n                attr, value = __import__(\"builtins\").next(loopIteratorE)\n            except __import__(\"builtins\").StopIteration:\n                break\n            setattr(self, attr, value)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-e8728b6a59c05261", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "22f1faf5124324c975d12565687ae34c2441871d266298c31a32762513b39bd0", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 589, "local_path": "control-flow/lower-for-to-while/I13__requests__Session__445bc7d6.py", "order": 13, "original_content_sha256": "d4e8935a7862e68dd1da5123168fe72025fd2b5bbdcc290017ef136565f0a2e6", "parent_variant_id": "pyint-d802e4513ae9-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/sessions.py#L395-L905", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 6, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 6, "synchronous_for_loops_eligible": 6, "synchronous_for_loops_found": 6}, "unit_kind": "class", "unit_name": "Session", "variant_id": "pyint-c030445bc7d6-I13", "group_id": "py-e8728b6a59c05261", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 798, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-207037d58e53-SRC", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass DispatchingJinjaLoader(BaseLoader):\n    \"\"\"A loader that looks for templates in the application and all\n    the blueprint folders.\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self.app = app\n\n    def get_source(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n            return self._get_source_explained(environment, template)\n        return self._get_source_fast(environment, template)\n\n    def _get_source_explained(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        attempts = []\n        rv: tuple[str, str | None, t.Callable[[], bool] | None] | None\n        trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n        for srcobj, loader in self._iter_loaders(template):\n            try:\n                rv = loader.get_source(environment, template)\n                if trv is None:\n                    trv = rv\n            except TemplateNotFound:\n                rv = None\n            attempts.append((loader, srcobj, rv))\n\n        from .debughelpers import explain_template_loading_attempts\n\n        explain_template_loading_attempts(self.app, template, attempts)\n\n        if trv is not None:\n            return trv\n        raise TemplateNotFound(template)\n\n    def _get_source_fast(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        for _srcobj, loader in self._iter_loaders(template):\n            try:\n                return loader.get_source(environment, template)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(template)\n\n    def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n        loader = self.app.jinja_loader\n        if loader is not None:\n            yield self.app, loader\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                yield blueprint, loader\n\n    def list_templates(self) -> list[str]:\n        result = set()\n        loader = self.app.jinja_loader\n        if loader is not None:\n            result.update(loader.list_templates())\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                for template in loader.list_templates():\n                    result.add(template)\n\n        return list(result)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-e9c9f80ff9f3c900", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 84, "local_path": "source-original/SRC__flask__DispatchingJinjaLoader__37d58e53.py", "order": 0, "original_content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L49-L120", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "DispatchingJinjaLoader", "variant_id": "pyint-207037d58e53-SRC", "group_id": "py-e9c9f80ff9f3c900", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 379, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-49238b9219ca-I01", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass DispatchingJinjaLoader(BaseLoader):\n    \n\n    def __init__(self, app: App) -> None:\n        self.app = app\n\n    def get_source(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n            return self._get_source_explained(environment, template)\n        return self._get_source_fast(environment, template)\n\n    def _get_source_explained(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        attempts = []\n        rv: tuple[str, str | None, t.Callable[[], bool] | None] | None\n        trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n        for srcobj, loader in self._iter_loaders(template):\n            try:\n                rv = loader.get_source(environment, template)\n                if trv is None:\n                    trv = rv\n            except TemplateNotFound:\n                rv = None\n            attempts.append((loader, srcobj, rv))\n\n        from .debughelpers import explain_template_loading_attempts\n\n        explain_template_loading_attempts(self.app, template, attempts)\n\n        if trv is not None:\n            return trv\n        raise TemplateNotFound(template)\n\n    def _get_source_fast(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        for _srcobj, loader in self._iter_loaders(template):\n            try:\n                return loader.get_source(environment, template)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(template)\n\n    def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n        loader = self.app.jinja_loader\n        if loader is not None:\n            yield self.app, loader\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                yield blueprint, loader\n\n    def list_templates(self) -> list[str]:\n        result = set()\n        loader = self.app.jinja_loader\n        if loader is not None:\n            result.update(loader.list_templates())\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                for template in loader.list_templates():\n                    result.add(template)\n\n        return list(result)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-e9c9f80ff9f3c900", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "d783637dc86d1dbcc8c7e5ec532390752bbad214c37e6b8c106ed529e21f7b63", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 82, "local_path": "comments/remove-comments/I01__flask__DispatchingJinjaLoader__8b9219ca.py", "order": 1, "original_content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "parent_variant_id": "pyint-207037d58e53-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L49-L120", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 98, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "DispatchingJinjaLoader", "variant_id": "pyint-49238b9219ca-I01", "group_id": "py-e9c9f80ff9f3c900", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 380, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cbbab2fcea9c-I02", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass DispatchingJinjaLoader(BaseLoader):\n    \"\"\"A loader that looks for templates in the application and all\n    the blueprint folders.\n    \"\"\"\n\n    def __init__(self, app2: App) -> None:\n        self.app = app2\n\n    def get(\n        self, env: BaseEnvironment, tem: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n            return self.get2(env, tem)\n        return self.get3(env, tem)\n\n    def get2(\n        self, env2: BaseEnvironment, tem2: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        att = []\n        rv2: tuple[str, str | None, t.Callable[[], bool] | None] | None\n        trv2: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n        for src, loa in self.iter(tem2):\n            try:\n                rv2 = loa.get_source(env2, tem2)\n                if trv2 is None:\n                    trv2 = rv2\n            except TemplateNotFound:\n                rv2 = None\n            att.append((loa, src, rv2))\n\n        from .debughelpers import explain_template_loading_attempts\n\n        explain_template_loading_attempts(self.app, tem2, att)\n\n        if trv2 is not None:\n            return trv2\n        raise TemplateNotFound(tem2)\n\n    def get3(\n        self, env3: BaseEnvironment, tem3: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        for src2, loa2 in self.iter(tem3):\n            try:\n                return loa2.get_source(env3, tem3)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(tem3)\n\n    def iter(self, tem4: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n        loa3 = self.app.jinja_loader\n        if loa3 is not None:\n            yield self.app, loa3\n\n        for blu in self.app.iter_blueprints():\n            loa3 = blu.jinja_loader\n            if loa3 is not None:\n                yield blu, loa3\n\n    def list2(self) -> list[str]:\n        res = set()\n        loa4 = self.app.jinja_loader\n        if loa4 is not None:\n            res.update(loa4.list_templates())\n\n        for blu2 in self.app.iter_blueprints():\n            loa4 = blu2.jinja_loader\n            if loa4 is not None:\n                for tem5 in loa4.list_templates():\n                    res.add(tem5)\n\n        return list(res)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-e9c9f80ff9f3c900", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "a4d9816d6d32da84f281b8cf797b5038e610cd1bea5ce5ced456391de1c33986", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 84, "local_path": "identifiers/shorten-identifiers/I02__flask__DispatchingJinjaLoader__b2fcea9c.py", "order": 2, "original_content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "parent_variant_id": "pyint-207037d58e53-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L49-L120", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 75, "identifiers_declared": 26}, "unit_kind": "class", "unit_name": "DispatchingJinjaLoader", "variant_id": "pyint-cbbab2fcea9c-I02", "group_id": "py-e9c9f80ff9f3c900", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 381, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-08c6c35c1f3e-I03", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass DispatchingJinjaLoader(BaseLoader):\n    \"\"\"A loader that looks for templates in the application and all\n    the blueprint folders.\n    \"\"\"\n\n    def __init__(self, map: App) -> None:\n        self.app = map\n\n    def readBuffer(\n        self, secureToken: BaseEnvironment, nextData: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n            return self.validateAccount(secureToken, nextData)\n        return self.validateRequest(secureToken, nextData)\n\n    def validateAccount(\n        self, sharedIndex: BaseEnvironment, nextNode: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        document = []\n        map: tuple[str, str | None, t.Callable[[], bool] | None] | None\n        key: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n        for config, buffer in self.refreshClient(nextNode):\n            try:\n                map = buffer.get_source(sharedIndex, nextNode)\n                if key is None:\n                    key = map\n            except TemplateNotFound:\n                map = None\n            document.append((buffer, config, map))\n\n        from .debughelpers import explain_template_loading_attempts\n\n        explain_template_loading_attempts(self.app, nextNode, document)\n\n        if key is not None:\n            return key\n        raise TemplateNotFound(nextNode)\n\n    def validateRequest(\n        self, defaultPath: BaseEnvironment, customer: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        for session, option in self.refreshClient(customer):\n            try:\n                return option.get_source(defaultPath, customer)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(customer)\n\n    def refreshClient(self, localKey: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n        status = self.app.jinja_loader\n        if status is not None:\n            yield self.app, status\n\n        for tempValue in self.app.iter_blueprints():\n            status = tempValue.jinja_loader\n            if status is not None:\n                yield tempValue, status\n\n    def refreshBalance(self) -> list[str]:\n        amount = set()\n        record = self.app.jinja_loader\n        if record is not None:\n            amount.update(record.list_templates())\n\n        for finalMode in self.app.iter_blueprints():\n            record = finalMode.jinja_loader\n            if record is not None:\n                for schedule in record.list_templates():\n                    amount.add(schedule)\n\n        return list(amount)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-e9c9f80ff9f3c900", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "2eabcd1f385d1532f7c0ee08857cb6cbe2a332f2295a4277b6c0cf3ffc9a6568", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 84, "local_path": "identifiers/mislead-identifiers/I03__flask__DispatchingJinjaLoader__c35c1f3e.py", "order": 3, "original_content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "parent_variant_id": "pyint-207037d58e53-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L49-L120", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 75, "identifiers_declared": 26, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 1, "local_exact_length_matches": 20, "local_random_pool_selections": 21, "local_total_length_difference": 1, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 3, "method_random_pool_selections": 5, "method_total_length_difference": 7}, "unit_kind": "class", "unit_name": "DispatchingJinjaLoader", "variant_id": "pyint-08c6c35c1f3e-I03", "group_id": "py-e9c9f80ff9f3c900", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 382, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2ca4b9e4378b-I04", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass DispatchingJinjaLoader(BaseLoader):\n    \"\"\"A loader that looks for templates in the application and all\n    the blueprint folders.\n    \"\"\"\n\n    def __init__(self, f: App) -> None:\n        self.app = f\n\n    def a(\n        self, g: BaseEnvironment, h: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n            return self.b(g, h)\n        return self.c(g, h)\n\n    def b(\n        self, i: BaseEnvironment, j: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        k = []\n        l: tuple[str, str | None, t.Callable[[], bool] | None] | None\n        m: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n        for n, o in self.d(j):\n            try:\n                l = o.get_source(i, j)\n                if m is None:\n                    m = l\n            except TemplateNotFound:\n                l = None\n            k.append((o, n, l))\n\n        from .debughelpers import explain_template_loading_attempts\n\n        explain_template_loading_attempts(self.app, j, k)\n\n        if m is not None:\n            return m\n        raise TemplateNotFound(j)\n\n    def c(\n        self, p: BaseEnvironment, q: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        for r, s in self.d(q):\n            try:\n                return s.get_source(p, q)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(q)\n\n    def d(self, u: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n        v = self.app.jinja_loader\n        if v is not None:\n            yield self.app, v\n\n        for w in self.app.iter_blueprints():\n            v = w.jinja_loader\n            if v is not None:\n                yield w, v\n\n    def e(self) -> list[str]:\n        x = set()\n        y = self.app.jinja_loader\n        if y is not None:\n            x.update(y.list_templates())\n\n        for z in self.app.iter_blueprints():\n            y = z.jinja_loader\n            if y is not None:\n                for A in y.list_templates():\n                    x.add(A)\n\n        return list(x)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-e9c9f80ff9f3c900", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "5e26493d6b8b965d4339b0d8d70a843573ebb33e6b6af6c753e9cb5d5db49321", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 84, "local_path": "identifiers/garble-identifiers/I04__flask__DispatchingJinjaLoader__b9e4378b.py", "order": 4, "original_content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "parent_variant_id": "pyint-207037d58e53-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L49-L120", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 75, "identifiers_declared": 26}, "unit_kind": "class", "unit_name": "DispatchingJinjaLoader", "variant_id": "pyint-2ca4b9e4378b-I04", "group_id": "py-e9c9f80ff9f3c900", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 383, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7adc6d9df512-I05", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass DispatchingJinjaLoader(BaseLoader):\n    \"\"\"A loader that looks for templates in the application and all\n    the blueprint folders.\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self.app = app\n\n    def get_source(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n            return self._get_source_explained(environment, template)\n        return self._get_source_fast(environment, template)\n\n    def _get_source_explained(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        attempts = []\n        rv: tuple[str, str | None, t.Callable[[], bool] | None] | None\n        trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n        for srcobj, loader in self._iter_loaders(template):\n            try:\n                rv = loader.get_source(environment, template)\n                if trv is None:\n                    trv = rv\n            except TemplateNotFound:\n                rv = None\n            attempts.append((loader, srcobj, rv))\n\n        from .debughelpers import explain_template_loading_attempts\n\n        explain_template_loading_attempts(self.app, template, attempts)\n\n        if trv is not None:\n            return trv\n        raise TemplateNotFound(template)\n\n    def _get_source_fast(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        for _srcobj, loader in self._iter_loaders(template):\n            try:\n                return loader.get_source(environment, template)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(template)\n\n    def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n        loader = self.app.jinja_loader\n        if loader is not None:\n            yield self.app, loader\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                yield blueprint, loader\n\n    def list_templates(self) -> list[str]:\n        result = set()\n        loader = self.app.jinja_loader\n        if loader is not None:\n            result.update(loader.list_templates())\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                for template in loader.list_templates():\n                    result.add(template)\n\n        return list(result)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-e9c9f80ff9f3c900", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 84, "local_path": "expressions/encode-integer-literals/I05__flask__DispatchingJinjaLoader__6d9df512.py", "order": 5, "original_content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "parent_variant_id": "pyint-207037d58e53-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L49-L120", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "DispatchingJinjaLoader", "variant_id": "pyint-7adc6d9df512-I05", "group_id": "py-e9c9f80ff9f3c900", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 384, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4e7dc64fc843-I06", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass DispatchingJinjaLoader(BaseLoader):\n    \"\"\"A loader that looks for templates in the application and all\n    the blueprint folders.\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self.app = app\n\n    def get_source(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if not (self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]):\n            pass\n        else:\n            return self._get_source_explained(environment, template)\n        return self._get_source_fast(environment, template)\n\n    def _get_source_explained(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        attempts = []\n        rv: tuple[str, str | None, t.Callable[[], bool] | None] | None\n        trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n        for srcobj, loader in self._iter_loaders(template):\n            try:\n                rv = loader.get_source(environment, template)\n                if not (trv is None):\n                    pass\n                else:\n                    trv = rv\n            except TemplateNotFound:\n                rv = None\n            attempts.append((loader, srcobj, rv))\n\n        from .debughelpers import explain_template_loading_attempts\n\n        explain_template_loading_attempts(self.app, template, attempts)\n\n        if not (trv is not None):\n            pass\n        else:\n            return trv\n        raise TemplateNotFound(template)\n\n    def _get_source_fast(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        for _srcobj, loader in self._iter_loaders(template):\n            try:\n                return loader.get_source(environment, template)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(template)\n\n    def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n        loader = self.app.jinja_loader\n        if not (loader is not None):\n            pass\n        else:\n            yield self.app, loader\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if not (loader is not None):\n                pass\n            else:\n                yield blueprint, loader\n\n    def list_templates(self) -> list[str]:\n        result = set()\n        loader = self.app.jinja_loader\n        if not (loader is not None):\n            pass\n        else:\n            result.update(loader.list_templates())\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if not (loader is not None):\n                pass\n            else:\n                for template in loader.list_templates():\n                    result.add(template)\n\n        return list(result)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-e9c9f80ff9f3c900", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "d139125e202940c3b6c3fd8e785198df58e8a10839608c06d67f46137d15d647", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 98, "local_path": "expressions/invert-conditions/I06__flask__DispatchingJinjaLoader__c64fc843.py", "order": 6, "original_content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "parent_variant_id": "pyint-207037d58e53-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L49-L120", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 7}, "unit_kind": "class", "unit_name": "DispatchingJinjaLoader", "variant_id": "pyint-4e7dc64fc843-I06", "group_id": "py-e9c9f80ff9f3c900", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 385, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4fb9ea2fe0f0-I07", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass DispatchingJinjaLoader(BaseLoader):\n    \"\"\"A loader that looks for templates in the application and all\n    the blueprint folders.\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        if ((0x995b ^ 0x995b) != 0):\n            raise AssertionError()\n        self.app = app\n\n    def get_source(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if ((0x1d5d ^ 0x1d5d) != 0):\n            raise AssertionError()\n        if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n            return self._get_source_explained(environment, template)\n        return self._get_source_fast(environment, template)\n\n    def _get_source_explained(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if ((0x2e5b ^ 0x2e5b) != 0):\n            raise AssertionError()\n        attempts = []\n        rv: tuple[str, str | None, t.Callable[[], bool] | None] | None\n        trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n        for srcobj, loader in self._iter_loaders(template):\n            try:\n                rv = loader.get_source(environment, template)\n                if trv is None:\n                    trv = rv\n            except TemplateNotFound:\n                rv = None\n            attempts.append((loader, srcobj, rv))\n\n        from .debughelpers import explain_template_loading_attempts\n\n        explain_template_loading_attempts(self.app, template, attempts)\n\n        if trv is not None:\n            return trv\n        raise TemplateNotFound(template)\n\n    def _get_source_fast(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if ((0x2a85 ^ 0x2a85) != 0):\n            raise AssertionError()\n        for _srcobj, loader in self._iter_loaders(template):\n            try:\n                return loader.get_source(environment, template)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(template)\n\n    def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n        if ((0xfa97 ^ 0xfa97) != 0):\n            raise AssertionError()\n        loader = self.app.jinja_loader\n        if loader is not None:\n            yield self.app, loader\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                yield blueprint, loader\n\n    def list_templates(self) -> list[str]:\n        if ((0xb250 ^ 0xb250) != 0):\n            raise AssertionError()\n        result = set()\n        loader = self.app.jinja_loader\n        if loader is not None:\n            result.update(loader.list_templates())\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                for template in loader.list_templates():\n                    result.add(template)\n\n        return list(result)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-e9c9f80ff9f3c900", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "23e213a596660ddb8ffe6a9fa44dc3f7948f96dc8069e5cccb2ef2805118230b", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 96, "local_path": "code-injection/insert-dead-branches/I07__flask__DispatchingJinjaLoader__ea2fe0f0.py", "order": 7, "original_content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "parent_variant_id": "pyint-207037d58e53-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L49-L120", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 6}, "unit_kind": "class", "unit_name": "DispatchingJinjaLoader", "variant_id": "pyint-4fb9ea2fe0f0-I07", "group_id": "py-e9c9f80ff9f3c900", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 386, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e6d396e773ea-I08", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass DispatchingJinjaLoader(BaseLoader):\n    \"\"\"A loader that looks for templates in the application and all\n    the blueprint folders.\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self.app = app\n\n    def get_source(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n            return self._get_source_explained(environment, template)\n        return self._get_source_fast(environment, template)\n\n    def _get_source_explained(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        total_score = 240\n        number_of_scores = 3\n        average_score = total_score / number_of_scores\n        attempts = []\n        rv: tuple[str, str | None, t.Callable[[], bool] | None] | None\n        trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n        for srcobj, loader in self._iter_loaders(template):\n            try:\n                rv = loader.get_source(environment, template)\n                if trv is None:\n                    trv = rv\n            except TemplateNotFound:\n                rv = None\n            attempts.append((loader, srcobj, rv))\n\n        from .debughelpers import explain_template_loading_attempts\n\n        explain_template_loading_attempts(self.app, template, attempts)\n\n        if trv is not None:\n            return trv\n        raise TemplateNotFound(template)\n\n    def _get_source_fast(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        for _srcobj, loader in self._iter_loaders(template):\n            try:\n                return loader.get_source(environment, template)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(template)\n\n    def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n        loader = self.app.jinja_loader\n        if loader is not None:\n            yield self.app, loader\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                yield blueprint, loader\n\n    def list_templates(self) -> list[str]:\n        result = set()\n        loader = self.app.jinja_loader\n        if loader is not None:\n            result.update(loader.list_templates())\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                for template in loader.list_templates():\n                    result.add(template)\n\n        return list(result)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-e9c9f80ff9f3c900", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "78986d7b88c3416a9317dd50bc771f0f010a8099697859163310ecb39f554612", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 87, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__DispatchingJinjaLoader__96e773ea.py", "order": 8, "original_content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "parent_variant_id": "pyint-207037d58e53-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L49-L120", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 5}, "unit_kind": "class", "unit_name": "DispatchingJinjaLoader", "variant_id": "pyint-e6d396e773ea-I08", "group_id": "py-e9c9f80ff9f3c900", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 387, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2bc85f36169b-I09", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass DispatchingJinjaLoader(BaseLoader):\n    \"\"\"A loader that looks for templates in the application and all\n    the blueprint folders.\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self.app = app\n\n    def get_source(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n            return self._get_source_explained(environment, template)\n        return self._get_source_fast(environment, template)\n\n    def _get_source_explained(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        attempts = []\n        rv: tuple[str, str | None, t.Callable[[], bool] | None] | None\n        trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n        for srcobj, loader in self._iter_loaders(template):\n            try:\n                rv = loader.get_source(environment, template)\n                if trv is None:\n                    trv = rv\n            except TemplateNotFound:\n                rv = None\n            attempts.append((loader, srcobj, rv))\n\n        from .debughelpers import explain_template_loading_attempts\n\n        explain_template_loading_attempts(self.app, template, attempts)\n\n        if trv is not None:\n            return trv\n        raise TemplateNotFound(template)\n\n    def _get_source_fast(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        for _srcobj, loader in self._iter_loaders(template):\n            try:\n                return loader.get_source(environment, template)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(template)\n\n    def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n        lI0O_69bcf6a5, lI0O_ea9526d3 = 0x9057, ~0x9057\n        lI0O_69bcf6a5 = (lI0O_69bcf6a5 & lI0O_ea9526d3) | (lI0O_69bcf6a5 ^ lI0O_69bcf6a5)\n        lI0O_ea9526d3 ^= lI0O_ea9526d3\n        loader = self.app.jinja_loader\n        if loader is not None:\n            yield self.app, loader\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                yield blueprint, loader\n\n    def list_templates(self) -> list[str]:\n        result = set()\n        loader = self.app.jinja_loader\n        if loader is not None:\n            result.update(loader.list_templates())\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                for template in loader.list_templates():\n                    result.add(template)\n\n        return list(result)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-e9c9f80ff9f3c900", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "461f9b34d724fe68f0c8f5dedabda9abbf87f847f3fdba7f472bc5570b4629f3", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 87, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__DispatchingJinjaLoader__5f36169b.py", "order": 9, "original_content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "parent_variant_id": "pyint-207037d58e53-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L49-L120", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 9}, "unit_kind": "class", "unit_name": "DispatchingJinjaLoader", "variant_id": "pyint-2bc85f36169b-I09", "group_id": "py-e9c9f80ff9f3c900", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 388, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a8a36aba2355-I10", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\nclass DispatchingJinjaLoader(BaseLoader):\n    \"\"\"A loader that looks for templates in the application and all\n    the blueprint folders.\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self.app = app\n\n    def get_source(\n        self, environment: BaseEnvironment, template: str     ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n            return self._get_source_explained(environment, template)\n        return self._get_source_fast(environment, template)\n\n    def _get_source_explained(         self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        attempts = []\n        rv: tuple[str, str | None, t.Callable[[], bool] | None] | None\n        trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n        for srcobj, loader in self._iter_loaders(template):\n            try:\n                rv = loader.get_source(environment, template)\n                if trv is None:\n                    trv = rv\n            except TemplateNotFound:\n                rv = None\n            attempts.append((loader, srcobj, rv))\n\n        from .debughelpers import explain_template_loading_attempts\n        explain_template_loading_attempts(self.app, template, attempts)\n\n        if trv is not None:\n            return trv\n        raise TemplateNotFound(template)\n    def _get_source_fast(\n        self, environment: BaseEnvironment, template: str     ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        for _srcobj, loader in self._iter_loaders(template):\n            try:\n                return loader.get_source(environment, template)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(template)\n    def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n        loader = self.app.jinja_loader\n        if loader is not None:\n            yield self.app, loader\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                yield blueprint, loader\n\n    def list_templates(self) -> list[str]:\n        result = set()\n        loader = self.app.jinja_loader\n        if loader is not None:\n            result.update(loader.list_templates())\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                for template in loader.list_templates():\n                    result.add(template)\n\n        return list(result)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-e9c9f80ff9f3c900", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "59385ac75696cb6ea0d36b668854ab62e5af8a9d9232202630f3accc83f3ddfb", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 76, "local_path": "layout/partially-compact-layout/I10__flask__DispatchingJinjaLoader__6aba2355.py", "order": 10, "original_content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "parent_variant_id": "pyint-207037d58e53-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L49-L120", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 20, "line_break_groups_removed": 8, "line_breaks_removed": 8, "whitespace_characters_removed": 5}, "unit_kind": "class", "unit_name": "DispatchingJinjaLoader", "variant_id": "pyint-a8a36aba2355-I10", "group_id": "py-e9c9f80ff9f3c900", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 389, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e7e84f895162-I11", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass DispatchingJinjaLoader(BaseLoader):\n    \"\"\"A loader that looks for templates in the application and all\n    the blueprint folders.\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self.app = app\n\n    def get_source(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n            return self._get_source_explained(environment, template)\n        return self._get_source_fast(environment, template)\n\n    def _get_source_explained(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        attempts = []\n        rv: tuple[str, str | None, t.Callable[[], bool] | None] | None\n        trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n        for srcobj, loader in self._iter_loaders(template):\n            try:\n                rv = loader.get_source(environment, template)\n                if trv is None:\n                    trv = rv\n            except TemplateNotFound:\n                rv = None\n            attempts.append((loader, srcobj, rv))\n\n        from .debughelpers import explain_template_loading_attempts\n\n        explain_template_loading_attempts(self.app, template, attempts)\n\n        if trv is not None:\n            return trv\n        raise TemplateNotFound(template)\n\n    def _get_source_fast(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        for _srcobj, loader in self._iter_loaders(template):\n            try:\n                return loader.get_source(environment, template)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(template)\n\n    def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n        loader = self.app.jinja_loader\n        if loader is not None:\n            yield self.app, loader\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                yield blueprint, loader\n\n    def list_templates(self) -> list[str]:\n        result = set()\n        loader = self.app.jinja_loader\n        if loader is not None:\n            result.update(loader.list_templates())\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                for template in loader.list_templates():\n                    result.add(template)\n\n        return list(result)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-e9c9f80ff9f3c900", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 84, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__DispatchingJinjaLoader__4f895162.py", "order": 11, "original_content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "parent_variant_id": "pyint-207037d58e53-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L49-L120", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "DispatchingJinjaLoader", "variant_id": "pyint-e7e84f895162-I11", "group_id": "py-e9c9f80ff9f3c900", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 390, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-96ca4f0252d8-I12", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass DispatchingJinjaLoader(BaseLoader):\n    \"\"\"A loader that looks for templates in the application and all\n    the blueprint folders.\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self.app = app\n\n    def get_source(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n            return self._get_source_explained(environment, template)\n        return self._get_source_fast(environment, template)\n\n    def _get_source_explained(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        attempts = []\n        rv: tuple[str, str | None, t.Callable[[], bool] | None] | None\n        trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n        for srcobj, loader in self._iter_loaders(template):\n            try:\n                rv = loader.get_source(environment, template)\n                if trv is None:\n                    trv = rv\n            except TemplateNotFound:\n                rv = None\n            attempts.append((loader, srcobj, rv))\n\n        from .debughelpers import explain_template_loading_attempts\n\n        explain_template_loading_attempts(self.app, template, attempts)\n\n        if trv is not None:\n            return trv\n        raise TemplateNotFound(template)\n\n    def _get_source_fast(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        for _srcobj, loader in self._iter_loaders(template):\n            try:\n                return loader.get_source(environment, template)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(template)\n\n    def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n        loader = self.app.jinja_loader\n        if loader is not None:\n            yield self.app, loader\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                yield blueprint, loader\n\n    def list_templates(self) -> list[str]:\n        result = set()\n        loader = self.app.jinja_loader\n        if loader is not None:\n            result.update(loader.list_templates())\n\n        for blueprint in self.app.iter_blueprints():\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                for template in loader.list_templates():\n                    result.add(template)\n\n        return list(result)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-e9c9f80ff9f3c900", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 84, "local_path": "data-flow/inline-intermediate-variables/I12__flask__DispatchingJinjaLoader__4f0252d8.py", "order": 12, "original_content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "parent_variant_id": "pyint-207037d58e53-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L49-L120", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "DispatchingJinjaLoader", "variant_id": "pyint-96ca4f0252d8-I12", "group_id": "py-e9c9f80ff9f3c900", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 391, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0b47332e20fc-I13", "source": "from __future__ import annotations\nimport typing as t\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nclass DispatchingJinjaLoader(BaseLoader):\n    \"\"\"A loader that looks for templates in the application and all\n    the blueprint folders.\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self.app = app\n\n    def get_source(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n            return self._get_source_explained(environment, template)\n        return self._get_source_fast(environment, template)\n\n    def _get_source_explained(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        attempts = []\n        rv: tuple[str, str | None, t.Callable[[], bool] | None] | None\n        trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n        loopIterator = __import__(\"builtins\").iter(self._iter_loaders(template))\n        while True:\n            try:\n                srcobj, loader = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            try:\n                rv = loader.get_source(environment, template)\n                if trv is None:\n                    trv = rv\n            except TemplateNotFound:\n                rv = None\n            attempts.append((loader, srcobj, rv))\n\n        from .debughelpers import explain_template_loading_attempts\n\n        explain_template_loading_attempts(self.app, template, attempts)\n\n        if trv is not None:\n            return trv\n        raise TemplateNotFound(template)\n\n    def _get_source_fast(\n        self, environment: BaseEnvironment, template: str\n    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n        loopIteratorA = __import__(\"builtins\").iter(self._iter_loaders(template))\n        while True:\n            try:\n                _srcobj, loader = __import__(\"builtins\").next(loopIteratorA)\n            except __import__(\"builtins\").StopIteration:\n                break\n            try:\n                return loader.get_source(environment, template)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(template)\n\n    def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n        loader = self.app.jinja_loader\n        if loader is not None:\n            yield self.app, loader\n\n        loopIteratorB = __import__(\"builtins\").iter(self.app.iter_blueprints())\n        while True:\n            try:\n                blueprint = __import__(\"builtins\").next(loopIteratorB)\n            except __import__(\"builtins\").StopIteration:\n                break\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                yield blueprint, loader\n\n    def list_templates(self) -> list[str]:\n        result = set()\n        loader = self.app.jinja_loader\n        if loader is not None:\n            result.update(loader.list_templates())\n\n        loopIteratorD = __import__(\"builtins\").iter(self.app.iter_blueprints())\n        while True:\n            try:\n                blueprint = __import__(\"builtins\").next(loopIteratorD)\n            except __import__(\"builtins\").StopIteration:\n                break\n            loader = blueprint.jinja_loader\n            if loader is not None:\n                loopIteratorC = __import__(\"builtins\").iter(loader.list_templates())\n                while True:\n                    try:\n                        template = __import__(\"builtins\").next(loopIteratorC)\n                    except __import__(\"builtins\").StopIteration:\n                        break\n                    result.add(template)\n\n        return list(result)\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-e9c9f80ff9f3c900", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "fd268fd5b15f59b35ab7e2aca613770b91228b41b07fe743e5e416a39c8c08e4", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 109, "local_path": "control-flow/lower-for-to-while/I13__flask__DispatchingJinjaLoader__332e20fc.py", "order": 13, "original_content_sha256": "cdb031a9a3a9cda15f146900030eec5a93aaa38121b2fa0cc6167527fbec3f66", "parent_variant_id": "pyint-207037d58e53-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/templating.py#L49-L120", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 5, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 5, "synchronous_for_loops_eligible": 5, "synchronous_for_loops_found": 5}, "unit_kind": "class", "unit_name": "DispatchingJinjaLoader", "variant_id": "pyint-0b47332e20fc-I13", "group_id": "py-e9c9f80ff9f3c900", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 392, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f8952e499e9b-SRC", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass JSONProvider:\n    \"\"\"A standard set of JSON operations for an application. Subclasses\n    of this can be used to customize JSON behavior or use different\n    JSON libraries.\n\n    To implement a provider for a specific library, subclass this base\n    class and implement at least :meth:`dumps` and :meth:`loads`. All\n    other methods have default implementations.\n\n    To use a different provider, either subclass ``Flask`` and set\n    :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n    :attr:`app.json <flask.Flask.json>` to an instance of the class.\n\n    :param app: An application instance. This will be stored as a\n        :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n    .. versionadded:: 2.2\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self._app: App = weakref.proxy(app)\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON.\n\n        :param obj: The data to serialize.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n        \"\"\"Serialize data as JSON and write to a file.\n\n        :param obj: The data to serialize.\n        :param fp: A file opened for writing text. Should use the UTF-8\n            encoding to be valid JSON.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        fp.write(self.dumps(obj, **kwargs))\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON read from a file.\n\n        :param fp: A file opened for reading text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        return self.loads(fp.read(), **kwargs)\n\n    def _prepare_response_obj(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> t.Any:\n        if args and kwargs:\n            raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n        if not args and not kwargs:\n            return None\n\n        if len(args) == 1:\n            return args[0]\n\n        return args or kwargs\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with the ``application/json``\n        mimetype.\n\n        The :func:`~flask.json.jsonify` function calls this method for\n        the current application.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        return self._app.response_class(self.dumps(obj), mimetype=\"application/json\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-eae625b66a3ddd1d", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 97, "local_path": "source-original/SRC__flask__JSONProvider__2e499e9b.py", "order": 0, "original_content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L19-L105", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "JSONProvider", "variant_id": "pyint-f8952e499e9b-SRC", "group_id": "py-eae625b66a3ddd1d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 365, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2a111e7f467d-I01", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass JSONProvider:\n    \n\n    def __init__(self, app: App) -> None:\n        self._app: App = weakref.proxy(app)\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \n        raise NotImplementedError\n\n    def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n        \n        fp.write(self.dumps(obj, **kwargs))\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \n        raise NotImplementedError\n\n    def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n        \n        return self.loads(fp.read(), **kwargs)\n\n    def _prepare_response_obj(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> t.Any:\n        if args and kwargs:\n            raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n        if not args and not kwargs:\n            return None\n\n        if len(args) == 1:\n            return args[0]\n\n        return args or kwargs\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \n        obj = self._prepare_response_obj(args, kwargs)\n        return self._app.response_class(self.dumps(obj), mimetype=\"application/json\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-eae625b66a3ddd1d", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "bf2cf0b2f8174000c00b9cc1227a7612031fb8f42cc083adfc248f07888b5142", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 50, "local_path": "comments/remove-comments/I01__flask__JSONProvider__1e7f467d.py", "order": 1, "original_content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "parent_variant_id": "pyint-f8952e499e9b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L19-L105", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 2052, "comments_removed": 6, "docstrings_removed": 6, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "JSONProvider", "variant_id": "pyint-2a111e7f467d-I01", "group_id": "py-eae625b66a3ddd1d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 366, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2f583f92c5a9-I02", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass JSONProvider:\n    \"\"\"A standard set of JSON operations for an application. Subclasses\n    of this can be used to customize JSON behavior or use different\n    JSON libraries.\n\n    To implement a provider for a specific library, subclass this base\n    class and implement at least :meth:`dumps` and :meth:`loads`. All\n    other methods have default implementations.\n\n    To use a different provider, either subclass ``Flask`` and set\n    :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n    :attr:`app.json <flask.Flask.json>` to an instance of the class.\n\n    :param app: An application instance. This will be stored as a\n        :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n    .. versionadded:: 2.2\n    \"\"\"\n\n    def __init__(self, app2: App) -> None:\n        self._app: App = weakref.proxy(app2)\n\n    def dum(self, obj2: t.Any, **kwa: t.Any) -> str:\n        \"\"\"Serialize data as JSON.\n\n        :param obj: The data to serialize.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def dum2(self, obj3: t.Any, fp2: t.IO[str], **kwa2: t.Any) -> None:\n        \"\"\"Serialize data as JSON and write to a file.\n\n        :param obj: The data to serialize.\n        :param fp: A file opened for writing text. Should use the UTF-8\n            encoding to be valid JSON.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        fp2.write(self.dum(obj3, **kwa2))\n\n    def loa(self, s: str | bytes, **kwa3: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def loa2(self, fp3: t.IO[t.AnyStr], **kwa4: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON read from a file.\n\n        :param fp: A file opened for reading text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        return self.loa(fp3.read(), **kwa4)\n\n    def prepare(\n        self, arg: tuple[t.Any, ...], kwa5: dict[str, t.Any]\n    ) -> t.Any:\n        if arg and kwa5:\n            raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n        if not arg and not kwa5:\n            return None\n\n        if len(arg) == 1:\n            return arg[0]\n\n        return arg or kwa5\n\n    def res(self, *arg2: t.Any, **kwa6: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with the ``application/json``\n        mimetype.\n\n        The :func:`~flask.json.jsonify` function calls this method for\n        the current application.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj4 = self.prepare(arg2, kwa6)\n        return self._app.response_class(self.dum(obj4), mimetype=\"application/json\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-eae625b66a3ddd1d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "bacb4012e3cf8b5ddd32d2bdd1612b0cb1321ebc5936e48ab1cace1c6ffbe9f8", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 97, "local_path": "identifiers/shorten-identifiers/I02__flask__JSONProvider__3f92c5a9.py", "order": 2, "original_content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "parent_variant_id": "pyint-f8952e499e9b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L19-L105", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 42, "identifiers_declared": 21}, "unit_kind": "class", "unit_name": "JSONProvider", "variant_id": "pyint-2f583f92c5a9-I02", "group_id": "py-eae625b66a3ddd1d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 367, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c2c03c8b051d-I03", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass JSONProvider:\n    \"\"\"A standard set of JSON operations for an application. Subclasses\n    of this can be used to customize JSON behavior or use different\n    JSON libraries.\n\n    To implement a provider for a specific library, subclass this base\n    class and implement at least :meth:`dumps` and :meth:`loads`. All\n    other methods have default implementations.\n\n    To use a different provider, either subclass ``Flask`` and set\n    :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n    :attr:`app.json <flask.Flask.json>` to an instance of the class.\n\n    :param app: An application instance. This will be stored as a\n        :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n    .. versionadded:: 2.2\n    \"\"\"\n\n    def __init__(self, map: App) -> None:\n        self._app: App = weakref.proxy(map)\n\n    def close(self, key: t.Any, **record: t.Any) -> str:\n        \"\"\"Serialize data as JSON.\n\n        :param obj: The data to serialize.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def save(self, key: t.Any, age: t.IO[str], **offset: t.Any) -> None:\n        \"\"\"Serialize data as JSON and write to a file.\n\n        :param obj: The data to serialize.\n        :param fp: A file opened for writing text. Should use the UTF-8\n            encoding to be valid JSON.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        age.write(self.close(key, **offset))\n\n    def clear(self, key: str | bytes, **source: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def open(self, age: t.IO[t.AnyStr], **target: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON read from a file.\n\n        :param fp: A file opened for reading text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        return self.clear(age.read(), **target)\n\n    def validateAddress(\n        self, size: tuple[t.Any, ...], window: dict[str, t.Any]\n    ) -> t.Any:\n        if size and window:\n            raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n        if not size and not window:\n            return None\n\n        if len(size) == 1:\n            return size[0]\n\n        return size or window\n\n    def loadUser(self, *node: t.Any, **offset: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with the ``application/json``\n        mimetype.\n\n        The :func:`~flask.json.jsonify` function calls this method for\n        the current application.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        map = self.validateAddress(node, offset)\n        return self._app.response_class(self.close(map), mimetype=\"application/json\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-eae625b66a3ddd1d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "46fae89f2790a6bdbab0b7654357c177c2b790fc1c80ba4836963e84187a327b", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 97, "local_path": "identifiers/mislead-identifiers/I03__flask__JSONProvider__3c8b051d.py", "order": 3, "original_content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "parent_variant_id": "pyint-f8952e499e9b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L19-L105", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 42, "identifiers_declared": 21, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 1, "local_exact_length_matches": 12, "local_random_pool_selections": 15, "local_total_length_difference": 4, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 5, "method_random_pool_selections": 6, "method_total_length_difference": 6}, "unit_kind": "class", "unit_name": "JSONProvider", "variant_id": "pyint-c2c03c8b051d-I03", "group_id": "py-eae625b66a3ddd1d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 368, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8a3d3804ac61-I04", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass JSONProvider:\n    \"\"\"A standard set of JSON operations for an application. Subclasses\n    of this can be used to customize JSON behavior or use different\n    JSON libraries.\n\n    To implement a provider for a specific library, subclass this base\n    class and implement at least :meth:`dumps` and :meth:`loads`. All\n    other methods have default implementations.\n\n    To use a different provider, either subclass ``Flask`` and set\n    :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n    :attr:`app.json <flask.Flask.json>` to an instance of the class.\n\n    :param app: An application instance. This will be stored as a\n        :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n    .. versionadded:: 2.2\n    \"\"\"\n\n    def __init__(self, g: App) -> None:\n        self._app: App = weakref.proxy(g)\n\n    def a(self, h: t.Any, **i: t.Any) -> str:\n        \"\"\"Serialize data as JSON.\n\n        :param obj: The data to serialize.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def b(self, j: t.Any, k: t.IO[str], **l: t.Any) -> None:\n        \"\"\"Serialize data as JSON and write to a file.\n\n        :param obj: The data to serialize.\n        :param fp: A file opened for writing text. Should use the UTF-8\n            encoding to be valid JSON.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        k.write(self.a(j, **l))\n\n    def c(self, m: str | bytes, **n: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def d(self, o: t.IO[t.AnyStr], **p: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON read from a file.\n\n        :param fp: A file opened for reading text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        return self.c(o.read(), **p)\n\n    def e(\n        self, q: tuple[t.Any, ...], r: dict[str, t.Any]\n    ) -> t.Any:\n        if q and r:\n            raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n        if not q and not r:\n            return None\n\n        if len(q) == 1:\n            return q[0]\n\n        return q or r\n\n    def f(self, *s: t.Any, **u: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with the ``application/json``\n        mimetype.\n\n        The :func:`~flask.json.jsonify` function calls this method for\n        the current application.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        v = self.e(s, u)\n        return self._app.response_class(self.a(v), mimetype=\"application/json\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-eae625b66a3ddd1d", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "edf42725c70e8e9cd207475ef9ebd99e554475bbf797dec01adeab38c515108d", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 97, "local_path": "identifiers/garble-identifiers/I04__flask__JSONProvider__3804ac61.py", "order": 4, "original_content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "parent_variant_id": "pyint-f8952e499e9b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L19-L105", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 42, "identifiers_declared": 21}, "unit_kind": "class", "unit_name": "JSONProvider", "variant_id": "pyint-8a3d3804ac61-I04", "group_id": "py-eae625b66a3ddd1d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 369, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c8f8ddfc91f4-I05", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass JSONProvider:\n    \"\"\"A standard set of JSON operations for an application. Subclasses\n    of this can be used to customize JSON behavior or use different\n    JSON libraries.\n\n    To implement a provider for a specific library, subclass this base\n    class and implement at least :meth:`dumps` and :meth:`loads`. All\n    other methods have default implementations.\n\n    To use a different provider, either subclass ``Flask`` and set\n    :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n    :attr:`app.json <flask.Flask.json>` to an instance of the class.\n\n    :param app: An application instance. This will be stored as a\n        :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n    .. versionadded:: 2.2\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self._app: App = weakref.proxy(app)\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON.\n\n        :param obj: The data to serialize.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n        \"\"\"Serialize data as JSON and write to a file.\n\n        :param obj: The data to serialize.\n        :param fp: A file opened for writing text. Should use the UTF-8\n            encoding to be valid JSON.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        fp.write(self.dumps(obj, **kwargs))\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON read from a file.\n\n        :param fp: A file opened for reading text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        return self.loads(fp.read(), **kwargs)\n\n    def _prepare_response_obj(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> t.Any:\n        if args and kwargs:\n            raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n        if not args and not kwargs:\n            return None\n\n        if len(args) == 0x1:\n            return args[0x0]\n\n        return args or kwargs\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with the ``application/json``\n        mimetype.\n\n        The :func:`~flask.json.jsonify` function calls this method for\n        the current application.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        return self._app.response_class(self.dumps(obj), mimetype=\"application/json\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-eae625b66a3ddd1d", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "1bfe41cd540e91244f10e6f9eb5c4a23ab5353675614106982ca01a13988faa5", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 97, "local_path": "expressions/encode-integer-literals/I05__flask__JSONProvider__ddfc91f4.py", "order": 5, "original_content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "parent_variant_id": "pyint-f8952e499e9b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L19-L105", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 2}, "unit_kind": "class", "unit_name": "JSONProvider", "variant_id": "pyint-c8f8ddfc91f4-I05", "group_id": "py-eae625b66a3ddd1d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 370, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-126794e56bca-I06", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass JSONProvider:\n    \"\"\"A standard set of JSON operations for an application. Subclasses\n    of this can be used to customize JSON behavior or use different\n    JSON libraries.\n\n    To implement a provider for a specific library, subclass this base\n    class and implement at least :meth:`dumps` and :meth:`loads`. All\n    other methods have default implementations.\n\n    To use a different provider, either subclass ``Flask`` and set\n    :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n    :attr:`app.json <flask.Flask.json>` to an instance of the class.\n\n    :param app: An application instance. This will be stored as a\n        :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n    .. versionadded:: 2.2\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self._app: App = weakref.proxy(app)\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON.\n\n        :param obj: The data to serialize.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n        \"\"\"Serialize data as JSON and write to a file.\n\n        :param obj: The data to serialize.\n        :param fp: A file opened for writing text. Should use the UTF-8\n            encoding to be valid JSON.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        fp.write(self.dumps(obj, **kwargs))\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON read from a file.\n\n        :param fp: A file opened for reading text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        return self.loads(fp.read(), **kwargs)\n\n    def _prepare_response_obj(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> t.Any:\n        if not (args and kwargs):\n            pass\n        else:\n            raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n        if not (not args and not kwargs):\n            pass\n        else:\n            return None\n\n        if not (len(args) == 1):\n            pass\n        else:\n            return args[0]\n\n        return args or kwargs\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with the ``application/json``\n        mimetype.\n\n        The :func:`~flask.json.jsonify` function calls this method for\n        the current application.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        return self._app.response_class(self.dumps(obj), mimetype=\"application/json\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-eae625b66a3ddd1d", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "5d2c197d0e21db06354fa8942fef91ae77e1133276a7f38ded89de76b2db05bd", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 103, "local_path": "expressions/invert-conditions/I06__flask__JSONProvider__94e56bca.py", "order": 6, "original_content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "parent_variant_id": "pyint-f8952e499e9b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L19-L105", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 3}, "unit_kind": "class", "unit_name": "JSONProvider", "variant_id": "pyint-126794e56bca-I06", "group_id": "py-eae625b66a3ddd1d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 371, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-49ebf29432f2-I07", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass JSONProvider:\n    \"\"\"A standard set of JSON operations for an application. Subclasses\n    of this can be used to customize JSON behavior or use different\n    JSON libraries.\n\n    To implement a provider for a specific library, subclass this base\n    class and implement at least :meth:`dumps` and :meth:`loads`. All\n    other methods have default implementations.\n\n    To use a different provider, either subclass ``Flask`` and set\n    :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n    :attr:`app.json <flask.Flask.json>` to an instance of the class.\n\n    :param app: An application instance. This will be stored as a\n        :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n    .. versionadded:: 2.2\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        if ((0xdef5 ^ 0xdef5) != 0):\n            raise AssertionError()\n        self._app: App = weakref.proxy(app)\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON.\n\n        :param obj: The data to serialize.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        if ((0xfcc4 ^ 0xfcc4) != 0):\n            raise AssertionError()\n        raise NotImplementedError\n\n    def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n        \"\"\"Serialize data as JSON and write to a file.\n\n        :param obj: The data to serialize.\n        :param fp: A file opened for writing text. Should use the UTF-8\n            encoding to be valid JSON.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        if ((0xe131 ^ 0xe131) != 0):\n            raise AssertionError()\n        fp.write(self.dumps(obj, **kwargs))\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        if ((0xcd3a ^ 0xcd3a) != 0):\n            raise AssertionError()\n        raise NotImplementedError\n\n    def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON read from a file.\n\n        :param fp: A file opened for reading text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        if ((0x3e2d ^ 0x3e2d) != 0):\n            raise AssertionError()\n        return self.loads(fp.read(), **kwargs)\n\n    def _prepare_response_obj(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> t.Any:\n        if ((0x78ee ^ 0x78ee) != 0):\n            raise AssertionError()\n        if args and kwargs:\n            raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n        if not args and not kwargs:\n            return None\n\n        if len(args) == 1:\n            return args[0]\n\n        return args or kwargs\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with the ``application/json``\n        mimetype.\n\n        The :func:`~flask.json.jsonify` function calls this method for\n        the current application.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        if ((0xf095 ^ 0xf095) != 0):\n            raise AssertionError()\n        obj = self._prepare_response_obj(args, kwargs)\n        return self._app.response_class(self.dumps(obj), mimetype=\"application/json\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-eae625b66a3ddd1d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "b876ce7a4304cdf0fd8f1f24e3513e0f5ceb0eaa99a7ca9c136beb7d4b1546e6", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 111, "local_path": "code-injection/insert-dead-branches/I07__flask__JSONProvider__f29432f2.py", "order": 7, "original_content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "parent_variant_id": "pyint-f8952e499e9b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L19-L105", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 7}, "unit_kind": "class", "unit_name": "JSONProvider", "variant_id": "pyint-49ebf29432f2-I07", "group_id": "py-eae625b66a3ddd1d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 372, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-983901407c79-I08", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass JSONProvider:\n    \"\"\"A standard set of JSON operations for an application. Subclasses\n    of this can be used to customize JSON behavior or use different\n    JSON libraries.\n\n    To implement a provider for a specific library, subclass this base\n    class and implement at least :meth:`dumps` and :meth:`loads`. All\n    other methods have default implementations.\n\n    To use a different provider, either subclass ``Flask`` and set\n    :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n    :attr:`app.json <flask.Flask.json>` to an instance of the class.\n\n    :param app: An application instance. This will be stored as a\n        :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n    .. versionadded:: 2.2\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self._app: App = weakref.proxy(app)\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON.\n\n        :param obj: The data to serialize.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n        \"\"\"Serialize data as JSON and write to a file.\n\n        :param obj: The data to serialize.\n        :param fp: A file opened for writing text. Should use the UTF-8\n            encoding to be valid JSON.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        fp.write(self.dumps(obj, **kwargs))\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        previous_number = 0\n        current_number = 1\n        for sequence_step in range(4):\n            next_number = previous_number + current_number\n            previous_number = current_number\n            current_number = next_number\n        raise NotImplementedError\n\n    def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON read from a file.\n\n        :param fp: A file opened for reading text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        return self.loads(fp.read(), **kwargs)\n\n    def _prepare_response_obj(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> t.Any:\n        if args and kwargs:\n            raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n        if not args and not kwargs:\n            return None\n\n        if len(args) == 1:\n            return args[0]\n\n        return args or kwargs\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with the ``application/json``\n        mimetype.\n\n        The :func:`~flask.json.jsonify` function calls this method for\n        the current application.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        return self._app.response_class(self.dumps(obj), mimetype=\"application/json\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-eae625b66a3ddd1d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "39e322788c0671726520cee124a1523e624a3b949e77c585488a4f1594ee0213", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 103, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__JSONProvider__01407c79.py", "order": 8, "original_content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "parent_variant_id": "pyint-f8952e499e9b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L19-L105", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 8}, "unit_kind": "class", "unit_name": "JSONProvider", "variant_id": "pyint-983901407c79-I08", "group_id": "py-eae625b66a3ddd1d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 373, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fccd52c605ce-I09", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass JSONProvider:\n    \"\"\"A standard set of JSON operations for an application. Subclasses\n    of this can be used to customize JSON behavior or use different\n    JSON libraries.\n\n    To implement a provider for a specific library, subclass this base\n    class and implement at least :meth:`dumps` and :meth:`loads`. All\n    other methods have default implementations.\n\n    To use a different provider, either subclass ``Flask`` and set\n    :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n    :attr:`app.json <flask.Flask.json>` to an instance of the class.\n\n    :param app: An application instance. This will be stored as a\n        :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n    .. versionadded:: 2.2\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self._app: App = weakref.proxy(app)\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON.\n\n        :param obj: The data to serialize.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n        \"\"\"Serialize data as JSON and write to a file.\n\n        :param obj: The data to serialize.\n        :param fp: A file opened for writing text. Should use the UTF-8\n            encoding to be valid JSON.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        fp.write(self.dumps(obj, **kwargs))\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON read from a file.\n\n        :param fp: A file opened for reading text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        return self.loads(fp.read(), **kwargs)\n\n    def _prepare_response_obj(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> t.Any:\n        if args and kwargs:\n            raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n        if not args and not kwargs:\n            return None\n\n        if len(args) == 1:\n            return args[0]\n\n        return args or kwargs\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with the ``application/json``\n        mimetype.\n\n        The :func:`~flask.json.jsonify` function calls this method for\n        the current application.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        lI0O_c4cbcc03 = 0xaaf7 - 0xaaf7\n        lI0O_c4cbcc03 = (lI0O_c4cbcc03 | 0) if lI0O_c4cbcc03 == 0 else (lI0O_c4cbcc03 & 0)\n        obj = self._prepare_response_obj(args, kwargs)\n        return self._app.response_class(self.dumps(obj), mimetype=\"application/json\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-eae625b66a3ddd1d", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "4eca3c85d151358f51302c473145a84854612a2009b96db326b7a822ee5bf76e", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 99, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__JSONProvider__52c605ce.py", "order": 9, "original_content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "parent_variant_id": "pyint-f8952e499e9b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L19-L105", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 1}, "unit_kind": "class", "unit_name": "JSONProvider", "variant_id": "pyint-fccd52c605ce-I09", "group_id": "py-eae625b66a3ddd1d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 374, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-57b33ec7bedb-I10", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\nclass JSONProvider:\n    \"\"\"A standard set of JSON operations for an application. Subclasses\n    of this can be used to customize JSON behavior or use different\n    JSON libraries.\n\n    To implement a provider for a specific library, subclass this base\n    class and implement at least :meth:`dumps` and :meth:`loads`. All\n    other methods have default implementations.\n    To use a different provider, either subclass ``Flask`` and set\n    :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n    :attr:`app.json <flask.Flask.json>` to an instance of the class.\n\n    :param app: An application instance. This will be stored as a\n        :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n    .. versionadded:: 2.2\n    \"\"\"\n    def __init__(self, app: App) -> None:\n        self._app: App = weakref.proxy(app)\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON.\n\n        :param obj: The data to serialize.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n        \"\"\"Serialize data as JSON and write to a file.\n        :param obj: The data to serialize.\n        :param fp: A file opened for writing text. Should use the UTF-8\n            encoding to be valid JSON.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        fp.write(self.dumps(obj, **kwargs))\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON read from a file.\n\n        :param fp: A file opened for reading text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        return self.loads(fp.read(), **kwargs)\n\n    def _prepare_response_obj(         self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]     ) -> t.Any:\n        if args and kwargs:\n            raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n        if not args and not kwargs:\n            return None\n\n        if len(args) == 1:\n            return args[0]\n\n        return args or kwargs\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with the ``application/json``\n        mimetype.\n        The :func:`~flask.json.jsonify` function calls this method for\n        the current application.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        return self._app.response_class(self.dumps(obj), mimetype=\"application/json\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-eae625b66a3ddd1d", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "2008eca447cbdfbbf5232de37337d020f5b87faeef9b624631a39591806c8d96", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 88, "local_path": "layout/partially-compact-layout/I10__flask__JSONProvider__3ec7bedb.py", "order": 10, "original_content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "parent_variant_id": "pyint-f8952e499e9b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L19-L105", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 24, "line_break_groups_removed": 9, "line_breaks_removed": 9, "whitespace_characters_removed": 7}, "unit_kind": "class", "unit_name": "JSONProvider", "variant_id": "pyint-57b33ec7bedb-I10", "group_id": "py-eae625b66a3ddd1d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 375, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f6d71645da2d-I11", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass JSONProvider:\n    \"\"\"A standard set of JSON operations for an application. Subclasses\n    of this can be used to customize JSON behavior or use different\n    JSON libraries.\n\n    To implement a provider for a specific library, subclass this base\n    class and implement at least :meth:`dumps` and :meth:`loads`. All\n    other methods have default implementations.\n\n    To use a different provider, either subclass ``Flask`` and set\n    :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n    :attr:`app.json <flask.Flask.json>` to an instance of the class.\n\n    :param app: An application instance. This will be stored as a\n        :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n    .. versionadded:: 2.2\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self._app: App = weakref.proxy(app)\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON.\n\n        :param obj: The data to serialize.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n        \"\"\"Serialize data as JSON and write to a file.\n\n        :param obj: The data to serialize.\n        :param fp: A file opened for writing text. Should use the UTF-8\n            encoding to be valid JSON.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        fp.write(self.dumps(obj, **kwargs))\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON read from a file.\n\n        :param fp: A file opened for reading text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        return self.loads(fp.read(), **kwargs)\n\n    def _prepare_response_obj(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> t.Any:\n        if args and kwargs:\n            raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n        if not args and not kwargs:\n            return None\n\n        a = 2\n        b = -1\n        if len(args) == (a + b):\n            c = 1\n            d = -1\n            return args[(c + d)]\n\n        return args or kwargs\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with the ``application/json``\n        mimetype.\n\n        The :func:`~flask.json.jsonify` function calls this method for\n        the current application.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        return self._app.response_class(self.dumps(obj), mimetype=\"application/json\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-eae625b66a3ddd1d", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "db94ef2831f3aa5c697dd37ef1036683e70424df1a470162d4e2b7fc25ec3a9d", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 101, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__JSONProvider__1645da2d.py", "order": 11, "original_content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "parent_variant_id": "pyint-f8952e499e9b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L19-L105", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 2, "intermediate_variables_introduced": 4, "statements_augmented": 2}, "unit_kind": "class", "unit_name": "JSONProvider", "variant_id": "pyint-f6d71645da2d-I11", "group_id": "py-eae625b66a3ddd1d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 376, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f1fb1f3bffde-I12", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass JSONProvider:\n    \"\"\"A standard set of JSON operations for an application. Subclasses\n    of this can be used to customize JSON behavior or use different\n    JSON libraries.\n\n    To implement a provider for a specific library, subclass this base\n    class and implement at least :meth:`dumps` and :meth:`loads`. All\n    other methods have default implementations.\n\n    To use a different provider, either subclass ``Flask`` and set\n    :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n    :attr:`app.json <flask.Flask.json>` to an instance of the class.\n\n    :param app: An application instance. This will be stored as a\n        :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n    .. versionadded:: 2.2\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self._app: App = weakref.proxy(app)\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON.\n\n        :param obj: The data to serialize.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n        \"\"\"Serialize data as JSON and write to a file.\n\n        :param obj: The data to serialize.\n        :param fp: A file opened for writing text. Should use the UTF-8\n            encoding to be valid JSON.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        fp.write(self.dumps(obj, **kwargs))\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON read from a file.\n\n        :param fp: A file opened for reading text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        return self.loads(fp.read(), **kwargs)\n\n    def _prepare_response_obj(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> t.Any:\n        if args and kwargs:\n            raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n        if not args and not kwargs:\n            return None\n\n        if len(args) == 1:\n            return args[0]\n\n        return args or kwargs\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with the ``application/json``\n        mimetype.\n\n        The :func:`~flask.json.jsonify` function calls this method for\n        the current application.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        \n        return self._app.response_class(self.dumps((self._prepare_response_obj(args, kwargs))), mimetype=\"application/json\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-eae625b66a3ddd1d", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "f72ea2878a8974b20a34c9b852b36ce383a4764466f7fbcdaef5a1e339cce6fc", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 97, "local_path": "data-flow/inline-intermediate-variables/I12__flask__JSONProvider__1f3bffde.py", "order": 12, "original_content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "parent_variant_id": "pyint-f8952e499e9b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L19-L105", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "JSONProvider", "variant_id": "pyint-f1fb1f3bffde-I12", "group_id": "py-eae625b66a3ddd1d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 377, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-39d5335b9c18-I13", "source": "from __future__ import annotations\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\nfrom werkzeug.http import http_date\n\nclass JSONProvider:\n    \"\"\"A standard set of JSON operations for an application. Subclasses\n    of this can be used to customize JSON behavior or use different\n    JSON libraries.\n\n    To implement a provider for a specific library, subclass this base\n    class and implement at least :meth:`dumps` and :meth:`loads`. All\n    other methods have default implementations.\n\n    To use a different provider, either subclass ``Flask`` and set\n    :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n    :attr:`app.json <flask.Flask.json>` to an instance of the class.\n\n    :param app: An application instance. This will be stored as a\n        :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n    .. versionadded:: 2.2\n    \"\"\"\n\n    def __init__(self, app: App) -> None:\n        self._app: App = weakref.proxy(app)\n\n    def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n        \"\"\"Serialize data as JSON.\n\n        :param obj: The data to serialize.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n        \"\"\"Serialize data as JSON and write to a file.\n\n        :param obj: The data to serialize.\n        :param fp: A file opened for writing text. Should use the UTF-8\n            encoding to be valid JSON.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        fp.write(self.dumps(obj, **kwargs))\n\n    def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON.\n\n        :param s: Text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        raise NotImplementedError\n\n    def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n        \"\"\"Deserialize data as JSON read from a file.\n\n        :param fp: A file opened for reading text or UTF-8 bytes.\n        :param kwargs: May be passed to the underlying JSON library.\n        \"\"\"\n        return self.loads(fp.read(), **kwargs)\n\n    def _prepare_response_obj(\n        self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n    ) -> t.Any:\n        if args and kwargs:\n            raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n        if not args and not kwargs:\n            return None\n\n        if len(args) == 1:\n            return args[0]\n\n        return args or kwargs\n\n    def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n        \"\"\"Serialize the given arguments as JSON, and return a\n        :class:`~flask.Response` object with the ``application/json``\n        mimetype.\n\n        The :func:`~flask.json.jsonify` function calls this method for\n        the current application.\n\n        Either positional or keyword arguments can be given, not both.\n        If no arguments are given, ``None`` is serialized.\n\n        :param args: A single value to serialize, or multiple values to\n            treat as a list to serialize.\n        :param kwargs: Treat as a dict to serialize.\n        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        return self._app.response_class(self.dumps(obj), mimetype=\"application/json\")\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-eae625b66a3ddd1d", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 97, "local_path": "control-flow/lower-for-to-while/I13__flask__JSONProvider__335b9c18.py", "order": 13, "original_content_sha256": "e11fed6cafb0a517bb98e5bcb3bc02728ebacd5a09fbcbf81180ee2c16c39fa3", "parent_variant_id": "pyint-f8952e499e9b-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/json/provider.py#L19-L105", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "JSONProvider", "variant_id": "pyint-39d5335b9c18-I13", "group_id": "py-eae625b66a3ddd1d", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 378, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-e4dd2048c2c8-SRC", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass AppGroup(click.Group):\n    \"\"\"This works similar to a regular click :class:`~click.Group` but it\n    changes the behavior of the :meth:`command` decorator so that it\n    automatically wraps the functions in :func:`with_appcontext`.\n\n    Not to be confused with :class:`FlaskGroup`.\n    \"\"\"\n\n    def command(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n        unless it's disabled by passing ``with_appcontext=False``.\n        \"\"\"\n        wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n        def decorator(f: t.Callable[..., t.Any]) -> click.Command:\n            if wrap_for_ctx:\n                f = with_appcontext(f)\n            return super(AppGroup, self).command(*args, **kwargs)(f)  # type: ignore[no-any-return]\n\n        return decorator\n\n    def group(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it defaults the group class to\n        :class:`AppGroup`.\n        \"\"\"\n        kwargs.setdefault(\"cls\", AppGroup)\n        return super().group(*args, **kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-ed69315ccbf60a21", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 56, "local_path": "source-original/SRC__flask__AppGroup__2048c2c8.py", "order": 0, "original_content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "parent_variant_id": null, "readability_direction": "baseline", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L405-L437", "source_repository": "https://github.com/pallets/flask.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "AppGroup", "variant_id": "pyint-e4dd2048c2c8-SRC", "group_id": "py-ed69315ccbf60a21", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 505, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-dc4ee8ba69d4-I01", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass AppGroup(click.Group):\n    \n\n    def command(   \n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n        \n        wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n        def decorator(f: t.Callable[..., t.Any]) -> click.Command:\n            if wrap_for_ctx:\n                f = with_appcontext(f)\n            return super(AppGroup, self).command(*args, **kwargs)(f)   \n\n        return decorator\n\n    def group(   \n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n        \n        kwargs.setdefault(\"cls\", AppGroup)\n        return super().group(*args, **kwargs)   \n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-ed69315ccbf60a21", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "bfdedb958bb84f242bbc6b9e9d1dc32f0bc0bc23e2b753fba709ed3d6dd138de", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 45, "local_path": "comments/remove-comments/I01__flask__AppGroup__e8ba69d4.py", "order": 1, "original_content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "parent_variant_id": "pyint-e4dd2048c2c8-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L405-L437", "source_repository": "https://github.com/pallets/flask.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 759, "comments_removed": 7, "docstrings_removed": 3, "line_comments_removed": 4}, "unit_kind": "class", "unit_name": "AppGroup", "variant_id": "pyint-dc4ee8ba69d4-I01", "group_id": "py-ed69315ccbf60a21", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 506, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7c3c8fab7bc5-I02", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass AppGroup(click.Group):\n    \"\"\"This works similar to a regular click :class:`~click.Group` but it\n    changes the behavior of the :meth:`command` decorator so that it\n    automatically wraps the functions in :func:`with_appcontext`.\n\n    Not to be confused with :class:`FlaskGroup`.\n    \"\"\"\n\n    def com(  # type: ignore[override]\n        self, *arg: t.Any, **kwa: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n        unless it's disabled by passing ``with_appcontext=False``.\n        \"\"\"\n        wrap = kwa.pop(\"with_appcontext\", True)\n\n        def decorator(f2: t.Callable[..., t.Any]) -> click.Command:\n            if wrap_for_ctx:\n                f2 = with_appcontext(f2)\n            return super(AppGroup, self).command(*args, **kwargs)(f2)  # type: ignore[no-any-return]\n\n        return decorator\n\n    def gro(  # type: ignore[override]\n        self, *arg2: t.Any, **kwa2: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it defaults the group class to\n        :class:`AppGroup`.\n        \"\"\"\n        kwa2.setdefault(\"cls\", AppGroup)\n        return super().group(*arg2, **kwa2)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-ed69315ccbf60a21", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "f6bf92a5a015984cc06e63e9f0a393b3e0e7ae16fdb03d417347f431bcb19721", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 56, "local_path": "identifiers/shorten-identifiers/I02__flask__AppGroup__8fab7bc5.py", "order": 2, "original_content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "parent_variant_id": "pyint-e4dd2048c2c8-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L405-L437", "source_repository": "https://github.com/pallets/flask.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 15, "identifiers_declared": 8}, "unit_kind": "class", "unit_name": "AppGroup", "variant_id": "pyint-7c3c8fab7bc5-I02", "group_id": "py-ed69315ccbf60a21", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 507, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-57d8e7987acf-I03", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass AppGroup(click.Group):\n    \"\"\"This works similar to a regular click :class:`~click.Group` but it\n    changes the behavior of the :meth:`command` decorator so that it\n    automatically wraps the functions in :func:`with_appcontext`.\n\n    Not to be confused with :class:`FlaskGroup`.\n    \"\"\"\n\n    def execute(  # type: ignore[override]\n        self, *step: t.Any, **target: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n        unless it's disabled by passing ``with_appcontext=False``.\n        \"\"\"\n        sharedStatus = target.pop(\"with_appcontext\", True)\n\n        def decorator(age: t.Callable[..., t.Any]) -> click.Command:\n            if wrap_for_ctx:\n                age = with_appcontext(age)\n            return super(AppGroup, self).command(*args, **kwargs)(age)  # type: ignore[no-any-return]\n\n        return decorator\n\n    def write(  # type: ignore[override]\n        self, *step: t.Any, **source: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it defaults the group class to\n        :class:`AppGroup`.\n        \"\"\"\n        source.setdefault(\"cls\", AppGroup)\n        return super().group(*step, **source)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-ed69315ccbf60a21", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b55f5ed6dc5fe5682bc6a8232af41305f8efb9baf1a91666319b0a6bfeb55b6d", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 56, "local_path": "identifiers/mislead-identifiers/I03__flask__AppGroup__e7987acf.py", "order": 3, "original_content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "parent_variant_id": "pyint-e4dd2048c2c8-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L405-L437", "source_repository": "https://github.com/pallets/flask.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 15, "identifiers_declared": 8, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 5, "local_random_pool_selections": 6, "local_total_length_difference": 2, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 2, "method_random_pool_selections": 2, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "AppGroup", "variant_id": "pyint-57d8e7987acf-I03", "group_id": "py-ed69315ccbf60a21", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 508, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ad635361aff8-I04", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass AppGroup(click.Group):\n    \"\"\"This works similar to a regular click :class:`~click.Group` but it\n    changes the behavior of the :meth:`command` decorator so that it\n    automatically wraps the functions in :func:`with_appcontext`.\n\n    Not to be confused with :class:`FlaskGroup`.\n    \"\"\"\n\n    def a(  # type: ignore[override]\n        self, *c: t.Any, **d: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n        unless it's disabled by passing ``with_appcontext=False``.\n        \"\"\"\n        e = d.pop(\"with_appcontext\", True)\n\n        def decorator(g: t.Callable[..., t.Any]) -> click.Command:\n            if wrap_for_ctx:\n                g = with_appcontext(g)\n            return super(AppGroup, self).command(*args, **kwargs)(g)  # type: ignore[no-any-return]\n\n        return decorator\n\n    def b(  # type: ignore[override]\n        self, *h: t.Any, **i: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it defaults the group class to\n        :class:`AppGroup`.\n        \"\"\"\n        i.setdefault(\"cls\", AppGroup)\n        return super().group(*h, **i)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-ed69315ccbf60a21", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "cc9310a3f852e6203fde160367056ccb94d8f72fdc3f8c2412f5df18127099f5", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 56, "local_path": "identifiers/garble-identifiers/I04__flask__AppGroup__5361aff8.py", "order": 4, "original_content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "parent_variant_id": "pyint-e4dd2048c2c8-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L405-L437", "source_repository": "https://github.com/pallets/flask.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 15, "identifiers_declared": 8}, "unit_kind": "class", "unit_name": "AppGroup", "variant_id": "pyint-ad635361aff8-I04", "group_id": "py-ed69315ccbf60a21", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 509, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fad8e05a65ce-I05", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass AppGroup(click.Group):\n    \"\"\"This works similar to a regular click :class:`~click.Group` but it\n    changes the behavior of the :meth:`command` decorator so that it\n    automatically wraps the functions in :func:`with_appcontext`.\n\n    Not to be confused with :class:`FlaskGroup`.\n    \"\"\"\n\n    def command(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n        unless it's disabled by passing ``with_appcontext=False``.\n        \"\"\"\n        wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n        def decorator(f: t.Callable[..., t.Any]) -> click.Command:\n            if wrap_for_ctx:\n                f = with_appcontext(f)\n            return super(AppGroup, self).command(*args, **kwargs)(f)  # type: ignore[no-any-return]\n\n        return decorator\n\n    def group(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it defaults the group class to\n        :class:`AppGroup`.\n        \"\"\"\n        kwargs.setdefault(\"cls\", AppGroup)\n        return super().group(*args, **kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-ed69315ccbf60a21", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 56, "local_path": "expressions/encode-integer-literals/I05__flask__AppGroup__e05a65ce.py", "order": 5, "original_content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "parent_variant_id": "pyint-e4dd2048c2c8-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L405-L437", "source_repository": "https://github.com/pallets/flask.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "AppGroup", "variant_id": "pyint-fad8e05a65ce-I05", "group_id": "py-ed69315ccbf60a21", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 510, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a0aa1f2f9809-I06", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass AppGroup(click.Group):\n    \"\"\"This works similar to a regular click :class:`~click.Group` but it\n    changes the behavior of the :meth:`command` decorator so that it\n    automatically wraps the functions in :func:`with_appcontext`.\n\n    Not to be confused with :class:`FlaskGroup`.\n    \"\"\"\n\n    def command(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n        unless it's disabled by passing ``with_appcontext=False``.\n        \"\"\"\n        wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n        def decorator(f: t.Callable[..., t.Any]) -> click.Command:\n            if not (wrap_for_ctx):\n                pass\n            else:\n                f = with_appcontext(f)\n            return super(AppGroup, self).command(*args, **kwargs)(f)  # type: ignore[no-any-return]\n\n        return decorator\n\n    def group(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it defaults the group class to\n        :class:`AppGroup`.\n        \"\"\"\n        kwargs.setdefault(\"cls\", AppGroup)\n        return super().group(*args, **kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-ed69315ccbf60a21", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "9fdfa5599ee185e68101b943b84486fcbcf44dfbc5ede34bb21d0529da3ff3d4", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 58, "local_path": "expressions/invert-conditions/I06__flask__AppGroup__1f2f9809.py", "order": 6, "original_content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "parent_variant_id": "pyint-e4dd2048c2c8-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L405-L437", "source_repository": "https://github.com/pallets/flask.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "AppGroup", "variant_id": "pyint-a0aa1f2f9809-I06", "group_id": "py-ed69315ccbf60a21", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 511, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-03729b569a5e-I07", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass AppGroup(click.Group):\n    \"\"\"This works similar to a regular click :class:`~click.Group` but it\n    changes the behavior of the :meth:`command` decorator so that it\n    automatically wraps the functions in :func:`with_appcontext`.\n\n    Not to be confused with :class:`FlaskGroup`.\n    \"\"\"\n\n    def command(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n        unless it's disabled by passing ``with_appcontext=False``.\n        \"\"\"\n        if ((0xb748 ^ 0xb748) != 0):\n            raise AssertionError()\n        wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n        def decorator(f: t.Callable[..., t.Any]) -> click.Command:\n            if ((0xed82 ^ 0xed82) != 0):\n                raise AssertionError()\n            if wrap_for_ctx:\n                f = with_appcontext(f)\n            return super(AppGroup, self).command(*args, **kwargs)(f)  # type: ignore[no-any-return]\n\n        return decorator\n\n    def group(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it defaults the group class to\n        :class:`AppGroup`.\n        \"\"\"\n        if ((0x47a6 ^ 0x47a6) != 0):\n            raise AssertionError()\n        kwargs.setdefault(\"cls\", AppGroup)\n        return super().group(*args, **kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-ed69315ccbf60a21", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "cc551bd3ae022d83d588eec27284d6d760a641d6430a76f9700e8f893edca18f", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 62, "local_path": "code-injection/insert-dead-branches/I07__flask__AppGroup__9b569a5e.py", "order": 7, "original_content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "parent_variant_id": "pyint-e4dd2048c2c8-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L405-L437", "source_repository": "https://github.com/pallets/flask.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 3}, "unit_kind": "class", "unit_name": "AppGroup", "variant_id": "pyint-03729b569a5e-I07", "group_id": "py-ed69315ccbf60a21", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 512, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7ed9c516731e-I08", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass AppGroup(click.Group):\n    \"\"\"This works similar to a regular click :class:`~click.Group` but it\n    changes the behavior of the :meth:`command` decorator so that it\n    automatically wraps the functions in :func:`with_appcontext`.\n\n    Not to be confused with :class:`FlaskGroup`.\n    \"\"\"\n\n    def command(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n        unless it's disabled by passing ``with_appcontext=False``.\n        \"\"\"\n        wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n        def decorator(f: t.Callable[..., t.Any]) -> click.Command:\n            first_score = 72\n            second_score = 85\n            if first_score > second_score:\n                higher_score = first_score\n            else:\n                higher_score = second_score\n            if wrap_for_ctx:\n                f = with_appcontext(f)\n            return super(AppGroup, self).command(*args, **kwargs)(f)  # type: ignore[no-any-return]\n\n        return decorator\n\n    def group(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it defaults the group class to\n        :class:`AppGroup`.\n        \"\"\"\n        kwargs.setdefault(\"cls\", AppGroup)\n        return super().group(*args, **kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-ed69315ccbf60a21", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "5263178f0120c3bc8d9020a7180ea5b823981142cac568de7ac35303cb472f7a", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 62, "local_path": "code-injection/inject-readable-unrelated-code/I08__flask__AppGroup__c516731e.py", "order": 8, "original_content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "parent_variant_id": "pyint-e4dd2048c2c8-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L405-L437", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 3}, "unit_kind": "class", "unit_name": "AppGroup", "variant_id": "pyint-7ed9c516731e-I08", "group_id": "py-ed69315ccbf60a21", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 513, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-661be6c2bb70-I09", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass AppGroup(click.Group):\n    \"\"\"This works similar to a regular click :class:`~click.Group` but it\n    changes the behavior of the :meth:`command` decorator so that it\n    automatically wraps the functions in :func:`with_appcontext`.\n\n    Not to be confused with :class:`FlaskGroup`.\n    \"\"\"\n\n    def command(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n        unless it's disabled by passing ``with_appcontext=False``.\n        \"\"\"\n        wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n        def decorator(f: t.Callable[..., t.Any]) -> click.Command:\n            lI0O_dc2ebd45, lI0O_414f1cd3 = 0x7b24, ~0x7b24\n            lI0O_dc2ebd45 = (lI0O_dc2ebd45 & lI0O_414f1cd3) | (lI0O_dc2ebd45 ^ lI0O_dc2ebd45)\n            lI0O_414f1cd3 ^= lI0O_414f1cd3\n            if wrap_for_ctx:\n                f = with_appcontext(f)\n            return super(AppGroup, self).command(*args, **kwargs)(f)  # type: ignore[no-any-return]\n\n        return decorator\n\n    def group(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it defaults the group class to\n        :class:`AppGroup`.\n        \"\"\"\n        kwargs.setdefault(\"cls\", AppGroup)\n        return super().group(*args, **kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-ed69315ccbf60a21", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "2ce80edf02be461e0e0add5423d96371194237d1263023ed6c67c1d10385cc5e", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 59, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__flask__AppGroup__e6c2bb70.py", "order": 9, "original_content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "parent_variant_id": "pyint-e4dd2048c2c8-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L405-L437", "source_repository": "https://github.com/pallets/flask.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 9}, "unit_kind": "class", "unit_name": "AppGroup", "variant_id": "pyint-661be6c2bb70-I09", "group_id": "py-ed69315ccbf60a21", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 514, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d0925dc0f7a7-I10", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass AppGroup(click.Group):\n    \"\"\"This works similar to a regular click :class:`~click.Group` but it\n    changes the behavior of the :meth:`command` decorator so that it\n    automatically wraps the functions in :func:`with_appcontext`.\n\n    Not to be confused with :class:`FlaskGroup`.\n    \"\"\"\n    def command(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n        unless it's disabled by passing ``with_appcontext=False``.\n        \"\"\"\n        wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n        def decorator(f: t.Callable[..., t.Any]) -> click.Command:\n            if wrap_for_ctx:\n                f = with_appcontext(f)\n            return super(AppGroup, self).command(*args, **kwargs)(f)  # type: ignore[no-any-return]\n        return decorator\n\n    def group(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any     ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it defaults the group class to\n        :class:`AppGroup`.\n        \"\"\"\n        kwargs.setdefault(\"cls\", AppGroup)\n        return super().group(*args, **kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-ed69315ccbf60a21", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "78bc42e7bacca80436b3a9e0c85ee0e4a61ecb25fe5fcd8484e5c238be150f0a", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 53, "local_path": "layout/partially-compact-layout/I10__flask__AppGroup__5dc0f7a7.py", "order": 10, "original_content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "parent_variant_id": "pyint-e4dd2048c2c8-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L405-L437", "source_repository": "https://github.com/pallets/flask.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 8, "line_break_groups_removed": 3, "line_breaks_removed": 3, "whitespace_characters_removed": 2}, "unit_kind": "class", "unit_name": "AppGroup", "variant_id": "pyint-d0925dc0f7a7-I10", "group_id": "py-ed69315ccbf60a21", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 515, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-88b07c856030-I11", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass AppGroup(click.Group):\n    \"\"\"This works similar to a regular click :class:`~click.Group` but it\n    changes the behavior of the :meth:`command` decorator so that it\n    automatically wraps the functions in :func:`with_appcontext`.\n\n    Not to be confused with :class:`FlaskGroup`.\n    \"\"\"\n\n    def command(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n        unless it's disabled by passing ``with_appcontext=False``.\n        \"\"\"\n        wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n        def decorator(f: t.Callable[..., t.Any]) -> click.Command:\n            if wrap_for_ctx:\n                f = with_appcontext(f)\n            return super(AppGroup, self).command(*args, **kwargs)(f)  # type: ignore[no-any-return]\n\n        return decorator\n\n    def group(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it defaults the group class to\n        :class:`AppGroup`.\n        \"\"\"\n        kwargs.setdefault(\"cls\", AppGroup)\n        return super().group(*args, **kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-ed69315ccbf60a21", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 56, "local_path": "data-flow/introduce-numeric-intermediates/I11__flask__AppGroup__7c856030.py", "order": 11, "original_content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "parent_variant_id": "pyint-e4dd2048c2c8-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L405-L437", "source_repository": "https://github.com/pallets/flask.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "AppGroup", "variant_id": "pyint-88b07c856030-I11", "group_id": "py-ed69315ccbf60a21", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 516, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0219f7461604-I12", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass AppGroup(click.Group):\n    \"\"\"This works similar to a regular click :class:`~click.Group` but it\n    changes the behavior of the :meth:`command` decorator so that it\n    automatically wraps the functions in :func:`with_appcontext`.\n\n    Not to be confused with :class:`FlaskGroup`.\n    \"\"\"\n\n    def command(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n        unless it's disabled by passing ``with_appcontext=False``.\n        \"\"\"\n        wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n        def decorator(f: t.Callable[..., t.Any]) -> click.Command:\n            if wrap_for_ctx:\n                f = with_appcontext(f)\n            return super(AppGroup, self).command(*args, **kwargs)(f)  # type: ignore[no-any-return]\n\n        return decorator\n\n    def group(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it defaults the group class to\n        :class:`AppGroup`.\n        \"\"\"\n        kwargs.setdefault(\"cls\", AppGroup)\n        return super().group(*args, **kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-ed69315ccbf60a21", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 56, "local_path": "data-flow/inline-intermediate-variables/I12__flask__AppGroup__f7461604.py", "order": 12, "original_content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "parent_variant_id": "pyint-e4dd2048c2c8-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L405-L437", "source_repository": "https://github.com/pallets/flask.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "AppGroup", "variant_id": "pyint-0219f7461604-I12", "group_id": "py-ed69315ccbf60a21", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 517, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-d788ae10072a-I13", "source": "from __future__ import annotations\nimport ast\nimport collections.abc as cabc\nimport importlib.metadata\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import itemgetter\nfrom types import ModuleType\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nclass AppGroup(click.Group):\n    \"\"\"This works similar to a regular click :class:`~click.Group` but it\n    changes the behavior of the :meth:`command` decorator so that it\n    automatically wraps the functions in :func:`with_appcontext`.\n\n    Not to be confused with :class:`FlaskGroup`.\n    \"\"\"\n\n    def command(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n        unless it's disabled by passing ``with_appcontext=False``.\n        \"\"\"\n        wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n        def decorator(f: t.Callable[..., t.Any]) -> click.Command:\n            if wrap_for_ctx:\n                f = with_appcontext(f)\n            return super(AppGroup, self).command(*args, **kwargs)(f)  # type: ignore[no-any-return]\n\n        return decorator\n\n    def group(  # type: ignore[override]\n        self, *args: t.Any, **kwargs: t.Any\n    ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n        \"\"\"This works exactly like the method of the same name on a regular\n        :class:`click.Group` but it defaults the group class to\n        :class:`AppGroup`.\n        \"\"\"\n        kwargs.setdefault(\"cls\", AppGroup)\n        return super().group(*args, **kwargs)  # type: ignore[no-any-return]\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-ed69315ccbf60a21", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 56, "local_path": "control-flow/lower-for-to-while/I13__flask__AppGroup__ae10072a.py", "order": 13, "original_content_sha256": "d2734fefd227aa26533decba9867421e2697b70d3dcfdbf3c66d0d08a81dbab7", "parent_variant_id": "pyint-e4dd2048c2c8-SRC", "readability_direction": "decreasing", "source": "flask", "source_commit": "d318b683471101618febed18996405ad26462110", "source_name": "Flask", "source_path": "src/flask/cli.py#L405-L437", "source_repository": "https://github.com/pallets/flask.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "AppGroup", "variant_id": "pyint-d788ae10072a-I13", "group_id": "py-ed69315ccbf60a21", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 518, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4c5b4a4b5dfd-SRC", "source": "from ctypes import byref, c_double\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.envelope import Envelope, OGREnvelope\nfrom django.contrib.gis.gdal.error import GDALException, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding import force_bytes, force_str\n\nclass Layer(GDALBase):\n    \"\"\"\n    A class that wraps an OGR Layer, needs to be instantiated from a DataSource\n    object.\n    \"\"\"\n\n    def __init__(self, layer_ptr, ds):\n        \"\"\"\n        Initialize on an OGR C pointer to the Layer and the `DataSource` object\n        that owns this layer. The `DataSource` object is required so that a\n        reference to it is kept with this Layer. This prevents garbage\n        collection of the `DataSource` while this Layer is still active.\n        \"\"\"\n        if not layer_ptr:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = layer_ptr\n        self._ds = ds\n        self._ldefn = capi.get_layer_defn(self._ptr)\n        # Does the Layer support random reading?\n        self._random_read = self.test_capability(b\"RandomRead\")\n\n    def __getitem__(self, index):\n        \"Get the Feature at the specified index.\"\n        if isinstance(index, int):\n            # An integer index was given -- we cannot do a check based on the\n            # number of features because the beginning and ending feature IDs\n            # are not guaranteed to be 0 and len(layer)-1, respectively.\n            if index < 0:\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self._make_feature(index)\n        elif isinstance(index, slice):\n            # A slice was given\n            start, stop, stride = index.indices(self.num_feat)\n            return [self._make_feature(fid) for fid in range(start, stop, stride)]\n        else:\n            raise TypeError(\n                \"Integers and slices may only be used when indexing OGR Layers.\"\n            )\n\n    def __iter__(self):\n        \"Iterate over each Feature in the Layer.\"\n        # ResetReading() must be called before iteration is to begin.\n        capi.reset_reading(self._ptr)\n        for i in range(self.num_feat):\n            yield Feature(capi.get_next_feature(self._ptr), self)\n\n    def __len__(self):\n        \"The length is the number of features.\"\n        return self.num_feat\n\n    def __str__(self):\n        \"The string name of the layer.\"\n        return self.name\n\n    def _make_feature(self, feat_id):\n        \"\"\"\n        Helper routine for __getitem__ that constructs a Feature from the given\n        Feature ID. If the OGR Layer does not support random-access reading,\n        then each feature of the layer will be incremented through until the\n        a Feature is found matching the given feature ID.\n        \"\"\"\n        if self._random_read:\n            # If the Layer supports random reading, return.\n            try:\n                return Feature(capi.get_feature(self.ptr, feat_id), self)\n            except GDALException:\n                pass\n        else:\n            # Random access isn't supported, have to increment through\n            # each feature until the given feature ID is encountered.\n            for feat in self:\n                if feat.fid == feat_id:\n                    return feat\n        # Should have returned a Feature, raise an IndexError.\n        raise IndexError(\"Invalid feature id: %s.\" % feat_id)\n\n    # #### Layer properties ####\n    @property\n    def extent(self):\n        \"Return the extent (an Envelope) of this layer.\"\n        env = OGREnvelope()\n        capi.get_extent(self.ptr, byref(env), 1)\n        return Envelope(env)\n\n    @property\n    def name(self):\n        \"Return the name of this layer in the Data Source.\"\n        name = capi.get_fd_name(self._ldefn)\n        return force_str(name, self._ds.encoding, strings_only=True)\n\n    @property\n    def num_feat(self, force=1):\n        \"Return the number of features in the Layer.\"\n        return capi.get_feature_count(self.ptr, force)\n\n    @property\n    def num_fields(self):\n        \"Return the number of fields in the Layer.\"\n        return capi.get_field_count(self._ldefn)\n\n    @property\n    def geom_type(self):\n        \"Return the geometry type (OGRGeomType) of the Layer.\"\n        return OGRGeomType(capi.get_fd_geom_type(self._ldefn))\n\n    @property\n    def srs(self):\n        \"Return the Spatial Reference used in this Layer.\"\n        try:\n            ptr = capi.get_layer_srs(self.ptr)\n            return SpatialReference(srs_api.clone_srs(ptr))\n        except SRSException:\n            return None\n\n    @property\n    def fields(self):\n        \"\"\"\n        Return a list of string names corresponding to each of the Fields\n        available in this Layer.\n        \"\"\"\n        return [\n            force_str(\n                capi.get_field_name(capi.get_field_defn(self._ldefn, i)),\n                self._ds.encoding,\n                strings_only=True,\n            )\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_types(self):\n        \"\"\"\n        Return a list of the types of fields in this Layer. For example,\n        return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that\n        has an integer, a floating-point, and string fields.\n        \"\"\"\n        return [\n            OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_widths(self):\n        \"Return a list of the maximum field widths for the features.\"\n        return [\n            capi.get_field_width(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_precisions(self):\n        \"Return the field precisions for the features.\"\n        return [\n            capi.get_field_precision(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    def _get_spatial_filter(self):\n        try:\n            return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))\n        except GDALException:\n            return None\n\n    def _set_spatial_filter(self, filter):\n        if isinstance(filter, OGRGeometry):\n            capi.set_spatial_filter(self.ptr, filter.ptr)\n        elif isinstance(filter, (tuple, list)):\n            if not len(filter) == 4:\n                raise ValueError(\"Spatial filter list/tuple must have 4 elements.\")\n            # Map c_double onto params -- if a bad type is passed in it\n            # will be caught here.\n            xmin, ymin, xmax, ymax = map(c_double, filter)\n            capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)\n        elif filter is None:\n            capi.set_spatial_filter(self.ptr, None)\n        else:\n            raise TypeError(\n                \"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or \"\n                \"None.\"\n            )\n\n    spatial_filter = property(_get_spatial_filter, _set_spatial_filter)\n\n    # #### Layer Methods ####\n    def get_fields(self, field_name):\n        \"\"\"\n        Return a list containing the given field name for every Feature\n        in the Layer.\n        \"\"\"\n        if field_name not in self.fields:\n            raise GDALException(\"invalid field name: %s\" % field_name)\n        return [feat.get(field_name) for feat in self]\n\n    def get_geoms(self, geos=False):\n        \"\"\"\n        Return a list containing the OGRGeometry for every Feature in\n        the Layer.\n        \"\"\"\n        if geos:\n            from django.contrib.gis.geos import GEOSGeometry\n\n            return [GEOSGeometry(feat.geom.wkb) for feat in self]\n        else:\n            return [feat.geom for feat in self]\n\n    def test_capability(self, capability):\n        \"\"\"\n        Return a bool indicating whether the this Layer supports the given\n        capability (a string). Valid capability strings include:\n          'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',\n          'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',\n          'DeleteFeature', and 'FastSetNextByIndex'.\n        \"\"\"\n        return bool(capi.test_capability(self.ptr, force_bytes(capability)))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-f0442ed69445adbd", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 228, "local_path": "source-original/SRC__django__Layer__4a4b5dfd.py", "order": 0, "original_content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/gdal/layer.py#L21-L234", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "Layer", "variant_id": "pyint-4c5b4a4b5dfd-SRC", "group_id": "py-f0442ed69445adbd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 43, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cf52dd5e3ab4-I01", "source": "from ctypes import byref, c_double\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.envelope import Envelope, OGREnvelope\nfrom django.contrib.gis.gdal.error import GDALException, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding import force_bytes, force_str\n\nclass Layer(GDALBase):\n    \n\n    def __init__(self, layer_ptr, ds):\n        \n        if not layer_ptr:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = layer_ptr\n        self._ds = ds\n        self._ldefn = capi.get_layer_defn(self._ptr)\n         \n        self._random_read = self.test_capability(b\"RandomRead\")\n\n    def __getitem__(self, index):\n        \n        if isinstance(index, int):\n             \n             \n             \n            if index < 0:\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self._make_feature(index)\n        elif isinstance(index, slice):\n             \n            start, stop, stride = index.indices(self.num_feat)\n            return [self._make_feature(fid) for fid in range(start, stop, stride)]\n        else:\n            raise TypeError(\n                \"Integers and slices may only be used when indexing OGR Layers.\"\n            )\n\n    def __iter__(self):\n        \n         \n        capi.reset_reading(self._ptr)\n        for i in range(self.num_feat):\n            yield Feature(capi.get_next_feature(self._ptr), self)\n\n    def __len__(self):\n        \n        return self.num_feat\n\n    def __str__(self):\n        \n        return self.name\n\n    def _make_feature(self, feat_id):\n        \n        if self._random_read:\n             \n            try:\n                return Feature(capi.get_feature(self.ptr, feat_id), self)\n            except GDALException:\n                pass\n        else:\n             \n             \n            for feat in self:\n                if feat.fid == feat_id:\n                    return feat\n         \n        raise IndexError(\"Invalid feature id: %s.\" % feat_id)\n\n     \n    @property\n    def extent(self):\n        \n        env = OGREnvelope()\n        capi.get_extent(self.ptr, byref(env), 1)\n        return Envelope(env)\n\n    @property\n    def name(self):\n        \n        name = capi.get_fd_name(self._ldefn)\n        return force_str(name, self._ds.encoding, strings_only=True)\n\n    @property\n    def num_feat(self, force=1):\n        \n        return capi.get_feature_count(self.ptr, force)\n\n    @property\n    def num_fields(self):\n        \n        return capi.get_field_count(self._ldefn)\n\n    @property\n    def geom_type(self):\n        \n        return OGRGeomType(capi.get_fd_geom_type(self._ldefn))\n\n    @property\n    def srs(self):\n        \n        try:\n            ptr = capi.get_layer_srs(self.ptr)\n            return SpatialReference(srs_api.clone_srs(ptr))\n        except SRSException:\n            return None\n\n    @property\n    def fields(self):\n        \n        return [\n            force_str(\n                capi.get_field_name(capi.get_field_defn(self._ldefn, i)),\n                self._ds.encoding,\n                strings_only=True,\n            )\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_types(self):\n        \n        return [\n            OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_widths(self):\n        \n        return [\n            capi.get_field_width(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_precisions(self):\n        \n        return [\n            capi.get_field_precision(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    def _get_spatial_filter(self):\n        try:\n            return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))\n        except GDALException:\n            return None\n\n    def _set_spatial_filter(self, filter):\n        if isinstance(filter, OGRGeometry):\n            capi.set_spatial_filter(self.ptr, filter.ptr)\n        elif isinstance(filter, (tuple, list)):\n            if not len(filter) == 4:\n                raise ValueError(\"Spatial filter list/tuple must have 4 elements.\")\n             \n             \n            xmin, ymin, xmax, ymax = map(c_double, filter)\n            capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)\n        elif filter is None:\n            capi.set_spatial_filter(self.ptr, None)\n        else:\n            raise TypeError(\n                \"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or \"\n                \"None.\"\n            )\n\n    spatial_filter = property(_get_spatial_filter, _set_spatial_filter)\n\n     \n    def get_fields(self, field_name):\n        \n        if field_name not in self.fields:\n            raise GDALException(\"invalid field name: %s\" % field_name)\n        return [feat.get(field_name) for feat in self]\n\n    def get_geoms(self, geos=False):\n        \n        if geos:\n            from django.contrib.gis.geos import GEOSGeometry\n\n            return [GEOSGeometry(feat.geom.wkb) for feat in self]\n        else:\n            return [feat.geom for feat in self]\n\n    def test_capability(self, capability):\n        \n        return bool(capi.test_capability(self.ptr, force_bytes(capability)))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-f0442ed69445adbd", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "8c2bb7a35b3b6cc273b5a1cde8ce915e140578e54dc8d506d104b92eba2c8e7c", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 196, "local_path": "comments/remove-comments/I01__django__Layer__dd5e3ab4.py", "order": 1, "original_content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "parent_variant_id": "pyint-4c5b4a4b5dfd-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/gdal/layer.py#L21-L234", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 2850, "comments_removed": 34, "docstrings_removed": 20, "line_comments_removed": 14}, "unit_kind": "class", "unit_name": "Layer", "variant_id": "pyint-cf52dd5e3ab4-I01", "group_id": "py-f0442ed69445adbd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 44, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-2feb8ac53492-I02", "source": "from ctypes import byref, c_double\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.envelope import Envelope, OGREnvelope\nfrom django.contrib.gis.gdal.error import GDALException, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding import force_bytes, force_str\n\nclass Layer(GDALBase):\n    \"\"\"\n    A class that wraps an OGR Layer, needs to be instantiated from a DataSource\n    object.\n    \"\"\"\n\n    def __init__(self, layer, ds2):\n        \"\"\"\n        Initialize on an OGR C pointer to the Layer and the `DataSource` object\n        that owns this layer. The `DataSource` object is required so that a\n        reference to it is kept with this Layer. This prevents garbage\n        collection of the `DataSource` while this Layer is still active.\n        \"\"\"\n        if not layer:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = layer\n        self._ds = ds2\n        self._ldefn = capi.get_layer_defn(self._ptr)\n        # Does the Layer support random reading?\n        self._random_read = self.test(b\"RandomRead\")\n\n    def __getitem__(self, ind):\n        \"Get the Feature at the specified index.\"\n        if isinstance(ind, int):\n            # An integer index was given -- we cannot do a check based on the\n            # number of features because the beginning and ending feature IDs\n            # are not guaranteed to be 0 and len(layer)-1, respectively.\n            if ind < 0:\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self.make(ind)\n        elif isinstance(ind, slice):\n            # A slice was given\n            sta, sto, str = ind.indices(self.num)\n            return [self.make(fid2) for fid2 in range(sta, sto, str)]\n        else:\n            raise TypeError(\n                \"Integers and slices may only be used when indexing OGR Layers.\"\n            )\n\n    def __iter__(self):\n        \"Iterate over each Feature in the Layer.\"\n        # ResetReading() must be called before iteration is to begin.\n        capi.reset_reading(self._ptr)\n        for i2 in range(self.num):\n            yield Feature(capi.get_next_feature(self._ptr), self)\n\n    def __len__(self):\n        \"The length is the number of features.\"\n        return self.num\n\n    def __str__(self):\n        \"The string name of the layer.\"\n        return self.nam\n\n    def make(self, feat2):\n        \"\"\"\n        Helper routine for __getitem__ that constructs a Feature from the given\n        Feature ID. If the OGR Layer does not support random-access reading,\n        then each feature of the layer will be incremented through until the\n        a Feature is found matching the given feature ID.\n        \"\"\"\n        if self._random_read:\n            # If the Layer supports random reading, return.\n            try:\n                return Feature(capi.get_feature(self.ptr, feat2), self)\n            except GDALException:\n                pass\n        else:\n            # Random access isn't supported, have to increment through\n            # each feature until the given feature ID is encountered.\n            for fea in self:\n                if fea.fid == feat2:\n                    return fea\n        # Should have returned a Feature, raise an IndexError.\n        raise IndexError(\"Invalid feature id: %s.\" % feat2)\n\n    # #### Layer properties ####\n    @property\n    def ext(self):\n        \"Return the extent (an Envelope) of this layer.\"\n        env2 = OGREnvelope()\n        capi.get_extent(self.ptr, byref(env2), 1)\n        return Envelope(env2)\n\n    @property\n    def nam(self):\n        \"Return the name of this layer in the Data Source.\"\n        nam2 = capi.get_fd_name(self._ldefn)\n        return force_str(nam2, self._ds.encoding, strings_only=True)\n\n    @property\n    def num(self, for2=1):\n        \"Return the number of features in the Layer.\"\n        return capi.get_feature_count(self.ptr, for2)\n\n    @property\n    def num2(self):\n        \"Return the number of fields in the Layer.\"\n        return capi.get_field_count(self._ldefn)\n\n    @property\n    def geom2(self):\n        \"Return the geometry type (OGRGeomType) of the Layer.\"\n        return OGRGeomType(capi.get_fd_geom_type(self._ldefn))\n\n    @property\n    def srs(self):\n        \"Return the Spatial Reference used in this Layer.\"\n        try:\n            ptr2 = capi.get_layer_srs(self.ptr)\n            return SpatialReference(srs_api.clone_srs(ptr2))\n        except SRSException:\n            return None\n\n    @property\n    def fie(self):\n        \"\"\"\n        Return a list of string names corresponding to each of the Fields\n        available in this Layer.\n        \"\"\"\n        return [\n            force_str(\n                capi.get_field_name(capi.get_field_defn(self._ldefn, i3)),\n                self._ds.encoding,\n                strings_only=True,\n            )\n            for i3 in range(self.num2)\n        ]\n\n    @property\n    def field(self):\n        \"\"\"\n        Return a list of the types of fields in this Layer. For example,\n        return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that\n        has an integer, a floating-point, and string fields.\n        \"\"\"\n        return [\n            OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i4))]\n            for i4 in range(self.num2)\n        ]\n\n    @property\n    def field2(self):\n        \"Return a list of the maximum field widths for the features.\"\n        return [\n            capi.get_field_width(capi.get_field_defn(self._ldefn, i5))\n            for i5 in range(self.num2)\n        ]\n\n    @property\n    def field3(self):\n        \"Return the field precisions for the features.\"\n        return [\n            capi.get_field_precision(capi.get_field_defn(self._ldefn, i6))\n            for i6 in range(self.num2)\n        ]\n\n    def get2(self):\n        try:\n            return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))\n        except GDALException:\n            return None\n\n    def set(self, fil):\n        if isinstance(fil, OGRGeometry):\n            capi.set_spatial_filter(self.ptr, fil.ptr)\n        elif isinstance(fil, (tuple, list)):\n            if not len(fil) == 4:\n                raise ValueError(\"Spatial filter list/tuple must have 4 elements.\")\n            # Map c_double onto params -- if a bad type is passed in it\n            # will be caught here.\n            xmi, ymi, xma, yma = map(c_double, fil)\n            capi.set_spatial_filter_rect(self.ptr, xmi, ymi, xma, yma)\n        elif fil is None:\n            capi.set_spatial_filter(self.ptr, None)\n        else:\n            raise TypeError(\n                \"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or \"\n                \"None.\"\n            )\n\n    spatial_filter = property(_get_spatial_filter, _set_spatial_filter)\n\n    # #### Layer Methods ####\n    def get3(self, field4):\n        \"\"\"\n        Return a list containing the given field name for every Feature\n        in the Layer.\n        \"\"\"\n        if field4 not in self.fie:\n            raise GDALException(\"invalid field name: %s\" % field4)\n        return [fea2.get(field4) for fea2 in self]\n\n    def get4(self, geo=False):\n        \"\"\"\n        Return a list containing the OGRGeometry for every Feature in\n        the Layer.\n        \"\"\"\n        if geo:\n            from django.contrib.gis.geos import GEOSGeometry\n\n            return [GEOSGeometry(fea3.geom.wkb) for fea3 in self]\n        else:\n            return [fea3.geom for fea3 in self]\n\n    def test(self, cap):\n        \"\"\"\n        Return a bool indicating whether the this Layer supports the given\n        capability (a string). Valid capability strings include:\n          'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',\n          'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',\n          'DeleteFeature', and 'FastSetNextByIndex'.\n        \"\"\"\n        return bool(capi.test_capability(self.ptr, force_bytes(cap)))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-f0442ed69445adbd", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "38eabb9881ec5db79b2c84829212b9dc09b50f0f7caa9e03d1540881627991f3", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 228, "local_path": "identifiers/shorten-identifiers/I02__django__Layer__8ac53492.py", "order": 2, "original_content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "parent_variant_id": "pyint-4c5b4a4b5dfd-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/gdal/layer.py#L21-L234", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 101, "identifiers_declared": 44}, "unit_kind": "class", "unit_name": "Layer", "variant_id": "pyint-2feb8ac53492-I02", "group_id": "py-f0442ed69445adbd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 45, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-98a905660aaa-I03", "source": "from ctypes import byref, c_double\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.envelope import Envelope, OGREnvelope\nfrom django.contrib.gis.gdal.error import GDALException, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding import force_bytes, force_str\n\nclass Layer(GDALBase):\n    \"\"\"\n    A class that wraps an OGR Layer, needs to be instantiated from a DataSource\n    object.\n    \"\"\"\n\n    def __init__(self, localMode, key):\n        \"\"\"\n        Initialize on an OGR C pointer to the Layer and the `DataSource` object\n        that owns this layer. The `DataSource` object is required so that a\n        reference to it is kept with this Layer. This prevents garbage\n        collection of the `DataSource` while this Layer is still active.\n        \"\"\"\n        if not localMode:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = localMode\n        self._ds = key\n        self._ldefn = capi.get_layer_defn(self._ptr)\n        # Does the Layer support random reading?\n        self._random_read = self.validateMessage(b\"RandomRead\")\n\n    def __getitem__(self, order):\n        \"Get the Feature at the specified index.\"\n        if isinstance(order, int):\n            # An integer index was given -- we cannot do a check based on the\n            # number of features because the beginning and ending feature IDs\n            # are not guaranteed to be 0 and len(layer)-1, respectively.\n            if order < 0:\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self.validateState(order)\n        elif isinstance(order, slice):\n            # A slice was given\n            token, item, region = order.indices(self.sendData)\n            return [self.validateState(map) for map in range(token, item, region)]\n        else:\n            raise TypeError(\n                \"Integers and slices may only be used when indexing OGR Layers.\"\n            )\n\n    def __iter__(self):\n        \"Iterate over each Feature in the Layer.\"\n        # ResetReading() must be called before iteration is to begin.\n        capi.reset_reading(self._ptr)\n        for map in range(self.sendData):\n            yield Feature(capi.get_next_feature(self._ptr), self)\n\n    def __len__(self):\n        \"The length is the number of features.\"\n        return self.sendData\n\n    def __str__(self):\n        \"The string name of the layer.\"\n        return self.open\n\n    def validateState(self, nextKey):\n        \"\"\"\n        Helper routine for __getitem__ that constructs a Feature from the given\n        Feature ID. If the OGR Layer does not support random-access reading,\n        then each feature of the layer will be incremented through until the\n        a Feature is found matching the given feature ID.\n        \"\"\"\n        if self._random_read:\n            # If the Layer supports random reading, return.\n            try:\n                return Feature(capi.get_feature(self.ptr, nextKey), self)\n            except GDALException:\n                pass\n        else:\n            # Random access isn't supported, have to increment through\n            # each feature until the given feature ID is encountered.\n            for size in self:\n                if size.fid == nextKey:\n                    return size\n        # Should have returned a Feature, raise an IndexError.\n        raise IndexError(\"Invalid feature id: %s.\" % nextKey)\n\n    # #### Layer properties ####\n    @property\n    def upload(self):\n        \"Return the extent (an Envelope) of this layer.\"\n        map = OGREnvelope()\n        capi.get_extent(self.ptr, byref(map), 1)\n        return Envelope(map)\n\n    @property\n    def open(self):\n        \"Return the name of this layer in the Data Source.\"\n        node = capi.get_fd_name(self._ldefn)\n        return force_str(node, self._ds.encoding, strings_only=True)\n\n    @property\n    def sendData(self, score=1):\n        \"Return the number of features in the Layer.\"\n        return capi.get_feature_count(self.ptr, score)\n\n    @property\n    def loadResult(self):\n        \"Return the number of fields in the Layer.\"\n        return capi.get_field_count(self._ldefn)\n\n    @property\n    def saveIndex(self):\n        \"Return the geometry type (OGRGeomType) of the Layer.\"\n        return OGRGeomType(capi.get_fd_geom_type(self._ldefn))\n\n    @property\n    def add(self):\n        \"Return the Spatial Reference used in this Layer.\"\n        try:\n            age = capi.get_layer_srs(self.ptr)\n            return SpatialReference(srs_api.clone_srs(age))\n        except SRSException:\n            return None\n\n    @property\n    def cancel(self):\n        \"\"\"\n        Return a list of string names corresponding to each of the Fields\n        available in this Layer.\n        \"\"\"\n        return [\n            force_str(\n                capi.get_field_name(capi.get_field_defn(self._ldefn, key)),\n                self._ds.encoding,\n                strings_only=True,\n            )\n            for key in range(self.loadResult)\n        ]\n\n    @property\n    def parseBuffer(self):\n        \"\"\"\n        Return a list of the types of fields in this Layer. For example,\n        return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that\n        has an integer, a floating-point, and string fields.\n        \"\"\"\n        return [\n            OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, key))]\n            for key in range(self.loadResult)\n        ]\n\n    @property\n    def parseAddress(self):\n        \"Return a list of the maximum field widths for the features.\"\n        return [\n            capi.get_field_width(capi.get_field_defn(self._ldefn, age))\n            for age in range(self.loadResult)\n        ]\n\n    @property\n    def validateSession(self):\n        \"Return the field precisions for the features.\"\n        return [\n            capi.get_field_precision(capi.get_field_defn(self._ldefn, age))\n            for age in range(self.loadResult)\n        ]\n\n    def validateAddress(self):\n        try:\n            return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))\n        except GDALException:\n            return None\n\n    def validateBalance(self, client):\n        if isinstance(client, OGRGeometry):\n            capi.set_spatial_filter(self.ptr, client.ptr)\n        elif isinstance(client, (tuple, list)):\n            if not len(client) == 4:\n                raise ValueError(\"Spatial filter list/tuple must have 4 elements.\")\n            # Map c_double onto params -- if a bad type is passed in it\n            # will be caught here.\n            step, node, flag, mode = map(c_double, client)\n            capi.set_spatial_filter_rect(self.ptr, step, node, flag, mode)\n        elif client is None:\n            capi.set_spatial_filter(self.ptr, None)\n        else:\n            raise TypeError(\n                \"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or \"\n                \"None.\"\n            )\n\n    spatial_filter = property(_get_spatial_filter, _set_spatial_filter)\n\n    # #### Layer Methods ####\n    def sendClient(self, recentPath):\n        \"\"\"\n        Return a list containing the given field name for every Feature\n        in the Layer.\n        \"\"\"\n        if recentPath not in self.cancel:\n            raise GDALException(\"invalid field name: %s\" % recentPath)\n        return [item.get(recentPath) for item in self]\n\n    def findCount(self, user=False):\n        \"\"\"\n        Return a list containing the OGRGeometry for every Feature in\n        the Layer.\n        \"\"\"\n        if user:\n            from django.contrib.gis.geos import GEOSGeometry\n\n            return [GEOSGeometry(flag.geom.wkb) for flag in self]\n        else:\n            return [flag.geom for flag in self]\n\n    def validateMessage(self, nextConfig):\n        \"\"\"\n        Return a bool indicating whether the this Layer supports the given\n        capability (a string). Valid capability strings include:\n          'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',\n          'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',\n          'DeleteFeature', and 'FastSetNextByIndex'.\n        \"\"\"\n        return bool(capi.test_capability(self.ptr, force_bytes(nextConfig)))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-f0442ed69445adbd", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "2589be8330b792a32a42fd0d984313a03645b0797846e6868398719a9ef889ca", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 228, "local_path": "identifiers/mislead-identifiers/I03__django__Layer__05660aaa.py", "order": 3, "original_content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "parent_variant_id": "pyint-4c5b4a4b5dfd-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/gdal/layer.py#L21-L234", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 101, "identifiers_declared": 44, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 22, "local_random_pool_selections": 28, "local_total_length_difference": 11, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 1, "method_exact_length_matches": 13, "method_random_pool_selections": 16, "method_total_length_difference": 9}, "unit_kind": "class", "unit_name": "Layer", "variant_id": "pyint-98a905660aaa-I03", "group_id": "py-f0442ed69445adbd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 46, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-76d0396aa4c6-I04", "source": "from ctypes import byref, c_double\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.envelope import Envelope, OGREnvelope\nfrom django.contrib.gis.gdal.error import GDALException, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding import force_bytes, force_str\n\nclass Layer(GDALBase):\n    \"\"\"\n    A class that wraps an OGR Layer, needs to be instantiated from a DataSource\n    object.\n    \"\"\"\n\n    def __init__(self, r, s):\n        \"\"\"\n        Initialize on an OGR C pointer to the Layer and the `DataSource` object\n        that owns this layer. The `DataSource` object is required so that a\n        reference to it is kept with this Layer. This prevents garbage\n        collection of the `DataSource` while this Layer is still active.\n        \"\"\"\n        if not r:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = r\n        self._ds = s\n        self._ldefn = capi.get_layer_defn(self._ptr)\n        # Does the Layer support random reading?\n        self._random_read = self.q(b\"RandomRead\")\n\n    def __getitem__(self, t):\n        \"Get the Feature at the specified index.\"\n        if isinstance(t, int):\n            # An integer index was given -- we cannot do a check based on the\n            # number of features because the beginning and ending feature IDs\n            # are not guaranteed to be 0 and len(layer)-1, respectively.\n            if t < 0:\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self.a(t)\n        elif isinstance(t, slice):\n            # A slice was given\n            u, v, w = t.indices(self.d)\n            return [self.a(x) for x in range(u, v, w)]\n        else:\n            raise TypeError(\n                \"Integers and slices may only be used when indexing OGR Layers.\"\n            )\n\n    def __iter__(self):\n        \"Iterate over each Feature in the Layer.\"\n        # ResetReading() must be called before iteration is to begin.\n        capi.reset_reading(self._ptr)\n        for y in range(self.d):\n            yield Feature(capi.get_next_feature(self._ptr), self)\n\n    def __len__(self):\n        \"The length is the number of features.\"\n        return self.d\n\n    def __str__(self):\n        \"The string name of the layer.\"\n        return self.c\n\n    def a(self, z):\n        \"\"\"\n        Helper routine for __getitem__ that constructs a Feature from the given\n        Feature ID. If the OGR Layer does not support random-access reading,\n        then each feature of the layer will be incremented through until the\n        a Feature is found matching the given feature ID.\n        \"\"\"\n        if self._random_read:\n            # If the Layer supports random reading, return.\n            try:\n                return Feature(capi.get_feature(self.ptr, z), self)\n            except GDALException:\n                pass\n        else:\n            # Random access isn't supported, have to increment through\n            # each feature until the given feature ID is encountered.\n            for A in self:\n                if A.fid == z:\n                    return A\n        # Should have returned a Feature, raise an IndexError.\n        raise IndexError(\"Invalid feature id: %s.\" % z)\n\n    # #### Layer properties ####\n    @property\n    def b(self):\n        \"Return the extent (an Envelope) of this layer.\"\n        B = OGREnvelope()\n        capi.get_extent(self.ptr, byref(B), 1)\n        return Envelope(B)\n\n    @property\n    def c(self):\n        \"Return the name of this layer in the Data Source.\"\n        C = capi.get_fd_name(self._ldefn)\n        return force_str(C, self._ds.encoding, strings_only=True)\n\n    @property\n    def d(self, D=1):\n        \"Return the number of features in the Layer.\"\n        return capi.get_feature_count(self.ptr, D)\n\n    @property\n    def e(self):\n        \"Return the number of fields in the Layer.\"\n        return capi.get_field_count(self._ldefn)\n\n    @property\n    def f(self):\n        \"Return the geometry type (OGRGeomType) of the Layer.\"\n        return OGRGeomType(capi.get_fd_geom_type(self._ldefn))\n\n    @property\n    def g(self):\n        \"Return the Spatial Reference used in this Layer.\"\n        try:\n            E = capi.get_layer_srs(self.ptr)\n            return SpatialReference(srs_api.clone_srs(E))\n        except SRSException:\n            return None\n\n    @property\n    def h(self):\n        \"\"\"\n        Return a list of string names corresponding to each of the Fields\n        available in this Layer.\n        \"\"\"\n        return [\n            force_str(\n                capi.get_field_name(capi.get_field_defn(self._ldefn, F)),\n                self._ds.encoding,\n                strings_only=True,\n            )\n            for F in range(self.e)\n        ]\n\n    @property\n    def j(self):\n        \"\"\"\n        Return a list of the types of fields in this Layer. For example,\n        return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that\n        has an integer, a floating-point, and string fields.\n        \"\"\"\n        return [\n            OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, G))]\n            for G in range(self.e)\n        ]\n\n    @property\n    def k(self):\n        \"Return a list of the maximum field widths for the features.\"\n        return [\n            capi.get_field_width(capi.get_field_defn(self._ldefn, H))\n            for H in range(self.e)\n        ]\n\n    @property\n    def l(self):\n        \"Return the field precisions for the features.\"\n        return [\n            capi.get_field_precision(capi.get_field_defn(self._ldefn, I))\n            for I in range(self.e)\n        ]\n\n    def m(self):\n        try:\n            return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))\n        except GDALException:\n            return None\n\n    def n(self, J):\n        if isinstance(J, OGRGeometry):\n            capi.set_spatial_filter(self.ptr, J.ptr)\n        elif isinstance(J, (tuple, list)):\n            if not len(J) == 4:\n                raise ValueError(\"Spatial filter list/tuple must have 4 elements.\")\n            # Map c_double onto params -- if a bad type is passed in it\n            # will be caught here.\n            K, L, M, N = map(c_double, J)\n            capi.set_spatial_filter_rect(self.ptr, K, L, M, N)\n        elif J is None:\n            capi.set_spatial_filter(self.ptr, None)\n        else:\n            raise TypeError(\n                \"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or \"\n                \"None.\"\n            )\n\n    spatial_filter = property(_get_spatial_filter, _set_spatial_filter)\n\n    # #### Layer Methods ####\n    def o(self, O):\n        \"\"\"\n        Return a list containing the given field name for every Feature\n        in the Layer.\n        \"\"\"\n        if O not in self.h:\n            raise GDALException(\"invalid field name: %s\" % O)\n        return [P.get(O) for P in self]\n\n    def p(self, Q=False):\n        \"\"\"\n        Return a list containing the OGRGeometry for every Feature in\n        the Layer.\n        \"\"\"\n        if Q:\n            from django.contrib.gis.geos import GEOSGeometry\n\n            return [GEOSGeometry(R.geom.wkb) for R in self]\n        else:\n            return [R.geom for R in self]\n\n    def q(self, S):\n        \"\"\"\n        Return a bool indicating whether the this Layer supports the given\n        capability (a string). Valid capability strings include:\n          'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',\n          'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',\n          'DeleteFeature', and 'FastSetNextByIndex'.\n        \"\"\"\n        return bool(capi.test_capability(self.ptr, force_bytes(S)))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-f0442ed69445adbd", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "6ff3af33cf2537aea060552e0aff524ab11bc1d86caa75f8cc87fc9a0ca8df29", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 228, "local_path": "identifiers/garble-identifiers/I04__django__Layer__396aa4c6.py", "order": 4, "original_content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "parent_variant_id": "pyint-4c5b4a4b5dfd-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/gdal/layer.py#L21-L234", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 101, "identifiers_declared": 44}, "unit_kind": "class", "unit_name": "Layer", "variant_id": "pyint-76d0396aa4c6-I04", "group_id": "py-f0442ed69445adbd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 47, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f5cf4d6e57d1-I05", "source": "from ctypes import byref, c_double\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.envelope import Envelope, OGREnvelope\nfrom django.contrib.gis.gdal.error import GDALException, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding import force_bytes, force_str\n\nclass Layer(GDALBase):\n    \"\"\"\n    A class that wraps an OGR Layer, needs to be instantiated from a DataSource\n    object.\n    \"\"\"\n\n    def __init__(self, layer_ptr, ds):\n        \"\"\"\n        Initialize on an OGR C pointer to the Layer and the `DataSource` object\n        that owns this layer. The `DataSource` object is required so that a\n        reference to it is kept with this Layer. This prevents garbage\n        collection of the `DataSource` while this Layer is still active.\n        \"\"\"\n        if not layer_ptr:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = layer_ptr\n        self._ds = ds\n        self._ldefn = capi.get_layer_defn(self._ptr)\n        # Does the Layer support random reading?\n        self._random_read = self.test_capability(b\"RandomRead\")\n\n    def __getitem__(self, index):\n        \"Get the Feature at the specified index.\"\n        if isinstance(index, int):\n            # An integer index was given -- we cannot do a check based on the\n            # number of features because the beginning and ending feature IDs\n            # are not guaranteed to be 0 and len(layer)-1, respectively.\n            if index < 0x0:\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self._make_feature(index)\n        elif isinstance(index, slice):\n            # A slice was given\n            start, stop, stride = index.indices(self.num_feat)\n            return [self._make_feature(fid) for fid in range(start, stop, stride)]\n        else:\n            raise TypeError(\n                \"Integers and slices may only be used when indexing OGR Layers.\"\n            )\n\n    def __iter__(self):\n        \"Iterate over each Feature in the Layer.\"\n        # ResetReading() must be called before iteration is to begin.\n        capi.reset_reading(self._ptr)\n        for i in range(self.num_feat):\n            yield Feature(capi.get_next_feature(self._ptr), self)\n\n    def __len__(self):\n        \"The length is the number of features.\"\n        return self.num_feat\n\n    def __str__(self):\n        \"The string name of the layer.\"\n        return self.name\n\n    def _make_feature(self, feat_id):\n        \"\"\"\n        Helper routine for __getitem__ that constructs a Feature from the given\n        Feature ID. If the OGR Layer does not support random-access reading,\n        then each feature of the layer will be incremented through until the\n        a Feature is found matching the given feature ID.\n        \"\"\"\n        if self._random_read:\n            # If the Layer supports random reading, return.\n            try:\n                return Feature(capi.get_feature(self.ptr, feat_id), self)\n            except GDALException:\n                pass\n        else:\n            # Random access isn't supported, have to increment through\n            # each feature until the given feature ID is encountered.\n            for feat in self:\n                if feat.fid == feat_id:\n                    return feat\n        # Should have returned a Feature, raise an IndexError.\n        raise IndexError(\"Invalid feature id: %s.\" % feat_id)\n\n    # #### Layer properties ####\n    @property\n    def extent(self):\n        \"Return the extent (an Envelope) of this layer.\"\n        env = OGREnvelope()\n        capi.get_extent(self.ptr, byref(env), 0x1)\n        return Envelope(env)\n\n    @property\n    def name(self):\n        \"Return the name of this layer in the Data Source.\"\n        name = capi.get_fd_name(self._ldefn)\n        return force_str(name, self._ds.encoding, strings_only=True)\n\n    @property\n    def num_feat(self, force=0x1):\n        \"Return the number of features in the Layer.\"\n        return capi.get_feature_count(self.ptr, force)\n\n    @property\n    def num_fields(self):\n        \"Return the number of fields in the Layer.\"\n        return capi.get_field_count(self._ldefn)\n\n    @property\n    def geom_type(self):\n        \"Return the geometry type (OGRGeomType) of the Layer.\"\n        return OGRGeomType(capi.get_fd_geom_type(self._ldefn))\n\n    @property\n    def srs(self):\n        \"Return the Spatial Reference used in this Layer.\"\n        try:\n            ptr = capi.get_layer_srs(self.ptr)\n            return SpatialReference(srs_api.clone_srs(ptr))\n        except SRSException:\n            return None\n\n    @property\n    def fields(self):\n        \"\"\"\n        Return a list of string names corresponding to each of the Fields\n        available in this Layer.\n        \"\"\"\n        return [\n            force_str(\n                capi.get_field_name(capi.get_field_defn(self._ldefn, i)),\n                self._ds.encoding,\n                strings_only=True,\n            )\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_types(self):\n        \"\"\"\n        Return a list of the types of fields in this Layer. For example,\n        return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that\n        has an integer, a floating-point, and string fields.\n        \"\"\"\n        return [\n            OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_widths(self):\n        \"Return a list of the maximum field widths for the features.\"\n        return [\n            capi.get_field_width(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_precisions(self):\n        \"Return the field precisions for the features.\"\n        return [\n            capi.get_field_precision(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    def _get_spatial_filter(self):\n        try:\n            return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))\n        except GDALException:\n            return None\n\n    def _set_spatial_filter(self, filter):\n        if isinstance(filter, OGRGeometry):\n            capi.set_spatial_filter(self.ptr, filter.ptr)\n        elif isinstance(filter, (tuple, list)):\n            if not len(filter) == 0x4:\n                raise ValueError(\"Spatial filter list/tuple must have 4 elements.\")\n            # Map c_double onto params -- if a bad type is passed in it\n            # will be caught here.\n            xmin, ymin, xmax, ymax = map(c_double, filter)\n            capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)\n        elif filter is None:\n            capi.set_spatial_filter(self.ptr, None)\n        else:\n            raise TypeError(\n                \"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or \"\n                \"None.\"\n            )\n\n    spatial_filter = property(_get_spatial_filter, _set_spatial_filter)\n\n    # #### Layer Methods ####\n    def get_fields(self, field_name):\n        \"\"\"\n        Return a list containing the given field name for every Feature\n        in the Layer.\n        \"\"\"\n        if field_name not in self.fields:\n            raise GDALException(\"invalid field name: %s\" % field_name)\n        return [feat.get(field_name) for feat in self]\n\n    def get_geoms(self, geos=False):\n        \"\"\"\n        Return a list containing the OGRGeometry for every Feature in\n        the Layer.\n        \"\"\"\n        if geos:\n            from django.contrib.gis.geos import GEOSGeometry\n\n            return [GEOSGeometry(feat.geom.wkb) for feat in self]\n        else:\n            return [feat.geom for feat in self]\n\n    def test_capability(self, capability):\n        \"\"\"\n        Return a bool indicating whether the this Layer supports the given\n        capability (a string). Valid capability strings include:\n          'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',\n          'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',\n          'DeleteFeature', and 'FastSetNextByIndex'.\n        \"\"\"\n        return bool(capi.test_capability(self.ptr, force_bytes(capability)))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-f0442ed69445adbd", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "e9834ac30f6e90a41f64ceebfa56eea612c00ae691b900e4ac332642ed01a5c8", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 228, "local_path": "expressions/encode-integer-literals/I05__django__Layer__4d6e57d1.py", "order": 5, "original_content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "parent_variant_id": "pyint-4c5b4a4b5dfd-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/gdal/layer.py#L21-L234", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 4}, "unit_kind": "class", "unit_name": "Layer", "variant_id": "pyint-f5cf4d6e57d1-I05", "group_id": "py-f0442ed69445adbd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 48, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5dd03a65ae50-I06", "source": "from ctypes import byref, c_double\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.envelope import Envelope, OGREnvelope\nfrom django.contrib.gis.gdal.error import GDALException, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding import force_bytes, force_str\n\nclass Layer(GDALBase):\n    \"\"\"\n    A class that wraps an OGR Layer, needs to be instantiated from a DataSource\n    object.\n    \"\"\"\n\n    def __init__(self, layer_ptr, ds):\n        \"\"\"\n        Initialize on an OGR C pointer to the Layer and the `DataSource` object\n        that owns this layer. The `DataSource` object is required so that a\n        reference to it is kept with this Layer. This prevents garbage\n        collection of the `DataSource` while this Layer is still active.\n        \"\"\"\n        if not (not layer_ptr):\n            pass\n        else:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = layer_ptr\n        self._ds = ds\n        self._ldefn = capi.get_layer_defn(self._ptr)\n        # Does the Layer support random reading?\n        self._random_read = self.test_capability(b\"RandomRead\")\n\n    def __getitem__(self, index):\n        \"Get the Feature at the specified index.\"\n        if isinstance(index, int):\n            # An integer index was given -- we cannot do a check based on the\n            # number of features because the beginning and ending feature IDs\n            # are not guaranteed to be 0 and len(layer)-1, respectively.\n            if index < 0:\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self._make_feature(index)\n        elif isinstance(index, slice):\n            # A slice was given\n            start, stop, stride = index.indices(self.num_feat)\n            return [self._make_feature(fid) for fid in range(start, stop, stride)]\n        else:\n            raise TypeError(\n                \"Integers and slices may only be used when indexing OGR Layers.\"\n            )\n\n    def __iter__(self):\n        \"Iterate over each Feature in the Layer.\"\n        # ResetReading() must be called before iteration is to begin.\n        capi.reset_reading(self._ptr)\n        for i in range(self.num_feat):\n            yield Feature(capi.get_next_feature(self._ptr), self)\n\n    def __len__(self):\n        \"The length is the number of features.\"\n        return self.num_feat\n\n    def __str__(self):\n        \"The string name of the layer.\"\n        return self.name\n\n    def _make_feature(self, feat_id):\n        \"\"\"\n        Helper routine for __getitem__ that constructs a Feature from the given\n        Feature ID. If the OGR Layer does not support random-access reading,\n        then each feature of the layer will be incremented through until the\n        a Feature is found matching the given feature ID.\n        \"\"\"\n        if not (self._random_read):\n            # Random access isn't supported, have to increment through\n            # each feature until the given feature ID is encountered.\n            for feat in self:\n                if feat.fid == feat_id:\n                    return feat\n        else:\n            # If the Layer supports random reading, return.\n            try:\n                return Feature(capi.get_feature(self.ptr, feat_id), self)\n            except GDALException:\n                pass\n        # Should have returned a Feature, raise an IndexError.\n        raise IndexError(\"Invalid feature id: %s.\" % feat_id)\n\n    # #### Layer properties ####\n    @property\n    def extent(self):\n        \"Return the extent (an Envelope) of this layer.\"\n        env = OGREnvelope()\n        capi.get_extent(self.ptr, byref(env), 1)\n        return Envelope(env)\n\n    @property\n    def name(self):\n        \"Return the name of this layer in the Data Source.\"\n        name = capi.get_fd_name(self._ldefn)\n        return force_str(name, self._ds.encoding, strings_only=True)\n\n    @property\n    def num_feat(self, force=1):\n        \"Return the number of features in the Layer.\"\n        return capi.get_feature_count(self.ptr, force)\n\n    @property\n    def num_fields(self):\n        \"Return the number of fields in the Layer.\"\n        return capi.get_field_count(self._ldefn)\n\n    @property\n    def geom_type(self):\n        \"Return the geometry type (OGRGeomType) of the Layer.\"\n        return OGRGeomType(capi.get_fd_geom_type(self._ldefn))\n\n    @property\n    def srs(self):\n        \"Return the Spatial Reference used in this Layer.\"\n        try:\n            ptr = capi.get_layer_srs(self.ptr)\n            return SpatialReference(srs_api.clone_srs(ptr))\n        except SRSException:\n            return None\n\n    @property\n    def fields(self):\n        \"\"\"\n        Return a list of string names corresponding to each of the Fields\n        available in this Layer.\n        \"\"\"\n        return [\n            force_str(\n                capi.get_field_name(capi.get_field_defn(self._ldefn, i)),\n                self._ds.encoding,\n                strings_only=True,\n            )\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_types(self):\n        \"\"\"\n        Return a list of the types of fields in this Layer. For example,\n        return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that\n        has an integer, a floating-point, and string fields.\n        \"\"\"\n        return [\n            OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_widths(self):\n        \"Return a list of the maximum field widths for the features.\"\n        return [\n            capi.get_field_width(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_precisions(self):\n        \"Return the field precisions for the features.\"\n        return [\n            capi.get_field_precision(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    def _get_spatial_filter(self):\n        try:\n            return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))\n        except GDALException:\n            return None\n\n    def _set_spatial_filter(self, filter):\n        if isinstance(filter, OGRGeometry):\n            capi.set_spatial_filter(self.ptr, filter.ptr)\n        elif isinstance(filter, (tuple, list)):\n            if not len(filter) == 4:\n                raise ValueError(\"Spatial filter list/tuple must have 4 elements.\")\n            # Map c_double onto params -- if a bad type is passed in it\n            # will be caught here.\n            xmin, ymin, xmax, ymax = map(c_double, filter)\n            capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)\n        elif filter is None:\n            capi.set_spatial_filter(self.ptr, None)\n        else:\n            raise TypeError(\n                \"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or \"\n                \"None.\"\n            )\n\n    spatial_filter = property(_get_spatial_filter, _set_spatial_filter)\n\n    # #### Layer Methods ####\n    def get_fields(self, field_name):\n        \"\"\"\n        Return a list containing the given field name for every Feature\n        in the Layer.\n        \"\"\"\n        if not (field_name not in self.fields):\n            pass\n        else:\n            raise GDALException(\"invalid field name: %s\" % field_name)\n        return [feat.get(field_name) for feat in self]\n\n    def get_geoms(self, geos=False):\n        \"\"\"\n        Return a list containing the OGRGeometry for every Feature in\n        the Layer.\n        \"\"\"\n        if not (geos):\n            return [feat.geom for feat in self]\n        else:\n            from django.contrib.gis.geos import GEOSGeometry\n\n            return [GEOSGeometry(feat.geom.wkb) for feat in self]\n\n    def test_capability(self, capability):\n        \"\"\"\n        Return a bool indicating whether the this Layer supports the given\n        capability (a string). Valid capability strings include:\n          'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',\n          'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',\n          'DeleteFeature', and 'FastSetNextByIndex'.\n        \"\"\"\n        return bool(capi.test_capability(self.ptr, force_bytes(capability)))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-f0442ed69445adbd", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "6ca4903b0c922e8e5b4c49b7b07820eea453e57e1a62619ee76889137e4bf176", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 232, "local_path": "expressions/invert-conditions/I06__django__Layer__3a65ae50.py", "order": 6, "original_content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "parent_variant_id": "pyint-4c5b4a4b5dfd-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/gdal/layer.py#L21-L234", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 4}, "unit_kind": "class", "unit_name": "Layer", "variant_id": "pyint-5dd03a65ae50-I06", "group_id": "py-f0442ed69445adbd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 49, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cf6940ad79f0-I07", "source": "from ctypes import byref, c_double\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.envelope import Envelope, OGREnvelope\nfrom django.contrib.gis.gdal.error import GDALException, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding import force_bytes, force_str\n\nclass Layer(GDALBase):\n    \"\"\"\n    A class that wraps an OGR Layer, needs to be instantiated from a DataSource\n    object.\n    \"\"\"\n\n    def __init__(self, layer_ptr, ds):\n        \"\"\"\n        Initialize on an OGR C pointer to the Layer and the `DataSource` object\n        that owns this layer. The `DataSource` object is required so that a\n        reference to it is kept with this Layer. This prevents garbage\n        collection of the `DataSource` while this Layer is still active.\n        \"\"\"\n        if ((0x918 ^ 0x918) != 0):\n            raise AssertionError()\n        if not layer_ptr:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = layer_ptr\n        self._ds = ds\n        self._ldefn = capi.get_layer_defn(self._ptr)\n        # Does the Layer support random reading?\n        self._random_read = self.test_capability(b\"RandomRead\")\n\n    def __getitem__(self, index):\n        \"Get the Feature at the specified index.\"\n        if ((0x4971 ^ 0x4971) != 0):\n            raise AssertionError()\n        if isinstance(index, int):\n            # An integer index was given -- we cannot do a check based on the\n            # number of features because the beginning and ending feature IDs\n            # are not guaranteed to be 0 and len(layer)-1, respectively.\n            if index < 0:\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self._make_feature(index)\n        elif isinstance(index, slice):\n            # A slice was given\n            start, stop, stride = index.indices(self.num_feat)\n            return [self._make_feature(fid) for fid in range(start, stop, stride)]\n        else:\n            raise TypeError(\n                \"Integers and slices may only be used when indexing OGR Layers.\"\n            )\n\n    def __iter__(self):\n        \"Iterate over each Feature in the Layer.\"\n        if ((0x9387 ^ 0x9387) != 0):\n            raise AssertionError()\n        # ResetReading() must be called before iteration is to begin.\n        capi.reset_reading(self._ptr)\n        for i in range(self.num_feat):\n            yield Feature(capi.get_next_feature(self._ptr), self)\n\n    def __len__(self):\n        \"The length is the number of features.\"\n        if ((0xaeca ^ 0xaeca) != 0):\n            raise AssertionError()\n        return self.num_feat\n\n    def __str__(self):\n        \"The string name of the layer.\"\n        if ((0x6698 ^ 0x6698) != 0):\n            raise AssertionError()\n        return self.name\n\n    def _make_feature(self, feat_id):\n        \"\"\"\n        Helper routine for __getitem__ that constructs a Feature from the given\n        Feature ID. If the OGR Layer does not support random-access reading,\n        then each feature of the layer will be incremented through until the\n        a Feature is found matching the given feature ID.\n        \"\"\"\n        if ((0x3970 ^ 0x3970) != 0):\n            raise AssertionError()\n        if self._random_read:\n            # If the Layer supports random reading, return.\n            try:\n                return Feature(capi.get_feature(self.ptr, feat_id), self)\n            except GDALException:\n                pass\n        else:\n            # Random access isn't supported, have to increment through\n            # each feature until the given feature ID is encountered.\n            for feat in self:\n                if feat.fid == feat_id:\n                    return feat\n        # Should have returned a Feature, raise an IndexError.\n        raise IndexError(\"Invalid feature id: %s.\" % feat_id)\n\n    # #### Layer properties ####\n    @property\n    def extent(self):\n        \"Return the extent (an Envelope) of this layer.\"\n        if ((0xb7cc ^ 0xb7cc) != 0):\n            raise AssertionError()\n        env = OGREnvelope()\n        capi.get_extent(self.ptr, byref(env), 1)\n        return Envelope(env)\n\n    @property\n    def name(self):\n        \"Return the name of this layer in the Data Source.\"\n        if ((0xe708 ^ 0xe708) != 0):\n            raise AssertionError()\n        name = capi.get_fd_name(self._ldefn)\n        return force_str(name, self._ds.encoding, strings_only=True)\n\n    @property\n    def num_feat(self, force=1):\n        \"Return the number of features in the Layer.\"\n        if ((0x8c25 ^ 0x8c25) != 0):\n            raise AssertionError()\n        return capi.get_feature_count(self.ptr, force)\n\n    @property\n    def num_fields(self):\n        \"Return the number of fields in the Layer.\"\n        if ((0xfce0 ^ 0xfce0) != 0):\n            raise AssertionError()\n        return capi.get_field_count(self._ldefn)\n\n    @property\n    def geom_type(self):\n        \"Return the geometry type (OGRGeomType) of the Layer.\"\n        if ((0x6295 ^ 0x6295) != 0):\n            raise AssertionError()\n        return OGRGeomType(capi.get_fd_geom_type(self._ldefn))\n\n    @property\n    def srs(self):\n        \"Return the Spatial Reference used in this Layer.\"\n        if ((0x3aaf ^ 0x3aaf) != 0):\n            raise AssertionError()\n        try:\n            ptr = capi.get_layer_srs(self.ptr)\n            return SpatialReference(srs_api.clone_srs(ptr))\n        except SRSException:\n            return None\n\n    @property\n    def fields(self):\n        \"\"\"\n        Return a list of string names corresponding to each of the Fields\n        available in this Layer.\n        \"\"\"\n        if ((0xb854 ^ 0xb854) != 0):\n            raise AssertionError()\n        return [\n            force_str(\n                capi.get_field_name(capi.get_field_defn(self._ldefn, i)),\n                self._ds.encoding,\n                strings_only=True,\n            )\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_types(self):\n        \"\"\"\n        Return a list of the types of fields in this Layer. For example,\n        return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that\n        has an integer, a floating-point, and string fields.\n        \"\"\"\n        if ((0xea8 ^ 0xea8) != 0):\n            raise AssertionError()\n        return [\n            OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_widths(self):\n        \"Return a list of the maximum field widths for the features.\"\n        if ((0x4a38 ^ 0x4a38) != 0):\n            raise AssertionError()\n        return [\n            capi.get_field_width(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_precisions(self):\n        \"Return the field precisions for the features.\"\n        if ((0xf012 ^ 0xf012) != 0):\n            raise AssertionError()\n        return [\n            capi.get_field_precision(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    def _get_spatial_filter(self):\n        if ((0x6889 ^ 0x6889) != 0):\n            raise AssertionError()\n        try:\n            return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))\n        except GDALException:\n            return None\n\n    def _set_spatial_filter(self, filter):\n        if ((0xf5e3 ^ 0xf5e3) != 0):\n            raise AssertionError()\n        if isinstance(filter, OGRGeometry):\n            capi.set_spatial_filter(self.ptr, filter.ptr)\n        elif isinstance(filter, (tuple, list)):\n            if not len(filter) == 4:\n                raise ValueError(\"Spatial filter list/tuple must have 4 elements.\")\n            # Map c_double onto params -- if a bad type is passed in it\n            # will be caught here.\n            xmin, ymin, xmax, ymax = map(c_double, filter)\n            capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)\n        elif filter is None:\n            capi.set_spatial_filter(self.ptr, None)\n        else:\n            raise TypeError(\n                \"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or \"\n                \"None.\"\n            )\n\n    spatial_filter = property(_get_spatial_filter, _set_spatial_filter)\n\n    # #### Layer Methods ####\n    def get_fields(self, field_name):\n        \"\"\"\n        Return a list containing the given field name for every Feature\n        in the Layer.\n        \"\"\"\n        if ((0xeea7 ^ 0xeea7) != 0):\n            raise AssertionError()\n        if field_name not in self.fields:\n            raise GDALException(\"invalid field name: %s\" % field_name)\n        return [feat.get(field_name) for feat in self]\n\n    def get_geoms(self, geos=False):\n        \"\"\"\n        Return a list containing the OGRGeometry for every Feature in\n        the Layer.\n        \"\"\"\n        if ((0x9cd0 ^ 0x9cd0) != 0):\n            raise AssertionError()\n        if geos:\n            from django.contrib.gis.geos import GEOSGeometry\n\n            return [GEOSGeometry(feat.geom.wkb) for feat in self]\n        else:\n            return [feat.geom for feat in self]\n\n    def test_capability(self, capability):\n        \"\"\"\n        Return a bool indicating whether the this Layer supports the given\n        capability (a string). Valid capability strings include:\n          'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',\n          'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',\n          'DeleteFeature', and 'FastSetNextByIndex'.\n        \"\"\"\n        if ((0x314a ^ 0x314a) != 0):\n            raise AssertionError()\n        return bool(capi.test_capability(self.ptr, force_bytes(capability)))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-f0442ed69445adbd", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "9bddae6920d8ef29b39a77098090942360d8e19ec47024d6c2b44e3e07fc8956", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 270, "local_path": "code-injection/insert-dead-branches/I07__django__Layer__40ad79f0.py", "order": 7, "original_content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "parent_variant_id": "pyint-4c5b4a4b5dfd-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/gdal/layer.py#L21-L234", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 21}, "unit_kind": "class", "unit_name": "Layer", "variant_id": "pyint-cf6940ad79f0-I07", "group_id": "py-f0442ed69445adbd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 50, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4689fd3961d7-I08", "source": "from ctypes import byref, c_double\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.envelope import Envelope, OGREnvelope\nfrom django.contrib.gis.gdal.error import GDALException, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding import force_bytes, force_str\n\nclass Layer(GDALBase):\n    \"\"\"\n    A class that wraps an OGR Layer, needs to be instantiated from a DataSource\n    object.\n    \"\"\"\n\n    def __init__(self, layer_ptr, ds):\n        \"\"\"\n        Initialize on an OGR C pointer to the Layer and the `DataSource` object\n        that owns this layer. The `DataSource` object is required so that a\n        reference to it is kept with this Layer. This prevents garbage\n        collection of the `DataSource` while this Layer is still active.\n        \"\"\"\n        if not layer_ptr:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = layer_ptr\n        self._ds = ds\n        self._ldefn = capi.get_layer_defn(self._ptr)\n        # Does the Layer support random reading?\n        self._random_read = self.test_capability(b\"RandomRead\")\n\n    def __getitem__(self, index):\n        \"Get the Feature at the specified index.\"\n        if isinstance(index, int):\n            # An integer index was given -- we cannot do a check based on the\n            # number of features because the beginning and ending feature IDs\n            # are not guaranteed to be 0 and len(layer)-1, respectively.\n            if index < 0:\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self._make_feature(index)\n        elif isinstance(index, slice):\n            # A slice was given\n            start, stop, stride = index.indices(self.num_feat)\n            return [self._make_feature(fid) for fid in range(start, stop, stride)]\n        else:\n            raise TypeError(\n                \"Integers and slices may only be used when indexing OGR Layers.\"\n            )\n\n    def __iter__(self):\n        \"Iterate over each Feature in the Layer.\"\n        # ResetReading() must be called before iteration is to begin.\n        capi.reset_reading(self._ptr)\n        for i in range(self.num_feat):\n            yield Feature(capi.get_next_feature(self._ptr), self)\n\n    def __len__(self):\n        \"The length is the number of features.\"\n        return self.num_feat\n\n    def __str__(self):\n        \"The string name of the layer.\"\n        return self.name\n\n    def _make_feature(self, feat_id):\n        \"\"\"\n        Helper routine for __getitem__ that constructs a Feature from the given\n        Feature ID. If the OGR Layer does not support random-access reading,\n        then each feature of the layer will be incremented through until the\n        a Feature is found matching the given feature ID.\n        \"\"\"\n        if self._random_read:\n            # If the Layer supports random reading, return.\n            try:\n                return Feature(capi.get_feature(self.ptr, feat_id), self)\n            except GDALException:\n                pass\n        else:\n            # Random access isn't supported, have to increment through\n            # each feature until the given feature ID is encountered.\n            for feat in self:\n                if feat.fid == feat_id:\n                    return feat\n        # Should have returned a Feature, raise an IndexError.\n        raise IndexError(\"Invalid feature id: %s.\" % feat_id)\n\n    # #### Layer properties ####\n    @property\n    def extent(self):\n        \"Return the extent (an Envelope) of this layer.\"\n        env = OGREnvelope()\n        capi.get_extent(self.ptr, byref(env), 1)\n        return Envelope(env)\n\n    @property\n    def name(self):\n        \"Return the name of this layer in the Data Source.\"\n        name = capi.get_fd_name(self._ldefn)\n        return force_str(name, self._ds.encoding, strings_only=True)\n\n    @property\n    def num_feat(self, force=1):\n        \"Return the number of features in the Layer.\"\n        return capi.get_feature_count(self.ptr, force)\n\n    @property\n    def num_fields(self):\n        \"Return the number of fields in the Layer.\"\n        return capi.get_field_count(self._ldefn)\n\n    @property\n    def geom_type(self):\n        \"Return the geometry type (OGRGeomType) of the Layer.\"\n        return OGRGeomType(capi.get_fd_geom_type(self._ldefn))\n\n    @property\n    def srs(self):\n        \"Return the Spatial Reference used in this Layer.\"\n        try:\n            ptr = capi.get_layer_srs(self.ptr)\n            return SpatialReference(srs_api.clone_srs(ptr))\n        except SRSException:\n            return None\n\n    @property\n    def fields(self):\n        \"\"\"\n        Return a list of string names corresponding to each of the Fields\n        available in this Layer.\n        \"\"\"\n        return [\n            force_str(\n                capi.get_field_name(capi.get_field_defn(self._ldefn, i)),\n                self._ds.encoding,\n                strings_only=True,\n            )\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_types(self):\n        \"\"\"\n        Return a list of the types of fields in this Layer. For example,\n        return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that\n        has an integer, a floating-point, and string fields.\n        \"\"\"\n        return [\n            OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_widths(self):\n        \"Return a list of the maximum field widths for the features.\"\n        return [\n            capi.get_field_width(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_precisions(self):\n        \"Return the field precisions for the features.\"\n        return [\n            capi.get_field_precision(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    def _get_spatial_filter(self):\n        try:\n            return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))\n        except GDALException:\n            return None\n\n    def _set_spatial_filter(self, filter):\n        if isinstance(filter, OGRGeometry):\n            capi.set_spatial_filter(self.ptr, filter.ptr)\n        elif isinstance(filter, (tuple, list)):\n            if not len(filter) == 4:\n                raise ValueError(\"Spatial filter list/tuple must have 4 elements.\")\n            # Map c_double onto params -- if a bad type is passed in it\n            # will be caught here.\n            xmin, ymin, xmax, ymax = map(c_double, filter)\n            capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)\n        elif filter is None:\n            capi.set_spatial_filter(self.ptr, None)\n        else:\n            raise TypeError(\n                \"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or \"\n                \"None.\"\n            )\n\n    spatial_filter = property(_get_spatial_filter, _set_spatial_filter)\n\n    # #### Layer Methods ####\n    def get_fields(self, field_name):\n        \"\"\"\n        Return a list containing the given field name for every Feature\n        in the Layer.\n        \"\"\"\n        if field_name not in self.fields:\n            raise GDALException(\"invalid field name: %s\" % field_name)\n        return [feat.get(field_name) for feat in self]\n\n    def get_geoms(self, geos=False):\n        \"\"\"\n        Return a list containing the OGRGeometry for every Feature in\n        the Layer.\n        \"\"\"\n        if geos:\n            from django.contrib.gis.geos import GEOSGeometry\n\n            return [GEOSGeometry(feat.geom.wkb) for feat in self]\n        else:\n            return [feat.geom for feat in self]\n\n    def test_capability(self, capability):\n        \"\"\"\n        Return a bool indicating whether the this Layer supports the given\n        capability (a string). Valid capability strings include:\n          'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',\n          'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',\n          'DeleteFeature', and 'FastSetNextByIndex'.\n        \"\"\"\n        first_score = 72\n        second_score = 85\n        if first_score > second_score:\n            higher_score = first_score\n        else:\n            higher_score = second_score\n        return bool(capi.test_capability(self.ptr, force_bytes(capability)))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-f0442ed69445adbd", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "63cde1cd8cf84ce928dc8f0ae11f5889de38ff5a407569fa569c3c35513f07aa", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 234, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__Layer__fd3961d7.py", "order": 8, "original_content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "parent_variant_id": "pyint-4c5b4a4b5dfd-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/gdal/layer.py#L21-L234", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 6, "readable_template_index": 3}, "unit_kind": "class", "unit_name": "Layer", "variant_id": "pyint-4689fd3961d7-I08", "group_id": "py-f0442ed69445adbd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 51, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-bf85c699dd9d-I09", "source": "from ctypes import byref, c_double\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.envelope import Envelope, OGREnvelope\nfrom django.contrib.gis.gdal.error import GDALException, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding import force_bytes, force_str\n\nclass Layer(GDALBase):\n    \"\"\"\n    A class that wraps an OGR Layer, needs to be instantiated from a DataSource\n    object.\n    \"\"\"\n\n    def __init__(self, layer_ptr, ds):\n        \"\"\"\n        Initialize on an OGR C pointer to the Layer and the `DataSource` object\n        that owns this layer. The `DataSource` object is required so that a\n        reference to it is kept with this Layer. This prevents garbage\n        collection of the `DataSource` while this Layer is still active.\n        \"\"\"\n        if not layer_ptr:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = layer_ptr\n        self._ds = ds\n        self._ldefn = capi.get_layer_defn(self._ptr)\n        # Does the Layer support random reading?\n        self._random_read = self.test_capability(b\"RandomRead\")\n\n    def __getitem__(self, index):\n        \"Get the Feature at the specified index.\"\n        if isinstance(index, int):\n            # An integer index was given -- we cannot do a check based on the\n            # number of features because the beginning and ending feature IDs\n            # are not guaranteed to be 0 and len(layer)-1, respectively.\n            if index < 0:\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self._make_feature(index)\n        elif isinstance(index, slice):\n            # A slice was given\n            start, stop, stride = index.indices(self.num_feat)\n            return [self._make_feature(fid) for fid in range(start, stop, stride)]\n        else:\n            raise TypeError(\n                \"Integers and slices may only be used when indexing OGR Layers.\"\n            )\n\n    def __iter__(self):\n        \"Iterate over each Feature in the Layer.\"\n        # ResetReading() must be called before iteration is to begin.\n        capi.reset_reading(self._ptr)\n        for i in range(self.num_feat):\n            yield Feature(capi.get_next_feature(self._ptr), self)\n\n    def __len__(self):\n        \"The length is the number of features.\"\n        return self.num_feat\n\n    def __str__(self):\n        \"The string name of the layer.\"\n        return self.name\n\n    def _make_feature(self, feat_id):\n        \"\"\"\n        Helper routine for __getitem__ that constructs a Feature from the given\n        Feature ID. If the OGR Layer does not support random-access reading,\n        then each feature of the layer will be incremented through until the\n        a Feature is found matching the given feature ID.\n        \"\"\"\n        if self._random_read:\n            # If the Layer supports random reading, return.\n            try:\n                return Feature(capi.get_feature(self.ptr, feat_id), self)\n            except GDALException:\n                pass\n        else:\n            # Random access isn't supported, have to increment through\n            # each feature until the given feature ID is encountered.\n            for feat in self:\n                if feat.fid == feat_id:\n                    return feat\n        # Should have returned a Feature, raise an IndexError.\n        raise IndexError(\"Invalid feature id: %s.\" % feat_id)\n\n    # #### Layer properties ####\n    @property\n    def extent(self):\n        \"Return the extent (an Envelope) of this layer.\"\n        env = OGREnvelope()\n        capi.get_extent(self.ptr, byref(env), 1)\n        return Envelope(env)\n\n    @property\n    def name(self):\n        \"Return the name of this layer in the Data Source.\"\n        name = capi.get_fd_name(self._ldefn)\n        return force_str(name, self._ds.encoding, strings_only=True)\n\n    @property\n    def num_feat(self, force=1):\n        \"Return the number of features in the Layer.\"\n        return capi.get_feature_count(self.ptr, force)\n\n    @property\n    def num_fields(self):\n        \"Return the number of fields in the Layer.\"\n        return capi.get_field_count(self._ldefn)\n\n    @property\n    def geom_type(self):\n        \"Return the geometry type (OGRGeomType) of the Layer.\"\n        return OGRGeomType(capi.get_fd_geom_type(self._ldefn))\n\n    @property\n    def srs(self):\n        \"Return the Spatial Reference used in this Layer.\"\n        lI0O_4e671814, lI0O_acef4831 = 0x53ee, True\n        while lI0O_acef4831:\n            lI0O_4e671814 ^= 0x53ee\n            lI0O_acef4831 = False\n        try:\n            ptr = capi.get_layer_srs(self.ptr)\n            return SpatialReference(srs_api.clone_srs(ptr))\n        except SRSException:\n            return None\n\n    @property\n    def fields(self):\n        \"\"\"\n        Return a list of string names corresponding to each of the Fields\n        available in this Layer.\n        \"\"\"\n        return [\n            force_str(\n                capi.get_field_name(capi.get_field_defn(self._ldefn, i)),\n                self._ds.encoding,\n                strings_only=True,\n            )\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_types(self):\n        \"\"\"\n        Return a list of the types of fields in this Layer. For example,\n        return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that\n        has an integer, a floating-point, and string fields.\n        \"\"\"\n        return [\n            OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_widths(self):\n        \"Return a list of the maximum field widths for the features.\"\n        return [\n            capi.get_field_width(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_precisions(self):\n        \"Return the field precisions for the features.\"\n        return [\n            capi.get_field_precision(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    def _get_spatial_filter(self):\n        try:\n            return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))\n        except GDALException:\n            return None\n\n    def _set_spatial_filter(self, filter):\n        if isinstance(filter, OGRGeometry):\n            capi.set_spatial_filter(self.ptr, filter.ptr)\n        elif isinstance(filter, (tuple, list)):\n            if not len(filter) == 4:\n                raise ValueError(\"Spatial filter list/tuple must have 4 elements.\")\n            # Map c_double onto params -- if a bad type is passed in it\n            # will be caught here.\n            xmin, ymin, xmax, ymax = map(c_double, filter)\n            capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)\n        elif filter is None:\n            capi.set_spatial_filter(self.ptr, None)\n        else:\n            raise TypeError(\n                \"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or \"\n                \"None.\"\n            )\n\n    spatial_filter = property(_get_spatial_filter, _set_spatial_filter)\n\n    # #### Layer Methods ####\n    def get_fields(self, field_name):\n        \"\"\"\n        Return a list containing the given field name for every Feature\n        in the Layer.\n        \"\"\"\n        if field_name not in self.fields:\n            raise GDALException(\"invalid field name: %s\" % field_name)\n        return [feat.get(field_name) for feat in self]\n\n    def get_geoms(self, geos=False):\n        \"\"\"\n        Return a list containing the OGRGeometry for every Feature in\n        the Layer.\n        \"\"\"\n        if geos:\n            from django.contrib.gis.geos import GEOSGeometry\n\n            return [GEOSGeometry(feat.geom.wkb) for feat in self]\n        else:\n            return [feat.geom for feat in self]\n\n    def test_capability(self, capability):\n        \"\"\"\n        Return a bool indicating whether the this Layer supports the given\n        capability (a string). Valid capability strings include:\n          'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',\n          'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',\n          'DeleteFeature', and 'FastSetNextByIndex'.\n        \"\"\"\n        return bool(capi.test_capability(self.ptr, force_bytes(capability)))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-f0442ed69445adbd", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "35470330870688fb85128ca63dca4f4122c4f1af370db4b928aac900e96bd3b0", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 232, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__Layer__c699dd9d.py", "order": 9, "original_content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "parent_variant_id": "pyint-4c5b4a4b5dfd-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/gdal/layer.py#L21-L234", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 7}, "unit_kind": "class", "unit_name": "Layer", "variant_id": "pyint-bf85c699dd9d-I09", "group_id": "py-f0442ed69445adbd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 52, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3d07708e0cff-I10", "source": "from ctypes import byref, c_double\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.envelope import Envelope, OGREnvelope\nfrom django.contrib.gis.gdal.error import GDALException, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding import force_bytes, force_str\n\nclass Layer(GDALBase):\n    \"\"\"\n    A class that wraps an OGR Layer, needs to be instantiated from a DataSource\n    object.\n    \"\"\"\n    def __init__(self, layer_ptr, ds):\n        \"\"\"\n        Initialize on an OGR C pointer to the Layer and the `DataSource` object\n        that owns this layer. The `DataSource` object is required so that a\n        reference to it is kept with this Layer. This prevents garbage\n        collection of the `DataSource` while this Layer is still active.\n        \"\"\"\n        if not layer_ptr:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = layer_ptr\n        self._ds = ds\n        self._ldefn = capi.get_layer_defn(self._ptr)\n        # Does the Layer support random reading?\n        self._random_read = self.test_capability(b\"RandomRead\")\n    def __getitem__(self, index):\n        \"Get the Feature at the specified index.\"\n        if isinstance(index, int):\n            # An integer index was given -- we cannot do a check based on the\n            # number of features because the beginning and ending feature IDs\n            # are not guaranteed to be 0 and len(layer)-1, respectively.\n            if index < 0:\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self._make_feature(index)\n        elif isinstance(index, slice):\n            # A slice was given\n            start, stop, stride = index.indices(self.num_feat)\n            return [self._make_feature(fid) for fid in range(start, stop, stride)]\n        else:\n            raise TypeError(\n                \"Integers and slices may only be used when indexing OGR Layers.\"             )\n\n    def __iter__(self):\n        \"Iterate over each Feature in the Layer.\"\n        # ResetReading() must be called before iteration is to begin.\n        capi.reset_reading(self._ptr)\n        for i in range(self.num_feat):\n            yield Feature(capi.get_next_feature(self._ptr), self)\n\n    def __len__(self):\n        \"The length is the number of features.\"\n        return self.num_feat\n    def __str__(self):\n        \"The string name of the layer.\"\n        return self.name\n\n    def _make_feature(self, feat_id):\n        \"\"\"\n        Helper routine for __getitem__ that constructs a Feature from the given\n        Feature ID. If the OGR Layer does not support random-access reading,\n        then each feature of the layer will be incremented through until the\n        a Feature is found matching the given feature ID.\n        \"\"\"\n        if self._random_read:\n            # If the Layer supports random reading, return.\n            try:\n                return Feature(capi.get_feature(self.ptr, feat_id), self)\n            except GDALException:\n                pass\n        else:\n            # Random access isn't supported, have to increment through\n            # each feature until the given feature ID is encountered.\n            for feat in self:\n                if feat.fid == feat_id:\n                    return feat\n        # Should have returned a Feature, raise an IndexError.\n        raise IndexError(\"Invalid feature id: %s.\" % feat_id)\n\n    # #### Layer properties ####\n    @property\n    def extent(self):\n        \"Return the extent (an Envelope) of this layer.\"\n        env = OGREnvelope()\n        capi.get_extent(self.ptr, byref(env), 1)\n        return Envelope(env)\n\n    @property\n    def name(self):\n        \"Return the name of this layer in the Data Source.\"\n        name = capi.get_fd_name(self._ldefn)\n        return force_str(name, self._ds.encoding, strings_only=True)\n    @property\n    def num_feat(self, force=1):\n        \"Return the number of features in the Layer.\"\n        return capi.get_feature_count(self.ptr, force)\n    @property\n    def num_fields(self):\n        \"Return the number of fields in the Layer.\"\n        return capi.get_field_count(self._ldefn)\n    @property\n    def geom_type(self):\n        \"Return the geometry type (OGRGeomType) of the Layer.\"\n        return OGRGeomType(capi.get_fd_geom_type(self._ldefn))\n    @property\n    def srs(self):\n        \"Return the Spatial Reference used in this Layer.\"\n        try:\n            ptr = capi.get_layer_srs(self.ptr)\n            return SpatialReference(srs_api.clone_srs(ptr))\n        except SRSException:\n            return None\n    @property\n    def fields(self):\n        \"\"\"\n        Return a list of string names corresponding to each of the Fields\n        available in this Layer.\n        \"\"\"\n        return [\n            force_str(\n                capi.get_field_name(capi.get_field_defn(self._ldefn, i)),                 self._ds.encoding,\n                strings_only=True,             )             for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_types(self):\n        \"\"\"\n        Return a list of the types of fields in this Layer. For example,\n        return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that\n        has an integer, a floating-point, and string fields.\n        \"\"\"\n        return [\n            OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]             for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_widths(self):\n        \"Return a list of the maximum field widths for the features.\"\n        return [\n            capi.get_field_width(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n    @property\n    def field_precisions(self):\n        \"Return the field precisions for the features.\"\n        return [             capi.get_field_precision(capi.get_field_defn(self._ldefn, i))             for i in range(self.num_fields)\n        ]\n    def _get_spatial_filter(self):\n        try:\n            return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))\n        except GDALException:\n            return None\n\n    def _set_spatial_filter(self, filter):\n        if isinstance(filter, OGRGeometry):\n            capi.set_spatial_filter(self.ptr, filter.ptr)\n        elif isinstance(filter, (tuple, list)):\n            if not len(filter) == 4:\n                raise ValueError(\"Spatial filter list/tuple must have 4 elements.\")\n            # Map c_double onto params -- if a bad type is passed in it\n            # will be caught here.\n            xmin, ymin, xmax, ymax = map(c_double, filter)\n            capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)\n        elif filter is None:\n            capi.set_spatial_filter(self.ptr, None)\n        else:\n            raise TypeError(\n                \"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or \"\n                \"None.\"\n            )\n\n    spatial_filter = property(_get_spatial_filter, _set_spatial_filter)\n\n    # #### Layer Methods ####\n    def get_fields(self, field_name):\n        \"\"\"\n        Return a list containing the given field name for every Feature\n        in the Layer.\n        \"\"\"\n        if field_name not in self.fields:\n            raise GDALException(\"invalid field name: %s\" % field_name)\n        return [feat.get(field_name) for feat in self]\n\n    def get_geoms(self, geos=False):\n        \"\"\"\n        Return a list containing the OGRGeometry for every Feature in\n        the Layer.\n        \"\"\"\n        if geos:\n            from django.contrib.gis.geos import GEOSGeometry\n\n            return [GEOSGeometry(feat.geom.wkb) for feat in self]\n        else:\n            return [feat.geom for feat in self]\n    def test_capability(self, capability):\n        \"\"\"\n        Return a bool indicating whether the this Layer supports the given\n        capability (a string). Valid capability strings include:\n          'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',\n          'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',\n          'DeleteFeature', and 'FastSetNextByIndex'.\n        \"\"\"\n        return bool(capi.test_capability(self.ptr, force_bytes(capability)))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-f0442ed69445adbd", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "cd150b391c068b8bbe7ed9982dcac6b2a4c14aebc1543ac51a862493c74ecc91", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 210, "local_path": "layout/partially-compact-layout/I10__django__Layer__708e0cff.py", "order": 10, "original_content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "parent_variant_id": "pyint-4c5b4a4b5dfd-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/gdal/layer.py#L21-L234", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 45, "line_break_groups_removed": 18, "line_breaks_removed": 18, "whitespace_characters_removed": 11}, "unit_kind": "class", "unit_name": "Layer", "variant_id": "pyint-3d07708e0cff-I10", "group_id": "py-f0442ed69445adbd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 53, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7f51f58588e0-I11", "source": "from ctypes import byref, c_double\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.envelope import Envelope, OGREnvelope\nfrom django.contrib.gis.gdal.error import GDALException, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding import force_bytes, force_str\n\nclass Layer(GDALBase):\n    \"\"\"\n    A class that wraps an OGR Layer, needs to be instantiated from a DataSource\n    object.\n    \"\"\"\n\n    def __init__(self, layer_ptr, ds):\n        \"\"\"\n        Initialize on an OGR C pointer to the Layer and the `DataSource` object\n        that owns this layer. The `DataSource` object is required so that a\n        reference to it is kept with this Layer. This prevents garbage\n        collection of the `DataSource` while this Layer is still active.\n        \"\"\"\n        if not layer_ptr:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = layer_ptr\n        self._ds = ds\n        self._ldefn = capi.get_layer_defn(self._ptr)\n        # Does the Layer support random reading?\n        self._random_read = self.test_capability(b\"RandomRead\")\n\n    def __getitem__(self, index):\n        \"Get the Feature at the specified index.\"\n        if isinstance(index, int):\n            # An integer index was given -- we cannot do a check based on the\n            # number of features because the beginning and ending feature IDs\n            # are not guaranteed to be 0 and len(layer)-1, respectively.\n            a = 1\n            b = -1\n            if index < (a + b):\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self._make_feature(index)\n        elif isinstance(index, slice):\n            # A slice was given\n            start, stop, stride = index.indices(self.num_feat)\n            return [self._make_feature(fid) for fid in range(start, stop, stride)]\n        else:\n            raise TypeError(\n                \"Integers and slices may only be used when indexing OGR Layers.\"\n            )\n\n    def __iter__(self):\n        \"Iterate over each Feature in the Layer.\"\n        # ResetReading() must be called before iteration is to begin.\n        capi.reset_reading(self._ptr)\n        for i in range(self.num_feat):\n            yield Feature(capi.get_next_feature(self._ptr), self)\n\n    def __len__(self):\n        \"The length is the number of features.\"\n        return self.num_feat\n\n    def __str__(self):\n        \"The string name of the layer.\"\n        return self.name\n\n    def _make_feature(self, feat_id):\n        \"\"\"\n        Helper routine for __getitem__ that constructs a Feature from the given\n        Feature ID. If the OGR Layer does not support random-access reading,\n        then each feature of the layer will be incremented through until the\n        a Feature is found matching the given feature ID.\n        \"\"\"\n        if self._random_read:\n            # If the Layer supports random reading, return.\n            try:\n                return Feature(capi.get_feature(self.ptr, feat_id), self)\n            except GDALException:\n                pass\n        else:\n            # Random access isn't supported, have to increment through\n            # each feature until the given feature ID is encountered.\n            for feat in self:\n                if feat.fid == feat_id:\n                    return feat\n        # Should have returned a Feature, raise an IndexError.\n        raise IndexError(\"Invalid feature id: %s.\" % feat_id)\n\n    # #### Layer properties ####\n    @property\n    def extent(self):\n        \"Return the extent (an Envelope) of this layer.\"\n        env = OGREnvelope()\n        c = 2\n        d = -1\n        capi.get_extent(self.ptr, byref(env), (c + d))\n        return Envelope(env)\n\n    @property\n    def name(self):\n        \"Return the name of this layer in the Data Source.\"\n        name = capi.get_fd_name(self._ldefn)\n        return force_str(name, self._ds.encoding, strings_only=True)\n\n    @property\n    def num_feat(self, force=1):\n        \"Return the number of features in the Layer.\"\n        return capi.get_feature_count(self.ptr, force)\n\n    @property\n    def num_fields(self):\n        \"Return the number of fields in the Layer.\"\n        return capi.get_field_count(self._ldefn)\n\n    @property\n    def geom_type(self):\n        \"Return the geometry type (OGRGeomType) of the Layer.\"\n        return OGRGeomType(capi.get_fd_geom_type(self._ldefn))\n\n    @property\n    def srs(self):\n        \"Return the Spatial Reference used in this Layer.\"\n        try:\n            ptr = capi.get_layer_srs(self.ptr)\n            return SpatialReference(srs_api.clone_srs(ptr))\n        except SRSException:\n            return None\n\n    @property\n    def fields(self):\n        \"\"\"\n        Return a list of string names corresponding to each of the Fields\n        available in this Layer.\n        \"\"\"\n        return [\n            force_str(\n                capi.get_field_name(capi.get_field_defn(self._ldefn, i)),\n                self._ds.encoding,\n                strings_only=True,\n            )\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_types(self):\n        \"\"\"\n        Return a list of the types of fields in this Layer. For example,\n        return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that\n        has an integer, a floating-point, and string fields.\n        \"\"\"\n        return [\n            OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_widths(self):\n        \"Return a list of the maximum field widths for the features.\"\n        return [\n            capi.get_field_width(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_precisions(self):\n        \"Return the field precisions for the features.\"\n        return [\n            capi.get_field_precision(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    def _get_spatial_filter(self):\n        try:\n            return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))\n        except GDALException:\n            return None\n\n    def _set_spatial_filter(self, filter):\n        if isinstance(filter, OGRGeometry):\n            capi.set_spatial_filter(self.ptr, filter.ptr)\n        elif isinstance(filter, (tuple, list)):\n            e = 2\n            f = 2\n            if not len(filter) == (e + f):\n                raise ValueError(\"Spatial filter list/tuple must have 4 elements.\")\n            # Map c_double onto params -- if a bad type is passed in it\n            # will be caught here.\n            xmin, ymin, xmax, ymax = map(c_double, filter)\n            capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)\n        elif filter is None:\n            capi.set_spatial_filter(self.ptr, None)\n        else:\n            raise TypeError(\n                \"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or \"\n                \"None.\"\n            )\n\n    spatial_filter = property(_get_spatial_filter, _set_spatial_filter)\n\n    # #### Layer Methods ####\n    def get_fields(self, field_name):\n        \"\"\"\n        Return a list containing the given field name for every Feature\n        in the Layer.\n        \"\"\"\n        if field_name not in self.fields:\n            raise GDALException(\"invalid field name: %s\" % field_name)\n        return [feat.get(field_name) for feat in self]\n\n    def get_geoms(self, geos=False):\n        \"\"\"\n        Return a list containing the OGRGeometry for every Feature in\n        the Layer.\n        \"\"\"\n        if geos:\n            from django.contrib.gis.geos import GEOSGeometry\n\n            return [GEOSGeometry(feat.geom.wkb) for feat in self]\n        else:\n            return [feat.geom for feat in self]\n\n    def test_capability(self, capability):\n        \"\"\"\n        Return a bool indicating whether the this Layer supports the given\n        capability (a string). Valid capability strings include:\n          'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',\n          'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',\n          'DeleteFeature', and 'FastSetNextByIndex'.\n        \"\"\"\n        return bool(capi.test_capability(self.ptr, force_bytes(capability)))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-f0442ed69445adbd", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "bebf7b79005f2717a33aaf2ad76f5053cd1f9939da80e9c3e6768e388f005098", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 234, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__Layer__f58588e0.py", "order": 11, "original_content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "parent_variant_id": "pyint-4c5b4a4b5dfd-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/gdal/layer.py#L21-L234", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 3, "intermediate_variables_introduced": 6, "statements_augmented": 3}, "unit_kind": "class", "unit_name": "Layer", "variant_id": "pyint-7f51f58588e0-I11", "group_id": "py-f0442ed69445adbd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 54, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-71226d472070-I12", "source": "from ctypes import byref, c_double\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.envelope import Envelope, OGREnvelope\nfrom django.contrib.gis.gdal.error import GDALException, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding import force_bytes, force_str\n\nclass Layer(GDALBase):\n    \"\"\"\n    A class that wraps an OGR Layer, needs to be instantiated from a DataSource\n    object.\n    \"\"\"\n\n    def __init__(self, layer_ptr, ds):\n        \"\"\"\n        Initialize on an OGR C pointer to the Layer and the `DataSource` object\n        that owns this layer. The `DataSource` object is required so that a\n        reference to it is kept with this Layer. This prevents garbage\n        collection of the `DataSource` while this Layer is still active.\n        \"\"\"\n        if not layer_ptr:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = layer_ptr\n        self._ds = ds\n        self._ldefn = capi.get_layer_defn(self._ptr)\n        # Does the Layer support random reading?\n        self._random_read = self.test_capability(b\"RandomRead\")\n\n    def __getitem__(self, index):\n        \"Get the Feature at the specified index.\"\n        if isinstance(index, int):\n            # An integer index was given -- we cannot do a check based on the\n            # number of features because the beginning and ending feature IDs\n            # are not guaranteed to be 0 and len(layer)-1, respectively.\n            if index < 0:\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self._make_feature(index)\n        elif isinstance(index, slice):\n            # A slice was given\n            start, stop, stride = index.indices(self.num_feat)\n            return [self._make_feature(fid) for fid in range(start, stop, stride)]\n        else:\n            raise TypeError(\n                \"Integers and slices may only be used when indexing OGR Layers.\"\n            )\n\n    def __iter__(self):\n        \"Iterate over each Feature in the Layer.\"\n        # ResetReading() must be called before iteration is to begin.\n        capi.reset_reading(self._ptr)\n        for i in range(self.num_feat):\n            yield Feature(capi.get_next_feature(self._ptr), self)\n\n    def __len__(self):\n        \"The length is the number of features.\"\n        return self.num_feat\n\n    def __str__(self):\n        \"The string name of the layer.\"\n        return self.name\n\n    def _make_feature(self, feat_id):\n        \"\"\"\n        Helper routine for __getitem__ that constructs a Feature from the given\n        Feature ID. If the OGR Layer does not support random-access reading,\n        then each feature of the layer will be incremented through until the\n        a Feature is found matching the given feature ID.\n        \"\"\"\n        if self._random_read:\n            # If the Layer supports random reading, return.\n            try:\n                return Feature(capi.get_feature(self.ptr, feat_id), self)\n            except GDALException:\n                pass\n        else:\n            # Random access isn't supported, have to increment through\n            # each feature until the given feature ID is encountered.\n            for feat in self:\n                if feat.fid == feat_id:\n                    return feat\n        # Should have returned a Feature, raise an IndexError.\n        raise IndexError(\"Invalid feature id: %s.\" % feat_id)\n\n    # #### Layer properties ####\n    @property\n    def extent(self):\n        \"Return the extent (an Envelope) of this layer.\"\n        env = OGREnvelope()\n        capi.get_extent(self.ptr, byref(env), 1)\n        return Envelope(env)\n\n    @property\n    def name(self):\n        \"Return the name of this layer in the Data Source.\"\n        \n        return force_str((capi.get_fd_name(self._ldefn)), self._ds.encoding, strings_only=True)\n\n    @property\n    def num_feat(self, force=1):\n        \"Return the number of features in the Layer.\"\n        return capi.get_feature_count(self.ptr, force)\n\n    @property\n    def num_fields(self):\n        \"Return the number of fields in the Layer.\"\n        return capi.get_field_count(self._ldefn)\n\n    @property\n    def geom_type(self):\n        \"Return the geometry type (OGRGeomType) of the Layer.\"\n        return OGRGeomType(capi.get_fd_geom_type(self._ldefn))\n\n    @property\n    def srs(self):\n        \"Return the Spatial Reference used in this Layer.\"\n        try:\n            \n            return SpatialReference(srs_api.clone_srs((capi.get_layer_srs(self.ptr))))\n        except SRSException:\n            return None\n\n    @property\n    def fields(self):\n        \"\"\"\n        Return a list of string names corresponding to each of the Fields\n        available in this Layer.\n        \"\"\"\n        return [\n            force_str(\n                capi.get_field_name(capi.get_field_defn(self._ldefn, i)),\n                self._ds.encoding,\n                strings_only=True,\n            )\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_types(self):\n        \"\"\"\n        Return a list of the types of fields in this Layer. For example,\n        return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that\n        has an integer, a floating-point, and string fields.\n        \"\"\"\n        return [\n            OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_widths(self):\n        \"Return a list of the maximum field widths for the features.\"\n        return [\n            capi.get_field_width(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_precisions(self):\n        \"Return the field precisions for the features.\"\n        return [\n            capi.get_field_precision(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    def _get_spatial_filter(self):\n        try:\n            return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))\n        except GDALException:\n            return None\n\n    def _set_spatial_filter(self, filter):\n        if isinstance(filter, OGRGeometry):\n            capi.set_spatial_filter(self.ptr, filter.ptr)\n        elif isinstance(filter, (tuple, list)):\n            if not len(filter) == 4:\n                raise ValueError(\"Spatial filter list/tuple must have 4 elements.\")\n            # Map c_double onto params -- if a bad type is passed in it\n            # will be caught here.\n            xmin, ymin, xmax, ymax = map(c_double, filter)\n            capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)\n        elif filter is None:\n            capi.set_spatial_filter(self.ptr, None)\n        else:\n            raise TypeError(\n                \"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or \"\n                \"None.\"\n            )\n\n    spatial_filter = property(_get_spatial_filter, _set_spatial_filter)\n\n    # #### Layer Methods ####\n    def get_fields(self, field_name):\n        \"\"\"\n        Return a list containing the given field name for every Feature\n        in the Layer.\n        \"\"\"\n        if field_name not in self.fields:\n            raise GDALException(\"invalid field name: %s\" % field_name)\n        return [feat.get(field_name) for feat in self]\n\n    def get_geoms(self, geos=False):\n        \"\"\"\n        Return a list containing the OGRGeometry for every Feature in\n        the Layer.\n        \"\"\"\n        if geos:\n            from django.contrib.gis.geos import GEOSGeometry\n\n            return [GEOSGeometry(feat.geom.wkb) for feat in self]\n        else:\n            return [feat.geom for feat in self]\n\n    def test_capability(self, capability):\n        \"\"\"\n        Return a bool indicating whether the this Layer supports the given\n        capability (a string). Valid capability strings include:\n          'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',\n          'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',\n          'DeleteFeature', and 'FastSetNextByIndex'.\n        \"\"\"\n        return bool(capi.test_capability(self.ptr, force_bytes(capability)))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-f0442ed69445adbd", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "5a453749a48c322e1ca8c4488eaff6b9b7d048dd6a0692d33833dbc377e4f82d", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 228, "local_path": "data-flow/inline-intermediate-variables/I12__django__Layer__6d472070.py", "order": 12, "original_content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "parent_variant_id": "pyint-4c5b4a4b5dfd-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/gdal/layer.py#L21-L234", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 2, "intermediate_variables_available": 2, "intermediate_variables_inlined": 2, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "Layer", "variant_id": "pyint-71226d472070-I12", "group_id": "py-f0442ed69445adbd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 55, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f44cd8ea668b-I13", "source": "from ctypes import byref, c_double\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.envelope import Envelope, OGREnvelope\nfrom django.contrib.gis.gdal.error import GDALException, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding import force_bytes, force_str\n\nclass Layer(GDALBase):\n    \"\"\"\n    A class that wraps an OGR Layer, needs to be instantiated from a DataSource\n    object.\n    \"\"\"\n\n    def __init__(self, layer_ptr, ds):\n        \"\"\"\n        Initialize on an OGR C pointer to the Layer and the `DataSource` object\n        that owns this layer. The `DataSource` object is required so that a\n        reference to it is kept with this Layer. This prevents garbage\n        collection of the `DataSource` while this Layer is still active.\n        \"\"\"\n        if not layer_ptr:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = layer_ptr\n        self._ds = ds\n        self._ldefn = capi.get_layer_defn(self._ptr)\n        # Does the Layer support random reading?\n        self._random_read = self.test_capability(b\"RandomRead\")\n\n    def __getitem__(self, index):\n        \"Get the Feature at the specified index.\"\n        if isinstance(index, int):\n            # An integer index was given -- we cannot do a check based on the\n            # number of features because the beginning and ending feature IDs\n            # are not guaranteed to be 0 and len(layer)-1, respectively.\n            if index < 0:\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self._make_feature(index)\n        elif isinstance(index, slice):\n            # A slice was given\n            start, stop, stride = index.indices(self.num_feat)\n            return [self._make_feature(fid) for fid in range(start, stop, stride)]\n        else:\n            raise TypeError(\n                \"Integers and slices may only be used when indexing OGR Layers.\"\n            )\n\n    def __iter__(self):\n        \"Iterate over each Feature in the Layer.\"\n        # ResetReading() must be called before iteration is to begin.\n        capi.reset_reading(self._ptr)\n        loopIterator = __import__(\"builtins\").iter(range(self.num_feat))\n        while True:\n            try:\n                i = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            yield Feature(capi.get_next_feature(self._ptr), self)\n\n    def __len__(self):\n        \"The length is the number of features.\"\n        return self.num_feat\n\n    def __str__(self):\n        \"The string name of the layer.\"\n        return self.name\n\n    def _make_feature(self, feat_id):\n        \"\"\"\n        Helper routine for __getitem__ that constructs a Feature from the given\n        Feature ID. If the OGR Layer does not support random-access reading,\n        then each feature of the layer will be incremented through until the\n        a Feature is found matching the given feature ID.\n        \"\"\"\n        if self._random_read:\n            # If the Layer supports random reading, return.\n            try:\n                return Feature(capi.get_feature(self.ptr, feat_id), self)\n            except GDALException:\n                pass\n        else:\n            # Random access isn't supported, have to increment through\n            # each feature until the given feature ID is encountered.\n            loopIteratorA = __import__(\"builtins\").iter(self)\n            while True:\n                try:\n                    feat = __import__(\"builtins\").next(loopIteratorA)\n                except __import__(\"builtins\").StopIteration:\n                    break\n                if feat.fid == feat_id:\n                    return feat\n        # Should have returned a Feature, raise an IndexError.\n        raise IndexError(\"Invalid feature id: %s.\" % feat_id)\n\n    # #### Layer properties ####\n    @property\n    def extent(self):\n        \"Return the extent (an Envelope) of this layer.\"\n        env = OGREnvelope()\n        capi.get_extent(self.ptr, byref(env), 1)\n        return Envelope(env)\n\n    @property\n    def name(self):\n        \"Return the name of this layer in the Data Source.\"\n        name = capi.get_fd_name(self._ldefn)\n        return force_str(name, self._ds.encoding, strings_only=True)\n\n    @property\n    def num_feat(self, force=1):\n        \"Return the number of features in the Layer.\"\n        return capi.get_feature_count(self.ptr, force)\n\n    @property\n    def num_fields(self):\n        \"Return the number of fields in the Layer.\"\n        return capi.get_field_count(self._ldefn)\n\n    @property\n    def geom_type(self):\n        \"Return the geometry type (OGRGeomType) of the Layer.\"\n        return OGRGeomType(capi.get_fd_geom_type(self._ldefn))\n\n    @property\n    def srs(self):\n        \"Return the Spatial Reference used in this Layer.\"\n        try:\n            ptr = capi.get_layer_srs(self.ptr)\n            return SpatialReference(srs_api.clone_srs(ptr))\n        except SRSException:\n            return None\n\n    @property\n    def fields(self):\n        \"\"\"\n        Return a list of string names corresponding to each of the Fields\n        available in this Layer.\n        \"\"\"\n        return [\n            force_str(\n                capi.get_field_name(capi.get_field_defn(self._ldefn, i)),\n                self._ds.encoding,\n                strings_only=True,\n            )\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_types(self):\n        \"\"\"\n        Return a list of the types of fields in this Layer. For example,\n        return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that\n        has an integer, a floating-point, and string fields.\n        \"\"\"\n        return [\n            OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_widths(self):\n        \"Return a list of the maximum field widths for the features.\"\n        return [\n            capi.get_field_width(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    @property\n    def field_precisions(self):\n        \"Return the field precisions for the features.\"\n        return [\n            capi.get_field_precision(capi.get_field_defn(self._ldefn, i))\n            for i in range(self.num_fields)\n        ]\n\n    def _get_spatial_filter(self):\n        try:\n            return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))\n        except GDALException:\n            return None\n\n    def _set_spatial_filter(self, filter):\n        if isinstance(filter, OGRGeometry):\n            capi.set_spatial_filter(self.ptr, filter.ptr)\n        elif isinstance(filter, (tuple, list)):\n            if not len(filter) == 4:\n                raise ValueError(\"Spatial filter list/tuple must have 4 elements.\")\n            # Map c_double onto params -- if a bad type is passed in it\n            # will be caught here.\n            xmin, ymin, xmax, ymax = map(c_double, filter)\n            capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)\n        elif filter is None:\n            capi.set_spatial_filter(self.ptr, None)\n        else:\n            raise TypeError(\n                \"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or \"\n                \"None.\"\n            )\n\n    spatial_filter = property(_get_spatial_filter, _set_spatial_filter)\n\n    # #### Layer Methods ####\n    def get_fields(self, field_name):\n        \"\"\"\n        Return a list containing the given field name for every Feature\n        in the Layer.\n        \"\"\"\n        if field_name not in self.fields:\n            raise GDALException(\"invalid field name: %s\" % field_name)\n        return [feat.get(field_name) for feat in self]\n\n    def get_geoms(self, geos=False):\n        \"\"\"\n        Return a list containing the OGRGeometry for every Feature in\n        the Layer.\n        \"\"\"\n        if geos:\n            from django.contrib.gis.geos import GEOSGeometry\n\n            return [GEOSGeometry(feat.geom.wkb) for feat in self]\n        else:\n            return [feat.geom for feat in self]\n\n    def test_capability(self, capability):\n        \"\"\"\n        Return a bool indicating whether the this Layer supports the given\n        capability (a string). Valid capability strings include:\n          'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',\n          'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',\n          'DeleteFeature', and 'FastSetNextByIndex'.\n        \"\"\"\n        return bool(capi.test_capability(self.ptr, force_bytes(capability)))\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-f0442ed69445adbd", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "c4698a45141a1f3df81cebcf8d40481ccc9f0bcf3328712ef86ee9d17ce5e6b1", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 238, "local_path": "control-flow/lower-for-to-while/I13__django__Layer__d8ea668b.py", "order": 13, "original_content_sha256": "dccc30b0b89b82f9ca7a6cb533327f16aa88bdb4ad6080c52ded4e2f4deb829e", "parent_variant_id": "pyint-4c5b4a4b5dfd-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/contrib/gis/gdal/layer.py#L21-L234", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 2, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 2, "synchronous_for_loops_eligible": 2, "synchronous_for_loops_found": 2}, "unit_kind": "class", "unit_name": "Layer", "variant_id": "pyint-f44cd8ea668b-I13", "group_id": "py-f0442ed69445adbd", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 56, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ff03f511f80e-SRC", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MinLengthValidator:\n    min_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(value) < self.min_length:\n            msg = f\"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<min_len validator for {self.min_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-f205e68cfc9045f6", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 23, "local_path": "source-original/SRC__attrs___MinLengthValidator__f511f80e.py", "order": 0, "original_content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "parent_variant_id": null, "readability_direction": "baseline", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L584-L596", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "_MinLengthValidator", "variant_id": "pyint-ff03f511f80e-SRC", "group_id": "py-f205e68cfc9045f6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1233, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ecbea86cc1eb-I01", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MinLengthValidator:\n    min_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \n        if len(value) < self.min_length:\n            msg = f\"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<min_len validator for {self.min_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-f205e68cfc9045f6", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "abd780667a187b453109188add5102dbcb047e1e73862814283ef951c378c58f", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 21, "local_path": "comments/remove-comments/I01__attrs___MinLengthValidator__a86cc1eb.py", "order": 1, "original_content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "parent_variant_id": "pyint-ff03f511f80e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L584-L596", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 86, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "_MinLengthValidator", "variant_id": "pyint-ecbea86cc1eb-I01", "group_id": "py-f205e68cfc9045f6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1234, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-fe4f113dcd2e-I02", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MinLengthValidator:\n    min_length = attrib()\n\n    def __call__(self, ins, att, val):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(val) < self.min_length:\n            msg2 = f\"Length of '{att.name}' must be >= {self.min_length}: {len(val)}\"\n            raise ValueError(msg2)\n\n    def __repr__(self):\n        return f\"<min_len validator for {self.min_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-f205e68cfc9045f6", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "cf1f80cbbd92ac80d3c24e1036d098aeae82335ab7b8cfc4104ac1a0ad9dd6da", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 23, "local_path": "identifiers/shorten-identifiers/I02__attrs___MinLengthValidator__113dcd2e.py", "order": 2, "original_content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "parent_variant_id": "pyint-ff03f511f80e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L584-L596", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_MinLengthValidator", "variant_id": "pyint-fe4f113dcd2e-I02", "group_id": "py-f205e68cfc9045f6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1235, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0000ca0234ab-I03", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MinLengthValidator:\n    min_length = attrib()\n\n    def __call__(self, data, mode, limit):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(limit) < self.min_length:\n            key = f\"Length of '{mode.name}' must be >= {self.min_length}: {len(limit)}\"\n            raise ValueError(key)\n\n    def __repr__(self):\n        return f\"<min_len validator for {self.min_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-f205e68cfc9045f6", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b920b71266651f8a89eec3356ea50fa705cb1207625ac1cf44f8068eb5cb2d68", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 23, "local_path": "identifiers/mislead-identifiers/I03__attrs___MinLengthValidator__ca0234ab.py", "order": 3, "original_content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "parent_variant_id": "pyint-ff03f511f80e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L584-L596", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 4, "local_random_pool_selections": 4, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "_MinLengthValidator", "variant_id": "pyint-0000ca0234ab-I03", "group_id": "py-f205e68cfc9045f6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1236, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c6320e27caff-I04", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MinLengthValidator:\n    min_length = attrib()\n\n    def __call__(self, a, b, c):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(c) < self.min_length:\n            d = f\"Length of '{b.name}' must be >= {self.min_length}: {len(c)}\"\n            raise ValueError(d)\n\n    def __repr__(self):\n        return f\"<min_len validator for {self.min_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-f205e68cfc9045f6", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "3946f99198f552fc1b1fe411c8ce84cba91796b00896fc35479c68fae543c883", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 23, "local_path": "identifiers/garble-identifiers/I04__attrs___MinLengthValidator__0e27caff.py", "order": 4, "original_content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "parent_variant_id": "pyint-ff03f511f80e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L584-L596", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 8, "identifiers_declared": 4}, "unit_kind": "class", "unit_name": "_MinLengthValidator", "variant_id": "pyint-c6320e27caff-I04", "group_id": "py-f205e68cfc9045f6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1237, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-b94c689d8e7b-I05", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MinLengthValidator:\n    min_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(value) < self.min_length:\n            msg = f\"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<min_len validator for {self.min_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-f205e68cfc9045f6", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 23, "local_path": "expressions/encode-integer-literals/I05__attrs___MinLengthValidator__689d8e7b.py", "order": 5, "original_content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "parent_variant_id": "pyint-ff03f511f80e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L584-L596", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "_MinLengthValidator", "variant_id": "pyint-b94c689d8e7b-I05", "group_id": "py-f205e68cfc9045f6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1238, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1e98067322a5-I06", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MinLengthValidator:\n    min_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if not (len(value) < self.min_length):\n            pass\n        else:\n            msg = f\"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<min_len validator for {self.min_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-f205e68cfc9045f6", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "a832e34106cd6713f378345e01c932511fcede47ecd1366b0eff777c35d3394f", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 25, "local_path": "expressions/invert-conditions/I06__attrs___MinLengthValidator__067322a5.py", "order": 6, "original_content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "parent_variant_id": "pyint-ff03f511f80e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L584-L596", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 1}, "unit_kind": "class", "unit_name": "_MinLengthValidator", "variant_id": "pyint-1e98067322a5-I06", "group_id": "py-f205e68cfc9045f6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1239, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4d82addd4e19-I07", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MinLengthValidator:\n    min_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if ((0x949b ^ 0x949b) != 0):\n            raise AssertionError()\n        if len(value) < self.min_length:\n            msg = f\"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        if ((0x3d5 ^ 0x3d5) != 0):\n            raise AssertionError()\n        return f\"<min_len validator for {self.min_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-f205e68cfc9045f6", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "cabf12f65807221b8c816e882b38144681d655a770d0dfddfeea7143dc5a54c8", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 27, "local_path": "code-injection/insert-dead-branches/I07__attrs___MinLengthValidator__addd4e19.py", "order": 7, "original_content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "parent_variant_id": "pyint-ff03f511f80e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L584-L596", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 2}, "unit_kind": "class", "unit_name": "_MinLengthValidator", "variant_id": "pyint-4d82addd4e19-I07", "group_id": "py-f205e68cfc9045f6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1240, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0854c50ca049-I08", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MinLengthValidator:\n    min_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        remaining_steps = 3\n        while remaining_steps > 0:\n            remaining_steps -= 1\n        if len(value) < self.min_length:\n            msg = f\"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<min_len validator for {self.min_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-f205e68cfc9045f6", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "5bfc40bc830694ed4d6e08b79db8512570975349f14aa0200de80f915760185f", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 26, "local_path": "code-injection/inject-readable-unrelated-code/I08__attrs___MinLengthValidator__c50ca049.py", "order": 8, "original_content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "parent_variant_id": "pyint-ff03f511f80e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L584-L596", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 1}, "unit_kind": "class", "unit_name": "_MinLengthValidator", "variant_id": "pyint-0854c50ca049-I08", "group_id": "py-f205e68cfc9045f6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1241, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c34b9622dc25-I09", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MinLengthValidator:\n    min_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        lI0O_a0ac513d, lI0O_d345b7ff = 0xf134, True\n        while lI0O_d345b7ff:\n            lI0O_a0ac513d ^= 0xf134\n            lI0O_d345b7ff = False\n        if len(value) < self.min_length:\n            msg = f\"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<min_len validator for {self.min_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-f205e68cfc9045f6", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "f2e69ee47b68675e4eec1f8d0ab79cbd379737a8bb13dbb288502e87231a9e09", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 27, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__attrs___MinLengthValidator__9622dc25.py", "order": 9, "original_content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "parent_variant_id": "pyint-ff03f511f80e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L584-L596", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 7}, "unit_kind": "class", "unit_name": "_MinLengthValidator", "variant_id": "pyint-c34b9622dc25-I09", "group_id": "py-f205e68cfc9045f6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1242, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-390561c8dbc7-I10", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MinLengthValidator:\n    min_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(value) < self.min_length:\n            msg = f\"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}\"\n            raise ValueError(msg)\n    def __repr__(self):\n        return f\"<min_len validator for {self.min_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-f205e68cfc9045f6", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "5e610b61a69356bc327500768cbeaaf6ccbb192a1dac2fea9e8abe17090ddf65", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 22, "local_path": "layout/partially-compact-layout/I10__attrs___MinLengthValidator__61c8dbc7.py", "order": 10, "original_content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "parent_variant_id": "pyint-ff03f511f80e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L584-L596", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 3, "line_break_groups_removed": 1, "line_breaks_removed": 1, "whitespace_characters_removed": 1}, "unit_kind": "class", "unit_name": "_MinLengthValidator", "variant_id": "pyint-390561c8dbc7-I10", "group_id": "py-f205e68cfc9045f6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1243, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-19a90fc9f7de-I11", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MinLengthValidator:\n    min_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(value) < self.min_length:\n            msg = f\"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<min_len validator for {self.min_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-f205e68cfc9045f6", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 23, "local_path": "data-flow/introduce-numeric-intermediates/I11__attrs___MinLengthValidator__0fc9f7de.py", "order": 11, "original_content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "parent_variant_id": "pyint-ff03f511f80e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L584-L596", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "_MinLengthValidator", "variant_id": "pyint-19a90fc9f7de-I11", "group_id": "py-f205e68cfc9045f6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1244, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cb8b8de39ac9-I12", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MinLengthValidator:\n    min_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(value) < self.min_length:\n            \n            raise ValueError((f\"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}\"))\n\n    def __repr__(self):\n        return f\"<min_len validator for {self.min_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-f205e68cfc9045f6", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "12a060f60225d8021b120e4aa419b187d02b371caecc359605db36aff8abfa03", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 23, "local_path": "data-flow/inline-intermediate-variables/I12__attrs___MinLengthValidator__8de39ac9.py", "order": 12, "original_content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "parent_variant_id": "pyint-ff03f511f80e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L584-L596", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 1, "intermediate_variables_available": 1, "intermediate_variables_inlined": 1, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "_MinLengthValidator", "variant_id": "pyint-cb8b8de39ac9-I12", "group_id": "py-f205e68cfc9045f6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1245, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a166e64d8882-I13", "source": "import operator\nimport re\nfrom contextlib import contextmanager\nfrom re import Pattern\nfrom ._config import get_run_validators, set_run_validators\nfrom ._make import _AndValidator, and_, attrib, attrs\nfrom .converters import default_if_none\nfrom .exceptions import NotCallableError\n\n@attrs(repr=False, frozen=True, slots=True)\nclass _MinLengthValidator:\n    min_length = attrib()\n\n    def __call__(self, inst, attr, value):\n        \"\"\"\n        We use a callable class to be able to change the ``__repr__``.\n        \"\"\"\n        if len(value) < self.min_length:\n            msg = f\"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}\"\n            raise ValueError(msg)\n\n    def __repr__(self):\n        return f\"<min_len validator for {self.min_length}>\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-f205e68cfc9045f6", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 23, "local_path": "control-flow/lower-for-to-while/I13__attrs___MinLengthValidator__e64d8882.py", "order": 13, "original_content_sha256": "180336ca4c2f42ec3fe5b89317bbcedfad5166f9dffdcb2e001e0aa48d34bc1b", "parent_variant_id": "pyint-ff03f511f80e-SRC", "readability_direction": "decreasing", "source": "attrs", "source_commit": "764bf92a1c96abe4615b59f3e5a7b738b0340a94", "source_name": "attrs", "source_path": "src/attr/validators.py#L584-L596", "source_repository": "https://github.com/python-attrs/attrs.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "_MinLengthValidator", "variant_id": "pyint-a166e64d8882-I13", "group_id": "py-f205e68cfc9045f6", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1246, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-368dde67b1e7-SRC", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-f7b97a69719b721f", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 7, "local_path": "source-original/SRC__requests__HTTPError__de67b1e7.py", "order": 0, "original_content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "parent_variant_id": null, "readability_direction": "baseline", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L66-L67", "source_repository": "https://github.com/psf/requests.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "HTTPError", "variant_id": "pyint-368dde67b1e7-SRC", "group_id": "py-f7b97a69719b721f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1037, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ae8e6fbe197a-I01", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass HTTPError(RequestException):\n    pass\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-f7b97a69719b721f", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "172527589dcfe1fa986ae37e2addce337bb491fd5402435ea3f8c6da7ceb35e0", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 7, "local_path": "comments/remove-comments/I01__requests__HTTPError__6fbe197a.py", "order": 1, "original_content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "parent_variant_id": "pyint-368dde67b1e7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L66-L67", "source_repository": "https://github.com/psf/requests.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 25, "comments_removed": 1, "docstrings_removed": 1, "line_comments_removed": 0}, "unit_kind": "class", "unit_name": "HTTPError", "variant_id": "pyint-ae8e6fbe197a-I01", "group_id": "py-f7b97a69719b721f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1038, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-631f41ed3abf-I02", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-f7b97a69719b721f", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 7, "local_path": "identifiers/shorten-identifiers/I02__requests__HTTPError__41ed3abf.py", "order": 2, "original_content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "parent_variant_id": "pyint-368dde67b1e7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L66-L67", "source_repository": "https://github.com/psf/requests.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 0, "identifiers_declared": 0}, "unit_kind": "class", "unit_name": "HTTPError", "variant_id": "pyint-631f41ed3abf-I02", "group_id": "py-f7b97a69719b721f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1039, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-ce45c67b1dcf-I03", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-f7b97a69719b721f", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 7, "local_path": "identifiers/mislead-identifiers/I03__requests__HTTPError__c67b1dcf.py", "order": 3, "original_content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "parent_variant_id": "pyint-368dde67b1e7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L66-L67", "source_repository": "https://github.com/psf/requests.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 0, "identifiers_declared": 0, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 0, "local_exact_length_matches": 0, "local_random_pool_selections": 0, "local_total_length_difference": 0, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 0, "method_exact_length_matches": 0, "method_random_pool_selections": 0, "method_total_length_difference": 0}, "unit_kind": "class", "unit_name": "HTTPError", "variant_id": "pyint-ce45c67b1dcf-I03", "group_id": "py-f7b97a69719b721f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1040, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6467c1c2b2e7-I04", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-f7b97a69719b721f", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 7, "local_path": "identifiers/garble-identifiers/I04__requests__HTTPError__c1c2b2e7.py", "order": 4, "original_content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "parent_variant_id": "pyint-368dde67b1e7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L66-L67", "source_repository": "https://github.com/psf/requests.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 0, "identifiers_declared": 0}, "unit_kind": "class", "unit_name": "HTTPError", "variant_id": "pyint-6467c1c2b2e7-I04", "group_id": "py-f7b97a69719b721f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1041, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-af478370e5e4-I05", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-f7b97a69719b721f", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 7, "local_path": "expressions/encode-integer-literals/I05__requests__HTTPError__8370e5e4.py", "order": 5, "original_content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "parent_variant_id": "pyint-368dde67b1e7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L66-L67", "source_repository": "https://github.com/psf/requests.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 0}, "unit_kind": "class", "unit_name": "HTTPError", "variant_id": "pyint-af478370e5e4-I05", "group_id": "py-f7b97a69719b721f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1042, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-1aab335ba20d-I06", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-f7b97a69719b721f", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 7, "local_path": "expressions/invert-conditions/I06__requests__HTTPError__335ba20d.py", "order": 6, "original_content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "parent_variant_id": "pyint-368dde67b1e7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L66-L67", "source_repository": "https://github.com/psf/requests.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 0}, "unit_kind": "class", "unit_name": "HTTPError", "variant_id": "pyint-1aab335ba20d-I06", "group_id": "py-f7b97a69719b721f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1043, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4d8bb7dc5069-I07", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-f7b97a69719b721f", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 7, "local_path": "code-injection/insert-dead-branches/I07__requests__HTTPError__b7dc5069.py", "order": 7, "original_content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "parent_variant_id": "pyint-368dde67b1e7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L66-L67", "source_repository": "https://github.com/psf/requests.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 0}, "unit_kind": "class", "unit_name": "HTTPError", "variant_id": "pyint-4d8bb7dc5069-I07", "group_id": "py-f7b97a69719b721f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1044, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-98c13b3e87e7-I08", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-f7b97a69719b721f", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 7, "local_path": "code-injection/inject-readable-unrelated-code/I08__requests__HTTPError__3b3e87e7.py", "order": 8, "original_content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "parent_variant_id": "pyint-368dde67b1e7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L66-L67", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 0, "readable_lines_injected": 0, "readable_template_index": -1}, "unit_kind": "class", "unit_name": "HTTPError", "variant_id": "pyint-98c13b3e87e7-I08", "group_id": "py-f7b97a69719b721f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1045, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-4531d0676ccd-I09", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-f7b97a69719b721f", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 7, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__requests__HTTPError__d0676ccd.py", "order": 9, "original_content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "parent_variant_id": "pyint-368dde67b1e7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L66-L67", "source_repository": "https://github.com/psf/requests.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 0, "low_readability_template_index": -1}, "unit_kind": "class", "unit_name": "HTTPError", "variant_id": "pyint-4531d0676ccd-I09", "group_id": "py-f7b97a69719b721f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1046, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-f2dadbd970d7-I10", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-f7b97a69719b721f", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 7, "local_path": "layout/partially-compact-layout/I10__requests__HTTPError__dbd970d7.py", "order": 10, "original_content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "parent_variant_id": "pyint-368dde67b1e7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L66-L67", "source_repository": "https://github.com/psf/requests.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 1, "line_break_groups_removed": 0, "line_breaks_removed": 0, "whitespace_characters_removed": 0}, "unit_kind": "class", "unit_name": "HTTPError", "variant_id": "pyint-f2dadbd970d7-I10", "group_id": "py-f7b97a69719b721f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1047, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-12ed17ae4b79-I11", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-f7b97a69719b721f", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 7, "local_path": "data-flow/introduce-numeric-intermediates/I11__requests__HTTPError__17ae4b79.py", "order": 11, "original_content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "parent_variant_id": "pyint-368dde67b1e7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L66-L67", "source_repository": "https://github.com/psf/requests.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 0, "intermediate_variables_introduced": 0, "statements_augmented": 0}, "unit_kind": "class", "unit_name": "HTTPError", "variant_id": "pyint-12ed17ae4b79-I11", "group_id": "py-f7b97a69719b721f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1048, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-5d304c1337dd-I12", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-f7b97a69719b721f", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 7, "local_path": "data-flow/inline-intermediate-variables/I12__requests__HTTPError__4c1337dd.py", "order": 12, "original_content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "parent_variant_id": "pyint-368dde67b1e7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L66-L67", "source_repository": "https://github.com/psf/requests.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 0, "intermediate_variables_available": 0, "intermediate_variables_inlined": 0, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "HTTPError", "variant_id": "pyint-5d304c1337dd-I12", "group_id": "py-f7b97a69719b721f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1049, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-6ab07c8afe16-I13", "source": "from __future__ import annotations\nfrom typing import TYPE_CHECKING, Any\nfrom urllib3.exceptions import HTTPError as BaseHTTPError\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-f7b97a69719b721f", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 7, "local_path": "control-flow/lower-for-to-while/I13__requests__HTTPError__7c8afe16.py", "order": 13, "original_content_sha256": "cc11a0551e4c1c07dc112405629d73d5dc8202bdd4e9ffd3d8dca3b0f76d86a3", "parent_variant_id": "pyint-368dde67b1e7-SRC", "readability_direction": "decreasing", "source": "requests", "source_commit": "5460f467b02e49471c0fd6cfc9ca0adab6351f98", "source_name": "Requests", "source_path": "src/requests/exceptions.py#L66-L67", "source_repository": "https://github.com/psf/requests.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 0, "for_loops_skipped_for_comment": 0, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 0, "synchronous_for_loops_eligible": 0, "synchronous_for_loops_found": 0}, "unit_kind": "class", "unit_name": "HTTPError", "variant_id": "pyint-6ab07c8afe16-I13", "group_id": "py-f7b97a69719b721f", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 1050, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-c08262236fb4-SRC", "source": "import functools\nimport inspect\nfrom functools import partial\nfrom django import forms\nfrom django.apps import apps\nfrom django.conf import SettingsReference, settings\nfrom django.core import checks, exceptions\nfrom django.db import connection, connections, router\nfrom django.db.backends import utils\nfrom django.db.models import NOT_PROVIDED, Q\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.deletion import (\n    CASCADE,\n    DB_CASCADE,\n    DB_SET_DEFAULT,\n    DB_SET_NULL,\n    DO_NOTHING,\n    SET_DEFAULT,\n    SET_NULL,\n    DatabaseOnDelete,\n)\nfrom django.db.models.query_utils import PathInfo\nfrom django.db.models.utils import make_model_tuple\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext_lazy as _\nfrom . import Field\nfrom .mixins import FieldCacheMixin\nfrom .related_descriptors import (\n    ForeignKeyDeferredAttribute,\n    ForwardManyToOneDescriptor,\n    ForwardOneToOneDescriptor,\n    ManyToManyDescriptor,\n    ReverseManyToOneDescriptor,\n    ReverseOneToOneDescriptor,\n)\nfrom .related_lookups import (\n    RelatedExact,\n    RelatedGreaterThan,\n    RelatedGreaterThanOrEqual,\n    RelatedIn,\n    RelatedIsNull,\n    RelatedLessThan,\n    RelatedLessThanOrEqual,\n)\nfrom .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel\n\nclass ForeignObject(RelatedField):\n    \"\"\"\n    Abstraction of the ForeignKey relation to support multi-column relations.\n    \"\"\"\n\n    # Field flags\n    many_to_many = False\n    many_to_one = True\n    one_to_many = False\n    one_to_one = False\n\n    requires_unique_target = True\n    related_accessor_class = ReverseManyToOneDescriptor\n    forward_related_accessor_class = ForwardManyToOneDescriptor\n    rel_class = ForeignObjectRel\n\n    def __init__(\n        self,\n        to,\n        on_delete,\n        from_fields,\n        to_fields,\n        rel=None,\n        related_name=None,\n        related_query_name=None,\n        limit_choices_to=None,\n        parent_link=False,\n        swappable=True,\n        **kwargs,\n    ):\n        if rel is None:\n            rel = self.rel_class(\n                self,\n                to,\n                related_name=related_name,\n                related_query_name=related_query_name,\n                limit_choices_to=limit_choices_to,\n                parent_link=parent_link,\n                on_delete=on_delete,\n            )\n\n        super().__init__(\n            rel=rel,\n            related_name=related_name,\n            related_query_name=related_query_name,\n            limit_choices_to=limit_choices_to,\n            **kwargs,\n        )\n\n        self.from_fields = from_fields\n        self.to_fields = to_fields\n        self.swappable = swappable\n\n    def __copy__(self):\n        obj = super().__copy__()\n        # Remove any cached PathInfo values.\n        obj.__dict__.pop(\"path_infos\", None)\n        obj.__dict__.pop(\"reverse_path_infos\", None)\n        return obj\n\n    @property\n    def non_db_attrs(self):\n        if isinstance(self.remote_field.on_delete, DatabaseOnDelete):\n            # Database-level on_delete options are part of the column\n            # definition.\n            return super().non_db_attrs\n        return super().non_db_attrs + (\"on_delete\",)\n\n    def check(self, **kwargs):\n        return [\n            *super().check(**kwargs),\n            *self._check_to_fields_exist(),\n            *self._check_to_fields_composite_pk(),\n            *self._check_unique_target(),\n        ]\n\n    def _check_to_fields_exist(self):\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            if to_field:\n                try:\n                    self.remote_field.model._meta.get_field(to_field)\n                except exceptions.FieldDoesNotExist:\n                    errors.append(\n                        checks.Error(\n                            \"The to_field '%s' doesn't exist on the related \"\n                            \"model '%s'.\"\n                            % (to_field, self.remote_field.model._meta.label),\n                            obj=self,\n                            id=\"fields.E312\",\n                        )\n                    )\n        return errors\n\n    def _check_to_fields_composite_pk(self):\n        from django.db.models.fields.composite import CompositePrimaryKey\n\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            try:\n                field = (\n                    self.remote_field.model._meta.pk\n                    if to_field is None\n                    else self.remote_field.model._meta.get_field(to_field)\n                )\n            except exceptions.FieldDoesNotExist:\n                pass\n            else:\n                if isinstance(field, CompositePrimaryKey):\n                    errors.append(\n                        checks.Error(\n                            \"Field defines a relation involving model \"\n                            f\"{self.remote_field.model._meta.object_name!r} which has \"\n                            \"a CompositePrimaryKey and such relations are not \"\n                            \"supported.\",\n                            obj=self,\n                            id=\"fields.E347\",\n                        )\n                    )\n        return errors\n\n    def _check_unique_target(self):\n        rel_is_string = isinstance(self.remote_field.model, str)\n        if rel_is_string or not self.requires_unique_target:\n            return []\n\n        try:\n            self.foreign_related_fields\n        except exceptions.FieldDoesNotExist:\n            return []\n\n        if not self.foreign_related_fields:\n            return []\n\n        has_unique_constraint = any(\n            rel_field.unique for rel_field in self.foreign_related_fields\n        )\n        if not has_unique_constraint:\n            foreign_fields = {f.name for f in self.foreign_related_fields}\n            remote_opts = self.remote_field.model._meta\n            has_unique_constraint = (\n                any(\n                    frozenset(ut) <= foreign_fields\n                    for ut in remote_opts.unique_together\n                )\n                or any(\n                    frozenset(uc.fields) <= foreign_fields\n                    for uc in remote_opts.total_unique_constraints\n                )\n                # If the model defines a composite primary key and the foreign\n                # key refers to it, the target is unique.\n                or (\n                    frozenset(field.name for field in remote_opts.pk_fields)\n                    == foreign_fields\n                )\n            )\n\n        if not has_unique_constraint:\n            if len(self.foreign_related_fields) > 1:\n                field_combination = \", \".join(\n                    f\"'{rel_field.name}'\" for rel_field in self.foreign_related_fields\n                )\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"No subset of the fields {field_combination} on model \"\n                        f\"'{model_name}' is unique.\",\n                        hint=(\n                            \"Mark a single field as unique=True or add a set of \"\n                            \"fields to a unique constraint (via unique_together \"\n                            \"or a UniqueConstraint (without condition) in the \"\n                            \"model Meta.constraints).\"\n                        ),\n                        obj=self,\n                        id=\"fields.E310\",\n                    )\n                ]\n            else:\n                field_name = self.foreign_related_fields[0].name\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"'{model_name}.{field_name}' must be unique because it is \"\n                        \"referenced by a foreign key.\",\n                        hint=(\n                            \"Add unique=True to this field or add a \"\n                            \"UniqueConstraint (without condition) in the model \"\n                            \"Meta.constraints.\"\n                        ),\n                        obj=self,\n                        id=\"fields.E311\",\n                    )\n                ]\n        return []\n\n    def deconstruct(self):\n        name, path, args, kwargs = super().deconstruct()\n        kwargs[\"on_delete\"] = self.remote_field.on_delete\n        kwargs[\"from_fields\"] = self.from_fields\n        kwargs[\"to_fields\"] = self.to_fields\n\n        if self.remote_field.parent_link:\n            kwargs[\"parent_link\"] = self.remote_field.parent_link\n        if isinstance(self.remote_field.model, str):\n            if \".\" in self.remote_field.model:\n                app_label, model_name = self.remote_field.model.split(\".\")\n                kwargs[\"to\"] = \"%s.%s\" % (app_label, model_name.lower())\n            else:\n                kwargs[\"to\"] = self.remote_field.model.lower()\n        else:\n            kwargs[\"to\"] = self.remote_field.model._meta.label_lower\n        # If swappable is True, then see if we're actually pointing to the\n        # target of a swap.\n        swappable_setting = self.swappable_setting\n        if swappable_setting is not None:\n            # If it's already a settings reference, error\n            if hasattr(kwargs[\"to\"], \"setting_name\"):\n                if kwargs[\"to\"].setting_name != swappable_setting:\n                    raise ValueError(\n                        \"Cannot deconstruct a ForeignKey pointing to a model \"\n                        \"that is swapped in place of more than one model (%s and %s)\"\n                        % (kwargs[\"to\"].setting_name, swappable_setting)\n                    )\n            # Set it\n            kwargs[\"to\"] = SettingsReference(\n                kwargs[\"to\"],\n                swappable_setting,\n            )\n        return name, path, args, kwargs\n\n    def resolve_related_fields(self):\n        if not self.from_fields or len(self.from_fields) != len(self.to_fields):\n            raise ValueError(\n                \"Foreign Object from and to fields must be the same non-zero length\"\n            )\n        if isinstance(self.remote_field.model, str):\n            raise ValueError(\n                \"Related model %r cannot be resolved\" % self.remote_field.model\n            )\n        related_fields = []\n        for from_field_name, to_field_name in zip(self.from_fields, self.to_fields):\n            from_field = (\n                self\n                if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT\n                else self.opts.get_field(from_field_name)\n            )\n            to_field = (\n                self.remote_field.model._meta.pk\n                if to_field_name is None\n                else self.remote_field.model._meta.get_field(to_field_name)\n            )\n            related_fields.append((from_field, to_field))\n        return related_fields\n\n    @cached_property\n    def related_fields(self):\n        return self.resolve_related_fields()\n\n    @cached_property\n    def reverse_related_fields(self):\n        return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]\n\n    @cached_property\n    def local_related_fields(self):\n        return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)\n\n    @cached_property\n    def foreign_related_fields(self):\n        return tuple(\n            rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field\n        )\n\n    def get_local_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.local_related_fields)\n\n    def get_foreign_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.foreign_related_fields)\n\n    @staticmethod\n    def get_instance_value_for_fields(instance, fields):\n        ret = []\n        opts = instance._meta\n        for field in fields:\n            # Gotcha: in some cases (like fixture loading) a model can have\n            # different values in parent_ptr_id and parent's id. So, use\n            # instance.pk (that is, parent_ptr_id) when asked for instance.id.\n            if field.primary_key:\n                possible_parent_link = opts.get_ancestor_link(field.model)\n                if (\n                    not possible_parent_link\n                    or possible_parent_link.primary_key\n                    or possible_parent_link.model._meta.abstract\n                ):\n                    ret.append(instance.pk)\n                    continue\n            ret.append(getattr(instance, field.attname))\n        return tuple(ret)\n\n    def get_attname_column(self):\n        attname, column = super().get_attname_column()\n        return attname, None\n\n    def get_joining_fields(self, reverse_join=False):\n        return tuple(\n            self.reverse_related_fields if reverse_join else self.related_fields\n        )\n\n    def get_reverse_joining_fields(self):\n        return self.get_joining_fields(reverse_join=True)\n\n    def get_extra_descriptor_filter(self, instance):\n        \"\"\"\n        Return an extra filter condition for related object fetching when\n        user does 'instance.fieldname', that is the extra filter is used in\n        the descriptor of the field.\n\n        The filter should be either a dict usable in .filter(**kwargs) call or\n        a Q-object. The condition will be ANDed together with the relation's\n        joining columns.\n\n        A parallel method is get_extra_restriction() which is used in\n        JOIN and subquery conditions.\n        \"\"\"\n        return {}\n\n    def get_extra_restriction(self, alias, related_alias):\n        \"\"\"\n        Return a pair condition used for joining and subquery pushdown. The\n        condition is something that responds to as_sql(compiler, connection)\n        method.\n\n        Note that currently referring both the 'alias' and 'related_alias'\n        will not work in some conditions, like subquery pushdown.\n\n        A parallel method is get_extra_descriptor_filter() which is used in\n        instance.fieldname related object fetching.\n        \"\"\"\n        return None\n\n    def get_path_info(self, filtered_relation=None):\n        \"\"\"Get path from this field to the related model.\"\"\"\n        opts = self.remote_field.model._meta\n        from_opts = self.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=self.foreign_related_fields,\n                join_field=self,\n                m2m=False,\n                direct=True,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def path_infos(self):\n        return self.get_path_info()\n\n    def get_reverse_path_info(self, filtered_relation=None):\n        \"\"\"Get path from the related model to this field's model.\"\"\"\n        opts = self.model._meta\n        from_opts = self.remote_field.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=(opts.pk,),\n                join_field=self.remote_field,\n                m2m=not self.unique,\n                direct=False,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def reverse_path_infos(self):\n        return self.get_reverse_path_info()\n\n    @classmethod\n    @functools.cache\n    def get_class_lookups(cls):\n        bases = inspect.getmro(cls)\n        bases = bases[: bases.index(ForeignObject) + 1]\n        class_lookups = [parent.__dict__.get(\"class_lookups\", {}) for parent in bases]\n        return cls.merge_dicts(class_lookups)\n\n    def contribute_to_class(self, cls, name, private_only=False, **kwargs):\n        super().contribute_to_class(cls, name, private_only=private_only, **kwargs)\n        setattr(cls, self.name, self.forward_related_accessor_class(self))\n\n    def contribute_to_related_class(self, cls, related):\n        # Internal FK's - i.e., those with a related name ending with '+' -\n        # and swapped models don't get a related descriptor.\n        if not self.remote_field.hidden and not related.related_model._meta.swapped:\n            setattr(\n                cls._meta.concrete_model,\n                related.accessor_name,\n                self.related_accessor_class(related),\n            )\n            # While 'limit_choices_to' might be a callable, simply pass\n            # it along for later - this is too early because it's still\n            # model load time.\n            if self.remote_field.limit_choices_to:\n                cls._meta.related_fkey_lookups.append(\n                    self.remote_field.limit_choices_to\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": [], "base_sample_id": "py-f8771ea86cd1a84e", "category": "source", "construction_source": "pluggable-python-degrader", "content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "description": "Unmodified source class", "display_label": "SRC", "granularity": "class", "interference": null, "level": 0, "line_count": 461, "local_path": "source-original/SRC__django__ForeignObject__62236fb4.py", "order": 0, "original_content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "parent_variant_id": null, "readability_direction": "baseline", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/fields/related.py#L544-L958", "source_repository": "https://github.com/django/django.git", "stage": "original", "transformation_stats": {}, "unit_kind": "class", "unit_name": "ForeignObject", "variant_id": "pyint-c08262236fb4-SRC", "group_id": "py-f8771ea86cd1a84e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 267, "constructed_application_mode": "independent-interference", "is_baseline_variant": true, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-685da7375558-I01", "source": "import functools\nimport inspect\nfrom functools import partial\nfrom django import forms\nfrom django.apps import apps\nfrom django.conf import SettingsReference, settings\nfrom django.core import checks, exceptions\nfrom django.db import connection, connections, router\nfrom django.db.backends import utils\nfrom django.db.models import NOT_PROVIDED, Q\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.deletion import (\n    CASCADE,\n    DB_CASCADE,\n    DB_SET_DEFAULT,\n    DB_SET_NULL,\n    DO_NOTHING,\n    SET_DEFAULT,\n    SET_NULL,\n    DatabaseOnDelete,\n)\nfrom django.db.models.query_utils import PathInfo\nfrom django.db.models.utils import make_model_tuple\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext_lazy as _\nfrom . import Field\nfrom .mixins import FieldCacheMixin\nfrom .related_descriptors import (\n    ForeignKeyDeferredAttribute,\n    ForwardManyToOneDescriptor,\n    ForwardOneToOneDescriptor,\n    ManyToManyDescriptor,\n    ReverseManyToOneDescriptor,\n    ReverseOneToOneDescriptor,\n)\nfrom .related_lookups import (\n    RelatedExact,\n    RelatedGreaterThan,\n    RelatedGreaterThanOrEqual,\n    RelatedIn,\n    RelatedIsNull,\n    RelatedLessThan,\n    RelatedLessThanOrEqual,\n)\nfrom .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel\n\nclass ForeignObject(RelatedField):\n    \n\n     \n    many_to_many = False\n    many_to_one = True\n    one_to_many = False\n    one_to_one = False\n\n    requires_unique_target = True\n    related_accessor_class = ReverseManyToOneDescriptor\n    forward_related_accessor_class = ForwardManyToOneDescriptor\n    rel_class = ForeignObjectRel\n\n    def __init__(\n        self,\n        to,\n        on_delete,\n        from_fields,\n        to_fields,\n        rel=None,\n        related_name=None,\n        related_query_name=None,\n        limit_choices_to=None,\n        parent_link=False,\n        swappable=True,\n        **kwargs,\n    ):\n        if rel is None:\n            rel = self.rel_class(\n                self,\n                to,\n                related_name=related_name,\n                related_query_name=related_query_name,\n                limit_choices_to=limit_choices_to,\n                parent_link=parent_link,\n                on_delete=on_delete,\n            )\n\n        super().__init__(\n            rel=rel,\n            related_name=related_name,\n            related_query_name=related_query_name,\n            limit_choices_to=limit_choices_to,\n            **kwargs,\n        )\n\n        self.from_fields = from_fields\n        self.to_fields = to_fields\n        self.swappable = swappable\n\n    def __copy__(self):\n        obj = super().__copy__()\n         \n        obj.__dict__.pop(\"path_infos\", None)\n        obj.__dict__.pop(\"reverse_path_infos\", None)\n        return obj\n\n    @property\n    def non_db_attrs(self):\n        if isinstance(self.remote_field.on_delete, DatabaseOnDelete):\n             \n             \n            return super().non_db_attrs\n        return super().non_db_attrs + (\"on_delete\",)\n\n    def check(self, **kwargs):\n        return [\n            *super().check(**kwargs),\n            *self._check_to_fields_exist(),\n            *self._check_to_fields_composite_pk(),\n            *self._check_unique_target(),\n        ]\n\n    def _check_to_fields_exist(self):\n         \n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            if to_field:\n                try:\n                    self.remote_field.model._meta.get_field(to_field)\n                except exceptions.FieldDoesNotExist:\n                    errors.append(\n                        checks.Error(\n                            \"The to_field '%s' doesn't exist on the related \"\n                            \"model '%s'.\"\n                            % (to_field, self.remote_field.model._meta.label),\n                            obj=self,\n                            id=\"fields.E312\",\n                        )\n                    )\n        return errors\n\n    def _check_to_fields_composite_pk(self):\n        from django.db.models.fields.composite import CompositePrimaryKey\n\n         \n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            try:\n                field = (\n                    self.remote_field.model._meta.pk\n                    if to_field is None\n                    else self.remote_field.model._meta.get_field(to_field)\n                )\n            except exceptions.FieldDoesNotExist:\n                pass\n            else:\n                if isinstance(field, CompositePrimaryKey):\n                    errors.append(\n                        checks.Error(\n                            \"Field defines a relation involving model \"\n                            f\"{self.remote_field.model._meta.object_name!r} which has \"\n                            \"a CompositePrimaryKey and such relations are not \"\n                            \"supported.\",\n                            obj=self,\n                            id=\"fields.E347\",\n                        )\n                    )\n        return errors\n\n    def _check_unique_target(self):\n        rel_is_string = isinstance(self.remote_field.model, str)\n        if rel_is_string or not self.requires_unique_target:\n            return []\n\n        try:\n            self.foreign_related_fields\n        except exceptions.FieldDoesNotExist:\n            return []\n\n        if not self.foreign_related_fields:\n            return []\n\n        has_unique_constraint = any(\n            rel_field.unique for rel_field in self.foreign_related_fields\n        )\n        if not has_unique_constraint:\n            foreign_fields = {f.name for f in self.foreign_related_fields}\n            remote_opts = self.remote_field.model._meta\n            has_unique_constraint = (\n                any(\n                    frozenset(ut) <= foreign_fields\n                    for ut in remote_opts.unique_together\n                )\n                or any(\n                    frozenset(uc.fields) <= foreign_fields\n                    for uc in remote_opts.total_unique_constraints\n                )\n                 \n                 \n                or (\n                    frozenset(field.name for field in remote_opts.pk_fields)\n                    == foreign_fields\n                )\n            )\n\n        if not has_unique_constraint:\n            if len(self.foreign_related_fields) > 1:\n                field_combination = \", \".join(\n                    f\"'{rel_field.name}'\" for rel_field in self.foreign_related_fields\n                )\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"No subset of the fields {field_combination} on model \"\n                        f\"'{model_name}' is unique.\",\n                        hint=(\n                            \"Mark a single field as unique=True or add a set of \"\n                            \"fields to a unique constraint (via unique_together \"\n                            \"or a UniqueConstraint (without condition) in the \"\n                            \"model Meta.constraints).\"\n                        ),\n                        obj=self,\n                        id=\"fields.E310\",\n                    )\n                ]\n            else:\n                field_name = self.foreign_related_fields[0].name\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"'{model_name}.{field_name}' must be unique because it is \"\n                        \"referenced by a foreign key.\",\n                        hint=(\n                            \"Add unique=True to this field or add a \"\n                            \"UniqueConstraint (without condition) in the model \"\n                            \"Meta.constraints.\"\n                        ),\n                        obj=self,\n                        id=\"fields.E311\",\n                    )\n                ]\n        return []\n\n    def deconstruct(self):\n        name, path, args, kwargs = super().deconstruct()\n        kwargs[\"on_delete\"] = self.remote_field.on_delete\n        kwargs[\"from_fields\"] = self.from_fields\n        kwargs[\"to_fields\"] = self.to_fields\n\n        if self.remote_field.parent_link:\n            kwargs[\"parent_link\"] = self.remote_field.parent_link\n        if isinstance(self.remote_field.model, str):\n            if \".\" in self.remote_field.model:\n                app_label, model_name = self.remote_field.model.split(\".\")\n                kwargs[\"to\"] = \"%s.%s\" % (app_label, model_name.lower())\n            else:\n                kwargs[\"to\"] = self.remote_field.model.lower()\n        else:\n            kwargs[\"to\"] = self.remote_field.model._meta.label_lower\n         \n         \n        swappable_setting = self.swappable_setting\n        if swappable_setting is not None:\n             \n            if hasattr(kwargs[\"to\"], \"setting_name\"):\n                if kwargs[\"to\"].setting_name != swappable_setting:\n                    raise ValueError(\n                        \"Cannot deconstruct a ForeignKey pointing to a model \"\n                        \"that is swapped in place of more than one model (%s and %s)\"\n                        % (kwargs[\"to\"].setting_name, swappable_setting)\n                    )\n             \n            kwargs[\"to\"] = SettingsReference(\n                kwargs[\"to\"],\n                swappable_setting,\n            )\n        return name, path, args, kwargs\n\n    def resolve_related_fields(self):\n        if not self.from_fields or len(self.from_fields) != len(self.to_fields):\n            raise ValueError(\n                \"Foreign Object from and to fields must be the same non-zero length\"\n            )\n        if isinstance(self.remote_field.model, str):\n            raise ValueError(\n                \"Related model %r cannot be resolved\" % self.remote_field.model\n            )\n        related_fields = []\n        for from_field_name, to_field_name in zip(self.from_fields, self.to_fields):\n            from_field = (\n                self\n                if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT\n                else self.opts.get_field(from_field_name)\n            )\n            to_field = (\n                self.remote_field.model._meta.pk\n                if to_field_name is None\n                else self.remote_field.model._meta.get_field(to_field_name)\n            )\n            related_fields.append((from_field, to_field))\n        return related_fields\n\n    @cached_property\n    def related_fields(self):\n        return self.resolve_related_fields()\n\n    @cached_property\n    def reverse_related_fields(self):\n        return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]\n\n    @cached_property\n    def local_related_fields(self):\n        return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)\n\n    @cached_property\n    def foreign_related_fields(self):\n        return tuple(\n            rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field\n        )\n\n    def get_local_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.local_related_fields)\n\n    def get_foreign_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.foreign_related_fields)\n\n    @staticmethod\n    def get_instance_value_for_fields(instance, fields):\n        ret = []\n        opts = instance._meta\n        for field in fields:\n             \n             \n             \n            if field.primary_key:\n                possible_parent_link = opts.get_ancestor_link(field.model)\n                if (\n                    not possible_parent_link\n                    or possible_parent_link.primary_key\n                    or possible_parent_link.model._meta.abstract\n                ):\n                    ret.append(instance.pk)\n                    continue\n            ret.append(getattr(instance, field.attname))\n        return tuple(ret)\n\n    def get_attname_column(self):\n        attname, column = super().get_attname_column()\n        return attname, None\n\n    def get_joining_fields(self, reverse_join=False):\n        return tuple(\n            self.reverse_related_fields if reverse_join else self.related_fields\n        )\n\n    def get_reverse_joining_fields(self):\n        return self.get_joining_fields(reverse_join=True)\n\n    def get_extra_descriptor_filter(self, instance):\n        \n        return {}\n\n    def get_extra_restriction(self, alias, related_alias):\n        \n        return None\n\n    def get_path_info(self, filtered_relation=None):\n        \n        opts = self.remote_field.model._meta\n        from_opts = self.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=self.foreign_related_fields,\n                join_field=self,\n                m2m=False,\n                direct=True,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def path_infos(self):\n        return self.get_path_info()\n\n    def get_reverse_path_info(self, filtered_relation=None):\n        \n        opts = self.model._meta\n        from_opts = self.remote_field.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=(opts.pk,),\n                join_field=self.remote_field,\n                m2m=not self.unique,\n                direct=False,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def reverse_path_infos(self):\n        return self.get_reverse_path_info()\n\n    @classmethod\n    @functools.cache\n    def get_class_lookups(cls):\n        bases = inspect.getmro(cls)\n        bases = bases[: bases.index(ForeignObject) + 1]\n        class_lookups = [parent.__dict__.get(\"class_lookups\", {}) for parent in bases]\n        return cls.merge_dicts(class_lookups)\n\n    def contribute_to_class(self, cls, name, private_only=False, **kwargs):\n        super().contribute_to_class(cls, name, private_only=private_only, **kwargs)\n        setattr(cls, self.name, self.forward_related_accessor_class(self))\n\n    def contribute_to_related_class(self, cls, related):\n         \n         \n        if not self.remote_field.hidden and not related.related_model._meta.swapped:\n            setattr(\n                cls._meta.concrete_model,\n                related.accessor_name,\n                self.related_accessor_class(related),\n            )\n             \n             \n             \n            if self.remote_field.limit_choices_to:\n                cls._meta.related_fkey_lookups.append(\n                    self.remote_field.limit_choices_to\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["remove-comments"], "base_sample_id": "py-f8771ea86cd1a84e", "category": "comments", "construction_source": "pluggable-python-degrader", "content_sha256": "ce31e0ba95d7d0ff6f82fa1d7fdc701014e969c8b6334f123bb9289709c710d8", "description": "Remove comments and docstrings", "display_label": "I01", "granularity": "class", "interference": "remove-comments", "level": 1, "line_count": 438, "local_path": "comments/remove-comments/I01__django__ForeignObject__a7375558.py", "order": 1, "original_content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "parent_variant_id": "pyint-c08262236fb4-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/fields/related.py#L544-L958", "source_repository": "https://github.com/django/django.git", "stage": "remove-comments", "transformation_stats": {"comment_bytes_removed": 1985, "comments_removed": 25, "docstrings_removed": 5, "line_comments_removed": 20}, "unit_kind": "class", "unit_name": "ForeignObject", "variant_id": "pyint-685da7375558-I01", "group_id": "py-f8771ea86cd1a84e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 268, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-705ace115394-I02", "source": "import functools\nimport inspect\nfrom functools import partial\nfrom django import forms\nfrom django.apps import apps\nfrom django.conf import SettingsReference, settings\nfrom django.core import checks, exceptions\nfrom django.db import connection, connections, router\nfrom django.db.backends import utils\nfrom django.db.models import NOT_PROVIDED, Q\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.deletion import (\n    CASCADE,\n    DB_CASCADE,\n    DB_SET_DEFAULT,\n    DB_SET_NULL,\n    DO_NOTHING,\n    SET_DEFAULT,\n    SET_NULL,\n    DatabaseOnDelete,\n)\nfrom django.db.models.query_utils import PathInfo\nfrom django.db.models.utils import make_model_tuple\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext_lazy as _\nfrom . import Field\nfrom .mixins import FieldCacheMixin\nfrom .related_descriptors import (\n    ForeignKeyDeferredAttribute,\n    ForwardManyToOneDescriptor,\n    ForwardOneToOneDescriptor,\n    ManyToManyDescriptor,\n    ReverseManyToOneDescriptor,\n    ReverseOneToOneDescriptor,\n)\nfrom .related_lookups import (\n    RelatedExact,\n    RelatedGreaterThan,\n    RelatedGreaterThanOrEqual,\n    RelatedIn,\n    RelatedIsNull,\n    RelatedLessThan,\n    RelatedLessThanOrEqual,\n)\nfrom .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel\n\nclass ForeignObject(RelatedField):\n    \"\"\"\n    Abstraction of the ForeignKey relation to support multi-column relations.\n    \"\"\"\n\n    # Field flags\n    many_to_many = False\n    many_to_one = True\n    one_to_many = False\n    one_to_one = False\n\n    requires_unique_target = True\n    related_accessor_class = ReverseManyToOneDescriptor\n    forward_related_accessor_class = ForwardManyToOneDescriptor\n    rel_class = ForeignObjectRel\n\n    def __init__(\n        self,\n        to2,\n        on,\n        from2,\n        to3,\n        rel2=None,\n        related3=None,\n        related4=None,\n        limit=None,\n        parent2=False,\n        swa=True,\n        **kwa,\n    ):\n        if rel2 is None:\n            rel2 = self.rel_class(\n                self,\n                to2,\n                related_name=related3,\n                related_query_name=related4,\n                limit_choices_to=limit,\n                parent_link=parent2,\n                on_delete=on,\n            )\n\n        super().__init__(\n            rel=rel2,\n            related_name=related3,\n            related_query_name=related4,\n            limit_choices_to=limit,\n            **kwa,\n        )\n\n        self.from_fields = from2\n        self.to_fields = to3\n        self.swappable = swa\n\n    def __copy__(self):\n        obj2 = super().__copy__()\n        # Remove any cached PathInfo values.\n        obj2.__dict__.pop(\"path_infos\", None)\n        obj2.__dict__.pop(\"reverse_path_infos\", None)\n        return obj2\n\n    @property\n    def non(self):\n        if isinstance(self.remote_field.on_delete, DatabaseOnDelete):\n            # Database-level on_delete options are part of the column\n            # definition.\n            return super().non_db_attrs\n        return super().non_db_attrs + (\"on_delete\",)\n\n    def che(self, **kwa2):\n        return [\n            *super().check(**kwa2),\n            *self.check2(),\n            *self.check3(),\n            *self.check4(),\n        ]\n\n    def check2(self):\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        err = []\n        for to4 in self.to_fields:\n            if to4:\n                try:\n                    self.remote_field.model._meta.get_field(to4)\n                except exceptions.FieldDoesNotExist:\n                    err.append(\n                        checks.Error(\n                            \"The to_field '%s' doesn't exist on the related \"\n                            \"model '%s'.\"\n                            % (to4, self.remote_field.model._meta.label),\n                            obj=self,\n                            id=\"fields.E312\",\n                        )\n                    )\n        return err\n\n    def check3(self):\n        from django.db.models.fields.composite import CompositePrimaryKey\n\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        err2 = []\n        for to5 in self.to_fields:\n            try:\n                fie = (\n                    self.remote_field.model._meta.pk\n                    if to5 is None\n                    else self.remote_field.model._meta.get_field(to5)\n                )\n            except exceptions.FieldDoesNotExist:\n                pass\n            else:\n                if isinstance(fie, CompositePrimaryKey):\n                    err2.append(\n                        checks.Error(\n                            \"Field defines a relation involving model \"\n                            f\"{self.remote_field.model._meta.object_name!r} which has \"\n                            \"a CompositePrimaryKey and such relations are not \"\n                            \"supported.\",\n                            obj=self,\n                            id=\"fields.E347\",\n                        )\n                    )\n        return err2\n\n    def check4(self):\n        rel3 = isinstance(self.remote_field.model, str)\n        if rel3 or not self.requires_unique_target:\n            return []\n\n        try:\n            self.foreign\n        except exceptions.FieldDoesNotExist:\n            return []\n\n        if not self.foreign:\n            return []\n\n        has = any(\n            rel4.unique for rel4 in self.foreign\n        )\n        if not has:\n            foreign2 = {f2.name for f2 in self.foreign}\n            remote = self.remote_field.model._meta\n            has = (\n                any(\n                    frozenset(ut2) <= foreign2\n                    for ut2 in remote.unique_together\n                )\n                or any(\n                    frozenset(uc2.fields) <= foreign2\n                    for uc2 in remote.total_unique_constraints\n                )\n                # If the model defines a composite primary key and the foreign\n                # key refers to it, the target is unique.\n                or (\n                    frozenset(fie2.name for fie2 in remote.pk_fields)\n                    == foreign2\n                )\n            )\n\n        if not has:\n            if len(self.foreign) > 1:\n                field2 = \", \".join(\n                    f\"'{rel4.name}'\" for rel4 in self.foreign\n                )\n                model2 = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"No subset of the fields {field2} on model \"\n                        f\"'{model2}' is unique.\",\n                        hint=(\n                            \"Mark a single field as unique=True or add a set of \"\n                            \"fields to a unique constraint (via unique_together \"\n                            \"or a UniqueConstraint (without condition) in the \"\n                            \"model Meta.constraints).\"\n                        ),\n                        obj=self,\n                        id=\"fields.E310\",\n                    )\n                ]\n            else:\n                field3 = self.foreign[0].name\n                model2 = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"'{model2}.{field3}' must be unique because it is \"\n                        \"referenced by a foreign key.\",\n                        hint=(\n                            \"Add unique=True to this field or add a \"\n                            \"UniqueConstraint (without condition) in the model \"\n                            \"Meta.constraints.\"\n                        ),\n                        obj=self,\n                        id=\"fields.E311\",\n                    )\n                ]\n        return []\n\n    def dec(self):\n        nam, pat, arg, kwa3 = super().deconstruct()\n        kwa3[\"on_delete\"] = self.remote_field.on_delete\n        kwa3[\"from_fields\"] = self.from_fields\n        kwa3[\"to_fields\"] = self.to_fields\n\n        if self.remote_field.parent_link:\n            kwa3[\"parent_link\"] = self.remote_field.parent_link\n        if isinstance(self.remote_field.model, str):\n            if \".\" in self.remote_field.model:\n                app, model3 = self.remote_field.model.split(\".\")\n                kwa3[\"to\"] = \"%s.%s\" % (app, model3.lower())\n            else:\n                kwa3[\"to\"] = self.remote_field.model.lower()\n        else:\n            kwa3[\"to\"] = self.remote_field.model._meta.label_lower\n        # If swappable is True, then see if we're actually pointing to the\n        # target of a swap.\n        swappable2 = self.swappable_setting\n        if swappable2 is not None:\n            # If it's already a settings reference, error\n            if hasattr(kwa3[\"to\"], \"setting_name\"):\n                if kwa3[\"to\"].setting_name != swappable2:\n                    raise ValueError(\n                        \"Cannot deconstruct a ForeignKey pointing to a model \"\n                        \"that is swapped in place of more than one model (%s and %s)\"\n                        % (kwa3[\"to\"].setting_name, swappable2)\n                    )\n            # Set it\n            kwa3[\"to\"] = SettingsReference(\n                kwa3[\"to\"],\n                swappable2,\n            )\n        return nam, pat, arg, kwa3\n\n    def resolve(self):\n        if not self.from_fields or len(self.from_fields) != len(self.to_fields):\n            raise ValueError(\n                \"Foreign Object from and to fields must be the same non-zero length\"\n            )\n        if isinstance(self.remote_field.model, str):\n            raise ValueError(\n                \"Related model %r cannot be resolved\" % self.remote_field.model\n            )\n        related5 = []\n        for from3, to6 in zip(self.from_fields, self.to_fields):\n            from4 = (\n                self\n                if from3 == RECURSIVE_RELATIONSHIP_CONSTANT\n                else self.opts.get_field(from3)\n            )\n            to7 = (\n                self.remote_field.model._meta.pk\n                if to6 is None\n                else self.remote_field.model._meta.get_field(to6)\n            )\n            related5.append((from4, to7))\n        return related5\n\n    @cached_property\n    def related2(self):\n        return self.resolve()\n\n    @cached_property\n    def reverse(self):\n        return [(rhs, lhs) for lhs, rhs in self.related2]\n\n    @cached_property\n    def local(self):\n        return tuple(lhs2 for lhs2, rhs2 in self.related2)\n\n    @cached_property\n    def foreign(self):\n        return tuple(\n            rhs3 for lhs3, rhs3 in self.related2 if rhs3\n        )\n\n    def get2(self, ins):\n        return self.get4(ins, self.local)\n\n    def get3(self, ins2):\n        return self.get4(ins2, self.foreign)\n\n    @staticmethod\n    def get4(ins3, fie3):\n        ret2 = []\n        opt = ins3._meta\n        for fie4 in fie3:\n            # Gotcha: in some cases (like fixture loading) a model can have\n            # different values in parent_ptr_id and parent's id. So, use\n            # instance.pk (that is, parent_ptr_id) when asked for instance.id.\n            if fie4.primary_key:\n                possible = opt.get_ancestor_link(fie4.model)\n                if (\n                    not possible\n                    or possible.primary_key\n                    or possible.model._meta.abstract\n                ):\n                    ret2.append(ins3.pk)\n                    continue\n            ret2.append(getattr(ins3, fie4.attname))\n        return tuple(ret2)\n\n    def get5(self):\n        att, col = super().get_attname_column()\n        return att, None\n\n    def get6(self, reverse3=False):\n        return tuple(\n            self.reverse if reverse3 else self.related2\n        )\n\n    def get7(self):\n        return self.get6(reverse_join=True)\n\n    def get8(self, ins4):\n        \"\"\"\n        Return an extra filter condition for related object fetching when\n        user does 'instance.fieldname', that is the extra filter is used in\n        the descriptor of the field.\n\n        The filter should be either a dict usable in .filter(**kwargs) call or\n        a Q-object. The condition will be ANDed together with the relation's\n        joining columns.\n\n        A parallel method is get_extra_restriction() which is used in\n        JOIN and subquery conditions.\n        \"\"\"\n        return {}\n\n    def get9(self, ali, related6):\n        \"\"\"\n        Return a pair condition used for joining and subquery pushdown. The\n        condition is something that responds to as_sql(compiler, connection)\n        method.\n\n        Note that currently referring both the 'alias' and 'related_alias'\n        will not work in some conditions, like subquery pushdown.\n\n        A parallel method is get_extra_descriptor_filter() which is used in\n        instance.fieldname related object fetching.\n        \"\"\"\n        return None\n\n    def get10(self, filtered=None):\n        \"\"\"Get path from this field to the related model.\"\"\"\n        opt2 = self.remote_field.model._meta\n        from5 = self.model._meta\n        return [\n            PathInfo(\n                from_opts=from5,\n                to_opts=opt2,\n                target_fields=self.foreign,\n                join_field=self,\n                m2m=False,\n                direct=True,\n                filtered_relation=filtered,\n            )\n        ]\n\n    @cached_property\n    def path2(self):\n        return self.get10()\n\n    def get11(self, filtered2=None):\n        \"\"\"Get path from the related model to this field's model.\"\"\"\n        opt3 = self.model._meta\n        from6 = self.remote_field.model._meta\n        return [\n            PathInfo(\n                from_opts=from6,\n                to_opts=opt3,\n                target_fields=(opt3.pk,),\n                join_field=self.remote_field,\n                m2m=not self.unique,\n                direct=False,\n                filtered_relation=filtered2,\n            )\n        ]\n\n    @cached_property\n    def reverse2(self):\n        return self.get11()\n\n    @classmethod\n    @functools.cache\n    def get12(cls):\n        bas = inspect.getmro(cls)\n        bas = bas[: bas.index(ForeignObject) + 1]\n        class2 = [par.__dict__.get(\"class_lookups\", {}) for par in bas]\n        return cls.merge_dicts(class2)\n\n    def contribute(self, cls, nam2, private=False, **kwa4):\n        super().contribute_to_class(cls, nam2, private_only=private, **kwa4)\n        setattr(cls, self.name, self.forward_related_accessor_class(self))\n\n    def contribute2(self, cls, rel5):\n        # Internal FK's - i.e., those with a related name ending with '+' -\n        # and swapped models don't get a related descriptor.\n        if not self.remote_field.hidden and not rel5.related_model._meta.swapped:\n            setattr(\n                cls._meta.concrete_model,\n                rel5.accessor_name,\n                self.related_accessor_class(rel5),\n            )\n            # While 'limit_choices_to' might be a callable, simply pass\n            # it along for later - this is too early because it's still\n            # model load time.\n            if self.remote_field.limit_choices_to:\n                cls._meta.related_fkey_lookups.append(\n                    self.remote_field.limit_choices_to\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["shorten-identifiers"], "base_sample_id": "py-f8771ea86cd1a84e", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "b8372469614add49059d32b3dbeea66118dcfef63bd56847df027758e63f857d", "description": "Shorten method, parameter, and local names without collisions", "display_label": "I02", "granularity": "class", "interference": "shorten-identifiers", "level": 2, "line_count": 461, "local_path": "identifiers/shorten-identifiers/I02__django__ForeignObject__ce115394.py", "order": 2, "original_content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "parent_variant_id": "pyint-c08262236fb4-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/fields/related.py#L544-L958", "source_repository": "https://github.com/django/django.git", "stage": "shorten-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 249, "identifiers_declared": 101}, "unit_kind": "class", "unit_name": "ForeignObject", "variant_id": "pyint-705ace115394-I02", "group_id": "py-f8771ea86cd1a84e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 269, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-73865830712f-I03", "source": "import functools\nimport inspect\nfrom functools import partial\nfrom django import forms\nfrom django.apps import apps\nfrom django.conf import SettingsReference, settings\nfrom django.core import checks, exceptions\nfrom django.db import connection, connections, router\nfrom django.db.backends import utils\nfrom django.db.models import NOT_PROVIDED, Q\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.deletion import (\n    CASCADE,\n    DB_CASCADE,\n    DB_SET_DEFAULT,\n    DB_SET_NULL,\n    DO_NOTHING,\n    SET_DEFAULT,\n    SET_NULL,\n    DatabaseOnDelete,\n)\nfrom django.db.models.query_utils import PathInfo\nfrom django.db.models.utils import make_model_tuple\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext_lazy as _\nfrom . import Field\nfrom .mixins import FieldCacheMixin\nfrom .related_descriptors import (\n    ForeignKeyDeferredAttribute,\n    ForwardManyToOneDescriptor,\n    ForwardOneToOneDescriptor,\n    ManyToManyDescriptor,\n    ReverseManyToOneDescriptor,\n    ReverseOneToOneDescriptor,\n)\nfrom .related_lookups import (\n    RelatedExact,\n    RelatedGreaterThan,\n    RelatedGreaterThanOrEqual,\n    RelatedIn,\n    RelatedIsNull,\n    RelatedLessThan,\n    RelatedLessThanOrEqual,\n)\nfrom .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel\n\nclass ForeignObject(RelatedField):\n    \"\"\"\n    Abstraction of the ForeignKey relation to support multi-column relations.\n    \"\"\"\n\n    # Field flags\n    many_to_many = False\n    many_to_one = True\n    one_to_many = False\n    one_to_one = False\n\n    requires_unique_target = True\n    related_accessor_class = ReverseManyToOneDescriptor\n    forward_related_accessor_class = ForwardManyToOneDescriptor\n    rel_class = ForeignObjectRel\n\n    def __init__(\n        self,\n        map,\n        recentKey,\n        remoteScore,\n        finalMode,\n        key=None,\n        sharedWindow=None,\n        defaultSession=None,\n        currentAccount=None,\n        backupCount=False,\n        localPath=True,\n        **result,\n    ):\n        if key is None:\n            key = self.rel_class(\n                self,\n                map,\n                related_name=sharedWindow,\n                related_query_name=defaultSession,\n                limit_choices_to=currentAccount,\n                parent_link=backupCount,\n                on_delete=recentKey,\n            )\n\n        super().__init__(\n            rel=key,\n            related_name=sharedWindow,\n            related_query_name=defaultSession,\n            limit_choices_to=currentAccount,\n            **result,\n        )\n\n        self.from_fields = remoteScore\n        self.to_fields = finalMode\n        self.swappable = localPath\n\n    def __copy__(self):\n        age = super().__copy__()\n        # Remove any cached PathInfo values.\n        age.__dict__.pop(\"path_infos\", None)\n        age.__dict__.pop(\"reverse_path_infos\", None)\n        return age\n\n    @property\n    def checkBalance(self):\n        if isinstance(self.remote_field.on_delete, DatabaseOnDelete):\n            # Database-level on_delete options are part of the column\n            # definition.\n            return super().non_db_attrs\n        return super().non_db_attrs + (\"on_delete\",)\n\n    def store(self, **status):\n        return [\n            *super().check(**status),\n            *self.validateBalance(),\n            *self.validateAccount(),\n            *self.validateAddress(),\n        ]\n\n    def validateBalance(self):\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        amount = []\n        for duration in self.to_fields:\n            if duration:\n                try:\n                    self.remote_field.model._meta.get_field(duration)\n                except exceptions.FieldDoesNotExist:\n                    amount.append(\n                        checks.Error(\n                            \"The to_field '%s' doesn't exist on the related \"\n                            \"model '%s'.\"\n                            % (duration, self.remote_field.model._meta.label),\n                            obj=self,\n                            id=\"fields.E312\",\n                        )\n                    )\n        return amount\n\n    def validateAccount(self):\n        from django.db.models.fields.composite import CompositePrimaryKey\n\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        result = []\n        for category in self.to_fields:\n            try:\n                order = (\n                    self.remote_field.model._meta.pk\n                    if category is None\n                    else self.remote_field.model._meta.get_field(category)\n                )\n            except exceptions.FieldDoesNotExist:\n                pass\n            else:\n                if isinstance(order, CompositePrimaryKey):\n                    result.append(\n                        checks.Error(\n                            \"Field defines a relation involving model \"\n                            f\"{self.remote_field.model._meta.object_name!r} which has \"\n                            \"a CompositePrimaryKey and such relations are not \"\n                            \"supported.\",\n                            obj=self,\n                            id=\"fields.E347\",\n                        )\n                    )\n        return result\n\n    def validateAddress(self):\n        currentClient = isinstance(self.remote_field.model, str)\n        if currentClient or not self.requires_unique_target:\n            return []\n\n        try:\n            self.refreshSession\n        except exceptions.FieldDoesNotExist:\n            return []\n\n        if not self.refreshSession:\n            return []\n\n        defaultAccount = any(\n            finalData.unique for finalData in self.refreshSession\n        )\n        if not defaultAccount:\n            primaryAccount = {age.name for age in self.refreshSession}\n            remoteValue = self.remote_field.model._meta\n            defaultAccount = (\n                any(\n                    frozenset(key) <= primaryAccount\n                    for key in remoteValue.unique_together\n                )\n                or any(\n                    frozenset(map.fields) <= primaryAccount\n                    for map in remoteValue.total_unique_constraints\n                )\n                # If the model defines a composite primary key and the foreign\n                # key refers to it, the target is unique.\n                or (\n                    frozenset(order.name for order in remoteValue.pk_fields)\n                    == primaryAccount\n                )\n            )\n\n        if not defaultAccount:\n            if len(self.refreshSession) > 1:\n                defaultBalance = \", \".join(\n                    f\"'{finalData.name}'\" for finalData in self.refreshSession\n                )\n                secureMode = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"No subset of the fields {defaultBalance} on model \"\n                        f\"'{secureMode}' is unique.\",\n                        hint=(\n                            \"Mark a single field as unique=True or add a set of \"\n                            \"fields to a unique constraint (via unique_together \"\n                            \"or a UniqueConstraint (without condition) in the \"\n                            \"model Meta.constraints).\"\n                        ),\n                        obj=self,\n                        id=\"fields.E310\",\n                    )\n                ]\n            else:\n                finalCount = self.refreshSession[0].name\n                secureMode = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"'{secureMode}.{finalCount}' must be unique because it is \"\n                        \"referenced by a foreign key.\",\n                        hint=(\n                            \"Add unique=True to this field or add a \"\n                            \"UniqueConstraint (without condition) in the model \"\n                            \"Meta.constraints.\"\n                        ),\n                        obj=self,\n                        id=\"fields.E311\",\n                    )\n                ]\n        return []\n\n    def createCache(self):\n        size, item, flag, status = super().deconstruct()\n        status[\"on_delete\"] = self.remote_field.on_delete\n        status[\"from_fields\"] = self.from_fields\n        status[\"to_fields\"] = self.to_fields\n\n        if self.remote_field.parent_link:\n            status[\"parent_link\"] = self.remote_field.parent_link\n        if isinstance(self.remote_field.model, str):\n            if \".\" in self.remote_field.model:\n                timestamp, secureMode = self.remote_field.model.split(\".\")\n                status[\"to\"] = \"%s.%s\" % (timestamp, secureMode.lower())\n            else:\n                status[\"to\"] = self.remote_field.model.lower()\n        else:\n            status[\"to\"] = self.remote_field.model._meta.label_lower\n        # If swappable is True, then see if we're actually pointing to the\n        # target of a swap.\n        defaultBalance = self.swappable_setting\n        if defaultBalance is not None:\n            # If it's already a settings reference, error\n            if hasattr(status[\"to\"], \"setting_name\"):\n                if status[\"to\"].setting_name != defaultBalance:\n                    raise ValueError(\n                        \"Cannot deconstruct a ForeignKey pointing to a model \"\n                        \"that is swapped in place of more than one model (%s and %s)\"\n                        % (status[\"to\"].setting_name, defaultBalance)\n                    )\n            # Set it\n            status[\"to\"] = SettingsReference(\n                status[\"to\"],\n                defaultBalance,\n            )\n        return size, item, flag, status\n\n    def validateRequest(self):\n        if not self.from_fields or len(self.from_fields) != len(self.to_fields):\n            raise ValueError(\n                \"Foreign Object from and to fields must be the same non-zero length\"\n            )\n        if isinstance(self.remote_field.model, str):\n            raise ValueError(\n                \"Related model %r cannot be resolved\" % self.remote_field.model\n            )\n        pendingAddress = []\n        for defaultSession, pendingResult in zip(self.from_fields, self.to_fields):\n            nextBuffer = (\n                self\n                if defaultSession == RECURSIVE_RELATIONSHIP_CONSTANT\n                else self.opts.get_field(defaultSession)\n            )\n            location = (\n                self.remote_field.model._meta.pk\n                if pendingResult is None\n                else self.remote_field.model._meta.get_field(pendingResult)\n            )\n            pendingAddress.append((nextBuffer, location))\n        return pendingAddress\n\n    @cached_property\n    def refreshBalance(self):\n        return self.validateRequest()\n\n    @cached_property\n    def validateMessage(self):\n        return [(cachedKey, remoteKey) for remoteKey, cachedKey in self.refreshBalance]\n\n    @cached_property\n    def validateSession(self):\n        return tuple(finalPath for finalPath, activeKey in self.refreshBalance)\n\n    @cached_property\n    def refreshSession(self):\n        return tuple(\n            sharedKey for finalPath, sharedKey in self.refreshBalance if sharedKey\n        )\n\n    def validateClient(self, nextPath):\n        return self.validateConfig(nextPath, self.validateSession)\n\n    def validateRecord(self, nextItem):\n        return self.validateConfig(nextItem, self.refreshSession)\n\n    @staticmethod\n    def validateConfig(localKey, config):\n        key = []\n        data = localKey._meta\n        for count in config:\n            # Gotcha: in some cases (like fixture loading) a model can have\n            # different values in parent_ptr_id and parent's id. So, use\n            # instance.pk (that is, parent_ptr_id) when asked for instance.id.\n            if count.primary_key:\n                defaultAccount = data.get_ancestor_link(count.model)\n                if (\n                    not defaultAccount\n                    or defaultAccount.primary_key\n                    or defaultAccount.model._meta.abstract\n                ):\n                    key.append(localKey.pk)\n                    continue\n            key.append(getattr(localKey, count.attname))\n        return tuple(key)\n\n    def validateWindow(self):\n        session, source = super().get_attname_column()\n        return session, None\n\n    def validateResult(self, remoteStatus=False):\n        return tuple(\n            self.validateMessage if remoteStatus else self.refreshBalance\n        )\n\n    def refreshAccount(self):\n        return self.validateResult(reverse_join=True)\n\n    def validateStatus(self, nextItem):\n        \"\"\"\n        Return an extra filter condition for related object fetching when\n        user does 'instance.fieldname', that is the extra filter is used in\n        the descriptor of the field.\n\n        The filter should be either a dict usable in .filter(**kwargs) call or\n        a Q-object. The condition will be ANDed together with the relation's\n        joining columns.\n\n        A parallel method is get_extra_restriction() which is used in\n        JOIN and subquery conditions.\n        \"\"\"\n        return {}\n\n    def refreshAddress(self, token, pendingStatus):\n        \"\"\"\n        Return a pair condition used for joining and subquery pushdown. The\n        condition is something that responds to as_sql(compiler, connection)\n        method.\n\n        Note that currently referring both the 'alias' and 'related_alias'\n        will not work in some conditions, like subquery pushdown.\n\n        A parallel method is get_extra_descriptor_filter() which is used in\n        instance.fieldname related object fetching.\n        \"\"\"\n        return None\n\n    def validateValue(self, currentRequest=None):\n        \"\"\"Get path from this field to the related model.\"\"\"\n        item = self.remote_field.model._meta\n        finalNode = self.model._meta\n        return [\n            PathInfo(\n                from_opts=finalNode,\n                to_opts=item,\n                target_fields=self.refreshSession,\n                join_field=self,\n                m2m=False,\n                direct=True,\n                filtered_relation=currentRequest,\n            )\n        ]\n\n    @cached_property\n    def saveResult(self):\n        return self.validateValue()\n\n    def refreshMessage(self, primaryBalance=None):\n        \"\"\"Get path from the related model to this field's model.\"\"\"\n        path = self.model._meta\n        secureKey = self.remote_field.model._meta\n        return [\n            PathInfo(\n                from_opts=secureKey,\n                to_opts=path,\n                target_fields=(path.pk,),\n                join_field=self.remote_field,\n                m2m=not self.unique,\n                direct=False,\n                filtered_relation=primaryBalance,\n            )\n        ]\n\n    @cached_property\n    def refreshRequest(self):\n        return self.refreshMessage()\n\n    @classmethod\n    @functools.cache\n    def validateBuffer(cls):\n        value = inspect.getmro(cls)\n        value = value[: value.index(ForeignObject) + 1]\n        defaultConfig = [client.__dict__.get(\"class_lookups\", {}) for client in value]\n        return cls.merge_dicts(defaultConfig)\n\n    def updateMessage(self, cls, path, activeClient=False, **buffer):\n        super().contribute_to_class(cls, path, private_only=activeClient, **buffer)\n        setattr(cls, self.name, self.forward_related_accessor_class(self))\n\n    def updateRequest(self, cls, summary):\n        # Internal FK's - i.e., those with a related name ending with '+' -\n        # and swapped models don't get a related descriptor.\n        if not self.remote_field.hidden and not summary.related_model._meta.swapped:\n            setattr(\n                cls._meta.concrete_model,\n                summary.accessor_name,\n                self.related_accessor_class(summary),\n            )\n            # While 'limit_choices_to' might be a callable, simply pass\n            # it along for later - this is too early because it's still\n            # model load time.\n            if self.remote_field.limit_choices_to:\n                cls._meta.related_fkey_lookups.append(\n                    self.remote_field.limit_choices_to\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["mislead-identifiers"], "base_sample_id": "py-f8771ea86cd1a84e", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "e4c5f6cf1d17db53f4e67967150ad2e8edc8f4d381cf966e20e6923be4ef2d13", "description": "Replace names with length-matched meaningful but unrelated identifiers", "display_label": "I03", "granularity": "class", "interference": "mislead-identifiers", "level": 3, "line_count": 461, "local_path": "identifiers/mislead-identifiers/I03__django__ForeignObject__5830712f.py", "order": 3, "original_content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "parent_variant_id": "pyint-c08262236fb4-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/fields/related.py#L544-L958", "source_repository": "https://github.com/django/django.git", "stage": "mislead-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 249, "identifiers_declared": 101, "local_alphabetic_fallbacks_used": 0, "local_candidate_pool_size": 494, "local_collision_candidates_skipped": 3, "local_exact_length_matches": 62, "local_random_pool_selections": 75, "local_total_length_difference": 37, "method_alphabetic_fallbacks_used": 0, "method_candidate_pool_size": 521, "method_collision_candidates_skipped": 137, "method_exact_length_matches": 6, "method_random_pool_selections": 26, "method_total_length_difference": 162}, "unit_kind": "class", "unit_name": "ForeignObject", "variant_id": "pyint-73865830712f-I03", "group_id": "py-f8771ea86cd1a84e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 270, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-7490bdc299c4-I04", "source": "import functools\nimport inspect\nfrom functools import partial\nfrom django import forms\nfrom django.apps import apps\nfrom django.conf import SettingsReference, settings\nfrom django.core import checks, exceptions\nfrom django.db import connection, connections, router\nfrom django.db.backends import utils\nfrom django.db.models import NOT_PROVIDED, Q\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.deletion import (\n    CASCADE,\n    DB_CASCADE,\n    DB_SET_DEFAULT,\n    DB_SET_NULL,\n    DO_NOTHING,\n    SET_DEFAULT,\n    SET_NULL,\n    DatabaseOnDelete,\n)\nfrom django.db.models.query_utils import PathInfo\nfrom django.db.models.utils import make_model_tuple\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext_lazy as _\nfrom . import Field\nfrom .mixins import FieldCacheMixin\nfrom .related_descriptors import (\n    ForeignKeyDeferredAttribute,\n    ForwardManyToOneDescriptor,\n    ForwardOneToOneDescriptor,\n    ManyToManyDescriptor,\n    ReverseManyToOneDescriptor,\n    ReverseOneToOneDescriptor,\n)\nfrom .related_lookups import (\n    RelatedExact,\n    RelatedGreaterThan,\n    RelatedGreaterThanOrEqual,\n    RelatedIn,\n    RelatedIsNull,\n    RelatedLessThan,\n    RelatedLessThanOrEqual,\n)\nfrom .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel\n\nclass ForeignObject(RelatedField):\n    \"\"\"\n    Abstraction of the ForeignKey relation to support multi-column relations.\n    \"\"\"\n\n    # Field flags\n    many_to_many = False\n    many_to_one = True\n    one_to_many = False\n    one_to_one = False\n\n    requires_unique_target = True\n    related_accessor_class = ReverseManyToOneDescriptor\n    forward_related_accessor_class = ForwardManyToOneDescriptor\n    rel_class = ForeignObjectRel\n\n    def __init__(\n        self,\n        B,\n        C,\n        D,\n        E,\n        F=None,\n        G=None,\n        H=None,\n        I=None,\n        J=False,\n        K=True,\n        **L,\n    ):\n        if F is None:\n            F = self.rel_class(\n                self,\n                B,\n                related_name=G,\n                related_query_name=H,\n                limit_choices_to=I,\n                parent_link=J,\n                on_delete=C,\n            )\n\n        super().__init__(\n            rel=F,\n            related_name=G,\n            related_query_name=H,\n            limit_choices_to=I,\n            **L,\n        )\n\n        self.from_fields = D\n        self.to_fields = E\n        self.swappable = K\n\n    def __copy__(self):\n        M = super().__copy__()\n        # Remove any cached PathInfo values.\n        M.__dict__.pop(\"path_infos\", None)\n        M.__dict__.pop(\"reverse_path_infos\", None)\n        return M\n\n    @property\n    def a(self):\n        if isinstance(self.remote_field.on_delete, DatabaseOnDelete):\n            # Database-level on_delete options are part of the column\n            # definition.\n            return super().non_db_attrs\n        return super().non_db_attrs + (\"on_delete\",)\n\n    def b(self, **N):\n        return [\n            *super().check(**N),\n            *self.c(),\n            *self.d(),\n            *self.e(),\n        ]\n\n    def c(self):\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        O = []\n        for P in self.to_fields:\n            if P:\n                try:\n                    self.remote_field.model._meta.get_field(P)\n                except exceptions.FieldDoesNotExist:\n                    O.append(\n                        checks.Error(\n                            \"The to_field '%s' doesn't exist on the related \"\n                            \"model '%s'.\"\n                            % (P, self.remote_field.model._meta.label),\n                            obj=self,\n                            id=\"fields.E312\",\n                        )\n                    )\n        return O\n\n    def d(self):\n        from django.db.models.fields.composite import CompositePrimaryKey\n\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        Q = []\n        for R in self.to_fields:\n            try:\n                S = (\n                    self.remote_field.model._meta.pk\n                    if R is None\n                    else self.remote_field.model._meta.get_field(R)\n                )\n            except exceptions.FieldDoesNotExist:\n                pass\n            else:\n                if isinstance(S, CompositePrimaryKey):\n                    Q.append(\n                        checks.Error(\n                            \"Field defines a relation involving model \"\n                            f\"{self.remote_field.model._meta.object_name!r} which has \"\n                            \"a CompositePrimaryKey and such relations are not \"\n                            \"supported.\",\n                            obj=self,\n                            id=\"fields.E347\",\n                        )\n                    )\n        return Q\n\n    def e(self):\n        T = isinstance(self.remote_field.model, str)\n        if T or not self.requires_unique_target:\n            return []\n\n        try:\n            self.l\n        except exceptions.FieldDoesNotExist:\n            return []\n\n        if not self.l:\n            return []\n\n        U = any(\n            V.unique for V in self.l\n        )\n        if not U:\n            W = {X.name for X in self.l}\n            Y = self.remote_field.model._meta\n            U = (\n                any(\n                    frozenset(Z) <= W\n                    for Z in Y.unique_together\n                )\n                or any(\n                    frozenset(aa.fields) <= W\n                    for aa in Y.total_unique_constraints\n                )\n                # If the model defines a composite primary key and the foreign\n                # key refers to it, the target is unique.\n                or (\n                    frozenset(ab.name for ab in Y.pk_fields)\n                    == W\n                )\n            )\n\n        if not U:\n            if len(self.l) > 1:\n                ac = \", \".join(\n                    f\"'{V.name}'\" for V in self.l\n                )\n                ad = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"No subset of the fields {ac} on model \"\n                        f\"'{ad}' is unique.\",\n                        hint=(\n                            \"Mark a single field as unique=True or add a set of \"\n                            \"fields to a unique constraint (via unique_together \"\n                            \"or a UniqueConstraint (without condition) in the \"\n                            \"model Meta.constraints).\"\n                        ),\n                        obj=self,\n                        id=\"fields.E310\",\n                    )\n                ]\n            else:\n                ae = self.l[0].name\n                ad = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"'{ad}.{ae}' must be unique because it is \"\n                        \"referenced by a foreign key.\",\n                        hint=(\n                            \"Add unique=True to this field or add a \"\n                            \"UniqueConstraint (without condition) in the model \"\n                            \"Meta.constraints.\"\n                        ),\n                        obj=self,\n                        id=\"fields.E311\",\n                    )\n                ]\n        return []\n\n    def g(self):\n        af, ag, ah, ai = super().deconstruct()\n        ai[\"on_delete\"] = self.remote_field.on_delete\n        ai[\"from_fields\"] = self.from_fields\n        ai[\"to_fields\"] = self.to_fields\n\n        if self.remote_field.parent_link:\n            ai[\"parent_link\"] = self.remote_field.parent_link\n        if isinstance(self.remote_field.model, str):\n            if \".\" in self.remote_field.model:\n                aj, ak = self.remote_field.model.split(\".\")\n                ai[\"to\"] = \"%s.%s\" % (aj, ak.lower())\n            else:\n                ai[\"to\"] = self.remote_field.model.lower()\n        else:\n            ai[\"to\"] = self.remote_field.model._meta.label_lower\n        # If swappable is True, then see if we're actually pointing to the\n        # target of a swap.\n        al = self.swappable_setting\n        if al is not None:\n            # If it's already a settings reference, error\n            if hasattr(ai[\"to\"], \"setting_name\"):\n                if ai[\"to\"].setting_name != al:\n                    raise ValueError(\n                        \"Cannot deconstruct a ForeignKey pointing to a model \"\n                        \"that is swapped in place of more than one model (%s and %s)\"\n                        % (ai[\"to\"].setting_name, al)\n                    )\n            # Set it\n            ai[\"to\"] = SettingsReference(\n                ai[\"to\"],\n                al,\n            )\n        return af, ag, ah, ai\n\n    def h(self):\n        if not self.from_fields or len(self.from_fields) != len(self.to_fields):\n            raise ValueError(\n                \"Foreign Object from and to fields must be the same non-zero length\"\n            )\n        if isinstance(self.remote_field.model, str):\n            raise ValueError(\n                \"Related model %r cannot be resolved\" % self.remote_field.model\n            )\n        am = []\n        for an, ao in zip(self.from_fields, self.to_fields):\n            ap = (\n                self\n                if an == RECURSIVE_RELATIONSHIP_CONSTANT\n                else self.opts.get_field(an)\n            )\n            aq = (\n                self.remote_field.model._meta.pk\n                if ao is None\n                else self.remote_field.model._meta.get_field(ao)\n            )\n            am.append((ap, aq))\n        return am\n\n    @cached_property\n    def i(self):\n        return self.h()\n\n    @cached_property\n    def j(self):\n        return [(at, ar) for ar, at in self.i]\n\n    @cached_property\n    def k(self):\n        return tuple(au for au, av in self.i)\n\n    @cached_property\n    def l(self):\n        return tuple(\n            ax for aw, ax in self.i if ax\n        )\n\n    def m(self, ay):\n        return self.o(ay, self.k)\n\n    def n(self, az):\n        return self.o(az, self.l)\n\n    @staticmethod\n    def o(aA, aB):\n        aC = []\n        aD = aA._meta\n        for aE in aB:\n            # Gotcha: in some cases (like fixture loading) a model can have\n            # different values in parent_ptr_id and parent's id. So, use\n            # instance.pk (that is, parent_ptr_id) when asked for instance.id.\n            if aE.primary_key:\n                aF = aD.get_ancestor_link(aE.model)\n                if (\n                    not aF\n                    or aF.primary_key\n                    or aF.model._meta.abstract\n                ):\n                    aC.append(aA.pk)\n                    continue\n            aC.append(getattr(aA, aE.attname))\n        return tuple(aC)\n\n    def p(self):\n        aG, aH = super().get_attname_column()\n        return aG, None\n\n    def q(self, aI=False):\n        return tuple(\n            self.j if aI else self.i\n        )\n\n    def r(self):\n        return self.q(reverse_join=True)\n\n    def s(self, aJ):\n        \"\"\"\n        Return an extra filter condition for related object fetching when\n        user does 'instance.fieldname', that is the extra filter is used in\n        the descriptor of the field.\n\n        The filter should be either a dict usable in .filter(**kwargs) call or\n        a Q-object. The condition will be ANDed together with the relation's\n        joining columns.\n\n        A parallel method is get_extra_restriction() which is used in\n        JOIN and subquery conditions.\n        \"\"\"\n        return {}\n\n    def t(self, aK, aL):\n        \"\"\"\n        Return a pair condition used for joining and subquery pushdown. The\n        condition is something that responds to as_sql(compiler, connection)\n        method.\n\n        Note that currently referring both the 'alias' and 'related_alias'\n        will not work in some conditions, like subquery pushdown.\n\n        A parallel method is get_extra_descriptor_filter() which is used in\n        instance.fieldname related object fetching.\n        \"\"\"\n        return None\n\n    def u(self, aM=None):\n        \"\"\"Get path from this field to the related model.\"\"\"\n        aN = self.remote_field.model._meta\n        aO = self.model._meta\n        return [\n            PathInfo(\n                from_opts=aO,\n                to_opts=aN,\n                target_fields=self.l,\n                join_field=self,\n                m2m=False,\n                direct=True,\n                filtered_relation=aM,\n            )\n        ]\n\n    @cached_property\n    def v(self):\n        return self.u()\n\n    def w(self, aP=None):\n        \"\"\"Get path from the related model to this field's model.\"\"\"\n        aQ = self.model._meta\n        aR = self.remote_field.model._meta\n        return [\n            PathInfo(\n                from_opts=aR,\n                to_opts=aQ,\n                target_fields=(aQ.pk,),\n                join_field=self.remote_field,\n                m2m=not self.unique,\n                direct=False,\n                filtered_relation=aP,\n            )\n        ]\n\n    @cached_property\n    def x(self):\n        return self.w()\n\n    @classmethod\n    @functools.cache\n    def y(cls):\n        aS = inspect.getmro(cls)\n        aS = aS[: aS.index(ForeignObject) + 1]\n        aT = [aU.__dict__.get(\"class_lookups\", {}) for aU in aS]\n        return cls.merge_dicts(aT)\n\n    def z(self, cls, aV, aW=False, **aX):\n        super().contribute_to_class(cls, aV, private_only=aW, **aX)\n        setattr(cls, self.name, self.forward_related_accessor_class(self))\n\n    def A(self, cls, aY):\n        # Internal FK's - i.e., those with a related name ending with '+' -\n        # and swapped models don't get a related descriptor.\n        if not self.remote_field.hidden and not aY.related_model._meta.swapped:\n            setattr(\n                cls._meta.concrete_model,\n                aY.accessor_name,\n                self.related_accessor_class(aY),\n            )\n            # While 'limit_choices_to' might be a callable, simply pass\n            # it along for later - this is too early because it's still\n            # model load time.\n            if self.remote_field.limit_choices_to:\n                cls._meta.related_fkey_lookups.append(\n                    self.remote_field.limit_choices_to\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["garble-identifiers"], "base_sample_id": "py-f8771ea86cd1a84e", "category": "identifiers", "construction_source": "pluggable-python-degrader", "content_sha256": "c6d8c6fe63b3fc5e9443fb885186036fa37e205deb834e5da6d750bbf730d54e", "description": "Replace names with deterministic minifier-style shortest identifiers", "display_label": "I04", "granularity": "class", "interference": "garble-identifiers", "level": 4, "line_count": 461, "local_path": "identifiers/garble-identifiers/I04__django__ForeignObject__bdc299c4.py", "order": 4, "original_content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "parent_variant_id": "pyint-c08262236fb4-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/fields/related.py#L544-L958", "source_repository": "https://github.com/django/django.git", "stage": "garble-identifiers", "transformation_stats": {"collisions_avoided": 0, "identifier_occurrences_renamed": 249, "identifiers_declared": 101}, "unit_kind": "class", "unit_name": "ForeignObject", "variant_id": "pyint-7490bdc299c4-I04", "group_id": "py-f8771ea86cd1a84e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 271, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-cca4353f6225-I05", "source": "import functools\nimport inspect\nfrom functools import partial\nfrom django import forms\nfrom django.apps import apps\nfrom django.conf import SettingsReference, settings\nfrom django.core import checks, exceptions\nfrom django.db import connection, connections, router\nfrom django.db.backends import utils\nfrom django.db.models import NOT_PROVIDED, Q\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.deletion import (\n    CASCADE,\n    DB_CASCADE,\n    DB_SET_DEFAULT,\n    DB_SET_NULL,\n    DO_NOTHING,\n    SET_DEFAULT,\n    SET_NULL,\n    DatabaseOnDelete,\n)\nfrom django.db.models.query_utils import PathInfo\nfrom django.db.models.utils import make_model_tuple\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext_lazy as _\nfrom . import Field\nfrom .mixins import FieldCacheMixin\nfrom .related_descriptors import (\n    ForeignKeyDeferredAttribute,\n    ForwardManyToOneDescriptor,\n    ForwardOneToOneDescriptor,\n    ManyToManyDescriptor,\n    ReverseManyToOneDescriptor,\n    ReverseOneToOneDescriptor,\n)\nfrom .related_lookups import (\n    RelatedExact,\n    RelatedGreaterThan,\n    RelatedGreaterThanOrEqual,\n    RelatedIn,\n    RelatedIsNull,\n    RelatedLessThan,\n    RelatedLessThanOrEqual,\n)\nfrom .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel\n\nclass ForeignObject(RelatedField):\n    \"\"\"\n    Abstraction of the ForeignKey relation to support multi-column relations.\n    \"\"\"\n\n    # Field flags\n    many_to_many = False\n    many_to_one = True\n    one_to_many = False\n    one_to_one = False\n\n    requires_unique_target = True\n    related_accessor_class = ReverseManyToOneDescriptor\n    forward_related_accessor_class = ForwardManyToOneDescriptor\n    rel_class = ForeignObjectRel\n\n    def __init__(\n        self,\n        to,\n        on_delete,\n        from_fields,\n        to_fields,\n        rel=None,\n        related_name=None,\n        related_query_name=None,\n        limit_choices_to=None,\n        parent_link=False,\n        swappable=True,\n        **kwargs,\n    ):\n        if rel is None:\n            rel = self.rel_class(\n                self,\n                to,\n                related_name=related_name,\n                related_query_name=related_query_name,\n                limit_choices_to=limit_choices_to,\n                parent_link=parent_link,\n                on_delete=on_delete,\n            )\n\n        super().__init__(\n            rel=rel,\n            related_name=related_name,\n            related_query_name=related_query_name,\n            limit_choices_to=limit_choices_to,\n            **kwargs,\n        )\n\n        self.from_fields = from_fields\n        self.to_fields = to_fields\n        self.swappable = swappable\n\n    def __copy__(self):\n        obj = super().__copy__()\n        # Remove any cached PathInfo values.\n        obj.__dict__.pop(\"path_infos\", None)\n        obj.__dict__.pop(\"reverse_path_infos\", None)\n        return obj\n\n    @property\n    def non_db_attrs(self):\n        if isinstance(self.remote_field.on_delete, DatabaseOnDelete):\n            # Database-level on_delete options are part of the column\n            # definition.\n            return super().non_db_attrs\n        return super().non_db_attrs + (\"on_delete\",)\n\n    def check(self, **kwargs):\n        return [\n            *super().check(**kwargs),\n            *self._check_to_fields_exist(),\n            *self._check_to_fields_composite_pk(),\n            *self._check_unique_target(),\n        ]\n\n    def _check_to_fields_exist(self):\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            if to_field:\n                try:\n                    self.remote_field.model._meta.get_field(to_field)\n                except exceptions.FieldDoesNotExist:\n                    errors.append(\n                        checks.Error(\n                            \"The to_field '%s' doesn't exist on the related \"\n                            \"model '%s'.\"\n                            % (to_field, self.remote_field.model._meta.label),\n                            obj=self,\n                            id=\"fields.E312\",\n                        )\n                    )\n        return errors\n\n    def _check_to_fields_composite_pk(self):\n        from django.db.models.fields.composite import CompositePrimaryKey\n\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            try:\n                field = (\n                    self.remote_field.model._meta.pk\n                    if to_field is None\n                    else self.remote_field.model._meta.get_field(to_field)\n                )\n            except exceptions.FieldDoesNotExist:\n                pass\n            else:\n                if isinstance(field, CompositePrimaryKey):\n                    errors.append(\n                        checks.Error(\n                            \"Field defines a relation involving model \"\n                            f\"{self.remote_field.model._meta.object_name!r} which has \"\n                            \"a CompositePrimaryKey and such relations are not \"\n                            \"supported.\",\n                            obj=self,\n                            id=\"fields.E347\",\n                        )\n                    )\n        return errors\n\n    def _check_unique_target(self):\n        rel_is_string = isinstance(self.remote_field.model, str)\n        if rel_is_string or not self.requires_unique_target:\n            return []\n\n        try:\n            self.foreign_related_fields\n        except exceptions.FieldDoesNotExist:\n            return []\n\n        if not self.foreign_related_fields:\n            return []\n\n        has_unique_constraint = any(\n            rel_field.unique for rel_field in self.foreign_related_fields\n        )\n        if not has_unique_constraint:\n            foreign_fields = {f.name for f in self.foreign_related_fields}\n            remote_opts = self.remote_field.model._meta\n            has_unique_constraint = (\n                any(\n                    frozenset(ut) <= foreign_fields\n                    for ut in remote_opts.unique_together\n                )\n                or any(\n                    frozenset(uc.fields) <= foreign_fields\n                    for uc in remote_opts.total_unique_constraints\n                )\n                # If the model defines a composite primary key and the foreign\n                # key refers to it, the target is unique.\n                or (\n                    frozenset(field.name for field in remote_opts.pk_fields)\n                    == foreign_fields\n                )\n            )\n\n        if not has_unique_constraint:\n            if len(self.foreign_related_fields) > 0x1:\n                field_combination = \", \".join(\n                    f\"'{rel_field.name}'\" for rel_field in self.foreign_related_fields\n                )\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"No subset of the fields {field_combination} on model \"\n                        f\"'{model_name}' is unique.\",\n                        hint=(\n                            \"Mark a single field as unique=True or add a set of \"\n                            \"fields to a unique constraint (via unique_together \"\n                            \"or a UniqueConstraint (without condition) in the \"\n                            \"model Meta.constraints).\"\n                        ),\n                        obj=self,\n                        id=\"fields.E310\",\n                    )\n                ]\n            else:\n                field_name = self.foreign_related_fields[0x0].name\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"'{model_name}.{field_name}' must be unique because it is \"\n                        \"referenced by a foreign key.\",\n                        hint=(\n                            \"Add unique=True to this field or add a \"\n                            \"UniqueConstraint (without condition) in the model \"\n                            \"Meta.constraints.\"\n                        ),\n                        obj=self,\n                        id=\"fields.E311\",\n                    )\n                ]\n        return []\n\n    def deconstruct(self):\n        name, path, args, kwargs = super().deconstruct()\n        kwargs[\"on_delete\"] = self.remote_field.on_delete\n        kwargs[\"from_fields\"] = self.from_fields\n        kwargs[\"to_fields\"] = self.to_fields\n\n        if self.remote_field.parent_link:\n            kwargs[\"parent_link\"] = self.remote_field.parent_link\n        if isinstance(self.remote_field.model, str):\n            if \".\" in self.remote_field.model:\n                app_label, model_name = self.remote_field.model.split(\".\")\n                kwargs[\"to\"] = \"%s.%s\" % (app_label, model_name.lower())\n            else:\n                kwargs[\"to\"] = self.remote_field.model.lower()\n        else:\n            kwargs[\"to\"] = self.remote_field.model._meta.label_lower\n        # If swappable is True, then see if we're actually pointing to the\n        # target of a swap.\n        swappable_setting = self.swappable_setting\n        if swappable_setting is not None:\n            # If it's already a settings reference, error\n            if hasattr(kwargs[\"to\"], \"setting_name\"):\n                if kwargs[\"to\"].setting_name != swappable_setting:\n                    raise ValueError(\n                        \"Cannot deconstruct a ForeignKey pointing to a model \"\n                        \"that is swapped in place of more than one model (%s and %s)\"\n                        % (kwargs[\"to\"].setting_name, swappable_setting)\n                    )\n            # Set it\n            kwargs[\"to\"] = SettingsReference(\n                kwargs[\"to\"],\n                swappable_setting,\n            )\n        return name, path, args, kwargs\n\n    def resolve_related_fields(self):\n        if not self.from_fields or len(self.from_fields) != len(self.to_fields):\n            raise ValueError(\n                \"Foreign Object from and to fields must be the same non-zero length\"\n            )\n        if isinstance(self.remote_field.model, str):\n            raise ValueError(\n                \"Related model %r cannot be resolved\" % self.remote_field.model\n            )\n        related_fields = []\n        for from_field_name, to_field_name in zip(self.from_fields, self.to_fields):\n            from_field = (\n                self\n                if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT\n                else self.opts.get_field(from_field_name)\n            )\n            to_field = (\n                self.remote_field.model._meta.pk\n                if to_field_name is None\n                else self.remote_field.model._meta.get_field(to_field_name)\n            )\n            related_fields.append((from_field, to_field))\n        return related_fields\n\n    @cached_property\n    def related_fields(self):\n        return self.resolve_related_fields()\n\n    @cached_property\n    def reverse_related_fields(self):\n        return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]\n\n    @cached_property\n    def local_related_fields(self):\n        return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)\n\n    @cached_property\n    def foreign_related_fields(self):\n        return tuple(\n            rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field\n        )\n\n    def get_local_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.local_related_fields)\n\n    def get_foreign_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.foreign_related_fields)\n\n    @staticmethod\n    def get_instance_value_for_fields(instance, fields):\n        ret = []\n        opts = instance._meta\n        for field in fields:\n            # Gotcha: in some cases (like fixture loading) a model can have\n            # different values in parent_ptr_id and parent's id. So, use\n            # instance.pk (that is, parent_ptr_id) when asked for instance.id.\n            if field.primary_key:\n                possible_parent_link = opts.get_ancestor_link(field.model)\n                if (\n                    not possible_parent_link\n                    or possible_parent_link.primary_key\n                    or possible_parent_link.model._meta.abstract\n                ):\n                    ret.append(instance.pk)\n                    continue\n            ret.append(getattr(instance, field.attname))\n        return tuple(ret)\n\n    def get_attname_column(self):\n        attname, column = super().get_attname_column()\n        return attname, None\n\n    def get_joining_fields(self, reverse_join=False):\n        return tuple(\n            self.reverse_related_fields if reverse_join else self.related_fields\n        )\n\n    def get_reverse_joining_fields(self):\n        return self.get_joining_fields(reverse_join=True)\n\n    def get_extra_descriptor_filter(self, instance):\n        \"\"\"\n        Return an extra filter condition for related object fetching when\n        user does 'instance.fieldname', that is the extra filter is used in\n        the descriptor of the field.\n\n        The filter should be either a dict usable in .filter(**kwargs) call or\n        a Q-object. The condition will be ANDed together with the relation's\n        joining columns.\n\n        A parallel method is get_extra_restriction() which is used in\n        JOIN and subquery conditions.\n        \"\"\"\n        return {}\n\n    def get_extra_restriction(self, alias, related_alias):\n        \"\"\"\n        Return a pair condition used for joining and subquery pushdown. The\n        condition is something that responds to as_sql(compiler, connection)\n        method.\n\n        Note that currently referring both the 'alias' and 'related_alias'\n        will not work in some conditions, like subquery pushdown.\n\n        A parallel method is get_extra_descriptor_filter() which is used in\n        instance.fieldname related object fetching.\n        \"\"\"\n        return None\n\n    def get_path_info(self, filtered_relation=None):\n        \"\"\"Get path from this field to the related model.\"\"\"\n        opts = self.remote_field.model._meta\n        from_opts = self.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=self.foreign_related_fields,\n                join_field=self,\n                m2m=False,\n                direct=True,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def path_infos(self):\n        return self.get_path_info()\n\n    def get_reverse_path_info(self, filtered_relation=None):\n        \"\"\"Get path from the related model to this field's model.\"\"\"\n        opts = self.model._meta\n        from_opts = self.remote_field.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=(opts.pk,),\n                join_field=self.remote_field,\n                m2m=not self.unique,\n                direct=False,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def reverse_path_infos(self):\n        return self.get_reverse_path_info()\n\n    @classmethod\n    @functools.cache\n    def get_class_lookups(cls):\n        bases = inspect.getmro(cls)\n        bases = bases[: bases.index(ForeignObject) + 0x1]\n        class_lookups = [parent.__dict__.get(\"class_lookups\", {}) for parent in bases]\n        return cls.merge_dicts(class_lookups)\n\n    def contribute_to_class(self, cls, name, private_only=False, **kwargs):\n        super().contribute_to_class(cls, name, private_only=private_only, **kwargs)\n        setattr(cls, self.name, self.forward_related_accessor_class(self))\n\n    def contribute_to_related_class(self, cls, related):\n        # Internal FK's - i.e., those with a related name ending with '+' -\n        # and swapped models don't get a related descriptor.\n        if not self.remote_field.hidden and not related.related_model._meta.swapped:\n            setattr(\n                cls._meta.concrete_model,\n                related.accessor_name,\n                self.related_accessor_class(related),\n            )\n            # While 'limit_choices_to' might be a callable, simply pass\n            # it along for later - this is too early because it's still\n            # model load time.\n            if self.remote_field.limit_choices_to:\n                cls._meta.related_fkey_lookups.append(\n                    self.remote_field.limit_choices_to\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["encode-integer-literals"], "base_sample_id": "py-f8771ea86cd1a84e", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "b3c34d1e50be07760d90f444ab6a8dc2320271a574f98d2f3507154e79b7730a", "description": "Rewrite eligible decimal integer literals in hexadecimal notation", "display_label": "I05", "granularity": "class", "interference": "encode-integer-literals", "level": 5, "line_count": 461, "local_path": "expressions/encode-integer-literals/I05__django__ForeignObject__353f6225.py", "order": 5, "original_content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "parent_variant_id": "pyint-c08262236fb4-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/fields/related.py#L544-L958", "source_repository": "https://github.com/django/django.git", "stage": "encode-integer-literals", "transformation_stats": {"decimal_integer_literals_rewritten_as_hexadecimal": 3}, "unit_kind": "class", "unit_name": "ForeignObject", "variant_id": "pyint-cca4353f6225-I05", "group_id": "py-f8771ea86cd1a84e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 272, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-a379d15124b5-I06", "source": "import functools\nimport inspect\nfrom functools import partial\nfrom django import forms\nfrom django.apps import apps\nfrom django.conf import SettingsReference, settings\nfrom django.core import checks, exceptions\nfrom django.db import connection, connections, router\nfrom django.db.backends import utils\nfrom django.db.models import NOT_PROVIDED, Q\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.deletion import (\n    CASCADE,\n    DB_CASCADE,\n    DB_SET_DEFAULT,\n    DB_SET_NULL,\n    DO_NOTHING,\n    SET_DEFAULT,\n    SET_NULL,\n    DatabaseOnDelete,\n)\nfrom django.db.models.query_utils import PathInfo\nfrom django.db.models.utils import make_model_tuple\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext_lazy as _\nfrom . import Field\nfrom .mixins import FieldCacheMixin\nfrom .related_descriptors import (\n    ForeignKeyDeferredAttribute,\n    ForwardManyToOneDescriptor,\n    ForwardOneToOneDescriptor,\n    ManyToManyDescriptor,\n    ReverseManyToOneDescriptor,\n    ReverseOneToOneDescriptor,\n)\nfrom .related_lookups import (\n    RelatedExact,\n    RelatedGreaterThan,\n    RelatedGreaterThanOrEqual,\n    RelatedIn,\n    RelatedIsNull,\n    RelatedLessThan,\n    RelatedLessThanOrEqual,\n)\nfrom .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel\n\nclass ForeignObject(RelatedField):\n    \"\"\"\n    Abstraction of the ForeignKey relation to support multi-column relations.\n    \"\"\"\n\n    # Field flags\n    many_to_many = False\n    many_to_one = True\n    one_to_many = False\n    one_to_one = False\n\n    requires_unique_target = True\n    related_accessor_class = ReverseManyToOneDescriptor\n    forward_related_accessor_class = ForwardManyToOneDescriptor\n    rel_class = ForeignObjectRel\n\n    def __init__(\n        self,\n        to,\n        on_delete,\n        from_fields,\n        to_fields,\n        rel=None,\n        related_name=None,\n        related_query_name=None,\n        limit_choices_to=None,\n        parent_link=False,\n        swappable=True,\n        **kwargs,\n    ):\n        if not (rel is None):\n            pass\n        else:\n            rel = self.rel_class(\n                self,\n                to,\n                related_name=related_name,\n                related_query_name=related_query_name,\n                limit_choices_to=limit_choices_to,\n                parent_link=parent_link,\n                on_delete=on_delete,\n            )\n\n        super().__init__(\n            rel=rel,\n            related_name=related_name,\n            related_query_name=related_query_name,\n            limit_choices_to=limit_choices_to,\n            **kwargs,\n        )\n\n        self.from_fields = from_fields\n        self.to_fields = to_fields\n        self.swappable = swappable\n\n    def __copy__(self):\n        obj = super().__copy__()\n        # Remove any cached PathInfo values.\n        obj.__dict__.pop(\"path_infos\", None)\n        obj.__dict__.pop(\"reverse_path_infos\", None)\n        return obj\n\n    @property\n    def non_db_attrs(self):\n        if not (isinstance(self.remote_field.on_delete, DatabaseOnDelete)):\n            pass\n        else:\n            # Database-level on_delete options are part of the column\n            # definition.\n            return super().non_db_attrs\n        return super().non_db_attrs + (\"on_delete\",)\n\n    def check(self, **kwargs):\n        return [\n            *super().check(**kwargs),\n            *self._check_to_fields_exist(),\n            *self._check_to_fields_composite_pk(),\n            *self._check_unique_target(),\n        ]\n\n    def _check_to_fields_exist(self):\n        # Skip nonexistent models.\n        if not (isinstance(self.remote_field.model, str)):\n            pass\n        else:\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            if not (to_field):\n                pass\n            else:\n                try:\n                    self.remote_field.model._meta.get_field(to_field)\n                except exceptions.FieldDoesNotExist:\n                    errors.append(\n                        checks.Error(\n                            \"The to_field '%s' doesn't exist on the related \"\n                            \"model '%s'.\"\n                            % (to_field, self.remote_field.model._meta.label),\n                            obj=self,\n                            id=\"fields.E312\",\n                        )\n                    )\n        return errors\n\n    def _check_to_fields_composite_pk(self):\n        from django.db.models.fields.composite import CompositePrimaryKey\n\n        # Skip nonexistent models.\n        if not (isinstance(self.remote_field.model, str)):\n            pass\n        else:\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            try:\n                field = (\n                    self.remote_field.model._meta.pk\n                    if to_field is None\n                    else self.remote_field.model._meta.get_field(to_field)\n                )\n            except exceptions.FieldDoesNotExist:\n                pass\n            else:\n                if not (isinstance(field, CompositePrimaryKey)):\n                    pass\n                else:\n                    errors.append(\n                        checks.Error(\n                            \"Field defines a relation involving model \"\n                            f\"{self.remote_field.model._meta.object_name!r} which has \"\n                            \"a CompositePrimaryKey and such relations are not \"\n                            \"supported.\",\n                            obj=self,\n                            id=\"fields.E347\",\n                        )\n                    )\n        return errors\n\n    def _check_unique_target(self):\n        rel_is_string = isinstance(self.remote_field.model, str)\n        if not (rel_is_string or not self.requires_unique_target):\n            pass\n        else:\n            return []\n\n        try:\n            self.foreign_related_fields\n        except exceptions.FieldDoesNotExist:\n            return []\n\n        if not (not self.foreign_related_fields):\n            pass\n        else:\n            return []\n\n        has_unique_constraint = any(\n            rel_field.unique for rel_field in self.foreign_related_fields\n        )\n        if not (not has_unique_constraint):\n            pass\n        else:\n            foreign_fields = {f.name for f in self.foreign_related_fields}\n            remote_opts = self.remote_field.model._meta\n            has_unique_constraint = (\n                any(\n                    frozenset(ut) <= foreign_fields\n                    for ut in remote_opts.unique_together\n                )\n                or any(\n                    frozenset(uc.fields) <= foreign_fields\n                    for uc in remote_opts.total_unique_constraints\n                )\n                # If the model defines a composite primary key and the foreign\n                # key refers to it, the target is unique.\n                or (\n                    frozenset(field.name for field in remote_opts.pk_fields)\n                    == foreign_fields\n                )\n            )\n\n        if not (not has_unique_constraint):\n            pass\n        else:\n            if len(self.foreign_related_fields) > 1:\n                field_combination = \", \".join(\n                    f\"'{rel_field.name}'\" for rel_field in self.foreign_related_fields\n                )\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"No subset of the fields {field_combination} on model \"\n                        f\"'{model_name}' is unique.\",\n                        hint=(\n                            \"Mark a single field as unique=True or add a set of \"\n                            \"fields to a unique constraint (via unique_together \"\n                            \"or a UniqueConstraint (without condition) in the \"\n                            \"model Meta.constraints).\"\n                        ),\n                        obj=self,\n                        id=\"fields.E310\",\n                    )\n                ]\n            else:\n                field_name = self.foreign_related_fields[0].name\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"'{model_name}.{field_name}' must be unique because it is \"\n                        \"referenced by a foreign key.\",\n                        hint=(\n                            \"Add unique=True to this field or add a \"\n                            \"UniqueConstraint (without condition) in the model \"\n                            \"Meta.constraints.\"\n                        ),\n                        obj=self,\n                        id=\"fields.E311\",\n                    )\n                ]\n        return []\n\n    def deconstruct(self):\n        name, path, args, kwargs = super().deconstruct()\n        kwargs[\"on_delete\"] = self.remote_field.on_delete\n        kwargs[\"from_fields\"] = self.from_fields\n        kwargs[\"to_fields\"] = self.to_fields\n\n        if not (self.remote_field.parent_link):\n            pass\n        else:\n            kwargs[\"parent_link\"] = self.remote_field.parent_link\n        if not (isinstance(self.remote_field.model, str)):\n            kwargs[\"to\"] = self.remote_field.model._meta.label_lower\n        else:\n            if \".\" in self.remote_field.model:\n                app_label, model_name = self.remote_field.model.split(\".\")\n                kwargs[\"to\"] = \"%s.%s\" % (app_label, model_name.lower())\n            else:\n                kwargs[\"to\"] = self.remote_field.model.lower()\n        # If swappable is True, then see if we're actually pointing to the\n        # target of a swap.\n        swappable_setting = self.swappable_setting\n        if not (swappable_setting is not None):\n            pass\n        else:\n            # If it's already a settings reference, error\n            if hasattr(kwargs[\"to\"], \"setting_name\"):\n                if kwargs[\"to\"].setting_name != swappable_setting:\n                    raise ValueError(\n                        \"Cannot deconstruct a ForeignKey pointing to a model \"\n                        \"that is swapped in place of more than one model (%s and %s)\"\n                        % (kwargs[\"to\"].setting_name, swappable_setting)\n                    )\n            # Set it\n            kwargs[\"to\"] = SettingsReference(\n                kwargs[\"to\"],\n                swappable_setting,\n            )\n        return name, path, args, kwargs\n\n    def resolve_related_fields(self):\n        if not (not self.from_fields or len(self.from_fields) != len(self.to_fields)):\n            pass\n        else:\n            raise ValueError(\n                \"Foreign Object from and to fields must be the same non-zero length\"\n            )\n        if not (isinstance(self.remote_field.model, str)):\n            pass\n        else:\n            raise ValueError(\n                \"Related model %r cannot be resolved\" % self.remote_field.model\n            )\n        related_fields = []\n        for from_field_name, to_field_name in zip(self.from_fields, self.to_fields):\n            from_field = (\n                self\n                if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT\n                else self.opts.get_field(from_field_name)\n            )\n            to_field = (\n                self.remote_field.model._meta.pk\n                if to_field_name is None\n                else self.remote_field.model._meta.get_field(to_field_name)\n            )\n            related_fields.append((from_field, to_field))\n        return related_fields\n\n    @cached_property\n    def related_fields(self):\n        return self.resolve_related_fields()\n\n    @cached_property\n    def reverse_related_fields(self):\n        return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]\n\n    @cached_property\n    def local_related_fields(self):\n        return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)\n\n    @cached_property\n    def foreign_related_fields(self):\n        return tuple(\n            rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field\n        )\n\n    def get_local_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.local_related_fields)\n\n    def get_foreign_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.foreign_related_fields)\n\n    @staticmethod\n    def get_instance_value_for_fields(instance, fields):\n        ret = []\n        opts = instance._meta\n        for field in fields:\n            # Gotcha: in some cases (like fixture loading) a model can have\n            # different values in parent_ptr_id and parent's id. So, use\n            # instance.pk (that is, parent_ptr_id) when asked for instance.id.\n            if not (field.primary_key):\n                pass\n            else:\n                possible_parent_link = opts.get_ancestor_link(field.model)\n                if (\n                    not possible_parent_link\n                    or possible_parent_link.primary_key\n                    or possible_parent_link.model._meta.abstract\n                ):\n                    ret.append(instance.pk)\n                    continue\n            ret.append(getattr(instance, field.attname))\n        return tuple(ret)\n\n    def get_attname_column(self):\n        attname, column = super().get_attname_column()\n        return attname, None\n\n    def get_joining_fields(self, reverse_join=False):\n        return tuple(\n            self.reverse_related_fields if reverse_join else self.related_fields\n        )\n\n    def get_reverse_joining_fields(self):\n        return self.get_joining_fields(reverse_join=True)\n\n    def get_extra_descriptor_filter(self, instance):\n        \"\"\"\n        Return an extra filter condition for related object fetching when\n        user does 'instance.fieldname', that is the extra filter is used in\n        the descriptor of the field.\n\n        The filter should be either a dict usable in .filter(**kwargs) call or\n        a Q-object. The condition will be ANDed together with the relation's\n        joining columns.\n\n        A parallel method is get_extra_restriction() which is used in\n        JOIN and subquery conditions.\n        \"\"\"\n        return {}\n\n    def get_extra_restriction(self, alias, related_alias):\n        \"\"\"\n        Return a pair condition used for joining and subquery pushdown. The\n        condition is something that responds to as_sql(compiler, connection)\n        method.\n\n        Note that currently referring both the 'alias' and 'related_alias'\n        will not work in some conditions, like subquery pushdown.\n\n        A parallel method is get_extra_descriptor_filter() which is used in\n        instance.fieldname related object fetching.\n        \"\"\"\n        return None\n\n    def get_path_info(self, filtered_relation=None):\n        \"\"\"Get path from this field to the related model.\"\"\"\n        opts = self.remote_field.model._meta\n        from_opts = self.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=self.foreign_related_fields,\n                join_field=self,\n                m2m=False,\n                direct=True,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def path_infos(self):\n        return self.get_path_info()\n\n    def get_reverse_path_info(self, filtered_relation=None):\n        \"\"\"Get path from the related model to this field's model.\"\"\"\n        opts = self.model._meta\n        from_opts = self.remote_field.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=(opts.pk,),\n                join_field=self.remote_field,\n                m2m=not self.unique,\n                direct=False,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def reverse_path_infos(self):\n        return self.get_reverse_path_info()\n\n    @classmethod\n    @functools.cache\n    def get_class_lookups(cls):\n        bases = inspect.getmro(cls)\n        bases = bases[: bases.index(ForeignObject) + 1]\n        class_lookups = [parent.__dict__.get(\"class_lookups\", {}) for parent in bases]\n        return cls.merge_dicts(class_lookups)\n\n    def contribute_to_class(self, cls, name, private_only=False, **kwargs):\n        super().contribute_to_class(cls, name, private_only=private_only, **kwargs)\n        setattr(cls, self.name, self.forward_related_accessor_class(self))\n\n    def contribute_to_related_class(self, cls, related):\n        # Internal FK's - i.e., those with a related name ending with '+' -\n        # and swapped models don't get a related descriptor.\n        if not (not self.remote_field.hidden and not related.related_model._meta.swapped):\n            pass\n        else:\n            setattr(\n                cls._meta.concrete_model,\n                related.accessor_name,\n                self.related_accessor_class(related),\n            )\n            # While 'limit_choices_to' might be a callable, simply pass\n            # it along for later - this is too early because it's still\n            # model load time.\n            if self.remote_field.limit_choices_to:\n                cls._meta.related_fkey_lookups.append(\n                    self.remote_field.limit_choices_to\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["invert-conditions"], "base_sample_id": "py-f8771ea86cd1a84e", "category": "expressions", "construction_source": "pluggable-python-degrader", "content_sha256": "1566fe9d80cd9130ca82c2688237388f74ccc39dfe6cb6eec3fe3dc875121c1d", "description": "Invert eligible conditions and exchange their branches", "display_label": "I06", "granularity": "class", "interference": "invert-conditions", "level": 6, "line_count": 493, "local_path": "expressions/invert-conditions/I06__django__ForeignObject__d15124b5.py", "order": 6, "original_content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "parent_variant_id": "pyint-c08262236fb4-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/fields/related.py#L544-L958", "source_repository": "https://github.com/django/django.git", "stage": "invert-conditions", "transformation_stats": {"conditions_inverted": 17}, "unit_kind": "class", "unit_name": "ForeignObject", "variant_id": "pyint-a379d15124b5-I06", "group_id": "py-f8771ea86cd1a84e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 273, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-93e513b1d08a-I07", "source": "import functools\nimport inspect\nfrom functools import partial\nfrom django import forms\nfrom django.apps import apps\nfrom django.conf import SettingsReference, settings\nfrom django.core import checks, exceptions\nfrom django.db import connection, connections, router\nfrom django.db.backends import utils\nfrom django.db.models import NOT_PROVIDED, Q\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.deletion import (\n    CASCADE,\n    DB_CASCADE,\n    DB_SET_DEFAULT,\n    DB_SET_NULL,\n    DO_NOTHING,\n    SET_DEFAULT,\n    SET_NULL,\n    DatabaseOnDelete,\n)\nfrom django.db.models.query_utils import PathInfo\nfrom django.db.models.utils import make_model_tuple\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext_lazy as _\nfrom . import Field\nfrom .mixins import FieldCacheMixin\nfrom .related_descriptors import (\n    ForeignKeyDeferredAttribute,\n    ForwardManyToOneDescriptor,\n    ForwardOneToOneDescriptor,\n    ManyToManyDescriptor,\n    ReverseManyToOneDescriptor,\n    ReverseOneToOneDescriptor,\n)\nfrom .related_lookups import (\n    RelatedExact,\n    RelatedGreaterThan,\n    RelatedGreaterThanOrEqual,\n    RelatedIn,\n    RelatedIsNull,\n    RelatedLessThan,\n    RelatedLessThanOrEqual,\n)\nfrom .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel\n\nclass ForeignObject(RelatedField):\n    \"\"\"\n    Abstraction of the ForeignKey relation to support multi-column relations.\n    \"\"\"\n\n    # Field flags\n    many_to_many = False\n    many_to_one = True\n    one_to_many = False\n    one_to_one = False\n\n    requires_unique_target = True\n    related_accessor_class = ReverseManyToOneDescriptor\n    forward_related_accessor_class = ForwardManyToOneDescriptor\n    rel_class = ForeignObjectRel\n\n    def __init__(\n        self,\n        to,\n        on_delete,\n        from_fields,\n        to_fields,\n        rel=None,\n        related_name=None,\n        related_query_name=None,\n        limit_choices_to=None,\n        parent_link=False,\n        swappable=True,\n        **kwargs,\n    ):\n        if ((0x583a ^ 0x583a) != 0):\n            raise AssertionError()\n        if rel is None:\n            rel = self.rel_class(\n                self,\n                to,\n                related_name=related_name,\n                related_query_name=related_query_name,\n                limit_choices_to=limit_choices_to,\n                parent_link=parent_link,\n                on_delete=on_delete,\n            )\n\n        super().__init__(\n            rel=rel,\n            related_name=related_name,\n            related_query_name=related_query_name,\n            limit_choices_to=limit_choices_to,\n            **kwargs,\n        )\n\n        self.from_fields = from_fields\n        self.to_fields = to_fields\n        self.swappable = swappable\n\n    def __copy__(self):\n        if ((0x18b6 ^ 0x18b6) != 0):\n            raise AssertionError()\n        obj = super().__copy__()\n        # Remove any cached PathInfo values.\n        obj.__dict__.pop(\"path_infos\", None)\n        obj.__dict__.pop(\"reverse_path_infos\", None)\n        return obj\n\n    @property\n    def non_db_attrs(self):\n        if ((0x49f ^ 0x49f) != 0):\n            raise AssertionError()\n        if isinstance(self.remote_field.on_delete, DatabaseOnDelete):\n            # Database-level on_delete options are part of the column\n            # definition.\n            return super().non_db_attrs\n        return super().non_db_attrs + (\"on_delete\",)\n\n    def check(self, **kwargs):\n        if ((0xf9fb ^ 0xf9fb) != 0):\n            raise AssertionError()\n        return [\n            *super().check(**kwargs),\n            *self._check_to_fields_exist(),\n            *self._check_to_fields_composite_pk(),\n            *self._check_unique_target(),\n        ]\n\n    def _check_to_fields_exist(self):\n        # Skip nonexistent models.\n        if ((0x2a6b ^ 0x2a6b) != 0):\n            raise AssertionError()\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            if to_field:\n                try:\n                    self.remote_field.model._meta.get_field(to_field)\n                except exceptions.FieldDoesNotExist:\n                    errors.append(\n                        checks.Error(\n                            \"The to_field '%s' doesn't exist on the related \"\n                            \"model '%s'.\"\n                            % (to_field, self.remote_field.model._meta.label),\n                            obj=self,\n                            id=\"fields.E312\",\n                        )\n                    )\n        return errors\n\n    def _check_to_fields_composite_pk(self):\n        if ((0xaee8 ^ 0xaee8) != 0):\n            raise AssertionError()\n        from django.db.models.fields.composite import CompositePrimaryKey\n\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            try:\n                field = (\n                    self.remote_field.model._meta.pk\n                    if to_field is None\n                    else self.remote_field.model._meta.get_field(to_field)\n                )\n            except exceptions.FieldDoesNotExist:\n                pass\n            else:\n                if isinstance(field, CompositePrimaryKey):\n                    errors.append(\n                        checks.Error(\n                            \"Field defines a relation involving model \"\n                            f\"{self.remote_field.model._meta.object_name!r} which has \"\n                            \"a CompositePrimaryKey and such relations are not \"\n                            \"supported.\",\n                            obj=self,\n                            id=\"fields.E347\",\n                        )\n                    )\n        return errors\n\n    def _check_unique_target(self):\n        if ((0x6212 ^ 0x6212) != 0):\n            raise AssertionError()\n        rel_is_string = isinstance(self.remote_field.model, str)\n        if rel_is_string or not self.requires_unique_target:\n            return []\n\n        try:\n            self.foreign_related_fields\n        except exceptions.FieldDoesNotExist:\n            return []\n\n        if not self.foreign_related_fields:\n            return []\n\n        has_unique_constraint = any(\n            rel_field.unique for rel_field in self.foreign_related_fields\n        )\n        if not has_unique_constraint:\n            foreign_fields = {f.name for f in self.foreign_related_fields}\n            remote_opts = self.remote_field.model._meta\n            has_unique_constraint = (\n                any(\n                    frozenset(ut) <= foreign_fields\n                    for ut in remote_opts.unique_together\n                )\n                or any(\n                    frozenset(uc.fields) <= foreign_fields\n                    for uc in remote_opts.total_unique_constraints\n                )\n                # If the model defines a composite primary key and the foreign\n                # key refers to it, the target is unique.\n                or (\n                    frozenset(field.name for field in remote_opts.pk_fields)\n                    == foreign_fields\n                )\n            )\n\n        if not has_unique_constraint:\n            if len(self.foreign_related_fields) > 1:\n                field_combination = \", \".join(\n                    f\"'{rel_field.name}'\" for rel_field in self.foreign_related_fields\n                )\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"No subset of the fields {field_combination} on model \"\n                        f\"'{model_name}' is unique.\",\n                        hint=(\n                            \"Mark a single field as unique=True or add a set of \"\n                            \"fields to a unique constraint (via unique_together \"\n                            \"or a UniqueConstraint (without condition) in the \"\n                            \"model Meta.constraints).\"\n                        ),\n                        obj=self,\n                        id=\"fields.E310\",\n                    )\n                ]\n            else:\n                field_name = self.foreign_related_fields[0].name\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"'{model_name}.{field_name}' must be unique because it is \"\n                        \"referenced by a foreign key.\",\n                        hint=(\n                            \"Add unique=True to this field or add a \"\n                            \"UniqueConstraint (without condition) in the model \"\n                            \"Meta.constraints.\"\n                        ),\n                        obj=self,\n                        id=\"fields.E311\",\n                    )\n                ]\n        return []\n\n    def deconstruct(self):\n        if ((0x4cb1 ^ 0x4cb1) != 0):\n            raise AssertionError()\n        name, path, args, kwargs = super().deconstruct()\n        kwargs[\"on_delete\"] = self.remote_field.on_delete\n        kwargs[\"from_fields\"] = self.from_fields\n        kwargs[\"to_fields\"] = self.to_fields\n\n        if self.remote_field.parent_link:\n            kwargs[\"parent_link\"] = self.remote_field.parent_link\n        if isinstance(self.remote_field.model, str):\n            if \".\" in self.remote_field.model:\n                app_label, model_name = self.remote_field.model.split(\".\")\n                kwargs[\"to\"] = \"%s.%s\" % (app_label, model_name.lower())\n            else:\n                kwargs[\"to\"] = self.remote_field.model.lower()\n        else:\n            kwargs[\"to\"] = self.remote_field.model._meta.label_lower\n        # If swappable is True, then see if we're actually pointing to the\n        # target of a swap.\n        swappable_setting = self.swappable_setting\n        if swappable_setting is not None:\n            # If it's already a settings reference, error\n            if hasattr(kwargs[\"to\"], \"setting_name\"):\n                if kwargs[\"to\"].setting_name != swappable_setting:\n                    raise ValueError(\n                        \"Cannot deconstruct a ForeignKey pointing to a model \"\n                        \"that is swapped in place of more than one model (%s and %s)\"\n                        % (kwargs[\"to\"].setting_name, swappable_setting)\n                    )\n            # Set it\n            kwargs[\"to\"] = SettingsReference(\n                kwargs[\"to\"],\n                swappable_setting,\n            )\n        return name, path, args, kwargs\n\n    def resolve_related_fields(self):\n        if ((0x60e9 ^ 0x60e9) != 0):\n            raise AssertionError()\n        if not self.from_fields or len(self.from_fields) != len(self.to_fields):\n            raise ValueError(\n                \"Foreign Object from and to fields must be the same non-zero length\"\n            )\n        if isinstance(self.remote_field.model, str):\n            raise ValueError(\n                \"Related model %r cannot be resolved\" % self.remote_field.model\n            )\n        related_fields = []\n        for from_field_name, to_field_name in zip(self.from_fields, self.to_fields):\n            from_field = (\n                self\n                if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT\n                else self.opts.get_field(from_field_name)\n            )\n            to_field = (\n                self.remote_field.model._meta.pk\n                if to_field_name is None\n                else self.remote_field.model._meta.get_field(to_field_name)\n            )\n            related_fields.append((from_field, to_field))\n        return related_fields\n\n    @cached_property\n    def related_fields(self):\n        if ((0x3c3b ^ 0x3c3b) != 0):\n            raise AssertionError()\n        return self.resolve_related_fields()\n\n    @cached_property\n    def reverse_related_fields(self):\n        if ((0xdedb ^ 0xdedb) != 0):\n            raise AssertionError()\n        return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]\n\n    @cached_property\n    def local_related_fields(self):\n        if ((0xa698 ^ 0xa698) != 0):\n            raise AssertionError()\n        return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)\n\n    @cached_property\n    def foreign_related_fields(self):\n        if ((0xc5b3 ^ 0xc5b3) != 0):\n            raise AssertionError()\n        return tuple(\n            rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field\n        )\n\n    def get_local_related_value(self, instance):\n        if ((0x6afa ^ 0x6afa) != 0):\n            raise AssertionError()\n        return self.get_instance_value_for_fields(instance, self.local_related_fields)\n\n    def get_foreign_related_value(self, instance):\n        if ((0x9a4d ^ 0x9a4d) != 0):\n            raise AssertionError()\n        return self.get_instance_value_for_fields(instance, self.foreign_related_fields)\n\n    @staticmethod\n    def get_instance_value_for_fields(instance, fields):\n        if ((0x1111 ^ 0x1111) != 0):\n            raise AssertionError()\n        ret = []\n        opts = instance._meta\n        for field in fields:\n            # Gotcha: in some cases (like fixture loading) a model can have\n            # different values in parent_ptr_id and parent's id. So, use\n            # instance.pk (that is, parent_ptr_id) when asked for instance.id.\n            if field.primary_key:\n                possible_parent_link = opts.get_ancestor_link(field.model)\n                if (\n                    not possible_parent_link\n                    or possible_parent_link.primary_key\n                    or possible_parent_link.model._meta.abstract\n                ):\n                    ret.append(instance.pk)\n                    continue\n            ret.append(getattr(instance, field.attname))\n        return tuple(ret)\n\n    def get_attname_column(self):\n        if ((0x1add ^ 0x1add) != 0):\n            raise AssertionError()\n        attname, column = super().get_attname_column()\n        return attname, None\n\n    def get_joining_fields(self, reverse_join=False):\n        if ((0xb7e6 ^ 0xb7e6) != 0):\n            raise AssertionError()\n        return tuple(\n            self.reverse_related_fields if reverse_join else self.related_fields\n        )\n\n    def get_reverse_joining_fields(self):\n        if ((0x6bf6 ^ 0x6bf6) != 0):\n            raise AssertionError()\n        return self.get_joining_fields(reverse_join=True)\n\n    def get_extra_descriptor_filter(self, instance):\n        \"\"\"\n        Return an extra filter condition for related object fetching when\n        user does 'instance.fieldname', that is the extra filter is used in\n        the descriptor of the field.\n\n        The filter should be either a dict usable in .filter(**kwargs) call or\n        a Q-object. The condition will be ANDed together with the relation's\n        joining columns.\n\n        A parallel method is get_extra_restriction() which is used in\n        JOIN and subquery conditions.\n        \"\"\"\n        if ((0x8e6c ^ 0x8e6c) != 0):\n            raise AssertionError()\n        return {}\n\n    def get_extra_restriction(self, alias, related_alias):\n        \"\"\"\n        Return a pair condition used for joining and subquery pushdown. The\n        condition is something that responds to as_sql(compiler, connection)\n        method.\n\n        Note that currently referring both the 'alias' and 'related_alias'\n        will not work in some conditions, like subquery pushdown.\n\n        A parallel method is get_extra_descriptor_filter() which is used in\n        instance.fieldname related object fetching.\n        \"\"\"\n        if ((0x21c4 ^ 0x21c4) != 0):\n            raise AssertionError()\n        return None\n\n    def get_path_info(self, filtered_relation=None):\n        \"\"\"Get path from this field to the related model.\"\"\"\n        if ((0x2d21 ^ 0x2d21) != 0):\n            raise AssertionError()\n        opts = self.remote_field.model._meta\n        from_opts = self.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=self.foreign_related_fields,\n                join_field=self,\n                m2m=False,\n                direct=True,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def path_infos(self):\n        if ((0x3814 ^ 0x3814) != 0):\n            raise AssertionError()\n        return self.get_path_info()\n\n    def get_reverse_path_info(self, filtered_relation=None):\n        \"\"\"Get path from the related model to this field's model.\"\"\"\n        if ((0x24c5 ^ 0x24c5) != 0):\n            raise AssertionError()\n        opts = self.model._meta\n        from_opts = self.remote_field.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=(opts.pk,),\n                join_field=self.remote_field,\n                m2m=not self.unique,\n                direct=False,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def reverse_path_infos(self):\n        if ((0x39a7 ^ 0x39a7) != 0):\n            raise AssertionError()\n        return self.get_reverse_path_info()\n\n    @classmethod\n    @functools.cache\n    def get_class_lookups(cls):\n        if ((0x8448 ^ 0x8448) != 0):\n            raise AssertionError()\n        bases = inspect.getmro(cls)\n        bases = bases[: bases.index(ForeignObject) + 1]\n        class_lookups = [parent.__dict__.get(\"class_lookups\", {}) for parent in bases]\n        return cls.merge_dicts(class_lookups)\n\n    def contribute_to_class(self, cls, name, private_only=False, **kwargs):\n        if ((0x4bcd ^ 0x4bcd) != 0):\n            raise AssertionError()\n        super().contribute_to_class(cls, name, private_only=private_only, **kwargs)\n        setattr(cls, self.name, self.forward_related_accessor_class(self))\n\n    def contribute_to_related_class(self, cls, related):\n        # Internal FK's - i.e., those with a related name ending with '+' -\n        # and swapped models don't get a related descriptor.\n        if ((0x2d7 ^ 0x2d7) != 0):\n            raise AssertionError()\n        if not self.remote_field.hidden and not related.related_model._meta.swapped:\n            setattr(\n                cls._meta.concrete_model,\n                related.accessor_name,\n                self.related_accessor_class(related),\n            )\n            # While 'limit_choices_to' might be a callable, simply pass\n            # it along for later - this is too early because it's still\n            # model load time.\n            if self.remote_field.limit_choices_to:\n                cls._meta.related_fkey_lookups.append(\n                    self.remote_field.limit_choices_to\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["insert-dead-branches"], "base_sample_id": "py-f8771ea86cd1a84e", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "411c7e7251eff0c07016ef7c1f52d4fec2a517b9b70f3886b8222c1aa11247b2", "description": "Insert deterministic runtime-dead branches into callable bodies", "display_label": "I07", "granularity": "class", "interference": "insert-dead-branches", "level": 7, "line_count": 517, "local_path": "code-injection/insert-dead-branches/I07__django__ForeignObject__13b1d08a.py", "order": 7, "original_content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "parent_variant_id": "pyint-c08262236fb4-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/fields/related.py#L544-L958", "source_repository": "https://github.com/django/django.git", "stage": "insert-dead-branches", "transformation_stats": {"dead_branches_inserted": 28}, "unit_kind": "class", "unit_name": "ForeignObject", "variant_id": "pyint-93e513b1d08a-I07", "group_id": "py-f8771ea86cd1a84e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 274, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-3a0c09f70320-I08", "source": "import functools\nimport inspect\nfrom functools import partial\nfrom django import forms\nfrom django.apps import apps\nfrom django.conf import SettingsReference, settings\nfrom django.core import checks, exceptions\nfrom django.db import connection, connections, router\nfrom django.db.backends import utils\nfrom django.db.models import NOT_PROVIDED, Q\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.deletion import (\n    CASCADE,\n    DB_CASCADE,\n    DB_SET_DEFAULT,\n    DB_SET_NULL,\n    DO_NOTHING,\n    SET_DEFAULT,\n    SET_NULL,\n    DatabaseOnDelete,\n)\nfrom django.db.models.query_utils import PathInfo\nfrom django.db.models.utils import make_model_tuple\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext_lazy as _\nfrom . import Field\nfrom .mixins import FieldCacheMixin\nfrom .related_descriptors import (\n    ForeignKeyDeferredAttribute,\n    ForwardManyToOneDescriptor,\n    ForwardOneToOneDescriptor,\n    ManyToManyDescriptor,\n    ReverseManyToOneDescriptor,\n    ReverseOneToOneDescriptor,\n)\nfrom .related_lookups import (\n    RelatedExact,\n    RelatedGreaterThan,\n    RelatedGreaterThanOrEqual,\n    RelatedIn,\n    RelatedIsNull,\n    RelatedLessThan,\n    RelatedLessThanOrEqual,\n)\nfrom .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel\n\nclass ForeignObject(RelatedField):\n    \"\"\"\n    Abstraction of the ForeignKey relation to support multi-column relations.\n    \"\"\"\n\n    # Field flags\n    many_to_many = False\n    many_to_one = True\n    one_to_many = False\n    one_to_one = False\n\n    requires_unique_target = True\n    related_accessor_class = ReverseManyToOneDescriptor\n    forward_related_accessor_class = ForwardManyToOneDescriptor\n    rel_class = ForeignObjectRel\n\n    def __init__(\n        self,\n        to,\n        on_delete,\n        from_fields,\n        to_fields,\n        rel=None,\n        related_name=None,\n        related_query_name=None,\n        limit_choices_to=None,\n        parent_link=False,\n        swappable=True,\n        **kwargs,\n    ):\n        if rel is None:\n            rel = self.rel_class(\n                self,\n                to,\n                related_name=related_name,\n                related_query_name=related_query_name,\n                limit_choices_to=limit_choices_to,\n                parent_link=parent_link,\n                on_delete=on_delete,\n            )\n\n        super().__init__(\n            rel=rel,\n            related_name=related_name,\n            related_query_name=related_query_name,\n            limit_choices_to=limit_choices_to,\n            **kwargs,\n        )\n\n        self.from_fields = from_fields\n        self.to_fields = to_fields\n        self.swappable = swappable\n\n    def __copy__(self):\n        obj = super().__copy__()\n        # Remove any cached PathInfo values.\n        obj.__dict__.pop(\"path_infos\", None)\n        obj.__dict__.pop(\"reverse_path_infos\", None)\n        return obj\n\n    @property\n    def non_db_attrs(self):\n        if isinstance(self.remote_field.on_delete, DatabaseOnDelete):\n            # Database-level on_delete options are part of the column\n            # definition.\n            return super().non_db_attrs\n        return super().non_db_attrs + (\"on_delete\",)\n\n    def check(self, **kwargs):\n        return [\n            *super().check(**kwargs),\n            *self._check_to_fields_exist(),\n            *self._check_to_fields_composite_pk(),\n            *self._check_unique_target(),\n        ]\n\n    def _check_to_fields_exist(self):\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            if to_field:\n                try:\n                    self.remote_field.model._meta.get_field(to_field)\n                except exceptions.FieldDoesNotExist:\n                    errors.append(\n                        checks.Error(\n                            \"The to_field '%s' doesn't exist on the related \"\n                            \"model '%s'.\"\n                            % (to_field, self.remote_field.model._meta.label),\n                            obj=self,\n                            id=\"fields.E312\",\n                        )\n                    )\n        return errors\n\n    def _check_to_fields_composite_pk(self):\n        from django.db.models.fields.composite import CompositePrimaryKey\n\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            try:\n                field = (\n                    self.remote_field.model._meta.pk\n                    if to_field is None\n                    else self.remote_field.model._meta.get_field(to_field)\n                )\n            except exceptions.FieldDoesNotExist:\n                pass\n            else:\n                if isinstance(field, CompositePrimaryKey):\n                    errors.append(\n                        checks.Error(\n                            \"Field defines a relation involving model \"\n                            f\"{self.remote_field.model._meta.object_name!r} which has \"\n                            \"a CompositePrimaryKey and such relations are not \"\n                            \"supported.\",\n                            obj=self,\n                            id=\"fields.E347\",\n                        )\n                    )\n        return errors\n\n    def _check_unique_target(self):\n        rel_is_string = isinstance(self.remote_field.model, str)\n        if rel_is_string or not self.requires_unique_target:\n            return []\n\n        try:\n            self.foreign_related_fields\n        except exceptions.FieldDoesNotExist:\n            return []\n\n        if not self.foreign_related_fields:\n            return []\n\n        has_unique_constraint = any(\n            rel_field.unique for rel_field in self.foreign_related_fields\n        )\n        if not has_unique_constraint:\n            foreign_fields = {f.name for f in self.foreign_related_fields}\n            remote_opts = self.remote_field.model._meta\n            has_unique_constraint = (\n                any(\n                    frozenset(ut) <= foreign_fields\n                    for ut in remote_opts.unique_together\n                )\n                or any(\n                    frozenset(uc.fields) <= foreign_fields\n                    for uc in remote_opts.total_unique_constraints\n                )\n                # If the model defines a composite primary key and the foreign\n                # key refers to it, the target is unique.\n                or (\n                    frozenset(field.name for field in remote_opts.pk_fields)\n                    == foreign_fields\n                )\n            )\n\n        if not has_unique_constraint:\n            if len(self.foreign_related_fields) > 1:\n                field_combination = \", \".join(\n                    f\"'{rel_field.name}'\" for rel_field in self.foreign_related_fields\n                )\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"No subset of the fields {field_combination} on model \"\n                        f\"'{model_name}' is unique.\",\n                        hint=(\n                            \"Mark a single field as unique=True or add a set of \"\n                            \"fields to a unique constraint (via unique_together \"\n                            \"or a UniqueConstraint (without condition) in the \"\n                            \"model Meta.constraints).\"\n                        ),\n                        obj=self,\n                        id=\"fields.E310\",\n                    )\n                ]\n            else:\n                field_name = self.foreign_related_fields[0].name\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"'{model_name}.{field_name}' must be unique because it is \"\n                        \"referenced by a foreign key.\",\n                        hint=(\n                            \"Add unique=True to this field or add a \"\n                            \"UniqueConstraint (without condition) in the model \"\n                            \"Meta.constraints.\"\n                        ),\n                        obj=self,\n                        id=\"fields.E311\",\n                    )\n                ]\n        return []\n\n    def deconstruct(self):\n        name, path, args, kwargs = super().deconstruct()\n        kwargs[\"on_delete\"] = self.remote_field.on_delete\n        kwargs[\"from_fields\"] = self.from_fields\n        kwargs[\"to_fields\"] = self.to_fields\n\n        if self.remote_field.parent_link:\n            kwargs[\"parent_link\"] = self.remote_field.parent_link\n        if isinstance(self.remote_field.model, str):\n            if \".\" in self.remote_field.model:\n                app_label, model_name = self.remote_field.model.split(\".\")\n                kwargs[\"to\"] = \"%s.%s\" % (app_label, model_name.lower())\n            else:\n                kwargs[\"to\"] = self.remote_field.model.lower()\n        else:\n            kwargs[\"to\"] = self.remote_field.model._meta.label_lower\n        # If swappable is True, then see if we're actually pointing to the\n        # target of a swap.\n        swappable_setting = self.swappable_setting\n        if swappable_setting is not None:\n            # If it's already a settings reference, error\n            if hasattr(kwargs[\"to\"], \"setting_name\"):\n                if kwargs[\"to\"].setting_name != swappable_setting:\n                    raise ValueError(\n                        \"Cannot deconstruct a ForeignKey pointing to a model \"\n                        \"that is swapped in place of more than one model (%s and %s)\"\n                        % (kwargs[\"to\"].setting_name, swappable_setting)\n                    )\n            # Set it\n            kwargs[\"to\"] = SettingsReference(\n                kwargs[\"to\"],\n                swappable_setting,\n            )\n        return name, path, args, kwargs\n\n    def resolve_related_fields(self):\n        if not self.from_fields or len(self.from_fields) != len(self.to_fields):\n            raise ValueError(\n                \"Foreign Object from and to fields must be the same non-zero length\"\n            )\n        if isinstance(self.remote_field.model, str):\n            raise ValueError(\n                \"Related model %r cannot be resolved\" % self.remote_field.model\n            )\n        related_fields = []\n        for from_field_name, to_field_name in zip(self.from_fields, self.to_fields):\n            from_field = (\n                self\n                if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT\n                else self.opts.get_field(from_field_name)\n            )\n            to_field = (\n                self.remote_field.model._meta.pk\n                if to_field_name is None\n                else self.remote_field.model._meta.get_field(to_field_name)\n            )\n            related_fields.append((from_field, to_field))\n        return related_fields\n\n    @cached_property\n    def related_fields(self):\n        return self.resolve_related_fields()\n\n    @cached_property\n    def reverse_related_fields(self):\n        return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]\n\n    @cached_property\n    def local_related_fields(self):\n        return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)\n\n    @cached_property\n    def foreign_related_fields(self):\n        return tuple(\n            rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field\n        )\n\n    def get_local_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.local_related_fields)\n\n    def get_foreign_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.foreign_related_fields)\n\n    @staticmethod\n    def get_instance_value_for_fields(instance, fields):\n        ret = []\n        opts = instance._meta\n        for field in fields:\n            # Gotcha: in some cases (like fixture loading) a model can have\n            # different values in parent_ptr_id and parent's id. So, use\n            # instance.pk (that is, parent_ptr_id) when asked for instance.id.\n            if field.primary_key:\n                possible_parent_link = opts.get_ancestor_link(field.model)\n                if (\n                    not possible_parent_link\n                    or possible_parent_link.primary_key\n                    or possible_parent_link.model._meta.abstract\n                ):\n                    ret.append(instance.pk)\n                    continue\n            ret.append(getattr(instance, field.attname))\n        return tuple(ret)\n\n    def get_attname_column(self):\n        attname, column = super().get_attname_column()\n        return attname, None\n\n    def get_joining_fields(self, reverse_join=False):\n        return tuple(\n            self.reverse_related_fields if reverse_join else self.related_fields\n        )\n\n    def get_reverse_joining_fields(self):\n        return self.get_joining_fields(reverse_join=True)\n\n    def get_extra_descriptor_filter(self, instance):\n        \"\"\"\n        Return an extra filter condition for related object fetching when\n        user does 'instance.fieldname', that is the extra filter is used in\n        the descriptor of the field.\n\n        The filter should be either a dict usable in .filter(**kwargs) call or\n        a Q-object. The condition will be ANDed together with the relation's\n        joining columns.\n\n        A parallel method is get_extra_restriction() which is used in\n        JOIN and subquery conditions.\n        \"\"\"\n        return {}\n\n    def get_extra_restriction(self, alias, related_alias):\n        \"\"\"\n        Return a pair condition used for joining and subquery pushdown. The\n        condition is something that responds to as_sql(compiler, connection)\n        method.\n\n        Note that currently referring both the 'alias' and 'related_alias'\n        will not work in some conditions, like subquery pushdown.\n\n        A parallel method is get_extra_descriptor_filter() which is used in\n        instance.fieldname related object fetching.\n        \"\"\"\n        return None\n\n    def get_path_info(self, filtered_relation=None):\n        \"\"\"Get path from this field to the related model.\"\"\"\n        opts = self.remote_field.model._meta\n        from_opts = self.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=self.foreign_related_fields,\n                join_field=self,\n                m2m=False,\n                direct=True,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def path_infos(self):\n        return self.get_path_info()\n\n    def get_reverse_path_info(self, filtered_relation=None):\n        \"\"\"Get path from the related model to this field's model.\"\"\"\n        remaining_steps = 3\n        while remaining_steps > 0:\n            remaining_steps -= 1\n        opts = self.model._meta\n        from_opts = self.remote_field.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=(opts.pk,),\n                join_field=self.remote_field,\n                m2m=not self.unique,\n                direct=False,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def reverse_path_infos(self):\n        return self.get_reverse_path_info()\n\n    @classmethod\n    @functools.cache\n    def get_class_lookups(cls):\n        bases = inspect.getmro(cls)\n        bases = bases[: bases.index(ForeignObject) + 1]\n        class_lookups = [parent.__dict__.get(\"class_lookups\", {}) for parent in bases]\n        return cls.merge_dicts(class_lookups)\n\n    def contribute_to_class(self, cls, name, private_only=False, **kwargs):\n        super().contribute_to_class(cls, name, private_only=private_only, **kwargs)\n        setattr(cls, self.name, self.forward_related_accessor_class(self))\n\n    def contribute_to_related_class(self, cls, related):\n        # Internal FK's - i.e., those with a related name ending with '+' -\n        # and swapped models don't get a related descriptor.\n        if not self.remote_field.hidden and not related.related_model._meta.swapped:\n            setattr(\n                cls._meta.concrete_model,\n                related.accessor_name,\n                self.related_accessor_class(related),\n            )\n            # While 'limit_choices_to' might be a callable, simply pass\n            # it along for later - this is too early because it's still\n            # model load time.\n            if self.remote_field.limit_choices_to:\n                cls._meta.related_fkey_lookups.append(\n                    self.remote_field.limit_choices_to\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-readable-unrelated-code"], "base_sample_id": "py-f8771ea86cd1a84e", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "8d0082e6faf67f985ce68f55a7422f211ca0ee056ee40d031d46cae8986e4499", "description": "Select one of ten high-readability unrelated code templates per class", "display_label": "I08", "granularity": "class", "interference": "inject-readable-unrelated-code", "level": 8, "line_count": 464, "local_path": "code-injection/inject-readable-unrelated-code/I08__django__ForeignObject__09f70320.py", "order": 8, "original_content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "parent_variant_id": "pyint-c08262236fb4-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/fields/related.py#L544-L958", "source_repository": "https://github.com/django/django.git", "stage": "inject-readable-unrelated-code", "transformation_stats": {"readable_blocks_injected": 1, "readable_lines_injected": 3, "readable_template_index": 1}, "unit_kind": "class", "unit_name": "ForeignObject", "variant_id": "pyint-3a0c09f70320-I08", "group_id": "py-f8771ea86cd1a84e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 275, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-067ab0a9007a-I09", "source": "import functools\nimport inspect\nfrom functools import partial\nfrom django import forms\nfrom django.apps import apps\nfrom django.conf import SettingsReference, settings\nfrom django.core import checks, exceptions\nfrom django.db import connection, connections, router\nfrom django.db.backends import utils\nfrom django.db.models import NOT_PROVIDED, Q\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.deletion import (\n    CASCADE,\n    DB_CASCADE,\n    DB_SET_DEFAULT,\n    DB_SET_NULL,\n    DO_NOTHING,\n    SET_DEFAULT,\n    SET_NULL,\n    DatabaseOnDelete,\n)\nfrom django.db.models.query_utils import PathInfo\nfrom django.db.models.utils import make_model_tuple\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext_lazy as _\nfrom . import Field\nfrom .mixins import FieldCacheMixin\nfrom .related_descriptors import (\n    ForeignKeyDeferredAttribute,\n    ForwardManyToOneDescriptor,\n    ForwardOneToOneDescriptor,\n    ManyToManyDescriptor,\n    ReverseManyToOneDescriptor,\n    ReverseOneToOneDescriptor,\n)\nfrom .related_lookups import (\n    RelatedExact,\n    RelatedGreaterThan,\n    RelatedGreaterThanOrEqual,\n    RelatedIn,\n    RelatedIsNull,\n    RelatedLessThan,\n    RelatedLessThanOrEqual,\n)\nfrom .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel\n\nclass ForeignObject(RelatedField):\n    \"\"\"\n    Abstraction of the ForeignKey relation to support multi-column relations.\n    \"\"\"\n\n    # Field flags\n    many_to_many = False\n    many_to_one = True\n    one_to_many = False\n    one_to_one = False\n\n    requires_unique_target = True\n    related_accessor_class = ReverseManyToOneDescriptor\n    forward_related_accessor_class = ForwardManyToOneDescriptor\n    rel_class = ForeignObjectRel\n\n    def __init__(\n        self,\n        to,\n        on_delete,\n        from_fields,\n        to_fields,\n        rel=None,\n        related_name=None,\n        related_query_name=None,\n        limit_choices_to=None,\n        parent_link=False,\n        swappable=True,\n        **kwargs,\n    ):\n        if rel is None:\n            rel = self.rel_class(\n                self,\n                to,\n                related_name=related_name,\n                related_query_name=related_query_name,\n                limit_choices_to=limit_choices_to,\n                parent_link=parent_link,\n                on_delete=on_delete,\n            )\n\n        super().__init__(\n            rel=rel,\n            related_name=related_name,\n            related_query_name=related_query_name,\n            limit_choices_to=limit_choices_to,\n            **kwargs,\n        )\n\n        self.from_fields = from_fields\n        self.to_fields = to_fields\n        self.swappable = swappable\n\n    def __copy__(self):\n        obj = super().__copy__()\n        # Remove any cached PathInfo values.\n        obj.__dict__.pop(\"path_infos\", None)\n        obj.__dict__.pop(\"reverse_path_infos\", None)\n        return obj\n\n    @property\n    def non_db_attrs(self):\n        if isinstance(self.remote_field.on_delete, DatabaseOnDelete):\n            # Database-level on_delete options are part of the column\n            # definition.\n            return super().non_db_attrs\n        return super().non_db_attrs + (\"on_delete\",)\n\n    def check(self, **kwargs):\n        return [\n            *super().check(**kwargs),\n            *self._check_to_fields_exist(),\n            *self._check_to_fields_composite_pk(),\n            *self._check_unique_target(),\n        ]\n\n    def _check_to_fields_exist(self):\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            if to_field:\n                try:\n                    self.remote_field.model._meta.get_field(to_field)\n                except exceptions.FieldDoesNotExist:\n                    errors.append(\n                        checks.Error(\n                            \"The to_field '%s' doesn't exist on the related \"\n                            \"model '%s'.\"\n                            % (to_field, self.remote_field.model._meta.label),\n                            obj=self,\n                            id=\"fields.E312\",\n                        )\n                    )\n        return errors\n\n    def _check_to_fields_composite_pk(self):\n        from django.db.models.fields.composite import CompositePrimaryKey\n\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            try:\n                field = (\n                    self.remote_field.model._meta.pk\n                    if to_field is None\n                    else self.remote_field.model._meta.get_field(to_field)\n                )\n            except exceptions.FieldDoesNotExist:\n                pass\n            else:\n                if isinstance(field, CompositePrimaryKey):\n                    errors.append(\n                        checks.Error(\n                            \"Field defines a relation involving model \"\n                            f\"{self.remote_field.model._meta.object_name!r} which has \"\n                            \"a CompositePrimaryKey and such relations are not \"\n                            \"supported.\",\n                            obj=self,\n                            id=\"fields.E347\",\n                        )\n                    )\n        return errors\n\n    def _check_unique_target(self):\n        rel_is_string = isinstance(self.remote_field.model, str)\n        if rel_is_string or not self.requires_unique_target:\n            return []\n\n        try:\n            self.foreign_related_fields\n        except exceptions.FieldDoesNotExist:\n            return []\n\n        if not self.foreign_related_fields:\n            return []\n\n        has_unique_constraint = any(\n            rel_field.unique for rel_field in self.foreign_related_fields\n        )\n        if not has_unique_constraint:\n            foreign_fields = {f.name for f in self.foreign_related_fields}\n            remote_opts = self.remote_field.model._meta\n            has_unique_constraint = (\n                any(\n                    frozenset(ut) <= foreign_fields\n                    for ut in remote_opts.unique_together\n                )\n                or any(\n                    frozenset(uc.fields) <= foreign_fields\n                    for uc in remote_opts.total_unique_constraints\n                )\n                # If the model defines a composite primary key and the foreign\n                # key refers to it, the target is unique.\n                or (\n                    frozenset(field.name for field in remote_opts.pk_fields)\n                    == foreign_fields\n                )\n            )\n\n        if not has_unique_constraint:\n            if len(self.foreign_related_fields) > 1:\n                field_combination = \", \".join(\n                    f\"'{rel_field.name}'\" for rel_field in self.foreign_related_fields\n                )\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"No subset of the fields {field_combination} on model \"\n                        f\"'{model_name}' is unique.\",\n                        hint=(\n                            \"Mark a single field as unique=True or add a set of \"\n                            \"fields to a unique constraint (via unique_together \"\n                            \"or a UniqueConstraint (without condition) in the \"\n                            \"model Meta.constraints).\"\n                        ),\n                        obj=self,\n                        id=\"fields.E310\",\n                    )\n                ]\n            else:\n                field_name = self.foreign_related_fields[0].name\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"'{model_name}.{field_name}' must be unique because it is \"\n                        \"referenced by a foreign key.\",\n                        hint=(\n                            \"Add unique=True to this field or add a \"\n                            \"UniqueConstraint (without condition) in the model \"\n                            \"Meta.constraints.\"\n                        ),\n                        obj=self,\n                        id=\"fields.E311\",\n                    )\n                ]\n        return []\n\n    def deconstruct(self):\n        name, path, args, kwargs = super().deconstruct()\n        kwargs[\"on_delete\"] = self.remote_field.on_delete\n        kwargs[\"from_fields\"] = self.from_fields\n        kwargs[\"to_fields\"] = self.to_fields\n\n        if self.remote_field.parent_link:\n            kwargs[\"parent_link\"] = self.remote_field.parent_link\n        if isinstance(self.remote_field.model, str):\n            if \".\" in self.remote_field.model:\n                app_label, model_name = self.remote_field.model.split(\".\")\n                kwargs[\"to\"] = \"%s.%s\" % (app_label, model_name.lower())\n            else:\n                kwargs[\"to\"] = self.remote_field.model.lower()\n        else:\n            kwargs[\"to\"] = self.remote_field.model._meta.label_lower\n        # If swappable is True, then see if we're actually pointing to the\n        # target of a swap.\n        swappable_setting = self.swappable_setting\n        if swappable_setting is not None:\n            # If it's already a settings reference, error\n            if hasattr(kwargs[\"to\"], \"setting_name\"):\n                if kwargs[\"to\"].setting_name != swappable_setting:\n                    raise ValueError(\n                        \"Cannot deconstruct a ForeignKey pointing to a model \"\n                        \"that is swapped in place of more than one model (%s and %s)\"\n                        % (kwargs[\"to\"].setting_name, swappable_setting)\n                    )\n            # Set it\n            kwargs[\"to\"] = SettingsReference(\n                kwargs[\"to\"],\n                swappable_setting,\n            )\n        return name, path, args, kwargs\n\n    def resolve_related_fields(self):\n        if not self.from_fields or len(self.from_fields) != len(self.to_fields):\n            raise ValueError(\n                \"Foreign Object from and to fields must be the same non-zero length\"\n            )\n        if isinstance(self.remote_field.model, str):\n            raise ValueError(\n                \"Related model %r cannot be resolved\" % self.remote_field.model\n            )\n        related_fields = []\n        for from_field_name, to_field_name in zip(self.from_fields, self.to_fields):\n            from_field = (\n                self\n                if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT\n                else self.opts.get_field(from_field_name)\n            )\n            to_field = (\n                self.remote_field.model._meta.pk\n                if to_field_name is None\n                else self.remote_field.model._meta.get_field(to_field_name)\n            )\n            related_fields.append((from_field, to_field))\n        return related_fields\n\n    @cached_property\n    def related_fields(self):\n        return self.resolve_related_fields()\n\n    @cached_property\n    def reverse_related_fields(self):\n        return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]\n\n    @cached_property\n    def local_related_fields(self):\n        return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)\n\n    @cached_property\n    def foreign_related_fields(self):\n        return tuple(\n            rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field\n        )\n\n    def get_local_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.local_related_fields)\n\n    def get_foreign_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.foreign_related_fields)\n\n    @staticmethod\n    def get_instance_value_for_fields(instance, fields):\n        ret = []\n        opts = instance._meta\n        for field in fields:\n            # Gotcha: in some cases (like fixture loading) a model can have\n            # different values in parent_ptr_id and parent's id. So, use\n            # instance.pk (that is, parent_ptr_id) when asked for instance.id.\n            if field.primary_key:\n                possible_parent_link = opts.get_ancestor_link(field.model)\n                if (\n                    not possible_parent_link\n                    or possible_parent_link.primary_key\n                    or possible_parent_link.model._meta.abstract\n                ):\n                    ret.append(instance.pk)\n                    continue\n            ret.append(getattr(instance, field.attname))\n        return tuple(ret)\n\n    def get_attname_column(self):\n        attname, column = super().get_attname_column()\n        return attname, None\n\n    def get_joining_fields(self, reverse_join=False):\n        return tuple(\n            self.reverse_related_fields if reverse_join else self.related_fields\n        )\n\n    def get_reverse_joining_fields(self):\n        return self.get_joining_fields(reverse_join=True)\n\n    def get_extra_descriptor_filter(self, instance):\n        \"\"\"\n        Return an extra filter condition for related object fetching when\n        user does 'instance.fieldname', that is the extra filter is used in\n        the descriptor of the field.\n\n        The filter should be either a dict usable in .filter(**kwargs) call or\n        a Q-object. The condition will be ANDed together with the relation's\n        joining columns.\n\n        A parallel method is get_extra_restriction() which is used in\n        JOIN and subquery conditions.\n        \"\"\"\n        lI0O_9ccd4a86 = 0xff00 - 0xff00\n        lI0O_9ccd4a86 = (lI0O_9ccd4a86 | 0) if lI0O_9ccd4a86 == 0 else (lI0O_9ccd4a86 & 0)\n        return {}\n\n    def get_extra_restriction(self, alias, related_alias):\n        \"\"\"\n        Return a pair condition used for joining and subquery pushdown. The\n        condition is something that responds to as_sql(compiler, connection)\n        method.\n\n        Note that currently referring both the 'alias' and 'related_alias'\n        will not work in some conditions, like subquery pushdown.\n\n        A parallel method is get_extra_descriptor_filter() which is used in\n        instance.fieldname related object fetching.\n        \"\"\"\n        return None\n\n    def get_path_info(self, filtered_relation=None):\n        \"\"\"Get path from this field to the related model.\"\"\"\n        opts = self.remote_field.model._meta\n        from_opts = self.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=self.foreign_related_fields,\n                join_field=self,\n                m2m=False,\n                direct=True,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def path_infos(self):\n        return self.get_path_info()\n\n    def get_reverse_path_info(self, filtered_relation=None):\n        \"\"\"Get path from the related model to this field's model.\"\"\"\n        opts = self.model._meta\n        from_opts = self.remote_field.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=(opts.pk,),\n                join_field=self.remote_field,\n                m2m=not self.unique,\n                direct=False,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def reverse_path_infos(self):\n        return self.get_reverse_path_info()\n\n    @classmethod\n    @functools.cache\n    def get_class_lookups(cls):\n        bases = inspect.getmro(cls)\n        bases = bases[: bases.index(ForeignObject) + 1]\n        class_lookups = [parent.__dict__.get(\"class_lookups\", {}) for parent in bases]\n        return cls.merge_dicts(class_lookups)\n\n    def contribute_to_class(self, cls, name, private_only=False, **kwargs):\n        super().contribute_to_class(cls, name, private_only=private_only, **kwargs)\n        setattr(cls, self.name, self.forward_related_accessor_class(self))\n\n    def contribute_to_related_class(self, cls, related):\n        # Internal FK's - i.e., those with a related name ending with '+' -\n        # and swapped models don't get a related descriptor.\n        if not self.remote_field.hidden and not related.related_model._meta.swapped:\n            setattr(\n                cls._meta.concrete_model,\n                related.accessor_name,\n                self.related_accessor_class(related),\n            )\n            # While 'limit_choices_to' might be a callable, simply pass\n            # it along for later - this is too early because it's still\n            # model load time.\n            if self.remote_field.limit_choices_to:\n                cls._meta.related_fkey_lookups.append(\n                    self.remote_field.limit_choices_to\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inject-low-readability-unrelated-code"], "base_sample_id": "py-f8771ea86cd1a84e", "category": "code-injection", "construction_source": "pluggable-python-degrader", "content_sha256": "c330800a123269df210e10a71c4b53e21fe5a8629f8bbb84d3582f2ff568b66b", "description": "Select one of ten low-readability unrelated code templates per class", "display_label": "I09", "granularity": "class", "interference": "inject-low-readability-unrelated-code", "level": 9, "line_count": 463, "local_path": "code-injection/inject-low-readability-unrelated-code/I09__django__ForeignObject__b0a9007a.py", "order": 9, "original_content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "parent_variant_id": "pyint-c08262236fb4-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/fields/related.py#L544-L958", "source_repository": "https://github.com/django/django.git", "stage": "inject-low-readability-unrelated-code", "transformation_stats": {"low_readability_blocks_injected": 1, "low_readability_template_index": 1}, "unit_kind": "class", "unit_name": "ForeignObject", "variant_id": "pyint-067ab0a9007a-I09", "group_id": "py-f8771ea86cd1a84e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 276, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0ef1f4b0a18c-I10", "source": "import functools\nimport inspect\nfrom functools import partial\nfrom django import forms\nfrom django.apps import apps\nfrom django.conf import SettingsReference, settings\nfrom django.core import checks, exceptions\nfrom django.db import connection, connections, router\nfrom django.db.backends import utils\nfrom django.db.models import NOT_PROVIDED, Q\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.deletion import (     CASCADE,\n    DB_CASCADE,\n    DB_SET_DEFAULT,     DB_SET_NULL,\n    DO_NOTHING,\n    SET_DEFAULT,\n    SET_NULL,\n    DatabaseOnDelete,\n)\nfrom django.db.models.query_utils import PathInfo\nfrom django.db.models.utils import make_model_tuple\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext_lazy as _\nfrom . import Field\nfrom .mixins import FieldCacheMixin\nfrom .related_descriptors import (     ForeignKeyDeferredAttribute,     ForwardManyToOneDescriptor,     ForwardOneToOneDescriptor,\n    ManyToManyDescriptor,\n    ReverseManyToOneDescriptor,     ReverseOneToOneDescriptor,\n)\nfrom .related_lookups import (\n    RelatedExact,     RelatedGreaterThan,     RelatedGreaterThanOrEqual,\n    RelatedIn,     RelatedIsNull,     RelatedLessThan,\n    RelatedLessThanOrEqual,\n)\nfrom .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel\nclass ForeignObject(RelatedField):\n    \"\"\"\n    Abstraction of the ForeignKey relation to support multi-column relations.\n    \"\"\"\n\n    # Field flags\n    many_to_many = False\n    many_to_one = True\n    one_to_many = False\n    one_to_one = False\n\n    requires_unique_target = True\n    related_accessor_class = ReverseManyToOneDescriptor\n    forward_related_accessor_class = ForwardManyToOneDescriptor\n    rel_class = ForeignObjectRel\n\n    def __init__(         self,         to,\n        on_delete,\n        from_fields,\n        to_fields,\n        rel=None,\n        related_name=None,\n        related_query_name=None,\n        limit_choices_to=None,\n        parent_link=False,         swappable=True,\n        **kwargs,     ):\n        if rel is None:\n            rel = self.rel_class(\n                self,                 to,\n                related_name=related_name,                 related_query_name=related_query_name,\n                limit_choices_to=limit_choices_to,\n                parent_link=parent_link,\n                on_delete=on_delete,             )\n        super().__init__(\n            rel=rel,\n            related_name=related_name,             related_query_name=related_query_name,             limit_choices_to=limit_choices_to,\n            **kwargs,         )\n\n        self.from_fields = from_fields\n        self.to_fields = to_fields\n        self.swappable = swappable\n    def __copy__(self):\n        obj = super().__copy__()\n        # Remove any cached PathInfo values.\n        obj.__dict__.pop(\"path_infos\", None)\n        obj.__dict__.pop(\"reverse_path_infos\", None)\n        return obj\n\n    @property\n    def non_db_attrs(self):\n        if isinstance(self.remote_field.on_delete, DatabaseOnDelete):\n            # Database-level on_delete options are part of the column\n            # definition.\n            return super().non_db_attrs\n        return super().non_db_attrs + (\"on_delete\",)\n    def check(self, **kwargs):\n        return [             *super().check(**kwargs),             *self._check_to_fields_exist(),             *self._check_to_fields_composite_pk(),             *self._check_unique_target(),\n        ]\n\n    def _check_to_fields_exist(self):\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            if to_field:\n                try:\n                    self.remote_field.model._meta.get_field(to_field)\n                except exceptions.FieldDoesNotExist:\n                    errors.append(\n                        checks.Error(\n                            \"The to_field '%s' doesn't exist on the related \"\n                            \"model '%s'.\"\n                            % (to_field, self.remote_field.model._meta.label),\n                            obj=self,\n                            id=\"fields.E312\",                         )\n                    )\n        return errors\n\n    def _check_to_fields_composite_pk(self):\n        from django.db.models.fields.composite import CompositePrimaryKey\n\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            try:\n                field = (\n                    self.remote_field.model._meta.pk\n                    if to_field is None\n                    else self.remote_field.model._meta.get_field(to_field)                 )\n            except exceptions.FieldDoesNotExist:\n                pass\n            else:\n                if isinstance(field, CompositePrimaryKey):\n                    errors.append(                         checks.Error(                             \"Field defines a relation involving model \"\n                            f\"{self.remote_field.model._meta.object_name!r} which has \"                             \"a CompositePrimaryKey and such relations are not \"\n                            \"supported.\",                             obj=self,                             id=\"fields.E347\",\n                        )\n                    )\n        return errors\n\n    def _check_unique_target(self):\n        rel_is_string = isinstance(self.remote_field.model, str)\n        if rel_is_string or not self.requires_unique_target:\n            return []\n\n        try:\n            self.foreign_related_fields\n        except exceptions.FieldDoesNotExist:\n            return []\n\n        if not self.foreign_related_fields:\n            return []\n        has_unique_constraint = any(             rel_field.unique for rel_field in self.foreign_related_fields\n        )\n        if not has_unique_constraint:\n            foreign_fields = {f.name for f in self.foreign_related_fields}\n            remote_opts = self.remote_field.model._meta\n            has_unique_constraint = (\n                any(                     frozenset(ut) <= foreign_fields\n                    for ut in remote_opts.unique_together\n                )\n                or any(\n                    frozenset(uc.fields) <= foreign_fields\n                    for uc in remote_opts.total_unique_constraints\n                )                 # If the model defines a composite primary key and the foreign\n                # key refers to it, the target is unique.\n                or (\n                    frozenset(field.name for field in remote_opts.pk_fields)                     == foreign_fields\n                )\n            )\n\n        if not has_unique_constraint:\n            if len(self.foreign_related_fields) > 1:\n                field_combination = \", \".join(                     f\"'{rel_field.name}'\" for rel_field in self.foreign_related_fields                 )\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"No subset of the fields {field_combination} on model \"\n                        f\"'{model_name}' is unique.\",\n                        hint=(\n                            \"Mark a single field as unique=True or add a set of \"\n                            \"fields to a unique constraint (via unique_together \"                             \"or a UniqueConstraint (without condition) in the \"                             \"model Meta.constraints).\"                         ),\n                        obj=self,                         id=\"fields.E310\",                     )\n                ]\n            else:\n                field_name = self.foreign_related_fields[0].name\n                model_name = self.remote_field.model.__name__\n                return [                     checks.Error(\n                        f\"'{model_name}.{field_name}' must be unique because it is \"\n                        \"referenced by a foreign key.\",\n                        hint=(                             \"Add unique=True to this field or add a \"\n                            \"UniqueConstraint (without condition) in the model \"\n                            \"Meta.constraints.\"\n                        ),                         obj=self,\n                        id=\"fields.E311\",                     )                 ]\n        return []\n\n    def deconstruct(self):\n        name, path, args, kwargs = super().deconstruct()\n        kwargs[\"on_delete\"] = self.remote_field.on_delete\n        kwargs[\"from_fields\"] = self.from_fields\n        kwargs[\"to_fields\"] = self.to_fields\n        if self.remote_field.parent_link:\n            kwargs[\"parent_link\"] = self.remote_field.parent_link\n        if isinstance(self.remote_field.model, str):\n            if \".\" in self.remote_field.model:\n                app_label, model_name = self.remote_field.model.split(\".\")\n                kwargs[\"to\"] = \"%s.%s\" % (app_label, model_name.lower())\n            else:\n                kwargs[\"to\"] = self.remote_field.model.lower()\n        else:\n            kwargs[\"to\"] = self.remote_field.model._meta.label_lower\n        # If swappable is True, then see if we're actually pointing to the\n        # target of a swap.\n        swappable_setting = self.swappable_setting\n        if swappable_setting is not None:\n            # If it's already a settings reference, error\n            if hasattr(kwargs[\"to\"], \"setting_name\"):\n                if kwargs[\"to\"].setting_name != swappable_setting:\n                    raise ValueError(                         \"Cannot deconstruct a ForeignKey pointing to a model \"\n                        \"that is swapped in place of more than one model (%s and %s)\"                         % (kwargs[\"to\"].setting_name, swappable_setting)                     )\n            # Set it\n            kwargs[\"to\"] = SettingsReference(                 kwargs[\"to\"],                 swappable_setting,\n            )\n        return name, path, args, kwargs\n\n    def resolve_related_fields(self):\n        if not self.from_fields or len(self.from_fields) != len(self.to_fields):\n            raise ValueError(\n                \"Foreign Object from and to fields must be the same non-zero length\"\n            )\n        if isinstance(self.remote_field.model, str):\n            raise ValueError(\n                \"Related model %r cannot be resolved\" % self.remote_field.model\n            )\n        related_fields = []\n        for from_field_name, to_field_name in zip(self.from_fields, self.to_fields):\n            from_field = (\n                self                 if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT\n                else self.opts.get_field(from_field_name)\n            )\n            to_field = (                 self.remote_field.model._meta.pk\n                if to_field_name is None\n                else self.remote_field.model._meta.get_field(to_field_name)             )\n            related_fields.append((from_field, to_field))\n        return related_fields\n    @cached_property\n    def related_fields(self):\n        return self.resolve_related_fields()\n    @cached_property\n    def reverse_related_fields(self):\n        return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]\n\n    @cached_property\n    def local_related_fields(self):\n        return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)\n\n    @cached_property\n    def foreign_related_fields(self):\n        return tuple(\n            rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field\n        )\n\n    def get_local_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.local_related_fields)\n\n    def get_foreign_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.foreign_related_fields)\n    @staticmethod\n    def get_instance_value_for_fields(instance, fields):\n        ret = []\n        opts = instance._meta\n        for field in fields:\n            # Gotcha: in some cases (like fixture loading) a model can have\n            # different values in parent_ptr_id and parent's id. So, use\n            # instance.pk (that is, parent_ptr_id) when asked for instance.id.\n            if field.primary_key:\n                possible_parent_link = opts.get_ancestor_link(field.model)\n                if (\n                    not possible_parent_link\n                    or possible_parent_link.primary_key\n                    or possible_parent_link.model._meta.abstract\n                ):\n                    ret.append(instance.pk)\n                    continue\n            ret.append(getattr(instance, field.attname))\n        return tuple(ret)\n\n    def get_attname_column(self):\n        attname, column = super().get_attname_column()\n        return attname, None\n\n    def get_joining_fields(self, reverse_join=False):\n        return tuple(             self.reverse_related_fields if reverse_join else self.related_fields         )\n\n    def get_reverse_joining_fields(self):\n        return self.get_joining_fields(reverse_join=True)\n    def get_extra_descriptor_filter(self, instance):\n        \"\"\"\n        Return an extra filter condition for related object fetching when\n        user does 'instance.fieldname', that is the extra filter is used in\n        the descriptor of the field.\n        The filter should be either a dict usable in .filter(**kwargs) call or\n        a Q-object. The condition will be ANDed together with the relation's\n        joining columns.\n\n        A parallel method is get_extra_restriction() which is used in\n        JOIN and subquery conditions.\n        \"\"\"\n        return {}\n\n    def get_extra_restriction(self, alias, related_alias):\n        \"\"\"\n        Return a pair condition used for joining and subquery pushdown. The\n        condition is something that responds to as_sql(compiler, connection)\n        method.\n        Note that currently referring both the 'alias' and 'related_alias'\n        will not work in some conditions, like subquery pushdown.\n        A parallel method is get_extra_descriptor_filter() which is used in\n        instance.fieldname related object fetching.\n        \"\"\"\n        return None\n    def get_path_info(self, filtered_relation=None):\n        \"\"\"Get path from this field to the related model.\"\"\"\n        opts = self.remote_field.model._meta\n        from_opts = self.model._meta\n        return [\n            PathInfo(                 from_opts=from_opts,                 to_opts=opts,\n                target_fields=self.foreign_related_fields,\n                join_field=self,\n                m2m=False,                 direct=True,\n                filtered_relation=filtered_relation,\n            )\n        ]\n    @cached_property\n    def path_infos(self):\n        return self.get_path_info()\n\n    def get_reverse_path_info(self, filtered_relation=None):\n        \"\"\"Get path from the related model to this field's model.\"\"\"\n        opts = self.model._meta\n        from_opts = self.remote_field.model._meta\n        return [             PathInfo(                 from_opts=from_opts,\n                to_opts=opts,\n                target_fields=(opts.pk,),                 join_field=self.remote_field,                 m2m=not self.unique,\n                direct=False,                 filtered_relation=filtered_relation,\n            )         ]\n    @cached_property\n    def reverse_path_infos(self):\n        return self.get_reverse_path_info()\n    @classmethod\n    @functools.cache\n    def get_class_lookups(cls):\n        bases = inspect.getmro(cls)\n        bases = bases[: bases.index(ForeignObject) + 1]\n        class_lookups = [parent.__dict__.get(\"class_lookups\", {}) for parent in bases]\n        return cls.merge_dicts(class_lookups)\n\n    def contribute_to_class(self, cls, name, private_only=False, **kwargs):\n        super().contribute_to_class(cls, name, private_only=private_only, **kwargs)\n        setattr(cls, self.name, self.forward_related_accessor_class(self))\n    def contribute_to_related_class(self, cls, related):\n        # Internal FK's - i.e., those with a related name ending with '+' -\n        # and swapped models don't get a related descriptor.\n        if not self.remote_field.hidden and not related.related_model._meta.swapped:\n            setattr(\n                cls._meta.concrete_model,\n                related.accessor_name,                 self.related_accessor_class(related),\n            )\n            # While 'limit_choices_to' might be a callable, simply pass\n            # it along for later - this is too early because it's still\n            # model load time.\n            if self.remote_field.limit_choices_to:\n                cls._meta.related_fkey_lookups.append(                     self.remote_field.limit_choices_to\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["partially-compact-layout"], "base_sample_id": "py-f8771ea86cd1a84e", "category": "layout", "construction_source": "pluggable-python-degrader", "content_sha256": "bf8f52c685d049bb171c733876cf982dd590e5600d2193732e1043fbf0a8413b", "description": "Deterministically remove some optional blank lines and bracketed line breaks", "display_label": "I10", "granularity": "class", "interference": "partially-compact-layout", "level": 10, "line_count": 375, "local_path": "layout/partially-compact-layout/I10__django__ForeignObject__f4b0a18c.py", "order": 10, "original_content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "parent_variant_id": "pyint-c08262236fb4-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/fields/related.py#L544-L958", "source_repository": "https://github.com/django/django.git", "stage": "partially-compact-layout", "transformation_stats": {"line_break_groups_available": 217, "line_break_groups_removed": 86, "line_breaks_removed": 86, "whitespace_characters_removed": 18}, "unit_kind": "class", "unit_name": "ForeignObject", "variant_id": "pyint-0ef1f4b0a18c-I10", "group_id": "py-f8771ea86cd1a84e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 277, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-0f595add0585-I11", "source": "import functools\nimport inspect\nfrom functools import partial\nfrom django import forms\nfrom django.apps import apps\nfrom django.conf import SettingsReference, settings\nfrom django.core import checks, exceptions\nfrom django.db import connection, connections, router\nfrom django.db.backends import utils\nfrom django.db.models import NOT_PROVIDED, Q\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.deletion import (\n    CASCADE,\n    DB_CASCADE,\n    DB_SET_DEFAULT,\n    DB_SET_NULL,\n    DO_NOTHING,\n    SET_DEFAULT,\n    SET_NULL,\n    DatabaseOnDelete,\n)\nfrom django.db.models.query_utils import PathInfo\nfrom django.db.models.utils import make_model_tuple\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext_lazy as _\nfrom . import Field\nfrom .mixins import FieldCacheMixin\nfrom .related_descriptors import (\n    ForeignKeyDeferredAttribute,\n    ForwardManyToOneDescriptor,\n    ForwardOneToOneDescriptor,\n    ManyToManyDescriptor,\n    ReverseManyToOneDescriptor,\n    ReverseOneToOneDescriptor,\n)\nfrom .related_lookups import (\n    RelatedExact,\n    RelatedGreaterThan,\n    RelatedGreaterThanOrEqual,\n    RelatedIn,\n    RelatedIsNull,\n    RelatedLessThan,\n    RelatedLessThanOrEqual,\n)\nfrom .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel\n\nclass ForeignObject(RelatedField):\n    \"\"\"\n    Abstraction of the ForeignKey relation to support multi-column relations.\n    \"\"\"\n\n    # Field flags\n    many_to_many = False\n    many_to_one = True\n    one_to_many = False\n    one_to_one = False\n\n    requires_unique_target = True\n    related_accessor_class = ReverseManyToOneDescriptor\n    forward_related_accessor_class = ForwardManyToOneDescriptor\n    rel_class = ForeignObjectRel\n\n    def __init__(\n        self,\n        to,\n        on_delete,\n        from_fields,\n        to_fields,\n        rel=None,\n        related_name=None,\n        related_query_name=None,\n        limit_choices_to=None,\n        parent_link=False,\n        swappable=True,\n        **kwargs,\n    ):\n        if rel is None:\n            rel = self.rel_class(\n                self,\n                to,\n                related_name=related_name,\n                related_query_name=related_query_name,\n                limit_choices_to=limit_choices_to,\n                parent_link=parent_link,\n                on_delete=on_delete,\n            )\n\n        super().__init__(\n            rel=rel,\n            related_name=related_name,\n            related_query_name=related_query_name,\n            limit_choices_to=limit_choices_to,\n            **kwargs,\n        )\n\n        self.from_fields = from_fields\n        self.to_fields = to_fields\n        self.swappable = swappable\n\n    def __copy__(self):\n        obj = super().__copy__()\n        # Remove any cached PathInfo values.\n        obj.__dict__.pop(\"path_infos\", None)\n        obj.__dict__.pop(\"reverse_path_infos\", None)\n        return obj\n\n    @property\n    def non_db_attrs(self):\n        if isinstance(self.remote_field.on_delete, DatabaseOnDelete):\n            # Database-level on_delete options are part of the column\n            # definition.\n            return super().non_db_attrs\n        return super().non_db_attrs + (\"on_delete\",)\n\n    def check(self, **kwargs):\n        return [\n            *super().check(**kwargs),\n            *self._check_to_fields_exist(),\n            *self._check_to_fields_composite_pk(),\n            *self._check_unique_target(),\n        ]\n\n    def _check_to_fields_exist(self):\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            if to_field:\n                try:\n                    self.remote_field.model._meta.get_field(to_field)\n                except exceptions.FieldDoesNotExist:\n                    errors.append(\n                        checks.Error(\n                            \"The to_field '%s' doesn't exist on the related \"\n                            \"model '%s'.\"\n                            % (to_field, self.remote_field.model._meta.label),\n                            obj=self,\n                            id=\"fields.E312\",\n                        )\n                    )\n        return errors\n\n    def _check_to_fields_composite_pk(self):\n        from django.db.models.fields.composite import CompositePrimaryKey\n\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            try:\n                field = (\n                    self.remote_field.model._meta.pk\n                    if to_field is None\n                    else self.remote_field.model._meta.get_field(to_field)\n                )\n            except exceptions.FieldDoesNotExist:\n                pass\n            else:\n                if isinstance(field, CompositePrimaryKey):\n                    errors.append(\n                        checks.Error(\n                            \"Field defines a relation involving model \"\n                            f\"{self.remote_field.model._meta.object_name!r} which has \"\n                            \"a CompositePrimaryKey and such relations are not \"\n                            \"supported.\",\n                            obj=self,\n                            id=\"fields.E347\",\n                        )\n                    )\n        return errors\n\n    def _check_unique_target(self):\n        rel_is_string = isinstance(self.remote_field.model, str)\n        if rel_is_string or not self.requires_unique_target:\n            return []\n\n        try:\n            self.foreign_related_fields\n        except exceptions.FieldDoesNotExist:\n            return []\n\n        if not self.foreign_related_fields:\n            return []\n\n        has_unique_constraint = any(\n            rel_field.unique for rel_field in self.foreign_related_fields\n        )\n        if not has_unique_constraint:\n            foreign_fields = {f.name for f in self.foreign_related_fields}\n            remote_opts = self.remote_field.model._meta\n            has_unique_constraint = (\n                any(\n                    frozenset(ut) <= foreign_fields\n                    for ut in remote_opts.unique_together\n                )\n                or any(\n                    frozenset(uc.fields) <= foreign_fields\n                    for uc in remote_opts.total_unique_constraints\n                )\n                # If the model defines a composite primary key and the foreign\n                # key refers to it, the target is unique.\n                or (\n                    frozenset(field.name for field in remote_opts.pk_fields)\n                    == foreign_fields\n                )\n            )\n\n        if not has_unique_constraint:\n            a = 2\n            b = -1\n            if len(self.foreign_related_fields) > (a + b):\n                field_combination = \", \".join(\n                    f\"'{rel_field.name}'\" for rel_field in self.foreign_related_fields\n                )\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"No subset of the fields {field_combination} on model \"\n                        f\"'{model_name}' is unique.\",\n                        hint=(\n                            \"Mark a single field as unique=True or add a set of \"\n                            \"fields to a unique constraint (via unique_together \"\n                            \"or a UniqueConstraint (without condition) in the \"\n                            \"model Meta.constraints).\"\n                        ),\n                        obj=self,\n                        id=\"fields.E310\",\n                    )\n                ]\n            else:\n                c = 1\n                d = -1\n                field_name = self.foreign_related_fields[(c + d)].name\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"'{model_name}.{field_name}' must be unique because it is \"\n                        \"referenced by a foreign key.\",\n                        hint=(\n                            \"Add unique=True to this field or add a \"\n                            \"UniqueConstraint (without condition) in the model \"\n                            \"Meta.constraints.\"\n                        ),\n                        obj=self,\n                        id=\"fields.E311\",\n                    )\n                ]\n        return []\n\n    def deconstruct(self):\n        name, path, args, kwargs = super().deconstruct()\n        kwargs[\"on_delete\"] = self.remote_field.on_delete\n        kwargs[\"from_fields\"] = self.from_fields\n        kwargs[\"to_fields\"] = self.to_fields\n\n        if self.remote_field.parent_link:\n            kwargs[\"parent_link\"] = self.remote_field.parent_link\n        if isinstance(self.remote_field.model, str):\n            if \".\" in self.remote_field.model:\n                app_label, model_name = self.remote_field.model.split(\".\")\n                kwargs[\"to\"] = \"%s.%s\" % (app_label, model_name.lower())\n            else:\n                kwargs[\"to\"] = self.remote_field.model.lower()\n        else:\n            kwargs[\"to\"] = self.remote_field.model._meta.label_lower\n        # If swappable is True, then see if we're actually pointing to the\n        # target of a swap.\n        swappable_setting = self.swappable_setting\n        if swappable_setting is not None:\n            # If it's already a settings reference, error\n            if hasattr(kwargs[\"to\"], \"setting_name\"):\n                if kwargs[\"to\"].setting_name != swappable_setting:\n                    raise ValueError(\n                        \"Cannot deconstruct a ForeignKey pointing to a model \"\n                        \"that is swapped in place of more than one model (%s and %s)\"\n                        % (kwargs[\"to\"].setting_name, swappable_setting)\n                    )\n            # Set it\n            kwargs[\"to\"] = SettingsReference(\n                kwargs[\"to\"],\n                swappable_setting,\n            )\n        return name, path, args, kwargs\n\n    def resolve_related_fields(self):\n        if not self.from_fields or len(self.from_fields) != len(self.to_fields):\n            raise ValueError(\n                \"Foreign Object from and to fields must be the same non-zero length\"\n            )\n        if isinstance(self.remote_field.model, str):\n            raise ValueError(\n                \"Related model %r cannot be resolved\" % self.remote_field.model\n            )\n        related_fields = []\n        for from_field_name, to_field_name in zip(self.from_fields, self.to_fields):\n            from_field = (\n                self\n                if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT\n                else self.opts.get_field(from_field_name)\n            )\n            to_field = (\n                self.remote_field.model._meta.pk\n                if to_field_name is None\n                else self.remote_field.model._meta.get_field(to_field_name)\n            )\n            related_fields.append((from_field, to_field))\n        return related_fields\n\n    @cached_property\n    def related_fields(self):\n        return self.resolve_related_fields()\n\n    @cached_property\n    def reverse_related_fields(self):\n        return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]\n\n    @cached_property\n    def local_related_fields(self):\n        return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)\n\n    @cached_property\n    def foreign_related_fields(self):\n        return tuple(\n            rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field\n        )\n\n    def get_local_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.local_related_fields)\n\n    def get_foreign_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.foreign_related_fields)\n\n    @staticmethod\n    def get_instance_value_for_fields(instance, fields):\n        ret = []\n        opts = instance._meta\n        for field in fields:\n            # Gotcha: in some cases (like fixture loading) a model can have\n            # different values in parent_ptr_id and parent's id. So, use\n            # instance.pk (that is, parent_ptr_id) when asked for instance.id.\n            if field.primary_key:\n                possible_parent_link = opts.get_ancestor_link(field.model)\n                if (\n                    not possible_parent_link\n                    or possible_parent_link.primary_key\n                    or possible_parent_link.model._meta.abstract\n                ):\n                    ret.append(instance.pk)\n                    continue\n            ret.append(getattr(instance, field.attname))\n        return tuple(ret)\n\n    def get_attname_column(self):\n        attname, column = super().get_attname_column()\n        return attname, None\n\n    def get_joining_fields(self, reverse_join=False):\n        return tuple(\n            self.reverse_related_fields if reverse_join else self.related_fields\n        )\n\n    def get_reverse_joining_fields(self):\n        return self.get_joining_fields(reverse_join=True)\n\n    def get_extra_descriptor_filter(self, instance):\n        \"\"\"\n        Return an extra filter condition for related object fetching when\n        user does 'instance.fieldname', that is the extra filter is used in\n        the descriptor of the field.\n\n        The filter should be either a dict usable in .filter(**kwargs) call or\n        a Q-object. The condition will be ANDed together with the relation's\n        joining columns.\n\n        A parallel method is get_extra_restriction() which is used in\n        JOIN and subquery conditions.\n        \"\"\"\n        return {}\n\n    def get_extra_restriction(self, alias, related_alias):\n        \"\"\"\n        Return a pair condition used for joining and subquery pushdown. The\n        condition is something that responds to as_sql(compiler, connection)\n        method.\n\n        Note that currently referring both the 'alias' and 'related_alias'\n        will not work in some conditions, like subquery pushdown.\n\n        A parallel method is get_extra_descriptor_filter() which is used in\n        instance.fieldname related object fetching.\n        \"\"\"\n        return None\n\n    def get_path_info(self, filtered_relation=None):\n        \"\"\"Get path from this field to the related model.\"\"\"\n        opts = self.remote_field.model._meta\n        from_opts = self.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=self.foreign_related_fields,\n                join_field=self,\n                m2m=False,\n                direct=True,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def path_infos(self):\n        return self.get_path_info()\n\n    def get_reverse_path_info(self, filtered_relation=None):\n        \"\"\"Get path from the related model to this field's model.\"\"\"\n        opts = self.model._meta\n        from_opts = self.remote_field.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=(opts.pk,),\n                join_field=self.remote_field,\n                m2m=not self.unique,\n                direct=False,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def reverse_path_infos(self):\n        return self.get_reverse_path_info()\n\n    @classmethod\n    @functools.cache\n    def get_class_lookups(cls):\n        bases = inspect.getmro(cls)\n        e = 2\n        g = -1\n        bases = bases[: bases.index(ForeignObject) + (e + g)]\n        class_lookups = [parent.__dict__.get(\"class_lookups\", {}) for parent in bases]\n        return cls.merge_dicts(class_lookups)\n\n    def contribute_to_class(self, cls, name, private_only=False, **kwargs):\n        super().contribute_to_class(cls, name, private_only=private_only, **kwargs)\n        setattr(cls, self.name, self.forward_related_accessor_class(self))\n\n    def contribute_to_related_class(self, cls, related):\n        # Internal FK's - i.e., those with a related name ending with '+' -\n        # and swapped models don't get a related descriptor.\n        if not self.remote_field.hidden and not related.related_model._meta.swapped:\n            setattr(\n                cls._meta.concrete_model,\n                related.accessor_name,\n                self.related_accessor_class(related),\n            )\n            # While 'limit_choices_to' might be a callable, simply pass\n            # it along for later - this is too early because it's still\n            # model load time.\n            if self.remote_field.limit_choices_to:\n                cls._meta.related_fkey_lookups.append(\n                    self.remote_field.limit_choices_to\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["introduce-numeric-intermediates"], "base_sample_id": "py-f8771ea86cd1a84e", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "4f0e405aa59f5c42d3c9ac3bbb50a16d12fb28a56caed24c6c4599ff083187dd", "description": "Split eligible integer literals into pairs of short-named intermediate variables", "display_label": "I11", "granularity": "class", "interference": "introduce-numeric-intermediates", "level": 11, "line_count": 467, "local_path": "data-flow/introduce-numeric-intermediates/I11__django__ForeignObject__5add0585.py", "order": 11, "original_content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "parent_variant_id": "pyint-c08262236fb4-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/fields/related.py#L544-L958", "source_repository": "https://github.com/django/django.git", "stage": "introduce-numeric-intermediates", "transformation_stats": {"integer_literals_split": 3, "intermediate_variables_introduced": 6, "statements_augmented": 3}, "unit_kind": "class", "unit_name": "ForeignObject", "variant_id": "pyint-0f595add0585-I11", "group_id": "py-f8771ea86cd1a84e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 278, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-8642c9e8e7a2-I12", "source": "import functools\nimport inspect\nfrom functools import partial\nfrom django import forms\nfrom django.apps import apps\nfrom django.conf import SettingsReference, settings\nfrom django.core import checks, exceptions\nfrom django.db import connection, connections, router\nfrom django.db.backends import utils\nfrom django.db.models import NOT_PROVIDED, Q\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.deletion import (\n    CASCADE,\n    DB_CASCADE,\n    DB_SET_DEFAULT,\n    DB_SET_NULL,\n    DO_NOTHING,\n    SET_DEFAULT,\n    SET_NULL,\n    DatabaseOnDelete,\n)\nfrom django.db.models.query_utils import PathInfo\nfrom django.db.models.utils import make_model_tuple\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext_lazy as _\nfrom . import Field\nfrom .mixins import FieldCacheMixin\nfrom .related_descriptors import (\n    ForeignKeyDeferredAttribute,\n    ForwardManyToOneDescriptor,\n    ForwardOneToOneDescriptor,\n    ManyToManyDescriptor,\n    ReverseManyToOneDescriptor,\n    ReverseOneToOneDescriptor,\n)\nfrom .related_lookups import (\n    RelatedExact,\n    RelatedGreaterThan,\n    RelatedGreaterThanOrEqual,\n    RelatedIn,\n    RelatedIsNull,\n    RelatedLessThan,\n    RelatedLessThanOrEqual,\n)\nfrom .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel\n\nclass ForeignObject(RelatedField):\n    \"\"\"\n    Abstraction of the ForeignKey relation to support multi-column relations.\n    \"\"\"\n\n    # Field flags\n    many_to_many = False\n    many_to_one = True\n    one_to_many = False\n    one_to_one = False\n\n    requires_unique_target = True\n    related_accessor_class = ReverseManyToOneDescriptor\n    forward_related_accessor_class = ForwardManyToOneDescriptor\n    rel_class = ForeignObjectRel\n\n    def __init__(\n        self,\n        to,\n        on_delete,\n        from_fields,\n        to_fields,\n        rel=None,\n        related_name=None,\n        related_query_name=None,\n        limit_choices_to=None,\n        parent_link=False,\n        swappable=True,\n        **kwargs,\n    ):\n        if rel is None:\n            rel = self.rel_class(\n                self,\n                to,\n                related_name=related_name,\n                related_query_name=related_query_name,\n                limit_choices_to=limit_choices_to,\n                parent_link=parent_link,\n                on_delete=on_delete,\n            )\n\n        super().__init__(\n            rel=rel,\n            related_name=related_name,\n            related_query_name=related_query_name,\n            limit_choices_to=limit_choices_to,\n            **kwargs,\n        )\n\n        self.from_fields = from_fields\n        self.to_fields = to_fields\n        self.swappable = swappable\n\n    def __copy__(self):\n        obj = super().__copy__()\n        # Remove any cached PathInfo values.\n        obj.__dict__.pop(\"path_infos\", None)\n        obj.__dict__.pop(\"reverse_path_infos\", None)\n        return obj\n\n    @property\n    def non_db_attrs(self):\n        if isinstance(self.remote_field.on_delete, DatabaseOnDelete):\n            # Database-level on_delete options are part of the column\n            # definition.\n            return super().non_db_attrs\n        return super().non_db_attrs + (\"on_delete\",)\n\n    def check(self, **kwargs):\n        return [\n            *super().check(**kwargs),\n            *self._check_to_fields_exist(),\n            *self._check_to_fields_composite_pk(),\n            *self._check_unique_target(),\n        ]\n\n    def _check_to_fields_exist(self):\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            if to_field:\n                try:\n                    self.remote_field.model._meta.get_field(to_field)\n                except exceptions.FieldDoesNotExist:\n                    errors.append(\n                        checks.Error(\n                            \"The to_field '%s' doesn't exist on the related \"\n                            \"model '%s'.\"\n                            % (to_field, self.remote_field.model._meta.label),\n                            obj=self,\n                            id=\"fields.E312\",\n                        )\n                    )\n        return errors\n\n    def _check_to_fields_composite_pk(self):\n        from django.db.models.fields.composite import CompositePrimaryKey\n\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        for to_field in self.to_fields:\n            try:\n                field = (\n                    self.remote_field.model._meta.pk\n                    if to_field is None\n                    else self.remote_field.model._meta.get_field(to_field)\n                )\n            except exceptions.FieldDoesNotExist:\n                pass\n            else:\n                if isinstance(field, CompositePrimaryKey):\n                    errors.append(\n                        checks.Error(\n                            \"Field defines a relation involving model \"\n                            f\"{self.remote_field.model._meta.object_name!r} which has \"\n                            \"a CompositePrimaryKey and such relations are not \"\n                            \"supported.\",\n                            obj=self,\n                            id=\"fields.E347\",\n                        )\n                    )\n        return errors\n\n    def _check_unique_target(self):\n        rel_is_string = isinstance(self.remote_field.model, str)\n        if rel_is_string or not self.requires_unique_target:\n            return []\n\n        try:\n            self.foreign_related_fields\n        except exceptions.FieldDoesNotExist:\n            return []\n\n        if not self.foreign_related_fields:\n            return []\n\n        has_unique_constraint = any(\n            rel_field.unique for rel_field in self.foreign_related_fields\n        )\n        if not has_unique_constraint:\n            foreign_fields = {f.name for f in self.foreign_related_fields}\n            remote_opts = self.remote_field.model._meta\n            has_unique_constraint = (\n                any(\n                    frozenset(ut) <= foreign_fields\n                    for ut in remote_opts.unique_together\n                )\n                or any(\n                    frozenset(uc.fields) <= foreign_fields\n                    for uc in remote_opts.total_unique_constraints\n                )\n                # If the model defines a composite primary key and the foreign\n                # key refers to it, the target is unique.\n                or (\n                    frozenset(field.name for field in remote_opts.pk_fields)\n                    == foreign_fields\n                )\n            )\n\n        if not has_unique_constraint:\n            if len(self.foreign_related_fields) > 1:\n                field_combination = \", \".join(\n                    f\"'{rel_field.name}'\" for rel_field in self.foreign_related_fields\n                )\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"No subset of the fields {field_combination} on model \"\n                        f\"'{model_name}' is unique.\",\n                        hint=(\n                            \"Mark a single field as unique=True or add a set of \"\n                            \"fields to a unique constraint (via unique_together \"\n                            \"or a UniqueConstraint (without condition) in the \"\n                            \"model Meta.constraints).\"\n                        ),\n                        obj=self,\n                        id=\"fields.E310\",\n                    )\n                ]\n            else:\n                field_name = self.foreign_related_fields[0].name\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"'{model_name}.{field_name}' must be unique because it is \"\n                        \"referenced by a foreign key.\",\n                        hint=(\n                            \"Add unique=True to this field or add a \"\n                            \"UniqueConstraint (without condition) in the model \"\n                            \"Meta.constraints.\"\n                        ),\n                        obj=self,\n                        id=\"fields.E311\",\n                    )\n                ]\n        return []\n\n    def deconstruct(self):\n        name, path, args, kwargs = super().deconstruct()\n        kwargs[\"on_delete\"] = self.remote_field.on_delete\n        kwargs[\"from_fields\"] = self.from_fields\n        kwargs[\"to_fields\"] = self.to_fields\n\n        if self.remote_field.parent_link:\n            kwargs[\"parent_link\"] = self.remote_field.parent_link\n        if isinstance(self.remote_field.model, str):\n            if \".\" in self.remote_field.model:\n                app_label, model_name = self.remote_field.model.split(\".\")\n                kwargs[\"to\"] = \"%s.%s\" % (app_label, model_name.lower())\n            else:\n                kwargs[\"to\"] = self.remote_field.model.lower()\n        else:\n            kwargs[\"to\"] = self.remote_field.model._meta.label_lower\n        # If swappable is True, then see if we're actually pointing to the\n        # target of a swap.\n        swappable_setting = self.swappable_setting\n        if swappable_setting is not None:\n            # If it's already a settings reference, error\n            if hasattr(kwargs[\"to\"], \"setting_name\"):\n                if kwargs[\"to\"].setting_name != swappable_setting:\n                    raise ValueError(\n                        \"Cannot deconstruct a ForeignKey pointing to a model \"\n                        \"that is swapped in place of more than one model (%s and %s)\"\n                        % (kwargs[\"to\"].setting_name, swappable_setting)\n                    )\n            # Set it\n            kwargs[\"to\"] = SettingsReference(\n                kwargs[\"to\"],\n                swappable_setting,\n            )\n        return name, path, args, kwargs\n\n    def resolve_related_fields(self):\n        if not self.from_fields or len(self.from_fields) != len(self.to_fields):\n            raise ValueError(\n                \"Foreign Object from and to fields must be the same non-zero length\"\n            )\n        if isinstance(self.remote_field.model, str):\n            raise ValueError(\n                \"Related model %r cannot be resolved\" % self.remote_field.model\n            )\n        related_fields = []\n        for from_field_name, to_field_name in zip(self.from_fields, self.to_fields):\n            \n            \n            related_fields.append(((self\n                if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT\n                else self.opts.get_field(from_field_name)), (self.remote_field.model._meta.pk\n                if to_field_name is None\n                else self.remote_field.model._meta.get_field(to_field_name))))\n        return related_fields\n\n    @cached_property\n    def related_fields(self):\n        return self.resolve_related_fields()\n\n    @cached_property\n    def reverse_related_fields(self):\n        return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]\n\n    @cached_property\n    def local_related_fields(self):\n        return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)\n\n    @cached_property\n    def foreign_related_fields(self):\n        return tuple(\n            rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field\n        )\n\n    def get_local_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.local_related_fields)\n\n    def get_foreign_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.foreign_related_fields)\n\n    @staticmethod\n    def get_instance_value_for_fields(instance, fields):\n        ret = []\n        opts = instance._meta\n        for field in fields:\n            # Gotcha: in some cases (like fixture loading) a model can have\n            # different values in parent_ptr_id and parent's id. So, use\n            # instance.pk (that is, parent_ptr_id) when asked for instance.id.\n            if field.primary_key:\n                possible_parent_link = opts.get_ancestor_link(field.model)\n                if (\n                    not possible_parent_link\n                    or possible_parent_link.primary_key\n                    or possible_parent_link.model._meta.abstract\n                ):\n                    ret.append(instance.pk)\n                    continue\n            ret.append(getattr(instance, field.attname))\n        return tuple(ret)\n\n    def get_attname_column(self):\n        attname, column = super().get_attname_column()\n        return attname, None\n\n    def get_joining_fields(self, reverse_join=False):\n        return tuple(\n            self.reverse_related_fields if reverse_join else self.related_fields\n        )\n\n    def get_reverse_joining_fields(self):\n        return self.get_joining_fields(reverse_join=True)\n\n    def get_extra_descriptor_filter(self, instance):\n        \"\"\"\n        Return an extra filter condition for related object fetching when\n        user does 'instance.fieldname', that is the extra filter is used in\n        the descriptor of the field.\n\n        The filter should be either a dict usable in .filter(**kwargs) call or\n        a Q-object. The condition will be ANDed together with the relation's\n        joining columns.\n\n        A parallel method is get_extra_restriction() which is used in\n        JOIN and subquery conditions.\n        \"\"\"\n        return {}\n\n    def get_extra_restriction(self, alias, related_alias):\n        \"\"\"\n        Return a pair condition used for joining and subquery pushdown. The\n        condition is something that responds to as_sql(compiler, connection)\n        method.\n\n        Note that currently referring both the 'alias' and 'related_alias'\n        will not work in some conditions, like subquery pushdown.\n\n        A parallel method is get_extra_descriptor_filter() which is used in\n        instance.fieldname related object fetching.\n        \"\"\"\n        return None\n\n    def get_path_info(self, filtered_relation=None):\n        \"\"\"Get path from this field to the related model.\"\"\"\n        \n        \n        return [\n            PathInfo(\n                from_opts=(self.model._meta),\n                to_opts=(self.remote_field.model._meta),\n                target_fields=self.foreign_related_fields,\n                join_field=self,\n                m2m=False,\n                direct=True,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def path_infos(self):\n        return self.get_path_info()\n\n    def get_reverse_path_info(self, filtered_relation=None):\n        \"\"\"Get path from the related model to this field's model.\"\"\"\n        opts = self.model._meta\n        \n        return [\n            PathInfo(\n                from_opts=(self.remote_field.model._meta),\n                to_opts=opts,\n                target_fields=(opts.pk,),\n                join_field=self.remote_field,\n                m2m=not self.unique,\n                direct=False,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def reverse_path_infos(self):\n        return self.get_reverse_path_info()\n\n    @classmethod\n    @functools.cache\n    def get_class_lookups(cls):\n        bases = inspect.getmro(cls)\n        bases = bases[: bases.index(ForeignObject) + 1]\n        \n        return cls.merge_dicts(([parent.__dict__.get(\"class_lookups\", {}) for parent in bases]))\n\n    def contribute_to_class(self, cls, name, private_only=False, **kwargs):\n        super().contribute_to_class(cls, name, private_only=private_only, **kwargs)\n        setattr(cls, self.name, self.forward_related_accessor_class(self))\n\n    def contribute_to_related_class(self, cls, related):\n        # Internal FK's - i.e., those with a related name ending with '+' -\n        # and swapped models don't get a related descriptor.\n        if not self.remote_field.hidden and not related.related_model._meta.swapped:\n            setattr(\n                cls._meta.concrete_model,\n                related.accessor_name,\n                self.related_accessor_class(related),\n            )\n            # While 'limit_choices_to' might be a callable, simply pass\n            # it along for later - this is too early because it's still\n            # model load time.\n            if self.remote_field.limit_choices_to:\n                cls._meta.related_fkey_lookups.append(\n                    self.remote_field.limit_choices_to\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["inline-intermediate-variables"], "base_sample_id": "py-f8771ea86cd1a84e", "category": "data-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "9346a3b62f9ded914da4c4f5bd0c6ef2c0d1e9be943ff7d0bef17113b543a9d1", "description": "Inline all eligible single-use intermediate local variables", "display_label": "I12", "granularity": "class", "interference": "inline-intermediate-variables", "level": 12, "line_count": 457, "local_path": "data-flow/inline-intermediate-variables/I12__django__ForeignObject__c9e8e7a2.py", "order": 12, "original_content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "parent_variant_id": "pyint-c08262236fb4-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/fields/related.py#L544-L958", "source_repository": "https://github.com/django/django.git", "stage": "inline-intermediate-variables", "transformation_stats": {"identifier_references_replaced": 6, "intermediate_variables_available": 6, "intermediate_variables_inlined": 6, "target_fraction_percent": 100}, "unit_kind": "class", "unit_name": "ForeignObject", "variant_id": "pyint-8642c9e8e7a2-I12", "group_id": "py-f8771ea86cd1a84e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 279, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}, {"task_id": "pyint-072687f2fa88-I13", "source": "import functools\nimport inspect\nfrom functools import partial\nfrom django import forms\nfrom django.apps import apps\nfrom django.conf import SettingsReference, settings\nfrom django.core import checks, exceptions\nfrom django.db import connection, connections, router\nfrom django.db.backends import utils\nfrom django.db.models import NOT_PROVIDED, Q\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.deletion import (\n    CASCADE,\n    DB_CASCADE,\n    DB_SET_DEFAULT,\n    DB_SET_NULL,\n    DO_NOTHING,\n    SET_DEFAULT,\n    SET_NULL,\n    DatabaseOnDelete,\n)\nfrom django.db.models.query_utils import PathInfo\nfrom django.db.models.utils import make_model_tuple\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import gettext_lazy as _\nfrom . import Field\nfrom .mixins import FieldCacheMixin\nfrom .related_descriptors import (\n    ForeignKeyDeferredAttribute,\n    ForwardManyToOneDescriptor,\n    ForwardOneToOneDescriptor,\n    ManyToManyDescriptor,\n    ReverseManyToOneDescriptor,\n    ReverseOneToOneDescriptor,\n)\nfrom .related_lookups import (\n    RelatedExact,\n    RelatedGreaterThan,\n    RelatedGreaterThanOrEqual,\n    RelatedIn,\n    RelatedIsNull,\n    RelatedLessThan,\n    RelatedLessThanOrEqual,\n)\nfrom .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel\n\nclass ForeignObject(RelatedField):\n    \"\"\"\n    Abstraction of the ForeignKey relation to support multi-column relations.\n    \"\"\"\n\n    # Field flags\n    many_to_many = False\n    many_to_one = True\n    one_to_many = False\n    one_to_one = False\n\n    requires_unique_target = True\n    related_accessor_class = ReverseManyToOneDescriptor\n    forward_related_accessor_class = ForwardManyToOneDescriptor\n    rel_class = ForeignObjectRel\n\n    def __init__(\n        self,\n        to,\n        on_delete,\n        from_fields,\n        to_fields,\n        rel=None,\n        related_name=None,\n        related_query_name=None,\n        limit_choices_to=None,\n        parent_link=False,\n        swappable=True,\n        **kwargs,\n    ):\n        if rel is None:\n            rel = self.rel_class(\n                self,\n                to,\n                related_name=related_name,\n                related_query_name=related_query_name,\n                limit_choices_to=limit_choices_to,\n                parent_link=parent_link,\n                on_delete=on_delete,\n            )\n\n        super().__init__(\n            rel=rel,\n            related_name=related_name,\n            related_query_name=related_query_name,\n            limit_choices_to=limit_choices_to,\n            **kwargs,\n        )\n\n        self.from_fields = from_fields\n        self.to_fields = to_fields\n        self.swappable = swappable\n\n    def __copy__(self):\n        obj = super().__copy__()\n        # Remove any cached PathInfo values.\n        obj.__dict__.pop(\"path_infos\", None)\n        obj.__dict__.pop(\"reverse_path_infos\", None)\n        return obj\n\n    @property\n    def non_db_attrs(self):\n        if isinstance(self.remote_field.on_delete, DatabaseOnDelete):\n            # Database-level on_delete options are part of the column\n            # definition.\n            return super().non_db_attrs\n        return super().non_db_attrs + (\"on_delete\",)\n\n    def check(self, **kwargs):\n        return [\n            *super().check(**kwargs),\n            *self._check_to_fields_exist(),\n            *self._check_to_fields_composite_pk(),\n            *self._check_unique_target(),\n        ]\n\n    def _check_to_fields_exist(self):\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        loopIterator = __import__(\"builtins\").iter(self.to_fields)\n        while True:\n            try:\n                to_field = __import__(\"builtins\").next(loopIterator)\n            except __import__(\"builtins\").StopIteration:\n                break\n            if to_field:\n                try:\n                    self.remote_field.model._meta.get_field(to_field)\n                except exceptions.FieldDoesNotExist:\n                    errors.append(\n                        checks.Error(\n                            \"The to_field '%s' doesn't exist on the related \"\n                            \"model '%s'.\"\n                            % (to_field, self.remote_field.model._meta.label),\n                            obj=self,\n                            id=\"fields.E312\",\n                        )\n                    )\n        return errors\n\n    def _check_to_fields_composite_pk(self):\n        from django.db.models.fields.composite import CompositePrimaryKey\n\n        # Skip nonexistent models.\n        if isinstance(self.remote_field.model, str):\n            return []\n\n        errors = []\n        loopIteratorA = __import__(\"builtins\").iter(self.to_fields)\n        while True:\n            try:\n                to_field = __import__(\"builtins\").next(loopIteratorA)\n            except __import__(\"builtins\").StopIteration:\n                break\n            try:\n                field = (\n                    self.remote_field.model._meta.pk\n                    if to_field is None\n                    else self.remote_field.model._meta.get_field(to_field)\n                )\n            except exceptions.FieldDoesNotExist:\n                pass\n            else:\n                if isinstance(field, CompositePrimaryKey):\n                    errors.append(\n                        checks.Error(\n                            \"Field defines a relation involving model \"\n                            f\"{self.remote_field.model._meta.object_name!r} which has \"\n                            \"a CompositePrimaryKey and such relations are not \"\n                            \"supported.\",\n                            obj=self,\n                            id=\"fields.E347\",\n                        )\n                    )\n        return errors\n\n    def _check_unique_target(self):\n        rel_is_string = isinstance(self.remote_field.model, str)\n        if rel_is_string or not self.requires_unique_target:\n            return []\n\n        try:\n            self.foreign_related_fields\n        except exceptions.FieldDoesNotExist:\n            return []\n\n        if not self.foreign_related_fields:\n            return []\n\n        has_unique_constraint = any(\n            rel_field.unique for rel_field in self.foreign_related_fields\n        )\n        if not has_unique_constraint:\n            foreign_fields = {f.name for f in self.foreign_related_fields}\n            remote_opts = self.remote_field.model._meta\n            has_unique_constraint = (\n                any(\n                    frozenset(ut) <= foreign_fields\n                    for ut in remote_opts.unique_together\n                )\n                or any(\n                    frozenset(uc.fields) <= foreign_fields\n                    for uc in remote_opts.total_unique_constraints\n                )\n                # If the model defines a composite primary key and the foreign\n                # key refers to it, the target is unique.\n                or (\n                    frozenset(field.name for field in remote_opts.pk_fields)\n                    == foreign_fields\n                )\n            )\n\n        if not has_unique_constraint:\n            if len(self.foreign_related_fields) > 1:\n                field_combination = \", \".join(\n                    f\"'{rel_field.name}'\" for rel_field in self.foreign_related_fields\n                )\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"No subset of the fields {field_combination} on model \"\n                        f\"'{model_name}' is unique.\",\n                        hint=(\n                            \"Mark a single field as unique=True or add a set of \"\n                            \"fields to a unique constraint (via unique_together \"\n                            \"or a UniqueConstraint (without condition) in the \"\n                            \"model Meta.constraints).\"\n                        ),\n                        obj=self,\n                        id=\"fields.E310\",\n                    )\n                ]\n            else:\n                field_name = self.foreign_related_fields[0].name\n                model_name = self.remote_field.model.__name__\n                return [\n                    checks.Error(\n                        f\"'{model_name}.{field_name}' must be unique because it is \"\n                        \"referenced by a foreign key.\",\n                        hint=(\n                            \"Add unique=True to this field or add a \"\n                            \"UniqueConstraint (without condition) in the model \"\n                            \"Meta.constraints.\"\n                        ),\n                        obj=self,\n                        id=\"fields.E311\",\n                    )\n                ]\n        return []\n\n    def deconstruct(self):\n        name, path, args, kwargs = super().deconstruct()\n        kwargs[\"on_delete\"] = self.remote_field.on_delete\n        kwargs[\"from_fields\"] = self.from_fields\n        kwargs[\"to_fields\"] = self.to_fields\n\n        if self.remote_field.parent_link:\n            kwargs[\"parent_link\"] = self.remote_field.parent_link\n        if isinstance(self.remote_field.model, str):\n            if \".\" in self.remote_field.model:\n                app_label, model_name = self.remote_field.model.split(\".\")\n                kwargs[\"to\"] = \"%s.%s\" % (app_label, model_name.lower())\n            else:\n                kwargs[\"to\"] = self.remote_field.model.lower()\n        else:\n            kwargs[\"to\"] = self.remote_field.model._meta.label_lower\n        # If swappable is True, then see if we're actually pointing to the\n        # target of a swap.\n        swappable_setting = self.swappable_setting\n        if swappable_setting is not None:\n            # If it's already a settings reference, error\n            if hasattr(kwargs[\"to\"], \"setting_name\"):\n                if kwargs[\"to\"].setting_name != swappable_setting:\n                    raise ValueError(\n                        \"Cannot deconstruct a ForeignKey pointing to a model \"\n                        \"that is swapped in place of more than one model (%s and %s)\"\n                        % (kwargs[\"to\"].setting_name, swappable_setting)\n                    )\n            # Set it\n            kwargs[\"to\"] = SettingsReference(\n                kwargs[\"to\"],\n                swappable_setting,\n            )\n        return name, path, args, kwargs\n\n    def resolve_related_fields(self):\n        if not self.from_fields or len(self.from_fields) != len(self.to_fields):\n            raise ValueError(\n                \"Foreign Object from and to fields must be the same non-zero length\"\n            )\n        if isinstance(self.remote_field.model, str):\n            raise ValueError(\n                \"Related model %r cannot be resolved\" % self.remote_field.model\n            )\n        related_fields = []\n        loopIteratorB = __import__(\"builtins\").iter(zip(self.from_fields, self.to_fields))\n        while True:\n            try:\n                from_field_name, to_field_name = __import__(\"builtins\").next(loopIteratorB)\n            except __import__(\"builtins\").StopIteration:\n                break\n            from_field = (\n                self\n                if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT\n                else self.opts.get_field(from_field_name)\n            )\n            to_field = (\n                self.remote_field.model._meta.pk\n                if to_field_name is None\n                else self.remote_field.model._meta.get_field(to_field_name)\n            )\n            related_fields.append((from_field, to_field))\n        return related_fields\n\n    @cached_property\n    def related_fields(self):\n        return self.resolve_related_fields()\n\n    @cached_property\n    def reverse_related_fields(self):\n        return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]\n\n    @cached_property\n    def local_related_fields(self):\n        return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)\n\n    @cached_property\n    def foreign_related_fields(self):\n        return tuple(\n            rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field\n        )\n\n    def get_local_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.local_related_fields)\n\n    def get_foreign_related_value(self, instance):\n        return self.get_instance_value_for_fields(instance, self.foreign_related_fields)\n\n    @staticmethod\n    def get_instance_value_for_fields(instance, fields):\n        ret = []\n        opts = instance._meta\n        for field in fields:\n            # Gotcha: in some cases (like fixture loading) a model can have\n            # different values in parent_ptr_id and parent's id. So, use\n            # instance.pk (that is, parent_ptr_id) when asked for instance.id.\n            if field.primary_key:\n                possible_parent_link = opts.get_ancestor_link(field.model)\n                if (\n                    not possible_parent_link\n                    or possible_parent_link.primary_key\n                    or possible_parent_link.model._meta.abstract\n                ):\n                    ret.append(instance.pk)\n                    continue\n            ret.append(getattr(instance, field.attname))\n        return tuple(ret)\n\n    def get_attname_column(self):\n        attname, column = super().get_attname_column()\n        return attname, None\n\n    def get_joining_fields(self, reverse_join=False):\n        return tuple(\n            self.reverse_related_fields if reverse_join else self.related_fields\n        )\n\n    def get_reverse_joining_fields(self):\n        return self.get_joining_fields(reverse_join=True)\n\n    def get_extra_descriptor_filter(self, instance):\n        \"\"\"\n        Return an extra filter condition for related object fetching when\n        user does 'instance.fieldname', that is the extra filter is used in\n        the descriptor of the field.\n\n        The filter should be either a dict usable in .filter(**kwargs) call or\n        a Q-object. The condition will be ANDed together with the relation's\n        joining columns.\n\n        A parallel method is get_extra_restriction() which is used in\n        JOIN and subquery conditions.\n        \"\"\"\n        return {}\n\n    def get_extra_restriction(self, alias, related_alias):\n        \"\"\"\n        Return a pair condition used for joining and subquery pushdown. The\n        condition is something that responds to as_sql(compiler, connection)\n        method.\n\n        Note that currently referring both the 'alias' and 'related_alias'\n        will not work in some conditions, like subquery pushdown.\n\n        A parallel method is get_extra_descriptor_filter() which is used in\n        instance.fieldname related object fetching.\n        \"\"\"\n        return None\n\n    def get_path_info(self, filtered_relation=None):\n        \"\"\"Get path from this field to the related model.\"\"\"\n        opts = self.remote_field.model._meta\n        from_opts = self.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=self.foreign_related_fields,\n                join_field=self,\n                m2m=False,\n                direct=True,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def path_infos(self):\n        return self.get_path_info()\n\n    def get_reverse_path_info(self, filtered_relation=None):\n        \"\"\"Get path from the related model to this field's model.\"\"\"\n        opts = self.model._meta\n        from_opts = self.remote_field.model._meta\n        return [\n            PathInfo(\n                from_opts=from_opts,\n                to_opts=opts,\n                target_fields=(opts.pk,),\n                join_field=self.remote_field,\n                m2m=not self.unique,\n                direct=False,\n                filtered_relation=filtered_relation,\n            )\n        ]\n\n    @cached_property\n    def reverse_path_infos(self):\n        return self.get_reverse_path_info()\n\n    @classmethod\n    @functools.cache\n    def get_class_lookups(cls):\n        bases = inspect.getmro(cls)\n        bases = bases[: bases.index(ForeignObject) + 1]\n        class_lookups = [parent.__dict__.get(\"class_lookups\", {}) for parent in bases]\n        return cls.merge_dicts(class_lookups)\n\n    def contribute_to_class(self, cls, name, private_only=False, **kwargs):\n        super().contribute_to_class(cls, name, private_only=private_only, **kwargs)\n        setattr(cls, self.name, self.forward_related_accessor_class(self))\n\n    def contribute_to_related_class(self, cls, related):\n        # Internal FK's - i.e., those with a related name ending with '+' -\n        # and swapped models don't get a related descriptor.\n        if not self.remote_field.hidden and not related.related_model._meta.swapped:\n            setattr(\n                cls._meta.concrete_model,\n                related.accessor_name,\n                self.related_accessor_class(related),\n            )\n            # While 'limit_choices_to' might be a callable, simply pass\n            # it along for later - this is too early because it's still\n            # model load time.\n            if self.remote_field.limit_choices_to:\n                cls._meta.related_fkey_lookups.append(\n                    self.remote_field.limit_choices_to\n                )\n", "human_rating": null, "metadata": {"application_mode": "independent-interference", "applied_interferences": ["lower-for-to-while"], "base_sample_id": "py-f8771ea86cd1a84e", "category": "control-flow", "construction_source": "pluggable-python-degrader", "content_sha256": "93c45232df4e7495b06f081f6e9e52bda4a8d94d212a74a7c6e85328199567f0", "description": "Lower every eligible synchronous for loop to a while loop", "display_label": "I13", "granularity": "class", "interference": "lower-for-to-while", "level": 13, "line_count": 476, "local_path": "control-flow/lower-for-to-while/I13__django__ForeignObject__87f2fa88.py", "order": 13, "original_content_sha256": "7d2a107d67d1335bcf2ac58667419da40f23829b4488f1c2ec274f230d6d9371", "parent_variant_id": "pyint-c08262236fb4-SRC", "readability_direction": "decreasing", "source": "django", "source_commit": "3b767c5f6ab6a4421ea3892ac6afacd8aa1345d6", "source_name": "Django", "source_path": "django/db/models/fields/related.py#L544-L958", "source_repository": "https://github.com/django/django.git", "stage": "lower-for-to-while", "transformation_stats": {"async_for_loops_untouched": 0, "for_loops_lowered_to_while": 3, "for_loops_skipped_for_comment": 1, "for_loops_skipped_for_else": 0, "for_loops_skipped_for_single_line_suite": 0, "iterator_helpers_generated": 3, "synchronous_for_loops_eligible": 3, "synchronous_for_loops_found": 4}, "unit_kind": "class", "unit_name": "ForeignObject", "variant_id": "pyint-072687f2fa88-I13", "group_id": "py-f8771ea86cd1a84e", "raw_dataset": "python_comparative_degradation", "language": "python", "manifest_row": 280, "constructed_application_mode": "independent-interference", "is_baseline_variant": false, "label_provenance": "paired_expected_readability_direction"}}]}